Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Check if a String is whitespace, empty ("") or null in Java
Let’s say the following is our string.
String myStr = "";
Now, we will check whether the above string is whitespace, empty ("") or null.
if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
System.out.println("String is not null or not empty or not whitespace");
} else {
System.out.println("String is null or empty or whitespace");
}
The following is an example that checks for an empty string.
Example
public class Demo {
public static void main(String[] args) {
String myStr = "";
if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
System.out.println("String is not null or not empty or not whitespace");
} else {
System.out.println("String is null or empty or whitespace");
}
}
}
Output
String is null or empty or whitespace
Let us see another example that checks for whitespace input.
Example
public class Demo {
public static void main(String[] args) {
String myStr = " ";
if(myStr != null && !myStr.isEmpty() && !myStr.trim().isEmpty()) {
System.out.println("String is not null or not empty or not whitespace");
} else {
System.out.println("String is null or empty or whitespace");
}
}
}
Output
String is null or empty or whitespace
Advertisements
