Checking if a string is empty or null in Java
To check if a string is empty or null in Java, you can use the isEmpty() method of the java.lang.String class, which returns true if the string is empty, and false if it is not. Here is an example of how you can use isEmpty() to check if a string is empty
To check if a string is empty or null in Java, you can use the isEmpty() method of the java.lang.String class, which returns true if the string is empty, and false if it is not. Here is an example of how you can use isEmpty() to check if a string is empty:
import java.util.Scanner;
public class StringEmptyExample {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = in.nextLine();
if (input.isEmpty()) {
System.out.println("The string is empty");
} else {
System.out.println("The string is not empty");
}
}
}To check if a string is null, you can use the == operator to compare the string to null. This is the standard and safest approach for null reference checks in Java. Here is an example:
public class StringNullExample {
public static void main(String[] args) {
String input = null;
if (input == null) {
System.out.println("The string is null");
} else {
System.out.println("The string is not null");
}
}
}Alternatively, you can use java.util.Objects.isNull() for a more explicit null check:
import java.util.Objects;
public class StringNullExample {
public static void main(String[] args) {
String input = null;
if (Objects.isNull(input)) {
System.out.println("The string is null");
} else {
System.out.println("The string is not null");
}
}
}Note that String.equals(null) always returns false and will never detect a null reference, so it should not be used for null checks. For production-ready code, consider using Objects.requireNonNull() to enforce non-null constraints, or leverage utility classes like Apache Commons StringUtils.isEmpty() which safely handles both null and empty strings in a single call.