With int
and other primitive types, you're correct, the double declaration is largely superfluous.
But consider this example:
Object [] array = new String[5];
This is valid Java code (even though it is slightly broken*).
On a more general level it follows the same pattern as when you're initialising any variable with a new object:
Foo foo = new Foo();
The first Foo
is the type of the variable (what shape the box is), the second is the type of the actual object (what shape is the thing you put in the box).
Note: Starting with Java 10, you can declare local variables with the keyword var
, thus eliminating the need to specify the type twice:
var array = new int[5];
The compiler will infer from this that the type of array
will be the same as the object it's initialised with. (int[]
in this case).
*It is broken because if you try to put into the array anything other than a String
, the code only fails at runtime, not during compilation.