I’m very new to programming and I must be missing something here. The first section works. The second section blows up with an error. Why is that?
// this works
private static int[] test2 = {1,2,3};
// this is ok
private static int[] test1 = new int[3];
// these three lines do not work
// tooltip states ... "cannot find symbol. class test1. ']' expected."
test1[0] = 1;
test1[1] = 2;
test1[2] = 3;
From what you’ve posted, the lines
need to be inside a method or constructor. Looks like you have them outside at the class level. Lets say
MyClassis the name of your class. Add a constructor and put the three statements inside it:Edit: You can only declare variables directly inside the class. A declaration statement can, however, also include initialization (on the same line):
The following, on the other hand, is not a declaration and involves only initialization:
and so it can’t go directly under the class. It must be enclosed within a method, constructor or initialization block.
See Also:
Arrays Java tutorial at Oracle