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
|