Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit vs implicit call of toString

Tags:

java

tostring

I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.

For instance:

System.out.println("obj: "+obj); 

instead of:

System.out.println("obj: "+obj.toString()); 

Is there any difference apart from the null case?
Can the latter case work, when the former does not?

Edit:
What exactly is done, in case of the implicit call?

like image 871
Burkhard Avatar asked Nov 30 '08 09:11

Burkhard


People also ask

Is toString implicit?

When your toString() is implicit, you'll see that in the second append. Show activity on this post. toString() is invoked (or equivalent) if the result of toString() is null , use "null"

How do we call toString () method?

Your toString() method is actually being called by the println method.

Is toString method automatically called?

toString() gets invoked automatically. Object. toString() 's default implementation simply prints the object's class name followed by the object's hash code which isn't very helpful. So, one should usually override toString() to provide a more meaningful String representation of an object's runtime state.

What happens if you call toString on a String?

ToString is a method defined in the Object class, which is then inherited in every class in the entire framework. The ToString method in the String class has been overwritten with an implementation that simply returns itself. So there is no overhead in calling ToString() on a String-object.


1 Answers

There's little difference. Use the one that's shorter and works more often.

If you actually want to get the string value of an object for other reasons, and want it to be null friendly, do this:

String s = String.valueOf(obj); 

Edit: The question was extended, so I'll extend my answer.

In both cases, they compile to something like the following:

System.out.println(new StringBuilder().append("obj: ").append(obj).toString()); 

When your toString() is implicit, you'll see that in the second append.

If you look at the source code to java, you'll see that StringBuilder.append(Object) looks like this:

public StringBuilder append(Object obj) {     return append(String.valueOf(obj)); } 

where String.valueOf looks like this:

public static String valueOf(Object obj) {     return (obj == null) ? "null" : obj.toString(); } 

Now, if you toString() yourself, you bypass a null check and a stack frame and go straight to this in StringBuilder:

public StringBuilder append(String str) {     super.append(str);     return this; } 

So...very similar things happens in both cases. One just does a little more work.

like image 153
Dustin Avatar answered Sep 28 '22 08:09

Dustin