java - What is the difference between using and not using `New` keyword to define an array? -


this question has answer here:

look @ 2 simple program :

program 1:

public class genarray extends applet {     byte[] myarray  ={ (byte) 'm', (byte) 'o', (byte) 'd', (byte) 'e',             (byte) '1' }; } 

program 2:

public class genarray extends applet {     byte[] myarray = new byte[5];     {         myarray[0]  =(byte) 'm';         myarray[1]  =(byte) 'o';         myarray[2]  =(byte) 'd';         myarray[3]  =(byte) 'e';         myarray[4]  =(byte) '1';     } } 

i want know if there difference between myarray in last line of program-1 , myarray in last line of program-2? (any difference!)

in second program, { ... } not array delimiters, block delimetes; in case used give so-called initializer block, executed when new instance of class instantiated.

the "correct" way create initialized array is:

new byte[] { 1, 2, 3 }; 

this can used always, both when reference initialized , when existing reference used or when array passed method:

byte[] myarray = new byte[] { 1, 2, 3 };    // ok myarray = new byte[] { 4, 5, 6 };           // ok anobject.somemethod(new byte[] { 7, 8, 9}); // ok 

however, first variant common , therefore java allows leave new byte[] part out in particular case:

byte[] myarray = { 1, 2, 3 };    // ok myarray = { 4, 5, 6 };           // not compile anobject.somemethod({ 7, 8, 9}); // not compile 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -