This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

toString() method

 
luk Hann
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • 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
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13056
6
  • Mark post as helpful
  • send pies
  • 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:
 
ryan burgdorfer
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So in the above code, will the output be
AAA###
or
AAAZ
or
AAA###Z
?
 
Bob Young
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Output will be:
###
AAAZ
Note: seperate lines due to the println statement in the toString() method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic