Why does + work with Strings in Java? -


The Java operator can not overload, but + works fine for the string and integer and some other classes. How is this possible?

Update:
Why does this work?

  integer i = 4; Integer P = 5; Println (I p *); // print 20    

+ is not an example operator Overloading + is an equation operator and created in the language as an arithmetic-additional operator.

This means that someone is writing a program with Java, can not take overload of operators, but as far as the grammar of the Java language is concerned, + A combination is defined as an additional operator.

Edit

This works for the reason of other classes such as integer and double Does.

If you take a look at the biodecodes of a java program that makes string constants, you will see that it creates StringBuilder and addend () Java compiler sees the + operator and finds that operands are string and not primitive types (such as int ).

If you add an integer of biometrics to a program, you will see that it uses the iadd command to perform an extra work of integer. The reason for this is that the compiler knows that the operations for the operation + are integer.

As far as some Integer i = 4 , bytecode will show that you are actually doing integer I = integer.value (4) . It is called Autoboxing. Later, when you do something like i + p , where both i and p type integer < / Code>, the generated bytecode will show that you are i.intValue () + p.intValue () , where both types of return types are int ( Actual Bytecock Instructions iadd )

This is the reason that + works integer even if they are not the actual primitive type .

Comments