Java being object-oriented only deals with classes and objects so do if we do require any computation we use the help of object/s corresponding to the class. It is the most frequent method of Java been used to get a string representation of an object. Now you must be wondering that till now they were not using the same but getting string representation or in short output on the console while using System.out.print. It is because this method was getting automatically called when the print statement is written. So this method is overridden in order to return the values of the object which is showcased below via examples.
Example 1:
Java
| // file name: Main.javaclassComplex {    privatedoublere, im;            publicComplex(doublere, doubleim) {        this.re = re;        this.im = im;    }} // Driver class to test the Complex classpublicclassMain {    publicstaticvoidmain(String[] args) {        Complex c1 = newComplex(10, 15);        System.out.println(c1);    }} | 
Complex@214c265e
Output Explanation: The output is the class name, then ‘at’ sign, and at the end hashCode of the 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 the toString() method in our class to print proper output. For example, in the following code toString() is overridden to print the “Real + i Imag” form.
Example 2:
Java
| // Java Program to illustrate Overriding// toString() Method// Class 1publicclassGFG {        // Main driver method    publicstaticvoidmain(String[] args) {                // Creating object of class1        // inside main() method        Complex c1 = newComplex(10, 15);                // Printing the complex number        System.out.println(c1);    }}// Class 2// Helper classclassComplex {        // Attributes of a complex number    privatedoublere, im;        // Constructor to initialize a complex number    // Default    // public Complex() {    //     this.re = 0;    //     this.im = 0;    // }        // Constructor 2: Parameterized    publicComplex(doublere, doubleim) {                // This keyword refers to        // current complex number        this.re = re;        this.im = im;    }    // Getters    publicdoublegetReal() {        returnthis.re;    }    publicdoublegetImaginary() {        returnthis.im ;    }    // Setters    publicvoidsetReal(doublere) {        this.re = re;    }    publicvoidsetImaginary(doubleim) {        this.im = im;    }    // Overriding toString() method of String class    @Override    publicString toString() {        returnthis.re + " + "+ this.im + "i";    }} | 
 
 
10.0 + 15.0i
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


 
                                    







