Difference Between null and isEmpty in Java

In Java, particularly when you are working with String class, you may have a situation where a String object either has a null or empty string. Java treats null and empty as two different values. They both are not equal.

In Java, if a reference variable has its value as null, it means that it is not referring to any object. A good example of that kind of reference variable is as below:

String str = null;

Here, str is a reference variable of type String, but that reference variable is not pointing to any object, so its value will be null.

As soon as we instantiate an object using new keyword, an object gets created. Every object in Java has a memory location. So if we create an object and assign it to a variable as below, the memory location of that object gets stored in the reference variable.

String str = new String("");

Now str reference variable contains the address of a String object which has its value as empty. We can also write this statement in a short form as follows:

String str = "";

Still, we are creating a new String object here, and its reference is getting stored into the reference variable. Here, the object value is empty, but it has an address and it is stored within str variable.

So, when String reference variable is null it is not pointing to any String object. But when an empty String object reference is stored within that reference variable, it is now pointing to that empty object and cannot be called as null.

See also  How to round to 2 decimal places in Java

To check if the reference variable is pointing to any object or not we use null to compare as below:

		if(str == null) {
			System.out.println("str is not pointing to any object");
		}

But if that reference variable str is pointing to an object and if we want to check if it is empty we can use isEmpty method of String class as below:

		if(str.isEmpty()) {
			System.out.println("String object is empty");
		}

String.isEmpty returns true if the string is empty and false if the string is not empty.

Here, you can see a full example, where we are checking a String variable if it is null or empty.

package com.techstackjournal;


public class NullorEmpty {

	public static void main(String[] args) {
		String str = "";
		
		if(str == null) {
			System.out.println("str is not pointing to any object");
		} else {
			System.out.println("str is pointing to an object");
		}
		
		if(str.isEmpty()) {
			System.out.println("String object is empty");
		} else {
			System.out.println("String object is not empty");
		}
		
	}

}

Output:

str is pointing to an object
String object is empty

Conclusion

To check if a reference variable is not pointing to an object we use null along with == operator. To check if a String object has value we use isEmpty method.