Overriding toString() in Java

Course Curriculum

Overriding toString() in Java

Overriding toString() in Java

This post is similar to Overriding equals method in Java. Consider the following Java program:

// file name: Main.java

class Complex {
private double re, im;

public Complex(double re, double im) {
this.re = re;
this.im = im;
}
}

// Driver class to test the Complex class
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
System.out.println(c1);
}
}
Output:

Complex@19821f

The output is, class name, then ‘at’ sign, and at the end hashCode of object. All classes in Java inherit from the Object class, directly or indirectly (See point 1 of this). The Object class has some basic methods like clone(), toString(), equals(),.. etc. The default toString() method in Object prints “class name @ hash code”. We can override toString() method in our class to print proper output. For example, in the following code toString() is overridden to print “Real + i Imag” form.

// file name: Main.java

class Complex {
private double re, im;

public Complex(double re, double im) {
this.re = re;
this.im = im;
}

/* Returns the string representation of this Complex number.
The format of string is "Re + iIm" where Re is real part
and Im is imagenary part.*/
@Override
public String toString() {
return String.format(re + " + i" + im);
}
}

// Driver class to test the Complex class
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
System.out.println(c1);
}
}
Output:

10.0 + i15.0
In general, it is a good idea to override toString() as we get get proper output when an object is used in print() or println().

Overriding equals method in Java (Prev Lesson)
(Next Lesson) Instance Variable Hiding in Java
', { 'anonymize_ip': true });