Friday, June 17, 2016

Things to remember about Null Pointer Exception

Our day to day coding life, we are facing Null pointer exception in most cases. We can see some good points about this. 

1. The instanceof operator

Code: 
String str = null;
if(str instanceof String)
   System.out.println("String is an instance here");
else
   System.out.println("String is not an instance here");

Output:
String is not an instance here

You can use instanceof operator , even if the object reference equals to null. It will not throw null pointer exception.


2. Null with contains , containsKey and containsValue methods

Code: 
 
String value = map.get(key);
System.out.println(value.toString());  

We know map, which is working based on key and value concept. From the above code, suppose if value is null, then it will throw null pointer exception here.

To avoid Null pointer for above code : 
if(map.containsKey(key)) {
    String value = map.get(key);
    System.out.println(value.toString()); // Now No exception
}


3. Apache StringUtils class
 
if (StringUtils.isNotEmpty(str)) {
     System.out.println(str.toString());
}

We can use StringUtils.IsEmpty and StringUtils.equals also.


4. String comparison with equals 

This is very useful, in most of our programs.

String str = null;
 if(str.equals("Test")) { // Exception will throw here
    }

  To avoid above Code Error

String str = null;
    if("Test".equals(str)) { //No Exception now
    }


5. Ternary operator

String message = (str == null) ? "" : str.length();

From the above, if str is null, then assign empty for that, else calculate length.


6. valueOf() is better than toString()

    String str = null;
    System.out.println(String.valueOf(str));  // it will prints null        
    System.out.println(str.toString()); // it will throw NullPointer Exception


7. Working with Static method or Static members

Below code will not throw any error.

class Test {     
         public static void testMessage() {
              System.out.println("Test Message");
         }
    }

    public class TestStatic {
         public static void main(String[] args) {
              Test t = null;
              t.testMessage();
         }
    }

However, as per rule, static method should be called through class name only. Calling static method by object reference is not advisable.

No comments:

Post a Comment