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
randomcompiler
  • 309
  • 2
  • 14
  • 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 – abcdef Mar 16 '15 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". – randomcompiler Mar 16 '15 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: http://stackoverflow.com/questions/77718/why-doesnt-java-offer-operator-overloading Additionally, I recall reading somewhere before that the '+' in string concatenation is widely regarded a design flaw. – TayTay Mar 16 '15 at 18:55
  • possible duplicate of [Operator overloading in Java](http://stackoverflow.com/questions/1686699/operator-overloading-in-java) – Philipp Wendler Mar 16 '15 at 20:00
  • Not sure its a duplicate as the question is asking if you can do it but how java implements it – abcdef Mar 17 '15 at 06:30

1 Answers1

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

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523