5

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?

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
tr3quart1sta
  • 169
  • 1
  • 6

3 Answers3

9

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];
}
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • so, do i have to put everything in {}? for example { a[0] = 3124; } ? – tr3quart1sta Oct 21 '11 at 14:14
  • generally, you have to put things in methods. Initialization can happen together with the field, in a block, or in a constructor. But that's just initialization, not "everything" – Bozho Oct 21 '11 at 14:17
4
class FigureEditor
{
  int[] a = new int[5];
}

You can't use variables outside a method.

Grammin
  • 11,808
  • 22
  • 80
  • 138
  • @tr3quart1sta Welcome to StackOverflow; one way to give thanks for an answer is to "upvote" it with the up arrow to the left of the answer. You can also choose to "accept" the most helpful answer by clicking the check mark. – Michael McGowan Oct 21 '11 at 14:20
2

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];
 }
}
bharath
  • 14,283
  • 16
  • 57
  • 95