Null: nullable references and Optional (C# and Java)
A null reference is the oldest mistake in both languages. C# added a compiler analysis for it in 2019: a reference type is non-nullable unless it is written with a question mark, and the compiler warns when the code may dereference a null. Java has no such analysis in the language, and since Java 14 the runtime has a better message for the failure. The task is the same three lines in both.
The task in C#
One variable declared non-nullable and set to null, one declared nullable and used with the null-conditional operator, and then the dereference of the first. The program is four lines and it does not run to the end:
string name = null;
string? other = null;
Console.WriteLine($"other length {other?.Length ?? -1}");
Console.WriteLine($"name length {name.Length}");
The warnings
The build of the program above does not fail and does not stay silent. The compiler prints two warnings, the summary repeats them and counts them, and the program still crashes where they said it would:
dotnet build -nologo -v:q
echo "status: $?"
/tmp/r11/nulls/cs/Program.cs(1,15): warning CS8600: Converting null literal or possible null value to non-nullable type. [/tmp/r11/nulls/cs/app.csproj]
/tmp/r11/nulls/cs/Program.cs(5,34): warning CS8602: Dereference of a possibly null reference. [/tmp/r11/nulls/cs/app.csproj]
Build succeeded.
/tmp/r11/nulls/cs/Program.cs(1,15): warning CS8600: Converting null literal or possible null value to non-nullable type. [/tmp/r11/nulls/cs/app.csproj]
/tmp/r11/nulls/cs/Program.cs(5,34): warning CS8602: Dereference of a possibly null reference. [/tmp/r11/nulls/cs/app.csproj]
2 Warning(s)
0 Error(s)
Time Elapsed 00:00:03.05
build: 0
dotnet run
echo "status: $?"
other length -1
status: 134
The exception text is the one of every C# null dereference and the status is 134, which is 128 plus the signal the runtime raises, as lesson 062 measured. The warning said CS8602 at the exact place of the crash: the analysis is not a proof, and it is the only warning of the two compilers that this program gets.
The same task in Java
The same assignment and the same dereference. javac compiles it without a word, and the failure is a run-time one with a message that names the expression and the variable:
public class Nulls {
public static void main(String[] args) {
String name = null;
System.out.println("name length " + name.length());
}
}
javac -g -d out Nulls.java
java -cp out Nulls
echo "status: $?"
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "name" is null
at Nulls.main(Nulls.java:4)
status: 1
What differs
- C# warns at compile time, Java does not. The warning is not an error, and a project can turn it into one with TreatWarningsAsErrors, which lesson 009 of the C# course does.
- The Java message is the helpful NullPointerException of Java 14 and later: Cannot invoke "String.length()" because "name" is null. It names the variable only when the class was compiled with debug information, which is why the command on the page passes -g; the default build says <local1> instead.
- The C# analysis covers the flows of a method and the return types of the methods it calls; it cannot see a field that another thread sets to null. The Java message covers only the dereference that failed, which is why the two are complements and not alternatives.
- Java has Optional for the case "a value may be absent", and C# has nullable reference types for the same case. Neither removes null: both make a reader handle the absence, and both can be bypassed.
- A C# program can be compiled without the analysis (<Nullable>disable</Nullable>) and then it is in the same position as the Java one. The default of a new project is enable, which is why the warning appears here.
The next page is about the values a program copies: a struct in C#, a record and a wrapper in Java, and the boxed numbers that are not what they seem.
Exercises
- Add a method that returns a null string and see which line the C# warning names.
- Compile the Java program without -g and compare the message.
- Rewrite the Java program with Optional and the C# one with ?. and ??.
- Turn the C# warning into an error and read the build output.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a C# nullable warning say?
Answer
That a reference may be null where the code dereferences it
CS8602 names the dereference of a possibly null reference.
-
Which warning codes did the build print?
Answer
CS8600 and CS8602
The page shows the real build output with both.
-
What does this program print?
string? name = null; Console.WriteLine(name?.Length ?? -1);Answer
-1
The null-conditional operator plus ?? gives the fallback value.
-
What is the status of an unhandled exception on this runtime?
Answer
134
The measured run ends with status 134.
-
What does this program print?
string? name = null; Console.WriteLine(name is null);Answer
True
The pattern checks the value without dereferencing it.
-
What does the helpful NullPointerException name?
Answer
The expression and the variable that was null
The measured message names String.length() and name.
-
What does this program print?
string? city = null; Console.WriteLine(city ?? "missing");Answer
missing
The ?? operator takes the right side when the left is null.
-
Why does javac not warn about the null?
Answer
Java has no nullable-reference analysis in the compiler
The page compiles the same lines with no warning.
-
What does this program print?
string? value = null; Console.WriteLine(value == null);Answer
True
A nullable value set to null is null, which the pattern reports.
-
What does Optional offer in Java?
Answer
A value that may be absent, with methods to handle both cases
The page names it as the Java counterpart of the C# nullable types.
The C# program was built with the .NET SDK 10.0.303 and the Java program with OpenJDK 21.0.13.1 (javac 21.0.13.1), both run on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.
Article author: Arthur Isaev