Null indicates an uncertain object.
In Java, null is a keyword used to identify an uncertain object. Therefore, null can be assigned to a reference type variable, but null cannot be assigned to a basic type variable.
For example, int a = null; is incorrect. Ojbect o = null is correct.
In Java, the applicability of variables follows a principle that can be used only after being defined and initialized. We cannot print the value of a without specifying a value after int. This parameter is also applicable to reference type variables.
Sometimes, we define a reference type variable. At the beginning, a definite value cannot be provided, but no value is specified. The program may initialize the value in the try statement block. At this time, we will report an error when using the variables below. At this time, you can first specify a null value for the variable to solve the problem. For example:
Connection conn = null;
Try {
Conn = DriverManager. getConnection ("url", "user", "password ");
} Catch (SQLException e ){
E. printStackTrace ();
}
String catalog = conn. getCatalog ();
If you do not specify conn = null at the beginning, the last sentence will return an error.
II. null is neither an object nor an Objcet instance.
Although null itself can represent an uncertain Object, null itself is neither an Object nor an instance of java. lang. Object.
A simple example is provided:
// Is null an object? Is it of the Object type?
If (null instanceof java. lang. Object ){
System. out. println ("null belongs to the java. lang. Object type ");
} Else {
System. out. println ("null does not belong to the java. lang. Object type ");
}
Result: null is not of the java. lang. Object type.
Instance
Public class MainClass {
Public static void main (String [] args ){
String book = null;
If (book = null ){
Book = new String ();
}
}
}
Differences between null and ""
Null indicates that the new object has not been created, that is, the space has not yet been opened. "" indicates that the new object is not added, but the object is loaded with a null string.
Notes
If (temp = null | temp. equals ("") {...} pay attention to the order
Do not write if (temp. equals ("") | temp = null) {...} an error is thrown when temp is null.
Or write
If ("". equals (temp) | temp = null) {...} order can be changed