Here are some examples of checking for null values in Java along with detailed explanations:
- Using simple
if
statement:
String str = null;
if (str == null) {
System.out.println("String is null");
} else {
System.out.println("String is not null");
}
Explanation:
-
str
is initialized tonull
. - The
if
statement checks ifstr
is equal tonull
. - If
str
isnull
, 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:
-
str
is initialized tonull
. -
Objects.isNull()
method from thejava.util.Objects
class is used to check ifstr
is null. - If
str
isnull
, 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:
-
str
is initialized tonull
. - The ternary operator
?:
is used to check ifstr
isnull
. - If
str
isnull
, 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:
-
str
is initialized tonull
. -
Objects.requireNonNull()
method from thejava.util.Objects
class is used to check ifstr
is null. - If
str
isnull
, it throws aNullPointerException
, which is caught by thecatch
block, 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:
-
str
is initialized tonull
. -
StringUtils.isEmpty()
method from theorg.apache.commons.lang3.StringUtils
class is used to check ifstr
is null or empty. - If
str
isnull
or 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)