views:

86

answers:

3

Hello there. 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;
+4  A: 

From what you've posted, the lines

test1[0] = 1;
test1[1] = 2;
test1[2] = 3;

need to be inside a method or constructor. Looks like you have them outside at the class level. Lets say MyClass is the name of your class. Add a constructor and put the three statements inside it:

MyClass {
    test1[0] = 1;
    test1[1] = 2;
    test1[2] = 3;
}

Edit: You can only declare variables directly inside the class. A declaration statement can, however, also include initialization (on the same line):

int[] arrayA; // declare an array of integers
int[] arrayB = new int[5]; // declare and create an array of integers
int[] arrayC = {1, 2, 3}; // declare, create and initialize an array of integers

The following, on the other hand, is not a declaration and involves only initialization:

arrayB[0] = 1;

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

Samit G.
Good guess. I haven't thought he might actually put initialization right after definition.
Nikita Rybak
That's what I did - had them at the class level vs. in the constructor. I guess I was just wondering why the first way of initialization (int[] var = {x,y,z}) works at the class level and the other way doesn't. Mind boggling.
ConfusedWithJava
@ConfusedWithJava - see my edit above
Samit G.
+2  A: 

To work your java source file must be something like this:

public class Test
{
    // this works
    private static int[] test2 = {1,2,3};

    // this is ok
    private static int[] test1 = new int[3];

    public static void main( String args[] ){

        test1[0] = 1;
        test1[1] = 2;
        test1[2] = 3;
    }
}
Leniel Macaferi
+1  A: 

You can also put the code in a static initialization block which is executed when the class is loaded.

public class Test {
   // this works
   private static int[] test2 = {1,2,3};

   // this is ok
   private static int[] test1 = new int[3];

   static {
       test1[0] = 1;
       test1[1] = 2;
       test1[2] = 3;
   }
}
Jeroen Rosenberg