3
 class example{

   int[] quiz = new int[] { 10 , 20 };    //location 1

     public static void main(String[] args) {

int[] test = new int[2];   // location 2
test[0] = 2;
test[1] = 3;
 // other code
}

The above code run correctly. However the code below causes an error. My reasoning for the error is since quiz is declared outside the method it needs to be initialized immediately. However I am not sure if this is a correct explanation.

class example{

    int[] quiz = new int[2];    //location of error
    quiz[0] = 10;
    quiz[1] = 20;


     public static void main(String[] args) {

int[] test = new int[2];   // location 2
test[0] = 2;
test[1] = 3;
 //other code
}
D. Wheeler
  • 55
  • 4

1 Answers1

6

You would need an initialization block to do it the second way,

int[] quiz = new int[2];
{
    quiz[0] = 10;
    quiz[1] = 20;
}
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249