Null pointer chapter
Causes of a null pointer
1. Call an instance method on an empty object
test t=null;
t.method();
2. Invoke properties of empty objects
test t=null;
System.out.println(t.name);
3. Call the array length when the array is an empty object
private String[] address;
User user=new User();
System.out.println(user.address.length)
4. NULL is used as the value for Throwable
5. The return value of the method is NULL, which is used directly by the caller
A way to avoid null Pointers
2. Try to return NULL in the function, or give me a detailed comment 3. When passing an external value, be sure to do so in a timely manner unless explicitly stated (not NULL)
Null pointer caused by automatic unboxing
1. Null pointer appears in automatic unboxing of variable assignment
Long test=null;
long test_=test;
2. Null pointer is caused by automatic unboxing when passing parameter
public void test(int x,int y){
return x+y;
};
Integer x=null;
Integer y=null;
System.out.println(add(x,y));
3. Scenarios for size comparison
Long x=10L;
Long y=null;
System.out.println(compare(x,y));
Avoid null Pointers caused by automatic unboxing
2. For uncertain wrapper types, be sure to check for NULL 3. For a wrapper type that is NULL, the value is assigned to 0
What happens when an empty exception occurs in a string, array, or collection
1. String comparison
public static boolean StringEquals(String x,String y){ return x.equals(u); } System.out.println(StringEquals("xyz",null)); // false System.out.println(StringEquals(null,"xyz")); // Error null pointer because equals is called with null object
2. The array of objects is nulled even though it is not initialized
public static class User{
private String name;
}
User[] user=new User[10];
for(int i=0;i!=10;++i){
user[i]=new User(); //进行初始化
user[i].name="test"+i;
}
Add NULL to List is not an error, but addAll cannot add NULL otherwise it will cause a null pointer exception
AddAll source code is an array call toArray