Arian
Arian

Reputation: 7719

Java array pass without reference

I am trying to pass an array without using a reference, 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 the following code , it works , can anybody please 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;
    }

Upvotes: 5

Views: 2575

Answers (4)

Jan Koester
Jan Koester

Reputation: 1218

insertionSort({10,3,4,12,2})

is not valid java because you don't specify a type in your method call. The JVM does not know what type of array this is. Is it an array with double values or with int values?

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

Upvotes: 5

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

It has to be

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

{10,3,4,12,2} is a syntactic sugar for array initialization, which must go with the declaration statement like the one in the following -

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

Something as follows is not allowed too -

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

Upvotes: 10

gd1
gd1

Reputation: 11403

Nothing much to add to what others said.

However I believe the reason why you should use new int[]{10,3,4,12,2} (like others stated) and Java doesn't let you use just {10,3,4,12,2} is that Java is strong typed.

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

Well, actually it might infer the type from the method signature, and fire a compile error if it doesn't fit, but it seems complicated.

Upvotes: 1

moonwave99
moonwave99

Reputation: 22817

int[] array = { a, b, ...., n } is a shorthand initialization - you have to write:

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

to initialize it anonymously.

Upvotes: 1

Related Questions