• 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

Array

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following bit of code gets compiled can any one explain why???

int i[] = new int[]{};

it creates and array of length zero.......
if the code is modified
say

int i[] = new int []{1};
even then it comploed in the second case it creates an array and it is intialised explicitiy.....

but how come both the array creation be combined like this and the compiler dose not complain???

Thank you in advance.

Source:self.
 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
>>int i[] = new int[]{}
Yes, here it creates an empty array. The problem won't show up until you try to access an element out of it.

System.out.println(i); --> will print the object address
System.out.println(i[0]); --> runtime error

The second case you have, is a normal syntax for creating an anonymous array.
 
Srikanth Iyer
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes that part is understood but is possible to use both new and {} at the same time???
 
Srikanth Iyer
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh i almost forgot the anonymus array sorry.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The special brace syntax for initializing arrays at instantiation...

String[] theseStrings = { "abc", "def", "ghi" };

...is shorthand for...

String[] theseStrings = new String[] { "abc", "def", "ghi" };
 
I am not a spy. Definitely. Definitely not a spy. Not me. No way. But this tiny ad ...
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic