In this tutorial, we will write a java program to check whether the string is empty or not.
The strings are defined in the program and it is passed to the method as an argument. After checking for null and empty (built-in empty() function is used), a true or false value is returned accordingly. And finally displays the result.
The condition checking in this program is performed with the help of if..else statement:
Check if the String is empty or not in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | //check if the string is empty or not in java public class CheckForEmpty { public static void main(String[] args) { String string1 = "Simple2Code"; String string2 = ""; if(checkEmpty(string1 )) System.out.println("string1 is empty."); else System.out.println("string1 is not empty."); if(checkEmpty(string2 )) System.out.println("string2 is empty."); else System.out.println("string2 is not empty."); } public static boolean checkEmpty(String str) { if(str != null && !str.isEmpty()) { return false; } else { return true; } } } |
Output:
string1 is not empty.
string2 is empty.