2

I'm invoking

sb.append(i+"\n");

where

StringBuilder sb= new StringBuilder();
int i. 

What is i+"\n" cast to here-- a String, a StringBuffer, CharSequence, character array, ...?

StringBuilder has append() each taking a param which is an Object, a String, a StringBuilder (this one is a private method), a StringBuffer, a CharSequence parameter, character array, .. among others. I'm trying to find out which of these being invoked-- looking to avoid the call on String param for fast processing.

Thanks in advance.

4

1 回答 1

8

Whenever the operator + is applied to a String and a variable of any other type, you have String concatenation. The value of i + "\n" is a String.

The java language specification covers this

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time. The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

Therefore the append() method being called is the one which accepts a String argument.

As @scottb comments, Java first converts the objects involved in a String concatenation into String objects. This is described in the JLS chapter on String conversion. Primitives are unboxed to their wrapper types. If the reference is anything other than null, the toString() method is called on the referenced object. If the reference is null, then the String "null" is used.

于 2013-11-12T01:57:22.873 回答