This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes confused with the output from a code (Arrays) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "confused with the output from a code (Arrays)" Watch "confused with the output from a code (Arrays)" New topic
Author

confused with the output from a code (Arrays)

Geeta Gune
Greenhorn

Joined: Mar 19, 2002
Posts: 17

The code above when executed gives the output as "A". I do not understand why??
Can anybody please explain?? Also, if i modify the code in A and name the method as toString1(), then it gives the output as "A@1971" ..something like that..Why is this so??
Thanx in advance
Geeta
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
System.out is an object of type java.io.PrintStream. The println(Object) method of class PrintStream prints whatever returns from the invocation to String.valueOf(Object). The latter's code is:
return (obj == null) ? "null" : obj.toString();
that is, if the object is null, the string literal "null" will be printed, otherwise the toString() method is invoked on the object and the result is returned.
In your case, "A" gets printed because toString() is invoked on a1[0].
The java.lang.Object class implements a basic version of the toString method whose code looks as follows:
return getClass().getName() + "@" + Integer.toHexString(hashCode());
that is the class name, followed by "@", followed by the hashcode in a hexadecimal string.
When you renamed toString() to toString1(), the basic toString() version has been invoked, yielding the result you mentioned.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Geeta Gune
Greenhorn

Joined: Mar 19, 2002
Posts: 17
hi valentin,
I had no idea that printstream class prints whatever returns from the invocation to String.valueOf(Object). I checked it and realised that since we r overriding the toString() method of object class, we get the output as "A".I am absolutely clear now.
Thanks a lot valentin,
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: confused with the output from a code (Arrays)
 
Similar Threads
Why does it print "ALL"
Conversion of primitives to Strings when printing
Object Passing By Reference
help needed on Inner classes program
Read file from directory, update contents of the each file