-1

Why does the this keyword print exactly what the toString method is printing?

public class A {
    public static void main(String[] args) {
      Stuff s = new Stuff("in",5 );
      System.out.println(s);

      double doubleValue = 2.5 ;
      s.doSomething(doubleValue);
      System.out.println(doubleValue);

      s = new Stuff("more", 3);
      String str = "word";
      System.out.println(s.changeSomething(str));
      System.out.println(s);
      System.out.println(str);
   }
}

class Stuff {
    private static final int n =2 ;
    private String string;
    private int num;

    public Stuff(String s, int num) {
        this.num = num;
        string = s;
    }

    public void doSomething(double d) {
        d = d * num;
        System.out.println(this);
    }

    public double changeSomething(String s) {
        s = string;
        return n * num;
    }

    public String toString() {
        return string + " has " + num;
    }
}

This is the output I get

in has 5
in has 5
2.5
6.0
more has 3
word
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

4

System.out.println method does not know how to output an instance of a custom type, so the next best thing it can do is to call the toString method, which is available on all objects in Java and returns the string representation. In this case you have overridden it, so it actually executes your toString method and prints the result.

Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91
0

You can read the documentation of System.out.println(). System.out is a PrintStream. PrintStream::println(Object) calls PrintStream::print(Object), which calls String.valueOf(Object), which returns the string "null" if the reference is null; otherwise returns obj.toString().

newacct
  • 119,665
  • 29
  • 163
  • 224