toString

Hi,

I have a loop  like below where the name is printed, I dont need to typecast it or even use toString.

  I find this strange because,it is an object, we need to typecast, is automatic typecasting done for System.oout.println()??
 
 // accounts map
         for (Object user: users)
         {

            // get the value (quota) corresponding to the current
            // key (name) from the quota map

            Object quota = quotaMap.get(user);

            // print the key (name) - note that the typecase is optional
            System.out.print("Name: " + (String)user);

thanks...
zizi21Asked:
Who is Participating?
 
CEHJCommented:
toString is automatically called by System.out
0
 
CEHJCommented:
So, whatever type 'user' is, its toString will be called
0
 
william007Commented:
Hi,

If we have object like this
public class Object {
   
    /** Creates a new instance of Env */
    public Object() {
    }
    public String toString(){
        return "hello";
    }
}

if we type
System.out.println(new Object()),
it will print out "hello",
this is due to it will call the toString() method of this object automatically.
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
william007Commented:
Oops...never refresh my browser when typing:)
0
 
zizi21Author Commented:
basically, every object would have a toString that automatically converts to string ? sorry if this is obvious. just wish to reconfirm ..studying for exams..
0
 
CEHJCommented:
Yes. Since everything is a child of Object and Object defines toString
0
 
zizi21Author Commented:
thanks :)
0
 
CEHJCommented:
:-)

>>public class Object

You wouldn't want to call it that of course ;-)
0
 
william007Commented:
Hi zizi21, thanks:)

Hi CEHJ, yea...that doesn't sound good:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.