• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

toString() method

 
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
 
Author and all-around good cowpoke
Posts: 13078
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:
 
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
?
 
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.
 
What a show! What atmosphere! What fun! What a tiny ad!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic