1

I have a method doSomething() which accept Array as parameter. When I pass array like bellow:

package org.my;

public class ArrayMistry {

    public static void main(String ... args) {
        doSomething({1,2});// Compilation Error
    }   

    public static void doSomething(int[] params) {

    }   

}

I am getting compilation error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: Syntax error on token "doSomething", @ expected before this token Syntax error, insert "enum Identifier" to complete EnumHeader Syntax error, insert "EnumBody" to complete BlockStatements

at org.my.ArrayMistry.main(ArrayMistry.java:6)

Note:

if I pass as bellow then its OK:

public static void main(String ... args) {
    int[] p = {1,2};
    doSomething(p);// no Error
    doSomething(new int[]{1,2});// no Error
}
  • Read this post which explains the problem more in-depth: http://stackoverflow.com/questions/5387643/array-initialization-syntax-when-not-in-a-declaration – Matt C Mar 25 '16 at 04:25

5 Answers5

0

It's because you aren't declaring {1, 2} as a new array. It must be declared as new int[]{1,2} to function properly, otherwise you are not creating an array.

0

You have to make an array to pass into a method because you initialized the method that way. The reason this doSomething({1,2}); doesn't work is because the array has not been initialized and {1, 2} is not an array, it is just some numbers in a parenthesis. if you wanted to send an array you have to do something like this

int[] p = {1,2};
doSomething(p);
Suhas Bacchu
  • 37
  • 1
  • 1
  • 6
0

Your method doSomething() specifically accepts an array of integers as its parameters.

Note in both cases where it worked, you either passed an existing array, or created a new one when passing it in.

In your original example, you are passing an arbitrary set of numbers with no memory reserved, or type specified.

rhysvo
  • 38
  • 6
0

Another way to solve the problem is by passing a reference as a parameter to the function like this:

doSomething(new int[]{1,2});
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
0

Arrays are passed by reference. You need to create an array object with [1,2] and pass the reference of that created object to dosomething. The new keyword allocates space for the creation of this int array.

int[] arr = new int[]{1,2};
doSomething(arr);
Debosmit Ray
  • 5,228
  • 2
  • 27
  • 43