• 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

Arrays

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
My question is regarding arrays. I was going through the Mughal book, Chapter 4, and one of the section questions was "Which of these array declarations and initializations are not legal?"
One of the answers is:
int[] i = new int[2] {1,2};
I'm trying to understand why this is illegal, is it because if you're declaring, constructing, and initializing an array in one statement, you can't specify how many elements it will hold? Then how would you initialize an array declared as
int pizzas[] = new int[10];
In this case do you just "settle" for the default initialization, all elements in the pizzas array initialized to 0?
Thanks
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You EITHER tell it how many element it will be OR you initialize it with the specific values of the elements and that determines how many elements there will be. Otherwise we would have to have all sorts of rules on how to resolve conflicts if the number of specified elements does not match the list of elements provided.
Imagine
int[] i = new int[2] {1,2,5,8}; //problems
 
Dmitry Shekhter
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you Cindy, that clears it up.
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Refer to theJLS Chapter 10 and
JLS �15.10
Here are some things you can do to initialize an array:
// 1 - use an array initializer
int[] i = new int[] {1, 2};
// 2 - explicitly assign initial values
int[] i = new int[2];
i[0] = 1;
i[1] = 2;
// 3 - use a loop to assign initial values
int[] i = new int[];
for (int k = 0; k < i.length; k++)
{
i[k] = ... // initial value of current element
}
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic