Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Per Hansen
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Per Hansen
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey Rob Prime

Thanks for the fast reply and excellent explanation
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic