Search This Blog

Wednesday, October 5, 2011

[TIP] Avoiding null pointer exception while comparing strings

Most of the time in our code we compare a String variable with a constant string. If the variable is null then the .equals method throws a null pointer exception if invoked on that variable. This can be avoided if we use equals in the following way.

**

* Created by IntelliJ IDEA.

* User: aditya

* Date: 10/6/11

* Time: 9:35 AM

* To change this template use File | Settings | File Templates.

*/

public class NullException {

public static void main(String[] args) {

String s = null;

if("arudra".equals(s)){

System.out.println("s is arudra");

}else {

System.out.println("s is not arudra");

}

if(s.equals("arudra")){

System.out.println("s is arudra");

}else {

System.out.println("s is not arudra");

}

}

}

output

s is not arudra

Exception in thread "main" java.lang.NullPointerException

at NullException.main(NullException.java:16)

So the first if condition executes properly without throwing any exception, the reason for that we are invoking equals method on the constant String literal "arudra". However in the second case we are invoking the .equals() method on the null string which results in null pointer excetption.

So whenever we want to compare a String variable with a constant string, it is always better to write constant string. equals (string variable).

SocialTwist Tell-a-Friend