javastringbuilder

What actually happens in this case with StringBuilder?


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)


Solution

  • 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.