Here are some examples of checking for null values in Java along with detailed explanations:
- Using simple
ifstatement:
String str = null;
if (str == null) {
System.out.println("String is null");
} else {
System.out.println("String is not null");
}
Explanation:
-
stris initialized tonull. - The
ifstatement checks ifstris equal tonull. - If
strisnull, it prints "String is null"; otherwise, it prints "String is not null".
Output:
String is null
- Using
Objects.isNull()method:
import java.util.Objects;
String str = null;
if (Objects.isNull(str)) {
System.out.println("String is null");
} else {
System.out.println("String is not null");
}
Explanation:
-
stris initialized tonull. -
Objects.isNull()method from thejava.util.Objectsclass is used to check ifstris null. - If
strisnull, it prints "String is null"; otherwise, it prints "String is not null".
Output:
String is null
- Using ternary operator:
String str = null;
String result = (str == null) ? "String is null" : "String is not null";
System.out.println(result);
Explanation:
-
stris initialized tonull. - The ternary operator
?:is used to check ifstrisnull. - If
strisnull, it assigns "String is null" to theresult; otherwise, it assigns "String is not null".
Output:
String is null
- Using
Objects.requireNonNull()method:
import java.util.Objects;
String str = null;
try {
Objects.requireNonNull(str);
System.out.println("String is not null");
} catch (NullPointerException e) {
System.out.println("String is null");
}
Explanation:
-
stris initialized tonull. -
Objects.requireNonNull()method from thejava.util.Objectsclass is used to check ifstris null. - If
strisnull, it throws aNullPointerException, which is caught by thecatchblock, printing "String is null"; otherwise, it prints "String is not null".
Output:
String is null
- Using
StringUtils.isEmpty()method from Apache Commons Lang library:
import org.apache.commons.lang3.StringUtils;
String str = null;
if (StringUtils.isEmpty(str)) {
System.out.println("String is null or empty");
} else {
System.out.println("String is not null or empty");
}
Explanation:
-
stris initialized tonull. -
StringUtils.isEmpty()method from theorg.apache.commons.lang3.StringUtilsclass is used to check ifstris null or empty. - If
strisnullor empty, it prints "String is null or empty"; otherwise, it prints "String is not null or empty".
Output:
String is null or empty
These are different ways to check for null values in Java, each providing different functionalities and suited for different scenarios.
Top comments (0)