Reputation: 75
I'm confused when I declare and construct an array on separate lines in java outside of a method, thus it would be an instance variable, I get a compilation error, yet when I construct and initialize on one line it is fine, why does this happen?
public class HelloWorld {
//This works fine
int anArray [] = new int[5];
//this doesn't compile "syntax error on token ";", , expected"
int[] jumper;
jumper = new int[5];
public static void main(String[] args) {
}
void doStuff() {
//this works fine
int[] jumper;
jumper = new int[5];
}
}
Upvotes: 0
Views: 5914
Reputation: 6205
you simply can't run commands outside a method. Except for assigning a value upon variable declaration (except for som cases like the initializer blocks).
You can initialize the variable during declaration:
private int[] numbers = new int[5];
You can initialize in the constructor
class MyClass {
private int[] numbers;
public MyClass() {
numbers = new int[5];
}
}
Or initialize it in the initialization block
private int numbers[5];
{
numbers = new int[5];
}
Upvotes: 0
Reputation: 4403
A small syntax change will fix the compiler error:
int[] jumper;
{
jumper = new int[5];
}
Upvotes: 1
Reputation: 159754
jumper = new int[5];
is a statement and must appear in a method, constructor or initialization block.
As I think you are aware, you can do this:
int[] jumper = new int[5];
as you can make the assignment in the variable declaration.
Upvotes: 7