I’m having a very basic problem here which I was not able to find a solution to even though it must exist.
I have the following code:
public class Foo {
public static void main(String[] args) {
String foo;
if (foo != null) {
System.out.println("foo");
} else {
System.out.println("foo2");
}
}
}
It gives me
”variable might not have been initialized”
. Why is it that I have to assign null explicitly and not all variables are initialized with null by default?
It prevents you from accidentally using a local variable before it’s been definitely assigned. This is a good thing – it helps to prevent bugs. It’s a shame that it can’t be done for fields (instance and static variables) – but other than final variables, the compiler doesn’t know when you’re going to read them vs when you’re going to assign them – it can’t tell the order in which you’re going to call methods. Within a single method, it has much more information about the flow control, so can provide more checking for you.
If you want the value of a local variable to be null, why don’t you just explicitly set it to null? That not only keeps the compiler happy – it makes it clear what your intentions are too.
See chapter 16 of the Java Language Specification for more details on definite assignment.
Here’s an example of how it can prevent bugs:
What should happen if the collection is empty? Maybe we want to print “The last name was: null” – but maybe we should do something else. The fact that the above won’t compile (as
lastNameIncollectionmay not be assigned) forces the programmer to think about the case where the collection of names is empty.