BASIC JAVA: Getting NullPointerExceptions when comparing string values
 Education
 
Abstract
In our coding efforts, we need to make sure we consider the possibility of getting a string output that contains a null value.

If you compare the null value to a string value in Java™, you will get a NullPointerException.
 
 
Content
To avoid NullPointerExceptions and the efforts to catch and handle NullPointerExceptions; before assigning the String object, verify the source object is not null.


There are two programs examples shown below.
a) The first example compares the value LUNCH TIME! to a string to see if the string equals that value. In this example, the string is set to NULL and the program just compares the value LUNCH TIME! to the string to see if the string's value is LUNCH TIME! which it is not. In this case, an error is not thrown.


package trials;

public class NPE_String_COMP {

public static void main(String[] args)
{
String a = "LUNCH TIME!";
if (a.equals("lunch time!"))
{
System.out.println("First Test " + a);
}
if (a.equals("LUNCH TIME!"))
{
System.out.println("Second Test " + a);
}
a = null;

if("LUNCH TIME!".equals(a))
{
System.out.println("Third Test " + a);
}

}
}

OUTPUT:
Second Test LUNCH TIME!

b) In the second example, we added a fourth test, which actually compares a NULL value to the string LUNCH TIME!. In this case, the comparison is not done and a NullPointerException is thrown.

package trials;

public class NPE_String_COMP {

public static void main(String[] args)
{
String a = "LUNCH TIME!";
if (a.equals("lunch time!"))
{
System.out.println("First Test " + a);
}
if (a.equals("LUNCH TIME!"))
{
System.out.println("Second Test " + a);
}
a = null;

if("LUNCH TIME!".equals(a))
{
System.out.println("Third Test " + a);
}
if (a.equals("LUNCH TIME!"))
{
System.out.println("Fourth Test " + a);
}

}
}

OUTPUT:
Second Test LUNCH TIME!
java.lang.NullPointerException
at trials.NPE_String_COMP.main(NPE_String_COMP.java:23)
Exception in thread "main"

FURTHER Learning:
1) Case matters, as shown in the comparisons above.
2) The NullPointerException was thrown before the program actually progressed to the line in the code that cased the NullPointerException.

Note! The code above was developed and tested in WebSphere Application Developer version 5.1

 
 
Cross Reference information
Segment Product Component Platform Version Edition
Application Servers Runtimes for Java Technology Java SDK
 
 


Document Information


Product categories: Software > Application Servers > Distributed Application & Web Servers > WebSphere Application Server > Java 2 Connectivity (J2C)
Operating system(s): Windows
Software version: 6.1.1
Software edition:
Reference #: 7006283
IBM Group: Software Group
Modified date: Jul 1, 2005