check if string is not empty and not null

Java program to check if string is not empty and not null

In this sneppet you will learn how to check if string is not empty and not null in Java. Note, a String with just whitespace is not considered as empty in Java. The following are the ways to test whether string is not empty and no null in Java.

Example 1: Check if String is Not Empty or Not Null

package com.sneppets.java;

public class TestNotNullOrEmpty {
	
	public static void main (String[] args)
	{
		String firstString = " ";
		String secondString = null;
		
		if(isNotNullorEmpty(firstString)) {
			System.out.println("firstString is not null or empty");
		}else {
			System.out.println("firstString is null or empty");
		}
		
		if(isNotNullorEmpty(secondString)) {
			System.out.println("secondString is not null or empty");
		}else {
			System.out.println("secondString is null or empty");
		}
	}
	
	public static boolean isNotNullorEmpty(String str) {
		if(str != null && !str.isEmpty())
	        return true;
	    return false;
	}

}

Output:

firstString is null or empty
secondString is null or empty

Example 2: Using length() instead of isEmpty()

Change the isNotNullorEmpty() method as shown below. In this example we are using length() method instead of isEmpty() method of String. And it is the fastest way to check if String is empty o not.

public static boolean isNotNullorEmpty(String str) {
  if(str != null && str.length()>0)
    return true;
  return false;
}

Example 3: Using trim() method

We know that String with just a whitespace is not considered as empty String. So isNotNullorEmpty() method will return not empty. So for string with spaces we use trim() method. This method returns a copy of the string, with leading and tailing whitespace omitted.

Introduce whitespace in the firstString as shown below in example 1 and 2 and try running the program, you could see the program would return not empty.

String firstString = " ";
String secondString = null;

Make the following change in the isNotNullorEmpty() method to trim out all leading and trailing whitespace characters in the firstString and try running the program.

public static boolean isNotNullorEmpty(String str) {
  if(str != null && str.trim().length()>0)
    return true;
  return false;
}

So, the above method using trim() returns firstString is empty now.

Further Reading

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments