Java String isEmpty() method

isEmpty() method of the String class will tell you whether the String is empty or not. In this post, we will be learning about the isEmpty() method in detail.

  • Method declaration – public boolean isEmpty().
  • What does it do? – It will tell whether the string is empty or not by checking the length of the String.
  • What does it return? – It will return true if the string is empty; otherwise false.

Internal implemenation of isEmpty() method

    public boolean isEmpty() {
        return value.length == 0;
    }

So, it internally uses the checks the length of the String to see if the String is empty or not.

Code Example
public class Codekru {

	public static void main(String[] args) {

		String str1 = "hello codekru";
		String str2 = "";

		System.out.println("is str1 empty? " + str1.isEmpty());
		System.out.println("is str2 empty? " + str2.isEmpty());

	}
}

Output –

is str1 empty? false
is str2 empty? true

Yeah, we know. It’s super easy to use. 🙂

The What If scenarios

What if there are only spaces present in the String? How would the isEmpty() method behave?

Space is also considered a character and has a Unicode code point value attached to it, and that is 32. So, the isEmpty() method will return false.

public class Codekru {

	public static void main(String[] args) {

		String str1 = "  ";

		System.out.println("is str1 empty?: " + str1.isEmpty());

	}
}

Output –

is str1 empty?: false

So, always keeps this in mind while using the isEmpty() method.

What will happen if we use isEmpty() on a null string?

If you use the isEmpty() method on a null String, it will throw a NullPointerException.

public class Codekru {

	public static void main(String[] args) {

		String str1 = null;

		System.out.println("is str1 empty?: " + str1.isEmpty());

	}
}

Output –

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.isEmpty()" because "str1" is null

If you want to read more about the String and its methods, we suggest you read this article.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at admin@codekru.com.

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *