#What happens in the background when I override to String and Syso

1 messages ยท Page 1 of 1 (latest)

latent gate
#

Hello,

When I create a Java Class and there I override the toString method, why, is the toString method automatically called when I write System.out.println(objectName);

plush pewterBOT
#

<@&987246399047479336> please have a look, thanks.

latent gate
#

Also is there ressource on that, or like can I maybe, figure it out with debugger?

torn condor
#

bc thats what the method does

#

if u look inside the println method it looks sth like this:

latent gate
#

Syso, calls the toString?

torn condor
#
void println(Object o) {
  println(o.toString());
}
torn condor
#

toString is a method defined in the all-father class Object

#

so any java class has this method

latent gate
#

Ah, thats awesome.

#

but writing like Syso("This is a word" + a); // int a = 12;

#

what would happen then?

rigid schooner
#

thats two parts

torn condor
#

the compiler replaces ur string + with an actual method

rigid schooner
#

"This is a word" + a is an expression which turns into a String

latent gate
#

mhh

torn condor
#
  • is magic that is replaced by non-magic
latent gate
#

Should I look it up in the vscode debugger?

torn condor
#

for example (a bit simplified but u get the idea):

torn condor
#

"abc" + foo is replaced by "abc".append(foo)

#

and that method is an ordinary java method that u can look up

#

which calls toString

latent gate
#

append, calls toString?

torn condor
#

yes

#
String append(Object o) {
  return this.append(o.toString());
}
#

it looks sth like that

#

a method of the string class

latent gate
#

ok, thats

#

deep

torn condor
#

there is a bit more happening under the hood, especially with + but u should get the idea

#

๐Ÿ‘

latent gate
#

ill accept this for now.

#

thx

#

.close

plush pewterBOT
# latent gate .close

Looks like you attempted to use a command? Please note that we only use slash-commands on this server ๐Ÿ™‚

Try starting your message with a forward-slash / and Discord should open a popup showing you all available commands.
A command might then look like /foo ๐Ÿ‘