What does the `new` keyword do

后端 未结 9 1882
情深已故
情深已故 2020-12-01 09:41

I\'m following a Java tutorial online, trying to learn the language, and it\'s bouncing between two semantics for using arrays.

long results[] = new long[3]         


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 10:30

    In both cases you create an object.

    In first version:

    long results[] = new long[3];
    results[0] = 1;
    results[1] = 2;
    results[2] = 3;
    

    you say in first line that array size is 3. Then you put values into the array.

    In second version:

    long results[] = {1, 2, 3};
    

    You create the same array and initialize it in the same line. Java computes, that you gave 3 arguments and makes the new long[3] without Your help :)

提交回复
热议问题