xxxxxxxxxx
public class Main {
public static void main(String[] args) {
// Example string
String str = null;
// Check if string is null
if (str == null) {
System.out.println("String is null");
} else {
System.out.println("String is not null");
}
}
}
xxxxxxxxxx
if(str != null && !str.isEmpty()) { /* do your stuffs here */ }
xxxxxxxxxx
if(str != null && !str.isEmpty())
Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.
xxxxxxxxxx
/* You can use Apache Commons */
StringUtils.isEmpty(str)
/* which checks for empty strings and handles null gracefully. */
/* HINT */
/* the shorter and simler your code, the easier it is to test it */
xxxxxxxxxx
if (myString == null || myString.equals(""))
throw new IllegalArgumentException("empty string");
xxxxxxxxxx
//If you initialize it properly it will be blank. Add some null checks, strings aren't usually null
//will print null
String nullString = null;
System.out.println(nullString);
//will print empty String
String emptyString = new String();
System.out.println(emptyString);