Passing the array initializer directly to the method parameter does not work

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 previous code snippet, all expressions except the last are compiled and work fine. Although the last statement, which looks about the same as its immediate statement, the compiler throws a compile-time error - the illegal launch of an expression - is not an assertion. Why?

+4
source share
3 answers
 foo({1,2}); 

{1, 2} this array initialization only works where you declare the array. In other places, you need to create it using the new keyword.

That's why: -

 Object[] obj = {1, 2}; 

It was great .. This is because the type of the array is implied by the type of reference that we use on LHS. But, although we use it somewhere else, the compiler cannot find out the type (as in your case).

Try using: -

  foo(new Object[]{1,2}); 
+8
source

foo({1,2}); does not determine the type of array. Therefore, the compiler does not understand the syntax. All other declarations indicate the type of array.

+3
source

foo({1,2}); NOT an array.

And since your foo() method accepts an array type parameter, this does not work.

+1
source

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


All Articles