The moose likes Beginning Java and the fly likes illegal start of expression -- arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "illegal start of expression -- arrays" Watch "illegal start of expression -- arrays" New topic
Author

illegal start of expression -- arrays

Kai Middleton
Greenhorn

Joined: Jul 27, 2001
Posts: 12
Why is the java language structured such that in regard to my second invocation of the foo method I get a compiler error:



<I>Kai M.</I>
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The problem is that your foo method requires an int array and that is not what you are passing it. Arrays in java are objects, so you need to create one to send. It looks to me like neither invocation will work. All objects, except Strings, need to be explicitly created with the new keyword.
public class IllegalStartOfExpression{
public static void main(String [] args){
int[] x = new int[]{1, 2};
foo(x);
foo(new int[]{1, 2});
}
public static void foo(int[] x){
System.out.println(x[0]);
}
}

------------------
Brian Hoff
Sun Certified Programmer for the Java� 2 Platform
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

If I could add something: The confusing thing about anonymous arrays (which is what we're talking about), is that at first glance it appears that an initialization list is the anonymous array: The confusing part (for me) was that I have a book that says The construct (ie: the anonymous array) returns an array reference which can be assigned, and passed as a parameter. In particular, the following two examples are equivalent:
int[] intArray = {2,3,4,5};
int[] intArray = new int[] {2,3,4,5};

I thought that {2,3,4,5} was an anonymous array, but of course it's not, it's simply an initialization list, and not the anonymous array itself. So this list by itself cannot be passed to a method which expects an array.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: illegal start of expression -- arrays
 
Similar Threads
static method local variables
difference between static local variables and static global variables.
static variables inside a static method
((A)b).x what kind of construct is this?
Static Block