File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes why Customer[] customers[10]; doesnt work? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why Customer[] customers[10]; doesnt work?" Watch "why Customer[] customers[10]; doesnt work?" New topic

why Customer[] customers[10]; doesnt work?

Per Hansen

Joined: Oct 13, 2010
Posts: 4

This is simply out of curiosity. At school our teacher showed us a code example (I also have the pdf file she upload containing the code, so Im not misremembering).
The pdf doesnt show the whole code, but when I try to use some of the code to understand pointer arrays it didnt work, however I found another way that works.

This is not cut from her code, but im using the same exact layout just with different names.
This code is in main. And we have declared the class Customer.

line 9. Customer[] customers[10];

customers[0] = new Customer();
customers[0].name = "Bob";

when trying to compile this I get the message ']' expected Customer[] customers[10];
^ ']' illegal start of expression Customer[] customers[10];
This however works like a charm:
Customer[] customers = new Customer[10];
customers[0] = new Customer();
customers[0].name = "Bob";


Im using jdk1.6.0_21, I dont know what version her example is from though.
I wasted a lot of time with the first example without understanding why it will not compile. Could someone just tell me why the first example doesnt work?

Rob Spoor

Joined: Oct 27, 2005
Posts: 20273

Per Hansen wrote:Customer[] customers[10];

That's a declaration only. This is the same as Customer[][10] customers, or Customer customers[][10]. The issue is, you can't put a size in the declaration.

Customer[] customers = new Customer[10]; on the other hand is declaration with immediate initialization. The left hand side (declaration) doesn't specify the size, only the initialization does.

How To Ask Questions How To Answer Questions
Per Hansen

Joined: Oct 13, 2010
Posts: 4
Hey Rob Prime

Thanks for the fast reply and excellent explanation
I agree. Here's the link:
subject: why Customer[] customers[10]; doesnt work?
It's not a secret anymore!