Patrick S.
Patrick S.

Reputation: 11

Java Array Initialisation Beginner's Question

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.

Upvotes: 0

Views: 487

Answers (5)

Matthew Sowders
Matthew Sowders

Reputation: 1680

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();
  }
}

Upvotes: 0

meriton
meriton

Reputation: 70564

You could use an array initializer:

public class CycleTest {
    Cycle[] cy = {
        new Cycle(),
        new Cycle(),
        new Cycle()
    };
}

Upvotes: 4

asela38
asela38

Reputation: 4644

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.

Upvotes: 2

Noel Ang
Noel Ang

Reputation: 5099

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() { ... }
    ...
}

Upvotes: 3

user8681
user8681

Reputation:

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();
    }
}

Upvotes: 7

Related Questions