0

I'm new to Java and I know this is a dumb question, but I can't understand the way how Java is initializing his variables. I tried to do some test, but I can't figure out how does this is working.

When I was learning programming C or Java, the syntax of defining a new variable was like this:

type name;
int value;

and an array of integers:

type name[];
int values[];

In Java int[] val; this would be an array in array?

Ex:

int[] val = new int[2];

val[0] = 012345; // Error ?

The ex above is correct. So that means the following example is the same?

int val[] = new int[2];
val[0] = 123;
val[1] = 456;

int[] val2 = new int[2];
val2[0] = 789;
val2[0] = 101;
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Reteras Remus
  • 923
  • 5
  • 19
  • 34
  • 2
    possible duplicate of [What's the difference between two array declarations in Java?](http://stackoverflow.com/questions/7277889/whats-the-difference-between-two-array-declarations-in-java) – Mark Byers Dec 24 '12 at 00:40
  • "In Java, `int[] val;` would be an array in array?" No. It's a declaration of a reference to an array of ints. The actual array of ints is created with the call to `new int[2]`. – Marvo Dec 24 '12 at 00:54
  • The equivalent notation `int val[]` was introduced because it's familiar to those coming from C. – ignis Dec 24 '12 at 01:22
  • 1
    Another dupe: http://stackoverflow.com/questions/129178/difference-between-int-array-and-int-array – BalusC Dec 24 '12 at 02:00

2 Answers2

6

Yes int val[] = new int[2]; does exactly the same as int[] val2 = new int[2];.

From Java Language Specification

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both

So even something like

int[] val2[] = new int[2][3]

is correct (although unusual) for two dimensional array.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

Both declarations mean the same thing.

int val[] = new int[2];
int[] val2 = new int[2];

However, you should use the first notation. Most programmers consider it more readable.

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63
  • 1
    I believe you meant to say that most C programmers consider the first form more readable. – VGR Dec 24 '12 at 01:48
  • 1
    The following are types: `String`, `double`, `List`, `int[]`. Thus, the array specifier `[]` is part of the _type_, not part of the variable name. You should use the *second* notation. :) – cambecc Dec 24 '12 at 02:59
  • It's good that we don't have three ways of declaration. Third comment would say that the "new" version is most readable :) – Marcin Szymczak Dec 24 '12 at 10:29