Java.lang.String.isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of the String class is included in Java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0.
Syntax of Java String isEmpty()
public boolean isEmpty();
Return Value
- It returns true if the string length is 0.
- Returns false otherwise.
Example
Input String1 : Hello_Gfg
Input String2 :
Output for String1 : false
Output for String2 : true
Examples of String isEmpty() method
Example 1:
Java program to illustrate the working of isempty().
Java
class Gfg {
public static void main(String args[])
{
String str1 = "Hello_Gfg" ;
String str2 = "" ;
System.out.println(str1.isEmpty());
System.out.println(str2.isEmpty());
}
}
|
Example 2:
A Java Program to show that an empty string is different from a blank String.
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s1 = " " ;
String s2 = " Geek " ;
String s3 = "" ;
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
System.out.println(s3.isEmpty());
}
}
|
FAQ on Java String isEmpty()
Q1. Are Empty String and Null Strings the same?
Ans:
No, Empty Strings and Null Strings are not the same. Empty String supports isEmpty() whereas Null strings do not support isEmpty() method in Java.
Example:
String s1="";
String s2=null;
Program to demonstrate the difference between them:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s1 = "" ;
String s2 = null ;
if (s1 == s2) {
System.out.println( "Equal" );
}
else {
System.out.println( "Not Equal" );
}
}
}
|
Q2. What is Blank String?
Ans:
Blank Strings are strings that contain only white spaces. isEmpty() method in itself is not sufficient but if used with trim() method can tell if the string is empty or not.
Example:
Java
import java.io.*;
class GFG {
public static void main(String[] args)
{
String s1 = " " ;
if (s1.isEmpty())
System.out.println( "It is Empty" );
else
System.out.println( "Not Empty" );
if (s1.trim().isEmpty())
System.out.println( "Using trim(): It is Empty" );
else
System.out.println( "Not Empty" );
}
}
|
OutputNot Empty
Using trim(): It is Empty