There are a couple of basic ideas that would be handy to have in mind here. These are:
Pointer Dereferencing
Short Circuit Evaluation
Pointer Dereferencing.
In Java, types that are not primitive are called reference types. The variables for these types do not contain the value for the type, instead they contain a pointer to memory. For example:
String str;
String is a reference type. Once initialized, the variable str
will hold a reference or pointer to the memory location of the assigned String instance. Until initialized, variables for reference types have the value null
.
Before any member of a class instance (eg. methods or fields) can be accessed and used, the pointer for a reference type must be accessed to get the location of the member in memory. This is called dereferencing. If a reference type variable contains the null
value, then it is not possible to access any members. This is why an expression like this one is perilous:
`if (myString.equals("")) ...`
If the variable myString
contains null
or is not initialized, it cannot be dereferenced to a heap location. In this case an exception is raised and your program fails.
If you cannot guarantee that a String
variable won't contain null
then you should not use statements like the one above because it may raise a NullPointerException
in your code.
Short Circuit Evaluation.
Short circuit evaluation is where the evaluation of a multi-part expression is terminated before all of the parts have been evaluated -because- finishing the complete evaluation would not change the value of the expression. This most commonly applies to boolean expressions.
Consider an expression like this:
if (myString.trim().isEmpty()) { ... }
As discussed above, this expression leaves the program vulnerable to NullPointerExpressions
whenever myString contains null
and cannot be dereferenced. However this expression is safe:
if (myString == null || myString.trim().isEmpty) { ... }
In the above case, a NullPointerException
can never be thrown by this expression, even if myString contains null
. If myString is equal to null
, the first part of the expression is true
. In a boolean OR expression, true OR xx
, the result of the expression is always true no matter what xx
is. The Java environment therefore only executes the 1st part and not the second part. This is a good thing, because a NullPointerException would result if it had been.
Short circuit evaluation is commonly used in Java if-then
expressions to test for null conditions that would raise exceptions in subsequent parts of a logical expression.