What does the `new` keyword do

后端 未结 9 1912
情深已故
情深已故 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:12

    The following two code snippets are equals in compiling level. I write a Demo class like:

    public class NewArray {
        public static void main(String[] args) {
            long results[] = new long[3];
        }
    }
    

    and

    public class NewArray {
        public static void main(String[] args) {
            long results[] = {0,0,0};
        }
    }
    

    output of 'javap -c NewArray' is exactly the same:

    public static void main(java.lang.String[]);
      Code:
       0:   iconst_3
       1:   newarray long
       3:   astore_1
       4:   return
    
    }
    

    long results[] = new long[]{1,2,3}; and long results[] = {1,2,3}; are exactly the same too.

    So,although sometimes you are not using new key word,but the compile will regard them as equal.

提交回复
热议问题