java new对象 User user; 和 User user = null; 有什么区别
PHP中文网
PHP中文网 2017-04-18 10:32:27
0
5
707

User user;

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

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(5)
洪涛

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
阿神

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

PHPzhong

It seems to be the same

Ty80

No difference, the default initialization value is null

PHPzhong

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!