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:
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
. Here is an example of how you can do this:
import java.util.Scanner;
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");
}
}
}
You can also use the equals()
method to compare the string to null
, like this:
import java.util.Scanner;
public class StringNullExample {
public static void main(String[] args) {
String input = null;
if (input.equals(null)) {
System.out.println("The string is null");
} else {
System.out.println("The string is not null");
}
}
}
Note that if you use the equals()
method to compare a string to null
, you should check if the string is null
first, to avoid a NullPointerException
. Here is an example of how you can do this:
import java.util.Scanner;
public class StringNullExample {
public static void main(String[] args) {
String input = null;
if (input == null || input.equals(null)) {
System.out.println("The string is null");
} else {
System.out.println("The string is not null");
}
}
}