Convert null to other types in java

Casting to null will not throw an error. The test result is that if null is forced to the object, an exception will not be thrown, because the object itself can be null. But if it is a basic type, such as the forced conversion of int i = (Integer)obj, the intvalue method will be called internally to assign it to the basic type, so an error will be reported at this time.

code show as below 

1 Object obj = null;  
2 Integer s1 = (Integer)obj;  

The above can be executed normally, that is, there is no problem in assigning null to an object or assigning a forced type conversion to an object. What if s1 is the base type of int?

 

The code is as follows, no error will be reported when compiling

1 int s1 = (Integer)obj;  
2 System.out.println(s1);  

If executed, a java.lang.NullPointerException error is reported 

1  Object obj = null;  
2   int s1 = ((Integer)obj).intValue();  
3   System.out.println(s1);  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325158439&siteId=291194637