Hi everybody. Anyone kindly explain me the rule for + operator when used with objects & a String.I have the below doe for reference . class MyClass { int i=10; public String toString() { return String.valueOf(i); } } public class Ktest10 { public static void main(String[] args) { 1. MyClass m1=new MyClass(); 2. MyClass m2 = new MyClass(); 3. String s=m1 + m2; // gives compile error 4. System.out.println(m1); 5. String s1=m1 + "hello"; 6. System.out.println(s1) // prints 10hello } } At line 4 why doesn't toString method is invoked. i thought it is the behaviour of the + operator to invoke toString() as this is overidden in MyClass.Also System.out.println() at line 4 invokes toString() so 10 is printed. rest of lines 5 , 6 are as expected. So is it true that if one of the operand of the + operator is object the second one should be String. Please clarify this to me. with regds Kanth
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
At line 4 why doesn't toString method..... Assuming you meant line 3 .... In line 3, m1 and m2 are references to obj's of Myclass. And this class doesnot over-ride the "+" operator (not sure if you could do this, never tried). Also no string is involved in the expression. Hence the toString() is not invoked. How do you expect the compiler to know that it should use the toString() method. To the compiler it is an arithmetic operation. One way I know to force invocation of toString() is to replace line 3 with the foll. 3. String s= " " + m1 + m2; // replaced line. Now you see since we have a String in front, the compiler should invoke the toString() method. Also in System.out.println(), it is implicitly defined that the toString() method be called. Just so you understand the concept of System.out... try these: System.out.print(5+7); System.out.print(""+5+7); System.out.print(5+"" +7); System.out.print(5+7+""); These are important for the exam and you should be able to answer such qstns. Hope this helps. Regds. - satya
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
satya5 thanks for ur reply.But i was confused after reding the rules for + operator given in RHE. With rgds kanth