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?

0

3 Answers 3

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];
}
Sign up to request clarification or add additional context in comments.

2 Comments

so, do i have to put everything in {}? for example { a[0] = 3124; } ?
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"
4
class FigureEditor
{
  int[] a = new int[5];
}

You can't use variables outside a method.

1 Comment

@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.
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];
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.