In many pieces of example code I see variables instatiated with null values and later assigned more meaningful values.
I was just wondering why people may do this. I'm guessing try-catch blocks may well come into this, but I also see variables instantiated will null values inside of a try block.
(I'm sure this is a fairly language agnostic question, but just for reference I program almost entirely in Java)
All insights appreciated!
You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value. In the above example, null is assigned to a variable myVar. It means we have defined a variable but have not assigned any value yet, so value is absence.
You can think of NULL as an unknown or empty value. A variable is NULL until you assign a value or an object to it. This can be important because there are some commands that require a value and generate errors if the value is NULL.
A NULL value is a special marker used in SQL to indicate that a data value does not exist in the database. In other words, it is just a placeholder to denote values that are missing or that we do not know. NULL can be confusing and cumbersome at first.
Explicitly assigning a null value to variables that are no longer needed helps the garbage collector to identify the parts of memory that can be safely reclaimed.
The Java compiler detects in certain cases if a variable has not been initialized in all possible control flows and prints an error. To avoid these error messages, it's necessary to explicitly initialize the variable.
For example in this case:
public Integer foo() {
Integer result;
if (Math.random() < 0.5) {
result = 1;
}
return result;
}
The compiler would give this error message: "The local variable result may not have been initialized".
Here is what the Java Language Specification says:
Each local variable (§14.4) and every blank final (§4.5.4) field (§8.3.1.2) must have a definitely assigned value when any access of its value occurs. A Java compiler must carry out a specific conservative flow analysis to make sure that, for every access of a local variable or blank final field f, f is definitely assigned before the access; otherwise a compile-time error must occur.
Note that (in contrast to fields!) local variables are not automatically initialized to null
.
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