4

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.

  • 1
    What part is not clear? The first is legal Java. The second is not legal. Specifically, `arr = new int[N];` is **not** in a constructor, method, or initialization block. Also, `int arr[]` is **not** `static` or `final` (but it isn't necessary for `arr` to be `static` or `final` in your first example). – Elliott Frisch Oct 12 '19 at 06:48
  • @ElliottFrisch Thanks for the advice. I learnt the second part from a tutorial website. I wonder is there any circumstance that I can use "arr = new int [N];" to declare an array? – Zhiyuan Wan Oct 12 '19 at 07:06

2 Answers2

5

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249