tags:

views:

1402

answers:

4

Hello,

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?

+1  A: 

No difference except, like you say, the null safety. Always prefer the former to the latter.

cletus
+10  A: 

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.

Dustin
+2  A: 

As others have said - use the "" + obj method.

According to http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1]">The Java Language Spec:

  • If the term is null, use "null"
  • Primitive types are converted using the boxed-type constructor new Boolean(X) or whatever
  • toString() is invoked (or equivalent)
  • if the result of toString() is null, use "null"
  • Concatenate the strings.
Draemon
The 4th item on your list piqued my interest. For things that aren't strings, it appends String.valueOf(String.valueOf(ob)). It's cheap and meets the requirements, I suppose.
Dustin
heh - nifty. If I'm honest, I didn't know until I looked at the spec either - the distinction has never mattered. A good example of why I always go to the primary source if I can.
Draemon
+1  A: 

Actually, if your invariant says the object should never be null, it doesn't matter. So it depends on whether or not you accept obj to be null.

Pål GD