问题
this is what I've tried;
public String frontBack(String str) {
char begin = str.charAt(0);
char end = str.charAt(str.length()-1);
return begin+str.substring(1,str.length()-1)+end;
}
I've thought it would fail since begin and end are chars but it doesn't. How is that possible? Can anyone explain me please? Thanks!
回答1:
Java's '+' operator also serves as a concatenation operator. It can concatenate primitives and objects and would return you a string which is its result.
The following explanation assumes that you are familiar with Java's wrapper classes. In case you are not familiar with them, please give it a read.
Java's '+' operator converts all the primitive data types used in the statement to their equivalent Wrapper classes and invokes toString() method on those instances and uses that result, which is a string in the expression.
Ex: In Java, a statement like System.out.println( 3 + " Four " + 'C' );
ends up creating a String with the content "3 Four C"
.
In the above statement, 3 is a primitive int variable. " Four " is a String object and 'C' is a primitive char variable.
During '+' concat operation, 3 gets converted to its corresponding Wrapper class -> Integer. And then toString() method is called on it. Output is String 3 i.e., "3" " Four " is already a String and needs no further processing. 'C' gets converted to Character wrapper class and toString() method results in returning the String "C".
So finally, these three are added so that you get "3 Four C".
To Sum up:
- If a primitive is used in '+' operator, it would be converted to its Wrapper class and then toString() method is called on it and the result would be used for appending.
- If an object other than String is used, its toString() method would be called and its result would be used for appending.
- If a String is called, well, there is not much to do and the string itself gets used for appending.
来源:https://stackoverflow.com/questions/33067516/why-is-possible-to-concatenate-char-and-string-in-java