toString can't understand
hi. i have problems in understanding the toString method. here is my code. if someone would be kind enough to explain toString method with a simple example it will be great.
public String toString()
{
if (coins.size() == 0)
return"Purse[]";
String output ="Purse[";
for (String coin : coins)
{
output = output + coin +",";
}
output = output.substring(0, output.length() - 1);// remove the last ","
return output +"]";
}
This is one of the method used in an example from BIG JAVA. but i really cannot understand the functionality of using toString() why do we use toString(), is there any other way to write the same method above rather than using toString()? secondly and lastly can some specify a simple example of toString() method?
Thankyou
[1244 byte] By [
fastmikea] at [2007-11-26 18:56:19]

If you pass an Object to System.out.println(), the toString() method is invoked to represent the object. If you have some class A:
class A
{
int num;
public A(int num)
{
this.num = num;
}
public String toString()
{
return "Value: " + num;
}
public static void main(String[] args)
{
A a = new A(5);
System.out.println(a);
}
}
I don't understand what you don't understand.
toString is a method that's defined in Object, so every class has toString. Its purpose is to provide a human-readable textual representation of an object's state. The toString implementation in Object just prints the class and hashCode, or something to that effect. Any class that does not override toString does the same thing.
Classes like String, Integer, Date, etc. provide their own implementation of toString, as does this example here.
When you do System.out.println(obj);
or
String str = "The value was: " + obj;
obj's toString method is called.
In this case, if you print out this Purse object, you'll get "Purse[]" if it's empty, or "Purse[nickel, nickel, dime, quarter]" or something like that if it's not empty.