aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes + operator & toString() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "+ operator & toString()" Watch "+ operator & toString()" New topic
Author

+ operator & toString()

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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
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
satya5 thanks for ur reply.But i was confused after reding the rules for + operator given in RHE.
With rgds kanth
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: + operator & toString()
 
Similar Threads
equals()
== and equals question required
Rhe question -- identifiers
Clarification on Q6 Self-Test Chapter 3 K&B SCJP5
HashMap