Could anyone help me in my doubt ? We know java does not support operator overloading but considering the below segment : string x = string2 + string3 how does this happens with + operator ?? since its is not an operator overloading then how come is the concatenation taking place ? This is an interview question.so kindly help me. thx
Success is not doing extraordinary things but doing ordinary things extraordinarily well.
Joined: Sep 28, 2003
When u say string 1 = string2 + String 3; It does not append characters to the string referenced by string1. That's because Java strings are immutable, they don't change after they're created. What actually happens is that: 1 .StringBuffer is set up 2. string1 is copied to it 3. string 2 and string 3 are appended to the buffer The result is converted to a string The string1 reference is made to point at that string. The old string that string1 previously referenced is then made available for garbage collection. hope this helps.
Joined: Oct 07, 2003
Thx meena but would u tell me why "+" is used.. i mean to ask what is the role of +(plus) and how it acts.thx for earlier suggestion
Joined: Feb 10, 2001
Hi Saurabh, It is true that java dont allow operator overloading,but this dosent restrict java compiler and java interpreter from using it. what i mean to say is u cannot use operator overloading for programming in java,but it is used internally buy java. So i think u face this type of question in interview then u should also be prepare for questions like how how does 3-4 works in java and what is role of -. hope i did't confused u,do get back if ur not clear regards
All desirable things in life are either illegal, banned, expensive or married to someone else !!!
Along the lines of what Praful is saying, when the + is applied to operands of type String, it means concatenation. When applied to numeric operands, the + means addition. Because String is a different type that, say int, Java can define the operation of + differently as it applies to these two types. Thus one could say, as Praful does, that the compiler "overloads" the + operator internally, although this term is not usually applied to this situation. Operator overloading, which is found in C++ for example, but not in Java, is a specific feature which lets you, the programmer define the meaning of an operator relative to class types that you create. Operator overloading is not supported by Java, partly because it was deemed to be a source of ambiguity, potentially causing more trouble than it is worth.
For my latest books on Java, including my Java Programming Cookbook, see HerbSchildt.com