Passing Java array without reference

I am trying to pass an array without using a link, but directly with the values:

public static void main(String[] args){ int[] result = insertionSort({10,3,4,12,2}); } public static int[] insertionSort(int[] arr){ return arr; } 

but it returns the following exception:

 Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error on token(s), misplaced construct(s) Syntax error on token ")", delete this token 

When I try to execute the following code, it works, can someone explain the reason?

  public static void main(String[] args){ int[] arr = {10,3,4,12,2}; int[] result = insertionSort(arr); } public static int[] insertionSort(int[] arr){ return arr; } 
+4
source share
4 answers

It should be

 int[] result = insertionSort(new int[]{10,3,4,12,2}); 

{10,3,4,12,2} is the syntactic sugar to initialize the array, which should come with an expression similar to the following:

 int[] arr = {10,3,4,12,2}; 

The following is also not allowed:

 int[] arr; // already declared here but not initialized yet arr = {10,3,4,12,2}; // not a declaration statement so not allowed 
+8
source
 insertionSort({10,3,4,12,2}) 

java is invalid because you are not specifying a type in a method call. The JVM does not know what type of array it is. Is it an array with double values ​​or int values?

What you can do is insertionSort(new int[]{10, 3 ,4 12, 2});

+5
source

int[] array = { a, b, ...., n } - this is abbreviated initialization - you need to write:

 int[] result = insertionSort(new int[]{10,3,4,12,2}); 

to initialize it anonymously.

+1
source

Nothing much to add to what others have said.

However, I believe that you should use new int[]{10,3,4,12,2} (like the others declared), and Java does not allow you to use only {10,3,4,12,2} , so this that Java is heavily typed.

If you just use {10,3,4,12,2} , there is no concept of what the type of an array element can be. They seem to be integers, but they can be int , long , float , double , etc.

Well, actually it can infer the type from the method signature and start compiling if it doesn't work, but it seems complicated.

+1
source

Source: https://habr.com/ru/post/1437063/


All Articles