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]
# 1
http://www.javapractices.com/Topic55.cjp
zadoka at 2007-7-9 20:35:10 > top of Java-index,Java Essentials,New To Java...
# 2

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);

}

}

CaptainMorgan08a at 2007-7-9 20:35:10 > top of Java-index,Java Essentials,New To Java...
# 3

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.

jverda at 2007-7-9 20:35:10 > top of Java-index,Java Essentials,New To Java...
# 4
Captain Thanks for a simple example. so it's pretty much the same like printing out the statement. Great and simple example. i was just getting confused. but came to know that if we use System.out.println(""); the toString method is invoked automatically.
fastmikea at 2007-7-9 20:35:10 > top of Java-index,Java Essentials,New To Java...
# 5
Appreciate jverd. now i can take a deep breadth and work on toString() method.
fastmikea at 2007-7-9 20:35:10 > top of Java-index,Java Essentials,New To Java...