Java, operator overloading and “+” operator for String

喜夏-厌秋 提交于 2021-02-10 20:18:30

问题


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

回答1:


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

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.

In other words, when Java sees

String res = stringObj + someObj;

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



来源:https://stackoverflow.com/questions/29084340/java-operator-overloading-and-operator-for-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!