Saved Bookmarks
| 1. |
How do you check whether a String is empty in Java? |
|
Answer» The Java String class contains a particular method for determining whether or not a string is empty. The isEmpty() method DETERMINES whether or not a string has zero length. In the case where the length of the string is zero, it returns true, or else it returns false. Example: PUBLIC class StringEmpty{ // Function to determine if String is empty public static boolean isStringEmpty(String str) { //Use the isEmpty() method //to determine if the string is empty. if (str.isEmpty()) return true; else return false; } public static void main(String args[]) { String STR1="InterviewBit"; //non-empty string String STR2=""; //empty string System.out.println("Str1 \"" + str1 + "\" is empty? " + isStringEmpty(str1)); System.out.println("Str2 \"" + str2 + "\" is empty? " + isStringEmpty(str2)); }}Str1 "InterviewBit" is empty? falseStr2 "" is empty? true |
|