5

There's something I don't understand with array syntax. For example I can do that :

int[] tab = {1,2,3};

Let's say I have a method that takes an array as a parameter, I can do that: myMethod(tab);

But why can't I do that: myMethod({1,2,3})

Why do I have to add an extra "new int[]" like this: Method(new int[] {1,2,3})

Cohensius
  • 385
  • 7
  • 18
AntonBoarf
  • 1,239
  • 15
  • 31
  • 2
    Ask the creators of Java; this is what the syntax for arrays is. – Tim Biegeleisen May 11 '18 at 13:55
  • 1
    because java need you to tell it exactly the type of the values.. 1,2,3 can also be float, double, etc... – Surely May 11 '18 at 13:56
  • See https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html#jls-10.6 – khelwood May 11 '18 at 13:56
  • I think it's the same for c language then I think there must be a good reason, unfortunately I don't know which is – deFreitas May 11 '18 at 13:57
  • @Surely : I thought by default number like 5,6,7, etc were int. If you want other data types you have either to cast or be more specfic (6f if you want a float instead of int defalut type for example) – AntonBoarf May 11 '18 at 13:58
  • [1] https://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java check this other post – MoreCoffeeLessJava May 11 '18 at 13:59
  • @AntonBoarf because it can also be an Array of Object. It just means that the compiler can't inferred what is it if you will not provide a hint explicitly :) – Enzokie May 11 '18 at 14:00
  • In general the compiler can't guess the exact type of the array from the contents and be sure it's correct. You can have an array that just contains strings, but you might need it to be of type `Object[]`. – khelwood May 11 '18 at 14:00

2 Answers2

3

One possible explanation of this Java language design decision is that array initialization contains array type already.

For example:

int[] myArray = {1, 2, 3};

is unambiguous. But if a new array is created within an expression, it's not always clear which type to use, e.g.

myMethod({1, 2, 3})

could mean

myMethod(new int[] {1, 2, 3})

or

myMethod(new Integer[] {1, 2, 3})

or

myMethod(new Number[] {1, 2, 3})

or even

myMethod(new Object[] {1, 2, 3})
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
1

The syntax {1,2,3} (without new int[] in front of it) can only be used as an array initializer expression. In all other contexts (including method calls), you need to use the new operator.

More information on this tutorial : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

code_fish
  • 3,381
  • 5
  • 47
  • 90