1

I came across this tutorial and was wondering why the Java compiler would throw an error for the last example. Could someone explain?

Here's the excerpt:

--

Java Ugliness: Syntactic Irregularity and Ad Hoc Logic

In this irregular but convenient syntax: int[] v = {3,4};, it does several things in one shot: {array type declaration, value assignment, number of elements declaration, slots fulfillment}. However, this syntactical idiosyncrasy cannot be used generally. For example, the following is a syntax error:

int[] v = new int[2];
v = {3, 4};

Here's a complete code you can try.

public class H {
    public static void main(String[] args) {
        int[] v = new int[2];
        v = {3,4};
        System.out.print(v[0]);
    }
}

The compiler error is: “illegal start of expression”.

Chul Kwon
  • 137
  • 3
  • 11
  • possible duplicate of [How to declare an array in Java?](http://stackoverflow.com/questions/1200621/how-to-declare-an-array-in-java) – PM 77-1 Jun 30 '14 at 02:44

3 Answers3

4

Try this one:

public class H {
    public static void main(String[] args) {
        int[] v = {9,6}; // new array with default values
        System.out.print(v[0]);
        v = new int[]{3,4}; //note: this will create a new array
        System.out.print(v[0]);
    }
}
3

The "{}" brackets cannot be used after the array size has already been made. The code will not run because it tries to assign a size to an array that already has a size. To define the elements in the array after "int[] v = new int[2];", you must use "v[0] = 3;" and "v[1] = 4;"

Cameronc56
  • 102
  • 1
  • 8
0

This is just simply against the syntax's rules. You can do either of the following for the same results.

  1. int[] v = {3, 4};
  2. v[0] = 3; v[1] = 4;
user3758041
  • 179
  • 11