(0 Votes)
Exception or error name: NullPointerException
Type: Unchecked Exception
Overview:
A common menace in the Java world! Debugging this exception can be either as easy as putting a null check or can cause you to miss your meal!
Sample Trace:
Exception in thread "main" java.lang.NullPointerException
at TestClass.main(TestClass.java:7)
Root cause:
When a dot operation is performed on a null reference object.
Eg: For strings, checking the length like strTest.length() and strTest is null.
Possible resolution:
For objects which are dynamically assigned a value, perform a null check as below:
if(strTest!=null) {
System.out.println(strTest.length());
}For String objects, when performing null or empty string check, the order of check and using short circuit ‘and’ operator is very important. The below null or empty string check is prone to NullPointer:
if(!strTest.equals("") && strTest!=null) {
System.out.println(strTest.length());
}
The above code causes empty string equals check (using dot operator) to be performed prior to null check, leading to boom!! When the string is null.
if(strTest!=null & !strTest.equals("")) {
System.out.println(strTest.length());
}Since the above code does not use short circuit ‘add’ (&&), irrespective of the strTest!=null returning true or false, !strTest.equals(“”), will get executed. Hence, return of the boss
The correct way to perform a null or empty string check is:
if(strTest!=null && !strTest.equals("")) {
System.out.println(strTest.length());
}When strTest is null, strTest!=null returns false. Short circuit 'And' understand that, since the first condition is false, irrespective of the value of the second operation, the total expression will return false. So, it never bothers to evaluate the second expression, which is, !strTest.equals(""). Thus NullPointerException is prevented.
(0 Votes)




