This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Originally posted by Raj Kumar Bindal: But,How does it happen internally in java,that i want to know.
Java does not support Operator Overloading. The "+" operator on strings is specifically handled by the compiler.
As for what happens, the compiler will instantiate a StringBuffer or StringBuilder (for Java 5 and later) object, and call the append() methods with the string operands, followed by a toString() for the result.
[EDIT: Beaten to the answer again. These forums are fast... ]
Henry [ January 12, 2007: Message edited by: Henry Wong ]
There is no Java syntax for overloading the operator. The compiler just "knows" that the operator is overloaded for the String class.
With other words, the operator overloading isn't implemented in the source code for the String class, but hardcoded into the compiler.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Originally posted by Raj Kumar Bindal: + operator is overloaded for strings in java.But,i am not clear where it is defined and how the operator overloading happens internally.Please tell me.
If you mean what rule is applied by the compiler to decide whether to use arithmetic addition or string concatenation, it is like this: If one or both operands are a string, + means string concatenation, else + means addition.
So, if you write "Hello" + 1 + 2, this evaluates to "Hello12" because the operators are evaluated left to right. If you change the order of evaluation with parentheses and write "Hello" + (1 + 2), the rightmost + is evaluated first, and interpreted as an addition because both operands are int literals, so the expression evaluates to "Hello3". [ January 14, 2007: Message edited by: Enrico Savazzi ]