• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

+ overloded operator

 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println(" " +2 + 3);
System.out.println(2 + 3);
System.out.println(2 + 3 +"");
System.out.println(2 + "" +3);
A) Compilation error at line 3
B) Prints 23, 5, 5 and 23.
C) Prints 5, 5, 5 and 23.
D) Prints 23, 5, 23 and 23.
Why is B here the answer , i thought that the + operator is overloved, and if only one off the values is a string, it all values are considered as strings ???
I thought that line 3 is also 23 ???
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, the evaluation occurs from left to right. Thus, 2+3 is interpreted as a normal addition which yields 5.
The following link may help you:
JLS 15.18.1 String Concatenation Operator +
[ June 19, 2002: Message edited by: Valentin Crettaz ]
 
Frank Jacobsen
Ranch Hand
Posts: 358
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, im a not confused annymore !!!
Hopefully SCJP2 the 26 of june "Next week, uhhhh, im in trouble " !!!
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Frank
Remember that the operation are performed left to right.
In the first one one of the operands of the first + is a String so the operands will be concatenated together. The result of that is String so the last operand will be concatenated to the result of the first +.
In the second and third line neither of the operands of the first + is a String so the first thing done is straight addition (in the second one that's all that's done). After the addition it checkes again to see if either of the operands is a String. In the case of line 2 it is done in the case of line 3 there is a String so it takes the result of the first + and concatenates it with the "".
In the forth line, like the first line, one of the first two operands is a string so the result of 2 + "" is String which means that the final operand is also concatenated.
hope that helps
 
Deepali Pate
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good Luck for your exams.
Dont take chances if u are taking exam next week and u are asking this question i am bit concerned.
Have you prepared well on Threads and I/O?? Dont take them easy. Especially Synchronized blocks, Object locks and sleep(), yield() and wait()-notify(). Javaranch has really helped me with this no book can explain the way they do here
Also hope u have some very funny concepts(String pool, String GC, immutable) abt strings clear. Even on these topics i reckon NO BOOK OR DOCUMENTATION can help u like Javaranch.
Thanks to every responsible member of Javaranch.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic