0

I found how System.out.println(Object obj) works at this link: How an object will call toString method implicitly?

But, I'm still somewhat confused. So, I guess this is more of an append/concatenation (I do not know the correct term) but there's a bunch of things going on as I step into the next line of code when I call both System.out.println(Object obj) and System.out.println("foo" + bar) that I'd like to have a clear-cut picture going on.

For some background--I have created a class called Place that has its own toString().

System.out.println("foo" + bar);

    Place test = new Place("Disneyland");
    System.out.println("Testing " + test);

This code goes from the println statement to the toString() method in my Place class, but then Eclipse pulls up a new page where it says String.valueOf(Object) line: not available; Source not found. Then, after I step into again, I get the same sort of error page but instead for StringBuilder.append(Object). I then step into again and everything that I want outputted has outputted correctly. What makes these intermediary exception pages pull up?

  • There is nothing wrong about how `println()` works. That exception just mean you don't have the source code for the functions `String.valueOf(Object)` and `StringBuilder.append(Object)` for the debugger to show you during stepping. The debugger can show your own code since it's there you are writing, but not the library functions if the source code is not available. See [https://stackoverflow.com/a/6179462/10317684](https://stackoverflow.com/a/6179462/10317684) – Ricky Mo Nov 28 '18 at 03:18
  • The `valueOf` might come from something you're doing inside the `toString` implementation of your `Place` class. – Sotirios Delimanolis Nov 28 '18 at 03:28
  • @RickyMo Ahh i get it now, thank you!! – CoolRobloxKid12 Nov 28 '18 at 03:50

1 Answers1

0

The + operator in that context does string concatenation. String concatenation is fully described in the Java Language Specification. The conversion of bar is referenced in that section and is described fully in another section.

The reason you're seeing what you're seeing in the debugger is that you do not have the JDK sources mounted correctly in Eclipse, so it cannot step into JDK classes. String.valueOf() is used for the string conversion at runtime, and string concatenation is ultimately implemented by the javac compiler using the StringBuilder class (which is why you are seeing that). As the specification explains, the string conversion ultimately uses the object's toString() method. So that's why you're journeying through that code in the debugger. If you had the JDK sources mounted it'd be a little clearer because the actual JDK source code would appear rather than your "Source not found" messages.

David P. Caldwell
  • 3,394
  • 1
  • 19
  • 32