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
  • suppose this [post](http://java-demos.blogspot.com/2013/10/static-blocks-vs-instance-blocks.html) would be helpful to you to get a better expalnation. – Rajith Pemabandu May 20 '17 at 00:56
  • 2
    Declare and initialize on the same line: `int[] quiz = {10, 20};` or initialize your array within a method. – DevilsHnd May 20 '17 at 01:09

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
  • 191,680
  • 20
  • 149
  • 239