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?
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.
Arrays can be passed as arguments to method parameters. Because arrays are reference types, the method can change the value of the elements.
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.
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With