我对 Java 中的运算符重载有疑问。我知道Java不支持运算符重载,但是“+”运算符在下面有效的Java程序中做什么:
import java.util.*;
import java.lang.*;
import java.io.*;
class OperatorOverloadingTest
{
public static void main (String[] args) throws java.lang.Exception
{
String str1 = "Operator ";
String str2 = "overloading";
String str3 = str1+str2;
System.out.println(str3);
}
}
Stdout:
Operator overloading
最佳答案
这个运算符不是“重载”的,它是预定义的运算符,称为字符串连接运算符。
15.18.1 String Concatenation Operator
+
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.
换句话说,当Java看到
String res = stringObj + someObj;
它将表达式替换为代码,该代码通过将现有字符串值与 someObj.toString()
连接来构造结果字符串。
关于Java,字符串的运算符重载和 "+"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29084340/