ZMedia Purwodadi

Java String isEmpty() method explained | technical-arbaab

Table of Contents

Java String isEmpty() method 


It is a predefined function which is present in the Java.lang.String package. It is used to check whether is your string is empty or not. It returns boolean type true if the length of string is zero and false if the length of string is not zero. let us discuss this method in detail.

Syntax of isEmpty() method

 public boolean isEmpty() {}  

Example 01 of isEmpty() method

 public class IsEmpty {  
      public static void main(String[] args) {  
           String s = "Night";  
           System.out.println(s.isEmpty());  
           s="";  
           System.out.println(s.isEmpty());  
      }  
 }  

Output:

 false  
 true  

here, in the above example we have first declared a string which contains "night" so it prints false because it is not empty, it actually contains something which is "night" and then we explicitly empty this string by passing nothing to this string and hence it then prints true.

Example 02 of isEmpty() method

 public class IsEmpty {  
      public static void main(String[] args) {  
           String s="";  
           System.out.println(s.isEmpty());  
           System.out.println(s.length());  
      }  
 }  
Output:
 true  
 0  

In this example we have declared a empty string and check from isEmpty() function whether it is empty or not, obviously it will prints true, then we have checked the length of empty string from length() method and it has printed 0 because it contains nothing.

Imp.note: You can also try one more example in which you can take a string from user and it is now in the user's hand whether he enter a string and press enter or without entering a string he/she press enters, if without entering a string, enter is pressed show the output "you have entered a empty string" and if the string is entered and then enter is pressed then simply output the string.

 import java.util.Scanner;  
 public class IsEmpty {  
      public static void main(String[] args) {  
           Scanner sc = new Scanner(System.in);  
           System.out.println("enter a string");  
           String s = sc.nextLine();  
           if(s.isEmpty() || s.length()==0)  
           {  
                System.out.println("you have entered a empty string");  
           }  
           else  
           {  
                System.out.println(s);  
           }  
      }  
 }  

Output:

 enter a string  
 you have entered a empty string  

here, user press the enter button without entering a string that is why it is shown that "you have entered a empty string".

If you find this article helpful let us know in the comment section below and share it with your friends who wants to learn Java programming language .

Arbaab khan
Arbaab khan FEAR has two meanings "forget everything and run" "Face everything and rise" The choice is yours Welcome u in our tech blog

إرسال تعليق