Java,字符串的运算符重载和“+”运算符

Java, operator overloading and "+" operator for String

我对 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

这个运算符不是"overloaded",它是预定义的运算符,称为字符串连接运算符

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() 连接来构造结果字符串的代码。