[英]What is the implementation when + operator is used between two String Objects in Java?
Java does not support user defined overloaded operators. Java 不支持用户定义的重载运算符。 Java does allow the use of using the + operator between two String Objects. Java 确实允许在两个字符串对象之间使用 + 运算符。 When this happens, is there some internal/built in overloading to the + happening or what happens in order for two String objects to be added with the use of +?当发生这种情况时,是否有一些内部/内置的重载发生在 + 上,或者为了使用 + 添加两个 String 对象会发生什么?
There is no overloading of operator.没有运算符的重载。 The behavior of the +
operator is well-defined in the Java Language Specification , section 15.18. +
运算符的行为在Java 语言规范15.18 节中有明确定义。 Additive Operators : 加法运算符:
The operators
+
and-
are called the additive operators .运算符+
和-
称为加法运算符。
If the type of either operand of a
+
operator isString
, then the operation is string concatenation .如果+
运算符的任一操作数的类型为String
,则该操作为字符串连接。
Section 15.18.1.第15.18.1 节。 String Concatenation Operator +
then goes on saying: 字符串连接运算符+
然后继续说:
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.如果只有一个操作数表达式是String
类型,则在运行时对另一个操作数执行字符串转换 ( §5.1.11 ) 以生成字符串。The result of string concatenation is a reference to a
String
object that is the concatenation of the two operand strings.字符串连接的结果是对String
object 的引用,它是两个操作数字符串的连接。 The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.在新创建的字符串中,左侧操作数的字符位于右侧操作数的字符之前。
"+" operator (in this context) is not "overloaded", it is pre-defined operator, called String Concatenation Operator . “+”运算符(在此上下文中)不是“重载”,它是预定义的运算符,称为String Concatenation Operator 。
15.18.1 String Concatenation Operator
+
15.18.1 字符串连接运算符+
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.如果只有一个操作数表达式是字符串类型,则在运行时对另一个操作数执行字符串转换(第 5.1.11 节)以生成字符串。 The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings.字符串连接的结果是对字符串 object 的引用,它是两个操作数字符串的连接。 The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.在新创建的字符串中,左侧操作数的字符位于右侧操作数的字符之前。
In other words, when Java sees也就是说,当 Java 看到
String res = stringObj + someObj;
it replaces the expression with code that constructs the resulting string by concatenating an existing string value with someObj.toString()
.它用通过将现有字符串值与someObj.toString()
连接来构造结果字符串的代码替换表达式。
Reference: https://stackoverflow.com/a/29084397/11504153参考: https://stackoverflow.com/a/29084397/11504153
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.