What is the difference between creating an array object and assigning arrays with curly braces?

In Java, I found some tutorials online, and they teach differently when it comes to arrays,

Example 1:

Create an array object using the "new" keyword, and then assign values ​​to it.

int[] values;
values = new int[5];

values [0] = 10;
values [1] = 20;
values [2] = 30;
values [3] = 40;
values [4] = 50;

System.out.println (values[2]); //Output : 30

Example 2:

Use curly braces to assign values ​​to an array.

int[] values = {34,45,62,72}

System.out.println (values [2]); //Output : 62

What is the difference between the two examples?

+4
source share
5 answers

The difference is only in the source code side.

- . : -. , .

, , .

, .

, , : "" . , - (, ).

: , .class, javap -c:

1:

   0: iconst_5      
   1: newarray       int
   3: astore_1      
   4: aload_1       
   5: iconst_0      
   6: bipush        10
   7: iastore       

2:

   0: iconst_4      
   1: newarray       int
   3: dup           
   4: iconst_0      
   5: bipush        34
   7: iastore       

: ( , )

+3
  • , , , ( )
  • , ( , )
0

1 JVM 5 , 0. 2 JVM 4 , 0 , .

0

, , . , , .

0

.

1

int[] values; //array declaration
values = new int[5]; //array initialization, here memory will be allocated to values array.
values [0] = 10; //assignment of values
values [1] = 20;
values [2] = 30;
values [3] = 40;
values [4] = 50;

2 .

int[] values = {34,45,62,72}

, . , .

0

Source: https://habr.com/ru/post/1676594/


All Articles