Monday 30 June 2014

java.lang.NullPointerException

If you set a string to null then try to compare it with another value, you will get a java.lang.NullPointerException if you do it like this:

Solaris > cat prog39.java
public class prog39
{
public static void main (String args[])
  {
  String fred = null;
  if (fred.equals("OK"))
    System.out.println("Fred is OK");
  else
    System.out.println("Fred is not OK");
  }
}
Solaris > javac prog39.java
Solaris > java prog39
Exception in thread "main" java.lang.NullPointerException
        at prog39.main(prog39.java:6)
Solaris >
 
If you just make the string empty, the code will work, as you can see below:
 
Solaris > cat prog40.java
public class prog40
{
public static void main (String args[])
  {
  String fred1 = "";
  System.out.println
  ("Length of Fred1 is " + fred1.length());
  if (fred1.equals("OK"))
    System.out.println("Fred1 is OK");
  else
    System.out.println("Fred1 is not OK");
  
  String fred2 = new String();
  System.out.println
  ("Length of Fred2 is " + fred2.length());
  if (fred2.equals("OK"))
    System.out.println("Fred2 is OK");
  else
    System.out.println("Fred2 is not OK");
  }
}
Solaris > javac prog40.java
Solaris > java prog40
Length of Fred1 is 0
Fred1 is not OK
Length of Fred2 is 0
Fred2 is not OK
Solaris >

... and if the string contains a value, it works too: 

Solaris > cat prog41.java
public class prog41
{
public static void main (String args[])
  {
  String fred = "OK";
  if (fred.equals("OK"))
    System.out.println("Fred is OK");
  else
    System.out.println("Fred is not OK");
  }
}
Solaris > javac prog41.java
Solaris > java prog41
Fred is OK
Solaris >

... but if you really need to cater for a null string, you could try the following:

Solaris > cat prog42.java
public class prog42
{
public static void main (String args[])
  {
  String fred1 = null;
  if (fred1 != null && fred1.equals("OK"))
    System.out.println("Fred1 is OK");
  else
    System.out.println("Fred1 is not OK");
 
  String fred2 = "OK";
  if (fred2 != null && fred2.equals("OK"))
    System.out.println("Fred2 is OK");
  else
    System.out.println("Fred2 is not OK");
 
  String fred3 = null;
  if ("OK".equals(fred3))
    System.out.println("Fred3 is OK");
  else
    System.out.println("Fred3 is not OK");
 
  String fred4 = "OK";
  if ("OK".equals(fred4))
    System.out.println("Fred4 is OK");
  else
    System.out.println("Fred4 is not OK");
  }
}
Solaris > javac prog42.java
Solaris > java prog42
Fred1 is not OK
Fred2 is OK
Fred3 is not OK
Fred4 is OK
Solaris >