-1

I've run into this code from geeksforgeeks. And I didn't figure out why toString method is invoked due to System.out.println(c2) . I've expected that output is c2 object's address.

final class Complex {
    private  double re,  im;
    public Complex(double re, double im) {
        this.re = re;
        this.im = im;
    }
    Complex(Complex c)
    {
      System.out.println("Copy constructor called");
      re = c.re;
      im = c.im;
    }            
    public String toString() {
        return "(" + re + " + " + im + "i)";
    }            
}
class Main {
    public static void main(String[] args) {
         Complex c1 = new Complex(10, 15);
        Complex c2 = new Complex(c1);    
        Complex c3 = c1;  
        System.out.println(c2);
    }
}

Output is:

  Copy constructor called  
(10.0 + 15.0i)
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
choptxen
  • 57
  • 8
  • Would it be more obvious if `toString` had an `@Override` annotation on it? – Powerlord Apr 02 '18 at 19:30
  • Whenever you override `public String toString()` this method is invoked - simple as that... – zlakad Apr 02 '18 at 19:31
  • And just as importantly, any of the print methods that accept `Object` will call `toString` on said object. The default `toString` on `Object` just prints the address of it, but any class can override `toString` to provide their own behavior. – Powerlord Apr 02 '18 at 19:32

3 Answers3

2

Because when you call Systme.out.println for object type, it will try to convert the object the you passed to string by calling the following static method String.valueOf(x) and if you look into String.valueOf(x) you will find the following code :

/**
 * Returns the string representation of the {@code Object} argument.
 *
 * @param   obj   an {@code Object}.
 * @return  if the argument is {@code null}, then a string equal to
 *          {@code "null"}; otherwise, the value of
 *          {@code obj.toString()} is returned.
 * @see     java.lang.Object#toString()
 */
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();

if the object is not null called its toString() method

please read this how-does-system-out-print-work link for more info

Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39
1

println(Object o) is overloaded to call print(String.valueOf(o)) and then println()` see docs.

If the object does not override toString() Object.toString() is called.

You get the address from the subsequent call to hashCode(), if that method is not overridden.

leonardkraemer
  • 6,573
  • 1
  • 31
  • 54
-1

System.out.println() tends to call toString() when Object are passed. That's how it prints relatively meaningful output.

Steve11235
  • 2,849
  • 1
  • 17
  • 18