Java: String isEmpty() method

In this article, we will discuss how to check whether string is empty or NOT using String’s isEmpty() method

 

isEmpty() method:

  • This String method is used to check whether String is empty or NOT
  • Note: empty means string length with size ZERO (0) and not necessarily null

Method Signature:

public boolean isEmpty();

Returns:

  • Returns true, if and only if length() is 0

 

Examples on isEmpty() method:

  • Sample Java program to check whether String it empty or NOT

StringIsEmptyMethod.java

package in.bench.resources.string.methods;

public class StringIsEmptyMethod {

	public static void main(String[] args) {

		// test string-1
		String url = "BenchResources.Net";

		// invoke testEmpty() method with url
		testEmpty(url);

		// test string-2
		String emptyStr = "";

		// invoke testEmpty() method with emptyStr
		testEmpty(emptyStr);
	}

	public static void testEmpty(String str) {

		// checking using isEmpty() method
		if(str.isEmpty()) {
			System.out.println("The string '" + str 
					+ "' is Empty with length 0\n");
		}
		else {
			System.out.println("The string '" + str 
					+ "' is NOT Empty\n");
		}
	}
}

Output:

The string 'BenchResources.Net' is NOT Empty

The string '' is Empty with length 0

 

Advantages of using isEmpty() method:

  • Used to check string is empty before using for any string operations like concatenation, comparison, reverse, split, etc
  • Similarly, to check whether string reference contains any value or NOT

 

References:

 

Happy Coding !!
Happy Learning !!

Java: String join() method
Java: String intern() method