• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?

 
Sheriff
Posts: 22783
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey Rob Prime

Thanks for the fast reply and excellent explanation
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic