0

What is the problem with the following code?

class xyz
    {
      int[] array=new int[3];
      array[0]=0;
      array[1]=1;
      array[2]=2;

   public static void main(String[] args)
   {
   xyz a=new xyz();
   System.out.println(a.array[0]+" "+a.array[1]+" "+a.array[2]);
   }
  }

I am not able to initialize the array within the class but it works if it is initialized within a method of the class or the main function.

2 Answers2

2

The syntax to declare and initialize an array can be done in a single statement, like

int[] array = { 0, 1, 2 };

or you can use an initialization block. Like,

int[] array=new int[3];
{
    array[0]=0;
    array[1]=1;
    array[2]=2;
}
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226
  • 1
    Isn’t the second part of this not what OP has already, albeit outside of a method? – achAmháin Jun 26 '18 at 16:06
  • @notyou Yes, ***but*** OP's assignment statements **aren't** in an initialization block. – Elliott Frisch Jun 26 '18 at 16:08
  • yeah the OP is clearly trying to figure out how to make an instance of the object with a constructor doing the legwork for the array, I don't think this answer is what he was looking for – dave Jun 26 '18 at 16:08
  • Ah - I didn’t see that. – achAmháin Jun 26 '18 at 16:09
  • @aquaballin One distinction: an initialization block is **copied** into every constructor. So you would have to copy-and-paste this manually into every constructor for it to be equivalent. – Elliott Frisch Jun 26 '18 at 16:12
0
array[0]=0;
array[1]=1;
array[2]=2;

This is not legal Java. Executable code must be inside a method or constructor.

Code-Apprentice
  • 69,701
  • 17
  • 115
  • 226