Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Multidimensional arrays

 
Shweta R Dhaneshwar
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this example is from K&B
Given the following,

and the command-line invocation,
java CommandArgsThree 1 2 3
what is the result?

o/p is 123.

Doubt:argCopy is a 2d array.This array has two elements where each element is again a single dimensional array of two elements.This array is assigned to arguments passed at command line.the size of the first element of the array is 2,then how can we assign it 3 elements...i.e...can array size grow?
 
Amol Fuke
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes shewta array size can grow.
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No Aray size cannot grow.

You passed in 3 command line arguments so that Array has a size of 3.

With this line:

You replaced the Array at argCopy[0] with the args array which has a size of 3.

Java does not have true 2D Array's. What you have is an Array that holds other Arrays.

What you are doing is iterating over the args[].
 
Philip Heller
author
Ranch Hand
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is easier to understand if you approach it gradually. Consider this code:



In your imagination, the array might be a box with three compartments (like a bookcase lying down), with one int in each compartment. Now consider:



It's tempting to picture this array as a box with three compartments, with a String in each compartment. But that's not exactly right. A String is an object, not a primitive, and in Java we always relate to objects via references. So the array's compartments actually contain references to Strings, rather than strings.

Ok, now for the "2D" case:
String[][] argCopy = new String[2][2];
[CODE]

This declares that argCopy is an array that contains two elements. Each is a reference to an array of strings. So argCopy[0] is a reference to an array of strings. (And that's just a convenient way of talking about it. We understand that really there's no such thing as an array of strings ... there's really an array containing references to strings.)

When the "argCopy[0] = args" statement executes, the reference in argCopy[0] is replaced by another reference. That new reference has to be of type String[], otherwise the code won't compile. But the new String array can be of any size. In the code you sited, the new size was 3.

Hope this helps.
-- Phil
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic