Java、运算符重载和“+"字符串运算符 [英] Java, operator overloading and "+" operator for String

查看:114
本文介绍了Java、运算符重载和“+"字符串运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 中的运算符重载有疑问.我知道 Java 不支持运算符重载,但是下面有效的 Java 程序中的+"运算符是做什么的:

I have a doubt regarding operator overloading in Java. I know that Java does not support operator overloading but then what is the "+" operator doing in below valid Java program:

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

推荐答案

这个操作符不是重载"的,它是预定义的操作符,叫做String Concatenation Operator.

This operator is not "overloaded", it is pre-defined operator, called String Concatenation Operator.

15.18.1 字符串连接运算符 +

如果只有一个操作数表达式是字符串类型,则在运行时对另一个操作数执行字符串转换(第 5.1.11 节)以生成字符串.字符串连接的结果是对 String 对象的引用,该对象是两个操作数字符串的串联.左侧操作数的字符位于新创建的字符串中右侧操作数的字符之前.

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看到

In other words, when Java sees

String res = stringObj + someObj;

它用代码替换表达式,该代码通过将现有字符串值与 someObj.toString() 连接起来来构造结果字符串.

it replaces the expression with code that constructs the resulting string by concatenating an existing string value with someObj.toString().

这篇关于Java、运算符重载和“+"字符串运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆