Java Reference
In-Depth Information
Testing a String to be Empty
Sometimes you need to test whether a String object is empty. The length of an empty string is zero. There are three
ways to check for an empty string:
isEmpty() method.
Use the
equals() method.
Use the
String and check if it is zero.
Get the length of the
The following snippet of code shows how to use the three methods:
String str1 = "Hello";
String str2 = "";
// Using the isEmpty() method
boolean empty1 = str1.isEmpty(); // Assigns false to empty1
boolean empty2 = str2.isEmpty(); // Assigns true to empty1
// Using the equals() method
boolean empty3 = "".equals(str1); // Assigns false to empty3
boolean empty4 = "".equals(str2); // Assigns true to empty4
// Comparing length of the string with 0
boolean empty5 = str1.length() == 0; // Assigns false to empty5
boolean empty6 = str2.length() == 0; // Assigns true to empty6
Which of the above methods is the best? The first method may seem more readable as the method name suggests
what is intended. However, the second method is preferred as it handles the comparison with null gracefully. The
first and third methods throw a NullPointerException if the string is null . The second method returns false when
the string is null , for example, "".equals(null) returns false .
Changing the Case
To convert the content of a string to lower and upper case, you can use the toLowerCase() and the toUpperCase()
methods, respectively. For example, "Hello".toUpperCase() will return the string "HELLO" , whereas
"Hello".toLowerCase() will return the string "hello" .
Recall that String objects are immutable. When you use the toLowerCase() or toUpperCase() method on a
String object, the content of the original object is not modified. Rather, Java creates a new String object with the
identical content as the original String object with the cases of the original characters changed. The following snippet
of code creates three String objects:
String str1 = new String("Hello"); // str1 contains "Hello"
String str2 = str1.toUpperCase(); // str2 contains "HELLO"
String str3 = str1.toLowerCase(); // str3 contains "hello"
 
Search WWH ::




Custom Search