2

I have a small question, given the following snippet:

StringBuilder stringBuild = new StringBuilder(3); stringBuild.append("hello"); System.out.println(stringBuild+2); // if I omit the (+2) bit hence only stringBUild it works 

Does it call automatically toString() on object only in some circumstances? (circumstances: either no operation at all or a previous string contatanation)

1 Answer 1

7

The compiler never calls toString() on a method argument implicitly.

What you are probably thinking of, is that there is an overload of System.out.println which takes an Object (rather than a String) - this is the method that the compiler would link to. And this particular implementation of the method calls toString on the Object passed in (at runtime). That's just code though, it's nothing to do with compiler behaviour.

So passing in an Object to System.out.println "works". Passing in stringBuild+2 simply doesn't compile - there's no + operator on StringBuilder which takes an int. (And you can't create one yourself as Java doesn't allow for operator overloading.)

As ADTC and tom point out, there is implicit String conversion with the second argument to string concatenation (the + operator for strings). So while stringBuild doesn't have a + operator, stringBuild.toString() would, and you could call stringBuild.toString()+2.

Sign up to request clarification or add additional context in comments.

3 Comments

You may want to add that there's no custom operator overloading in Java. All arithmetic operators are used for arithmetic operations only, with the exception of + which is used for string concatenation (is there anything else?). The + sign only works on objects of the String type. So doing stringBuild.toString()+2 will work.
Example with implicit call to toString(): "hello " + new Object() { public String toString() { return "world!"; } }. Refer to JLS §15.18.1 and §5.1.11.
Thanks both - good points and I've included them in the answer. @tom, I take from JLS §5.4 that string conversion only ever happens for the strign concatenation operator. Let me know if you're aware of another context where this occurs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.