Code corner: Fun with Arrays

Fun With Arrays

Fun With Arrays

Which of these code fragments compile, and which do not?

 //Example 1
 int another[], y[];
 // Example 2
 int[] array, x[];
 //Example 3
 Object interesting = new Object[]{};

 

If you think either Example 1 or 2 compile, what code would you write to initialise them?

Reveal the answer…

All of the statements will compile. Example 1 is simply just creation of two array. to initialise these would just involve basic array syntax.

 int another[] = {}, y[] = {1,2,3};

Example 2 is more nuanced. this is creating an int array called array, and and 2d int array called x.  To initialise would look like this:

int[] array = {}, x[] = {{1,2,3},{4,5,6}};

Example 3 would absolutely compile too.  An Object Array is still an Object.

For more Java Array madness, check out this great post at vanilla java.

One Comment

  • Thank You.I learned something today!!

Join the Discussion

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>