简体   繁体   中英

Why can't you declare and initialize an array outside of a method in java?

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

}

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.

A small syntax change will fix the compiler error:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM