Java String isEmpty

Java string isEmpty

Well, read the method. It says is empty. It is asking that – hey, is the given string empty? But first, let’s understand what we mean by an empty string. Well, this is simple. An empty string means an empty string, which means the string which is empty! Or we can say that the string does not even contain space. Or in even other words, we can say that the string has a length of zero.

We have seen somewhere earlier how can we create an empty string. Well, still if you are confused about how to create an empty string, we are going to do a program for the same thing.

Have a look at the program –

public class StringMethods {
public static void main(String[] args) {
String str1 = “”;
// String str1 = new String(); → this is another way to create an empty string.
System.out.println(str1.isEmpty());
}
}

So, here we can see that the string is empty. The method is also asking that is the string empty? It just returns true or false. In this case, we are getting true as an output, since the string is empty.

Have a look at another program, in which, the string is not empty this time –

public class StringMethods {
public static void main(String[] args) {
String str1 = “Not an empty string”;
// String str1 = new String(); → this is another way to create an empty string.
System.out.println(str1.isEmpty());
}
}

This time, the output is going to be clearly false, since the string is not empty. You can see that another way of creating the empty string is mentioned in both programs. You can use either of the ways to create an empty string.