File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "collection" Watch "collection" New topic


AJ sisodia

Joined: Jan 19, 2005
Posts: 16
import java.util.*;

class Address
private String name;
private String street;
private String city;

Address(String n, String s, String c)
public String toString()
return name + "\n" + street + " \n" + city;

class UtilDemo
public static void main(String args[])
LinkedList L = new LinkedList();
L.add(new Address("Gili","11 Oak","L.A"));
L.add(new Address("Josh","97 JK avenue","Delhi"));
L.add(new Address("ritu","Bahadurgarh","HAryana"));

Iterator I= L.iterator();
Object O =;
System.out.println(O + "\n");

can't make out why are we using toString() method here and if not used why the program returns value like Address5437@*&()%^.

Could you help me understand Map.Entry by giving simple examples.(Please)
karthikeyan Chockalingam
Ranch Hand

Joined: Sep 06, 2003
Posts: 259
Below is the java doc for toString() method in Object. Hence we are using toString method to override inorder to ptovide a concise but informative representation that is easy for a person to read.

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
This is called overriding a method because the toString() method is already implemented in the Object superclass. However, this default implementation is typically not very helpful since it only gives the name of the class and some numerical value that represents the instance of the class.

However, you might wonder where the toString() method is even executed. It is hidden inside this line:

When you use the + operator with a String and an Object, the toString() method on the Object is called. By a mechanism called "polymorphism", the toString() method that is defined in the Address class will be called here.

I hope this helps.


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: collection
jQuery in Action, 3rd edition