tags:

views:

152

answers:

5

A super trivial beginner question on Java arrays:

Can anyone explain why the compiler doesn't like this:

class Cycle {}

public class CycleTest {
    Cycle[] cy = new Cycle[3];
    cy[0] = new Cycle();
    cy[1] = new Cycle();
    cy[2] = new Cycle();
}

Many thanks.

+7  A: 

It's because the code you are trying to execute isn't in a method or other type of code block. You have to declare a method or constructor in your class to contain the code.

For example:

public class CycleTest {
    private void initializeCycle() {
        Cycle[] cy = new Cycle[3];
        cy[0] = new Cycle();
        cy[1] = new Cycle();
        cy[2] = new Cycle();
    }
}
Jorn
Thanks to both for the help here: I guess it isn't entirely obvious to me why this doesn't count as field initialisation but instead must be in a method body but I'm most grateful all the same...P.
Patrick S.
It's not a _field initializer_. A field initializer, by definition, is whatever goes on the right side of `=` in the field definition, and ends at semicolon or comma (if there's more than one field declared at once). In your case, `new Cycle[3]` is the initializer, and the other 3 lines are just 3 assignment _statements_.
Pavel Minaev
+4  A: 

You could use an array initializer:

public class CycleTest {
    Cycle[] cy = {
        new Cycle(),
        new Cycle(),
        new Cycle()
    };
}
meriton
I don't think you need the `new Cycle[]` there.
Tom Hawtin - tackline
You're right. I have edited accordingly.
meriton
+3  A: 

And, if you actually intend Cycle[] cy to have object scope (versus only being accessible from within the method in which its defined):

public class CycleTest {
    private Cycle[] cy;
    private void initializeCycle() {
        cy = new Cycle[3];
        cy[0] = new Cycle();
        cy[1] = new Cycle();
        cy[2] = new Cycle();
    }
}

or

public class CycleTest {
    private Cycle[] cy = new Cycle[] {
        new Cycle(),
        new Cycle(),
        new Cycle(),
    };
    private void method() { ... }
    ...
}
Noel Ang
+1  A: 

To initialize instance variable you can use instance initializing block(similar, to static block)

class Cycle {}

public class CycleTest {
    Cycle[] cy = new Cycle[3];

    {
        cy[0] = new Cycle();
        cy[1] = new Cycle();
        cy[2] = new Cycle();
    }
}

or you should initialize it at declaration time.

asela38
A: 

You could provide a constructor for initialization data. A constructor gets called when you create an instance of an object, i.e. new. All you have to do is name it the same as the class and with no return type.

class Cycle {}

public class CycleTest {
  Cycle[] cy;

  // This is a constructor
  // you can put initialization here
  public CycleTest(){
    cy = new Cycle[3];
    cy[0] = new Cycle();
    cy[1] = new Cycle();
    cy[2] = new Cycle();
  }
}
Matthew Sowders