Friday, May 8, 2015

Avoid null with valueOf() method

In java the valueOf() and toString() would play the most role for displaying object output. However we should know, which is the best one to use?

We can avoid null, if we will use valueOf() method instead of toString() method.

See the below example for more understanding,

JavaHit javaObject = null;

// will not throw Null Poniter Exception
System.out.println(String.valueOf(javaObject));


// will throw Null Poniter Exception
System.out.println(javaObject.toString())