What is the use of toString method in Java and how can I use it

0 votes

I need to understand the concept of the toString() method, defined in the Object class in JAVA? Also how is it used, and what purpose does it serve ?

Apr 25, 2018 in Java by developer_1
• 3,320 points
3,743 views

2 answers to this question.

0 votes
The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.
There is no set requirement for what a toString() method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString() methods are auto-generated in IDEs.


For example, the following

public final class Coordinates {

    private final double x;
    private final double y;

    public Coordinates(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public static void main(String[] args) {
        Coordinates coordinates = new Coordinates(1, 2);
        System.out.println("Bourne's current location - " + coordinates);
    }
}

prints

Bourne's current location - Coordinates@addbf1 //concise, but not really useful to the reader

Now, overriding toString() in the Coordinates class as below,

@Override
public String toString() {
    return "(" + x + ", " + y + ")";
}

results in

Bourne's current location - (1.0, 2.0) //concise and informative

The usefulness of overriding toString() becomes even more when the method is invoked on collections containing references to these objects. For example, the following

public static void main(String[] args) {
    Coordinates bourneLocation = new Coordinates(90, 0);
    Coordinates bondLocation = new Coordinates(45, 90);
    Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
    locations.put("Jason Bourne", bourneLocation);
    locations.put("James Bond", bondLocation);
    System.out.println(locations);
}

prints

{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}

instead of this,

{James Bond=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}
answered Apr 25, 2018 by Rishabh
• 3,620 points
0 votes

Whenever you require to explore the constructor called value in the String form, you can simply use String toString() method.

import java.util.*;

class Bank {

    String n;
    String add;
    int an;
    int bal;
    int dep;

    public Bank(String n, String add, int an, int bal) {

        this.add = add;
        this.bal = bal;
        this.an = an;
        this.n = n;

    }
public String toString() {
        return "Name of the customer.:" + this.n + ",, "
                + "Address of the customer.:" + this.add + ",, " + "A/c no..:"
                + this.an + ",, " + "Balance in A/c..:" + this.bal;
    }
}

public class Demo2 {

    public static void main(String[] args) {

        List<Bank> l = new LinkedList<Bank>();

        Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
        Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
        Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
        Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
        Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
        l.add(b1);
        l.add(b2);
        l.add(b3);
        l.add(b4);
        l.add(b5);
Iterator<Bank> i = l.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
        }
    }

}
answered Aug 23, 2018 by Daisy
• 8,120 points

Related Questions In Java

0 votes
2 answers

How can I invoke a method when the method name is in the form of a given string?

You could probably use method invocation from reflection: Class<?> ...READ MORE

answered Aug 19, 2019 in Java by Sirajul
• 59,230 points
2,486 views
0 votes
2 answers

What is the use of @Override annotation in Java ? When do we use it ?

@Override annotation is used when we override ...READ MORE

answered Aug 14, 2019 in Java by Sirajul
• 59,230 points
3,053 views
0 votes
0 answers

What is TypeScript and why would I use it in place of JavaScript?

Could you kindly explain the TypeScript language? What ...READ MORE

Nov 16, 2022 in Java by Nicholas
• 7,760 points
241 views
0 votes
2 answers

How can I create File and write data in it using Java?

import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFiles{ ...READ MORE

answered Jul 26, 2018 in Java by samarth295
• 2,220 points
2,511 views
0 votes
2 answers

How do I replace character from string at specific indexes?

You could turn the String into a ...READ MORE

answered Aug 22, 2019 in Java by Sirajul
• 59,230 points
22,193 views
0 votes
1 answer

What is the 'instanceof' operator used for in Java?

It's an operator that returns true if ...READ MORE

answered May 23, 2018 in Java by Rishabh
• 3,620 points
783 views
0 votes
1 answer

String mapping without Case-Sensitivity

Yes, contains is case sensitive. You can ...READ MORE

answered Feb 5, 2019 in Java by developer_1
• 3,320 points
404 views
0 votes
3 answers

Check if a String is numeric in Java

Java 8 Lambda Expression is used: String someString ...READ MORE

answered Sep 3, 2018 in Java by Daisy
• 8,120 points
3,346 views
0 votes
1 answer

How can I get the current date and time in UTC or GMT in Java?

This definitely returns UTC time: as String ...READ MORE

answered Jun 7, 2018 in Java by Rishabh
• 3,620 points
27,041 views
0 votes
1 answer

What is the concept of Immutability for strings in Java ? Why are strings immutable ?

According to Effective Java, chapter 4, page 73, ...READ MORE

answered May 11, 2018 in Java by Rishabh
• 3,620 points
1,289 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP