为什么可以在 Java 中连接 Char 和 String?
这是我尝试过的;
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;
}
我认为它会失败,因为 begin 和 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!
推荐答案
Java 的 '+' 运算符也可用作连接运算符.它可以连接原语和对象,并返回一个字符串作为它的结果.
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.
以下解释假设您熟悉 Java 的包装类.如果您不熟悉它们,请阅读.
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 的+"运算符将语句中使用的所有原始数据类型转换为其等效的 Wrapper 类,并在这些实例上调用 toString() 方法并使用该结果,即表达式中的字符串.
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.
例如:在 Java 中,像 System.out.println( 3 + " Four " + 'C' );
这样的语句最终会创建一个内容为 "3 Four C"代码>.
Ex: In Java, a statement like System.out.println( 3 + " Four " + 'C' );
ends up creating a String with the content "3 Four C"
.
在上面的语句中,3 是一个原始的 int 变量.四"是一个字符串对象,C"是一个原始字符变量.
In the above statement, 3 is a primitive int variable. " Four " is a String object and 'C' is a primitive char variable.
在 '+' 连接操作期间,3 被转换为其对应的 Wrapper 类 -> Integer.然后对其调用 toString() 方法.输出为字符串 3,即 "3"四"已经是一个字符串,不需要进一步处理.'C' 被转换为字符包装类,并且 toString() 方法返回字符串C".
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".
所以最后,将这三个相加,得到3 Four C".
So finally, these three are added so that you get "3 Four C".
总结一下:
- 如果在 '+' 运算符中使用原语,则将其转换为 Wrapper 类,然后对其调用 toString() 方法并将结果用于追加.
- 如果使用 String 以外的对象,则会调用其 toString() 方法,并将其结果用于追加.
- 如果调用了一个字符串,那么没有什么可做的,字符串本身就被用于追加.
相关文章