• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

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" };
 
And will you succeed? Yes you will indeed! (98 and 3/4 % guaranteed) - Seuss. tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic