java - Why do I need to `{...}` to filling an array in the class scope? -


what's wrong below program?

package test;  public class test {      byte[] array = new byte[2];     array[0] = 'a';     array[1] = 'b'; } 

look,the ide indicate problems(click enlarge) :

enter image description here

in other word, why should move filler lines inner scope follow :

package test;  public class test {      byte[] array = new byte[2];     {         array[0] = 'a';         array[1] = 'b';     } } 

the ide doesn't have problem above program.

in snippet try assignments (to array: e.g. array[0] = 'a') outside method

public class test {     byte[] array = new byte[2];     array[0] = 'a';     array[1] = 'b'; } 

whereas in snippet assignments inside instance initializer block

public class test {     byte[] array = new byte[2];     {         array[0] = 'a';         array[1] = 'b';     } } 

if want in code example in init method

public class test {     byte[] array = new byte[2];      void initarray() {         array[0] = 'a';         array[1] = 'b';     } } 

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 -