The reason I chose this theme was because when I was educating a new engineer, I was asked to explain null and couldn't say anything.
String A = null;
String B = "";
When I set null and "" (empty string) for the String type, I couldn't explain what was different, so I'll dig into that and deepen my understanding. (At that time, I answered that "null" has no value and "" is an empty string. Reflection.)
2.NullPointerException
When does the so-called "nullpo" occur? As an example, it looks like this.
public class Sample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length());
}
}
I get a NullPointerException when I try to execute a method with null. (Null cannot use any method), so if there is a possibility that a null value will be set, I think it is common to put a check process called "null check" as shown in the code below.
public class Sample {
public static void main(String[] args) {
String str = strMake();
if (str != null) {
System.out.println(str.length());
}
}
private static String strMake () {
return null; //Write something
}
}
The String class has various methods. As a defense record, I will post a link to the reference site.
[Official document] https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html
Recommended Posts