File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

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

Per Hansen
Greenhorn

Joined: Oct 13, 2010
Posts: 4
Hi

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 x.java:9: ']' expected Customer[] customers[10];
^
x.java:9: ']' 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";

System.out.print(customers[0].name);

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
Sheriff

Joined: Oct 27, 2005
Posts: 19692
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Per Hansen
Greenhorn

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

Thanks for the fast reply and excellent explanation
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why Customer[] customers[10]; doesnt work?