C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The isEmpty method returns true. So the inner statements of the if-block are reached.
Java program that uses isEmpty
public class Program {
public static void main(String[] args) {
String value = "";
// See if string is empty.
if (value.isEmpty()) {
// Display string length.
System.out.println("String is empty, length = " +
value.length());
}
}
}
Output
String is empty, length = 0
And: Two empty strings can be separate in memory. This means they would have difference identities.
However: String equals() compares the inner characters of a string. This can correctly tell us if the string is empty.
EqualsJava program that uses equals, tests empty strings
public class Program {
public static void main(String[] args) {
String value = "";
// Two equal string literals can be tested for identity.
if (value == "") {
System.out.println("Test 1");
}
// A new empty string will not have the same identity.
// ... This test will not succeed.
String empty = new String("");
if (value == empty) {
System.out.println("Test 2"); // Not reached.
}
// The equals method tests for character equivalence.
// ... This test will succeed.
if (value.equals(empty)) {
System.out.println("Test 3");
}
}
}
Output
Test 1
Test 3
Java program that causes NullPointerException
public class Program {
public static void main(String[] args) {
String value = null;
// This program will not work.
if (value.isEmpty()) {
System.out.println(0);
}
}
}
Output
Exception in thread "main" java.lang.NullPointerException
at Program.main(Program.java:6)