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

标签 java string operator-overloading

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

相关文章:

python - 有没有更好的方法来交换没有占位符的字符串

c++ - 在模板类上重载 << 运算符

java - 例如,将 Iterator<Object> 转换为 Set<String> 的最佳方式

Java 泛型 : How to avoid casting in this example of java 2D generic arrays?

java - 如何查看JVM中JIT编译的代码?

javascript - 使用 JavaScript 将每个数组元素的首字母大写

string - 在 Scala 中使用 '==' 代替 equals 进行字符串比较

c++ - C++中的自定义运算符重载而无开销

c++ - 返回对象的两种形式有什么区别?

java - 扫描仪在使用 next() 或 nextFoo() 后跳过 nextLine()?