• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 310
  • Last Modified:

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...
0
zizi21
Asked:
zizi21
  • 4
  • 3
  • 2
2 Solutions
 
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 4
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now