This needs to be seen. Where User user; appears, let’s put the conclusion first:
If it is an attribute (field) of an object, there is no difference between the two writing methods.
If it is a local variable in a method, if there is no other place in the method to assign a value to user, a compilation error will occur.
If it is an attribute of an object, then during compilation, the Java compiler will automatically assign an initial value to the field (the original type is the default value; the reference type is null). For example, the following code:
public class TestInitialization {
private User userA;
}
After compilation, use javap to view the bytecode. The red part is the process of the compiler automatically assigning initial values:
If it is a local variable in a method, the compiler will not automatically assign an initial value. User user;只是定义的变量user,但并未给user在内存中分配空间,没有初始化,无法通过编译;User user = null;It is just the defined variable user, but no space is allocated to user in the memory. It is not initialized and cannot pass compilation; User user = null; not only defines the variable user, but also allocates memory for user Space, user now points to null.
This needs to be seen. Where
User user;
appears, let’s put the conclusion first:If it is an attribute (field) of an object, there is no difference between the two writing methods.
If it is a local variable in a method, if there is no other place in the method to assign a value to user, a compilation error will occur.
If it is an attribute of an object, then during compilation, the Java compiler will automatically assign an initial value to the field (the original type is the default value; the reference type is null). For example, the following code:
After compilation, use javap to view the bytecode. The red part is the process of the compiler automatically assigning initial values:
If it is a local variable in a method, the compiler will not automatically assign an initial value.
User user;
只是定义的变量user,但并未给user在内存中分配空间,没有初始化,无法通过编译;User user = null;
It is just the defined variable user, but no space is allocated to user in the memory. It is not initialized and cannot pass compilation;User user = null;
not only defines the variable user, but also allocates memory for user Space, user now points to null.If user is a local variable: using user before the first assignment (including initialization to null) is a compilation error
There is no difference after assignment
It seems to be the same
No difference, the default initialization value is null
No = There is no space for him in the stack. Adding =null specifies an empty placeholder in the stack