Overwrite toString() method in a Java class

  • The wrapper classes like ‘Integer’, ‘Double’, ‘Float’ will be having ‘toString()’ method in their classes. Implementation in that method is like they take input as respective type and return String value.
    eg: Integer i = 10;
    String ival = i.toString();
    Note that toString() method has the code to convert Integer to String.
  • You can not overwrite the toString() method of Integer class or any other wrapper classes. [you can’t extend Integer class as it is declared as Final. So you can not overwrite its toString() method. This applies to all wrapper classes.]
  • If you want to store your class object as key in map. you can do it, but when you try to print the keys present in the Map then it’ll return the hashcode of address where the class object stored in hash memory, instead returning exact key. So you need to overwrite the ‘toString()’ method to give your own implementation. By default toString() method returns hashcode, so by overwriting this method in your class you can return any value for the class object instead of its hashcode.
  • Check the below Java code.

package model;

import java.util.HashMap;
import java.util.Map.Entry;

public class Price {

int itemsCount;
String itemName;

Price(int item, String name) {
this.itemsCount = item;
this.itemName = name;

public static void main(String[] args) {
HashMap<Price, String> hm = new HashMap<>();
hm.put(new Price(10, "Oranges"), "Fruit Orange");
hm.put(new Price(20, "Mangos"), "Fruit Mango");
hm.put(new Price(30, "Bananas"), "Fruit Banana");
hm.put(new Price(30, "Grapes"), "Fruit Grapes");

for (Entry<Price, String> entry : hm.entrySet()) {
System.out.println("Key:" + entry.getKey() + " & Value:" + entry.getValue());


public String toString() {
return this.itemName+this.itemsCount;
//return "ravi";



Output if you don’t overwrite the toString() method:

Key:model.Price@7852e922 & Value:Fruit Banana
Key:model.Price@15db9742 & Value:Fruit Orange
Key:model.Price@6d06d69c & Value:Fruit Mango
Key:model.Price@4e25154f & Value:Fruit Grapes

Output after overwriting the toString() method:

Key:Bananas30 & Value:Fruit Banana
Key:Oranges10 & Value:Fruit Orange
Key:Mangos20 & Value:Fruit Mango
Key:Grapes30 & Value:Fruit Grapes

// If you return ‘ravi’ in toString() method then it’ll return ‘ravi’ as key for all records.







Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s