Java - Null String

One problem that Java programmers often face is the string. If you use String.compareTo(), and one of the string is a null, you would get a NullPointerException. If you do Integer.parseInt(str), you would get a required: java.lang.String error. Obviously, you would want to check for a null string and/or avoid it.

Why do we get a NullPointerException?
Java Strings are objects, not primitives such as char or int. The java.lang.String class was created to make string manipulation easier.

char s[] = {'m', 'a', 'n'};

Without the String class we would have to use arrays of char as above. String class not only makes this task simpler but also comes with many handy methods for string manipulation.

String s1 = "man";

s1 is a pointer to the object String which contains the characters m, a, and n in this sequence. By default, Strings and initialized to null. A null is a pointer to nowhere. When we compare two strings, s1 and s2, we compare the objects they are pointing to. If s2 is null, then we are comparing the object s1 is pointing to with a pointer which points to nowhere. This generates a NullPointerException at runtime.

Checking for a null String
The easiest way to check for a null string it to compare it to null.

String str = null;

if (str == null) {
  System.out.println("Null String Found");
}

Avoiding Null String
String.compareTo() is a commonly used method for comparing strings. It would throw a NullPointerException when it encounter a null pointer. The String.equals() method return false when you compare a string with a null string.

String s1;
String s2;

System.out.println(s1.compareTo(s2));	// NullPointerException
System.out.println(s1.equals(s2));		// false

Therefore, using String.equals() prevents a NullPointerException.

nullCheck
Following is a useful method for checking for null strings

public boolean nullCheck(str) {
  return str.equals(null);
}

String str = null;

if (!nullCheck(str)) {
  // use the string 
} else {
  // the string is null
}

This article has been updated based on user comments.

The nullcheck method seems

The nullcheck method seems to be wrong.

the code is working

the code is working. here is the full example.

public class NullString {
public boolean nullCheck(String str) {
return str.equals(null);
}
}

public class testNullString {
public static void main(String[] args) {
NullString ns = new NullString();
String str = "test";
if (!ns.nullCheck(str)) {
System.out.println("String is not null");
} else {
System.out.println("Found a null string");
}
}
}