Java String isEmpty()

This java tutorial shows how to use the isEmpty() method of java.lang.String class. This method returns boolean data type which signifies if the String length is 0 or not. This method generally checks if the string is empty (string length is 0).

The java string isEmpty() method checks if this string is empty or not. It returns true, if length of string is 0 otherwise false. In other words, true is returned if string is empty otherwise it returns false.

Internal implementation
public boolean isEmpty() { return value.length == 0; }
Syntax
public boolean isEmpty()
Returns

true if length is 0 otherwise false.

Compatibility Version:

Requires Java 1.6 and up

Example :

This example source code demonstrates the use of isEmpty() method of String class. We have also added on this java code that checks the length of the String.

public class Test { public static void main(String[] args) { String input = "This is example demo of isEmpty method"; if(input.isEmpty()){ System.out.println("String input is empty with length "+input.length()); } else{ System.out.println("String input is not empty with length "+input.length()); } System.out.println("".isEmpty()); } }


Output:
String input is not empty with length 38 true
Java String isEmpty() method example
public class Test { public static void main(String args[]) { String s1=""; String s2="cprogramcoding"; System.out.println(s1.isEmpty()); System.out.println(s2.isEmpty()); } }


Output:
true false
Java String isEmpty() method example
public class Test { public static void main(String[] args) { String s1=""; String s2="cprogramcoding"; // Either length is zero or isEmpty is true if(s1.length()==0 || s1.isEmpty()) System.out.println("String s1 is empty"); else System.out.println("s1"); if(s2.length()==0 || s2.isEmpty()) System.out.println("String s2 is empty"); else System.out.println(s2); } }


Output:
String s1 is empty cprogramcoding
Java String isEmpty() method Example
public class Test { public static void main(String args[]) { //empty string String str1=""; //non-empty string String str2="hello"; //prints true System.out.println(str1.isEmpty()); //prints false System.out.println(str2.isEmpty()); } }


Output:
true false
Java String isEmpty() method Example to check if string is null or empty

As we have seen in the above example that isEmpty() method only checks whether the String is empty or not. If you want to check whether the String is null or empty both then you can do it as shown in the following example.

public class Test { public static void main(String args[]) { String str1 = null; String str2 = "cprogramcoding"; if(str1 == null || str1.isEmpty()) { System.out.println("String str1 is empty or null"); } else{ System.out.println(str1); } if(str2 == null || str2.isEmpty()) { System.out.println("String str2 is empty or null"); } else{ System.out.println(str2); } } }


Output:
String str1 is empty or null cprogramcoding



Instagram