Home  >  Q&A  >  body text

java new对象 User user; 和 User user = null; 有什么区别

User user;

User user = null;
这两种写法有什么区别呢?

PHP中文网PHP中文网2741 days ago714

reply all(5)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:34:27

    This needs to be seen. Where User user; appears, let’s put the conclusion first:

    1. If it is an attribute (field) of an object, there is no difference between the two writing methods.

    2. 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.

    那么问题来了`null`又是个什么鬼?
    http://stackoverflow.com/questions/2707322/what-is-null-in-java
    

    reply
    0
  • 阿神

    阿神2017-04-18 10:34:27

    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

    reply
    0
  • PHPz

    PHPz2017-04-18 10:34:27

    It seems to be the same

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:34:27

    No difference, the default initialization value is null

    reply
    0
  • PHPz

    PHPz2017-04-18 10:34:27

    No = There is no space for him in the stack. Adding =null specifies an empty placeholder in the stack

    reply
    0
  • Cancelreply