tr3quart1sta
tr3quart1sta

Reputation: 169

creating an array in a class

I have a compilation problem in a Java program:

class FigureEditor {
   int[] a;             ----- Syntax error on token ";", , expected
   a = new int[5];
}

What am I doing wrong?

Upvotes: 5

Views: 131

Answers (3)

bharath
bharath

Reputation: 14453

How its possible? you have to initialize the int[] a any of 1 following ways,

Possible ways:

class FigureEditor {
int[] a; {
a = new int[5];
 }
}

Or

class FigureEditor {
int[] a = new int[5];
}

Or

class FigureEditor {
int[] a;  
public FigureEditor() {
a = new int[5];
 }
}

Upvotes: 2

Grammin
Grammin

Reputation: 12205

class FigureEditor
{
  int[] a = new int[5];
}

You can't use variables outside a method.

Upvotes: 4

Bozho
Bozho

Reputation: 597036

You can't have "floating" statements in the class body.

Either initialize it directly:

int[] a = new int[5];

Or use an initializer block:

int[] a;
{
a = new int[5];
}

Upvotes: 9

Related Questions