2

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
5
  • 2
    I suspect the poster knows the obvious but is asking what does Java do under the hood. Ie is it calling a function to do + behind the scenes Commented Mar 16, 2015 at 18:34
  • @tnw: Of course that is the Quite Obvious part :D ! What I wanted to understand is whether Java has the operator overloading functionality inbuilt. But when we say that Java does not support operator overloading does it actually mean that "Java does not allow us to make use of this inbuilt operator overloading functionality, which it uses for String". Commented Mar 16, 2015 at 18:38
  • I don't quite understand your comment.. but to address your question, no, Java does not allow operator overloading. Please see this answer: stackoverflow.com/questions/77718/… Additionally, I recall reading somewhere before that the '+' in string concatenation is widely regarded a design flaw. Commented Mar 16, 2015 at 18:55
  • possible duplicate of Operator overloading in Java Commented Mar 16, 2015 at 20:00
  • Not sure its a duplicate as the question is asking if you can do it but how java implements it Commented Mar 17, 2015 at 6:30

1 Answer 1

5

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().

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.