Here's part of a small program I'm doing as a homework assignment:
public Exam maxGrade() {
Node p = firstNode;
int max = 0;
String name;
while (p!=null) {
if (p.info.getGrade()>max) {
max = p.info.getGrade();
name = p.info.getName();
}
p = p.next;
}
if (name==null)
return null;
else
return searchByName(name);
}
So when I go ahead and compile, the compiler outputs this message:
Student.java:127: error: variable name might not have been initialized if (name==null)
The problem is easily solved by substituting the fourth line with:
String name = null;
Now, I can see some logic in this. But I'd really like to grasp the workings behind the problem. I mean, it seems reasonable that the compiler checks whether a variable is initialized if it sees you're doing something with it in your code, but I don't think I'm doing anything that NEEDS the variable to be initialized.
According to sources like this when I simply declare my String (or any other Object) variable "name", it already points to null. Then why is it considered an anomaly to simply check if that value is null? Will the compiler consider an error anything that I do to my uninitialized variable other than assignments?
println(monthString); In order to use a local variable in java it must be initialized to something even if that something is setting it equal to null .
Uninitialized variables and fields are set to the zero value. For example, if you have a uninitialized variable of an integer type, its value will always default to 0. An uninitialized string will be the empty string. Likewise, the zero value for a pointer is nil .
Well, the JVM specification says that null is the default value for all references, so it's not specifically tied to the String. And actually, the specification doesn't mandate any concrete value encoding for null.
Local Variables If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error. Save this answer.
Fields of object type are initialized to null by default. Array members are also initialized to null by default.
Local variables are not - they must be initialized explicitly.
This is a good thing. Uninitialized variables are frequently an indication of error.
From "Initial Values of Variables" in chapter 4 of the Java Language Specification:
A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16).
The compiler requires that you initialize the Object to be null
if you're making any assumption as to its value. This is simply a (very useful) precaution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With