It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Dan Chisholm's Array Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Dan Chisholm Watch "Dan Chisholm New topic

Dan Chisholm's Array Question

Maria Garcia
Ranch Hand

Joined: Jul 14, 2002
Posts: 86

Can somebody explain step by step why this prints 'A' ?
[ December 10, 2002: Message edited by: Maria Garcia ]

SCJP 1.4
Vivek Talyan

Joined: Sep 03, 2002
Posts: 13
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.

SCJP2 (1.4)
Maria Garcia
Ranch Hand

Joined: Jul 14, 2002
Posts: 86
Thank you Vivek
Gustavo Adolpho Bonesso
Ranch Hand

Joined: May 11, 2002
Posts: 103
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"

Gustavo Adolpho Bonesso<br />SCJP1.4
Kathy Sierra
Cowgirl and Author

Joined: Oct 10, 2002
Posts: 1589
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:
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.

Co-Author of Head First Design Patterns
Just a Jini girl living in a J2EE world.
It is sorta covered in the JavaRanch Style Guide.
subject: Dan Chisholm's Array Question
It's not a secret anymore!