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
// Java program to demonstrate working of // isEmpty() method class Gfg { public static void main(String args[]) { // non-empty string String str1 = "Hello_Gfg" ; // empty string String str2 = "" ; // prints false System.out.println(str1.isEmpty()); // prints true System.out.println(str2.isEmpty()); } } |
false true
Example 2:
A Java Program to show that an empty string is different from a blank String.
Java
// Java Program to demonstrate // String isEmpty() method 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()); } } |
false false true
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
// Java Program to check if
// Empty String and Null String
// are equal
import
java.io.*;
// Driver Class
class
GFG {
// main function
public
static
void
main(String[] args)
{
String s1 =
""
;
String s2 =
null
;
// Chacking if Empty String is same as
// Null String
if
(s1 == s2) {
System.out.println(
"Equal"
);
}
else
{
System.out.println(
"Not Equal"
);
}
}
}
OutputNot 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
// Java Program to demonstrate
// Blank String
import
java.io.*;
// Driver Class
class
GFG {
// main function
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