-1

When println() is displaying an Object, which one of the Object's methods does println() call?

  • add()
  • toString()
  • equals()
  • compareTo()
  • String()

I'm Not Sure whether its toString or String can someone please clarify?

brainless coder
  • 6,310
  • 1
  • 20
  • 36

2 Answers2

1

None of them.
If you pass an Object to println() this

println(Object o) 

will be called which calls the String.valueOf(o) actually.

But then String.valueOf(o) calls the o.toString()if the o is not null.

So you can say its toString() indirectly.

See
println(java.lang.Object) and valueOf(java.lang.Object)

Saif
  • 6,804
  • 8
  • 40
  • 61
0

When using the signature println(Object) the toString() method is being used to output the string representation of that object.

When toString() is called on an object you've defined it will cascade up the hierarchy of superclasses until reaching java.lang.Object given that there is no overridden toString() method in any intermediate superclasses or the initial class. Upon reaching java.lang.Object the system will call the base toString() method which prints the String literal representation of that Object and is the reason why you will see some memory address in the output.

James S
  • 308
  • 1
  • 7