简体   繁体   中英

What is the difference between just declaring array of object and actually creating instance of it?

Why does first statement output "nothing1" and the second statement doesn't? If I am not wrong, then newly created array of object in statement second has default reference null.

class Solution
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Animal temp1[]=null;//statement first;
        if(temp1==null)
           System.out.println("nothing1");
        Animal temp2[]=new Animal[5];//statement second;
        if(temp2==null)
           System.out.println("nothing2");
    }
}
class Animal
{
    int name;
    int action;
    public Animal(int name, int action) {
        this.name = name;
        this.action = action;
    }
}

The first statement

Animal temp1[]=null;

declares an array variable and initializes it to null. Therefore "nothing1" is printed.

The second statement

Animal temp2[]=new Animal[5];

declares an array variable and initializes it to an array of length 5. The elements of this array (such as temp2[0] ) are initially all null , but the array reference itself ( temp2 ) is not null. Therefore "nothing2" is not printed.

在第一种情况下,数组尚未分配任何内存,但在以后的情况下,您已初始化了数组,因此需要一些内存块进行初始化,因此它的引用现在将指向一个内存位置,并且不会为null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM