Java String isEmpty() method explained | technical-arbaab
Java String isEmpty() method
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());
}
}
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".
إرسال تعليق