Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dan Chisholm's Array Question

 
Maria Garcia
Ranch Hand
Posts: 86
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Can somebody explain step by step why this prints 'A' ?
[ December 10, 2002: Message edited by: Maria Garcia ]
 
Vivek Talyan
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The call at line 7 is a3[2][1][0]. This returns the object of class A that was created earlier. Since this object is being used in a context where a it is being treated as a string (i.e. it is being passed as a parameter to the println() method), the compiler inserts a call to the toString() method of the object.
This results in "A" being printed.
Hope this makes sense.
 
Maria Garcia
Ranch Hand
Posts: 86
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Vivek
 
Gustavo Adolpho Bonesso
Ranch Hand
Posts: 103
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i�ll try to explane... Sorry about my bad English.
class A {
public String toString() {
return "A";
}
}
class B {
public static void main(String[] arg) {
A[] a1 = new A[1]; // a1 has a uni-dimensional Array of A class address...
A[][] a2 = new A[2][]; // a2 has a bi-dimensional Array of A class address...
A[][][] a3 = new A[3][][]; // a3 has a three-dimensional Array of A class address...
a1[0] = new A(); // A instance of A class is created and the address of this
// class is held by the a1 array (lets say, this address is
// xyz...)
a2[0] = a2[1] = a1; // Position 1 of bi-dimensional array a2 is the unidimensinal array a1.
// Position 0 of bi-dimensional array a2 is also the unidimensinal array a1.
a3[0] = a3[1] = a3[2] = a2; // The three positions of the first dimension of the
// three-dimensional array a3 holds the bi-dimensional array
// a2.
System.out.print(a3[2][1][0]); // So, a3 it�s a three-dimensinal array (3X2X1) of
// instances of class A. If you print any position of
// a3, you will get the toString() method of A, which
// simply print "A"
}
}
 
Kathy Sierra
Cowgirl and Author
Rancher
Posts: 1589
5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy -- I know this one is tough to explain in text (for me, anyway) so I've made a very detailed picture of what's happening. I have it in a 2-page PDF if anyone wants it.
If you'd like it, email me directly:
kathy.sierra@wickedlysmart.com
Cheers,
Kathy
p.s. that question is a pretty good example of the spirit of the exam. You are expected to know about multi-dimensional arrays, and we're not just talking 2D.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic