CodeGym /Java Blog /Java Objects /Java toString() Method
Author
Milan Vucic
Programming Tutor at Codementor.io

Java toString() Method

Published in the Java Objects group
Pretty often while creating a program, it’s necessary to find out the contents of an object. For these purposes, the Java Object class, the most basic Java class in the class hierarchy, defines a special toString() method. It returns a character string that describes the object. The default implementation of toString() method in Java produces output like this:

package.class@hashCode
i.e. toString, that was defined in java.lang.Object gives the hash code of the object in hexadecimal form. This is often not very clear and useful. So when creating a new class, it is customary to override toString() so that the return string contains the class name, names and values of all variables. Overriding the toString method correctly can help with logging and debugging a Java program, it provides valuable and important information. Simply put, the toString() method is used in Java to get a string object representing the value of a numeric object. In other words, it converts a number to a string. If the method takes a simple data type as an argument, then a string object is returned that represents the value of the simple data type.

Example of Java toString() method

Usually if you create a class, in addition to the toString() method in Java you need to override the equals, hashCode and compareTo methods in order to know how to work with its objects. But for now, let's focus on toString. In most cases, submitting textual information about an object is quite simple. You just need to understand what exactly the user would like to see when logging. Let's give an example and create a Class that describes a point on the plane. It has two coordinates: coordinateX, coordinateY. Naturally, they should be displayed on the screen if a user asks “what object’s this” just like the name of the class itself. This is what we’re going to demonstrate in the overridden toString() method. Now we create the class itself, its fields (coordinates), a constructor, getters for obtaining coordinates (sure, it’s possible not to create them, but from the standpoint of the correct use of OOP, getters are good practice). Just to illustrate, let's also create a method that creates a new point — the sum of the other two, and also override equals and hashCode methods.

public class Point implements Comparable<Point> {
   private final int coordinateX;
   private final int coordinateY;

   public Point(final int coordinateX, final int coordinateY) {
       this.coordinateX = coordinateX;
       this.coordinateY = coordinateY;
   }

   public int getX() {
       return coordinateX;
   }

   public int getY() {
       return coordinateY;
   }

   public Point sum(final Point that) {
       return new Point(coordinateX + that.coordinateX, coordinateY + that.coordinateY);
   }

// here we override toString with coordinates and class name 
   @Override
   public String toString() {
       return "Point{"
               + "X: " + getX()
               + ", Y: " + getY()
               +  '}';
   }

   @Override
   public boolean equals(Object o) {
       if (o == this) {
           return true;
       }
       if (o == null || o.getClass() != this.getClass()) {
           return false;
       }

   @Override
   public int hashCode() {
       return coordinateX + coordinateY;

   }
Now let’s create a testing class and a main method. There we’ve got two points and the third one, that we’re getting from the summation of two points. We apply toString method to this point and print it out.

//toString() method demo 
public class Test {
   public static void main(String[] args) {
       Point myPoint1 = new Point(5,7);
       Point myPoint2 = new Point(-2, 8);
       Point mySum = myPoint1.sum(myPoint2);
     //call toString explicitly
       System.out.println(mySum.toString());
   }
}
The result of this program work is below:
Point{X: 3, Y: 15}
You don't actually need to explicitly call the toString method, and most often don't. To call the toString() method, simply pass the desired object to System.out.println. So our test class will look like this:

//toString method demo 
public class Test {
   public static void main(String[] args) {
       Point myPoint1 = new Point(5,7);
       Point myPoint2 = new Point(-2, 8);
       Point mySum = myPoint1.sum(myPoint2);
       //call toString implicitly
       System.out.println(mySum);
   }
}
Java toString() Method - 1The output of the program is the same as before. What if we don't override the toString method, but want to print the object? In this case, the toString method of the Object class will be called. In our example, if we remove the toString method from our Point class, and leave everything as it is in the test class, we will get the following result:
Point@12
Here we’ve got the hash code of the object in hexadecimal.
Comments (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
matemate123 Level 50, Kraków, Poland
19 January 2023
18 in hexadecimal == 12 (0x12)
Siva sai Level 2, parvati puram, India
30 December 2022
hi pleaae give reply