Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing directly an array initializer to a method parameter doesn't work

Tags:

java

arrays

package arraypkg;

import java.util.Arrays;

public class Main
{
    private static void foo(Object o[])
    {
        System.out.printf("%s", Arrays.toString(o));
    }

    public static void main(String[] args)
    {
       Object []o=new Object[]{1,2,3,4,5};
       foo(o);                     //Passing an array of objects to the foo() method.

       foo(new Object[]{6,7,8,9}); //This is valid as obvious.

       Object[] o1 = {1, 2};      //This is also fine.
       foo(o1);

       foo({1,2});               //This looks something similar to the preceding one. This is however wrong and doesn't compile - not a statement.
    }
}

In the preceding code snippet all the expressions except the last one are compiled and run fine. Although the last statement which looks something similar to its immediate statement, the compiler issues a compile-time error - illegal start of expression - not a statement. Why?

like image 901
Tiny Avatar asked Oct 09 '12 17:10

Tiny


People also ask

Can you pass an array to a method the method receives?

You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.

Can arrays be passed as parameters to methods?

Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.

How do you pass an array directly to a function in C++?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.


1 Answers

foo({1,2});

{1, 2} this kind of array initialization only work at the place you are declaring an array.. At other places, you have to create it using new keyword..

That is why: -

Object[] obj = {1, 2};

Was fine.. This is because, the type of array, is implied by the type of reference we use on LHS.. But, while we use it somewhere else, Compiler cannot find out the type (Like in your case)..

Try using : -

  foo(new Object[]{1,2});
like image 63
Rohit Jain Avatar answered Oct 05 '22 07:10

Rohit Jain