简体   繁体   中英

I have the following two diffetent ways of declaring an integer array in Java, one works and one doesn't, why?

The following is first way of declaring, and it worked:

static final int N = 9;
public static int[] arr = new int[N];

This is the one that doesn't:

static final int N = 9;
int arr[];    //declaring array
arr = new int[N];  // allocating memory to array

Eclipse gave me the error reminder on the second line that I don't quite get it: Syntax error on token ";", , expected

Thank you for taking the time reading my question, any advice will be much appreciated.

From the public keyword in your first example, I'm guessing this appears directly inside a class definition.

arr = new int[N]; is executable code and executable code can't appear directly inside a class definition. Depending on whether it needs to be static , you have to put it either inside a constructor or inside a static initializer block .

As I mentioned in my initial comment, you can use that syntax in an initialization block (or a constructor). Like,

int arr[];    //declaring array
{
    arr = new int[N];   // allocating memory to array
}

or

public class MyClass {
    static final int N = 9;
    int arr[];    //declaring array
    public MyClass() {
        super();
        arr = new int[N];  // allocating memory to array
    }
}

Note that the two examples here are actually the same in byte-code. Initialization blocks (and statements) are copied by the compiler into constructors (including the default constructor) - basically as seen here.

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