• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

toString() method

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't quite understand how the following code works:
class Z {
public static void main(String[] args) {
System.out.println("AAA" + new Z());
}

public String toString() {
System.out.println("###");
return "Z";
}
}
What on earth toString() method did here? Why new Z() will invoke this method? What is something special about toString() method? I am very confused about this method, pls clarify me. Thanks.
Luk
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When the compiler sees and expression such as
"AAA" + obj
where obj is any object reference, it automatically assumes that what is wanted is the String representation of obj - ie the result of obj.toString()
I generally try to give every class I create a toString method that tells something about the state of the object - very handy in debugging.
Bill

------------------
author of:
 
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So in the above code, will the output be
AAA###
or
AAAZ
or
AAA###Z
?
 
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Output will be:
###
AAAZ
Note: seperate lines due to the println statement in the toString() method.
 
Yes, of course, and I accept that blame. In fact, i covet that blame. As does this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic