1
 MyClass mcc1d = new MyClass(18, "hello");
 System.out.println(mcc1a);

Why is the following the output of the code above?

MyClass@23fc625e
Turamarth
  • 2,282
  • 4
  • 25
  • 31
Omar
  • 31
  • 5
  • 2
    Does this answer your question? [Why does the default Object.toString() include the hashcode?](https://stackoverflow.com/questions/4712139/why-does-the-default-object-tostring-include-the-hashcode) – happy songs May 05 '22 at 14:47

1 Answers1

0

This is because in Java, System.out.println() applied on an object calls .toString(). The default of the .toString()-method returns the class name followed by @ followed by the hash representation of the object.

LinFelix
  • 1,026
  • 1
  • 13
  • 23
  • Let's not narrow it with `System.out.println(` method. Maybe this expression is more suitable: Any object can be converted to String in Java using `.toString()` method inherited by the Object class. By default, their Class Name and Hashcode are returned in this method. Therefore, you should override it and return whatever you want. – wolfenblut May 11 '22 at 11:13
  • How did I narrow it down? – LinFelix May 11 '22 at 14:06
  • not only `println()` method calls toString method. Instead, any conversion from an Object to String is done this way. – wolfenblut May 11 '22 at 14:21
  • Yes. However, the question asked why `println()` specifically behaves this way – LinFelix May 11 '22 at 14:23