Skip to content

Commit

Permalink
Added some null safety samples
Browse files Browse the repository at this point in the history
  • Loading branch information
wlybe committed Nov 2, 2023
1 parent 769f046 commit 84d4361
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
18 changes: 18 additions & 0 deletions material/samples/NullSafety.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// program that illustrates null safety in java
public class NullSafety {
public static void main(String[] args) {
@NotNull
String name;
name = null; //
String name2;
name2 = null;
System.out.println(name2.length()); // compile error
System.out.println(name2 == null ? 0 : name2.length());
}

public static int getLength2(String name) {
if (name == null)
return 0;
return name.length();
}
}
13 changes: 13 additions & 0 deletions material/samples/NullSafety.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
fun main() {
var name: String
name = null // compile error
val name2: String?
name2 = null
println(name2.length) // compile error
print(name?.length ?: 0)
}

fun getLength2(name: String?): Int {
if (name == null) return 0
return name.length
}

0 comments on commit 84d4361

Please sign in to comment.