Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

java - The concatenation of chars to form a string gives different results

Why, when I use the operation below to sum chars, does it return numbers instead of chars? Shouldn't it give the same result?

ret += ... ; // returns numbers

ret = ret + ...; // returns chars

The code below duplicates the chars:

doubleChar("The") → "TThhee"

public String doubleChar(String str) {

    String ret = "";
    for(int i = 0; i < str.length(); i++) {
        ret = ret + str.charAt(i) + str.charAt(i); // it concatenates the letters correctly
        //ret += str.charAt(i) + str.charAt(i); // it concatenates numbers
    }
    return ret;
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The result of the following expression

ret + str.charAt(i) + str.charAt(i); 

is the result of String concatenation. The Java language specification states

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.

The result of

str.charAt(i) + str.charAt(i); 

is the result of the additive operator applied to two numeric types. The Java language specification states

The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands. [...] The type of an additive expression on numeric operands is the promoted type of its operands.

In which case

str.charAt(i) + str.charAt(i); 

becomes an int holding the sum of the two char values. That is then concatenated to ret.


You might also want to know this about the compound assignment expression +=

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

In other words

ret += str.charAt(i) + str.charAt(i);

is equivalent to

ret = (String) ((ret) + (str.charAt(i) + str.charAt(i)));
                      |                ^ integer addition
                      |
                      ^ string concatenation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...