Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Majji Exam #24, Please help clarify

 
Mike Kelly
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the output for the following lines of code?
1: System.out.println(" " +2 + 3);
2: System.out.println(2 + 3);
3: System.out.println(2 + 3 +"");
4: 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.
B is correct answer, however I don't understand why the third line prints 5 instead of 23. What's the difference between line 1 and line 3?
Thanks Michael
 
rafa
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
are u sure that answer is b.
According to me it is c.
 
Raja Islam
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer B is a valid answer.
 
Mathew Sam
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
+ operator is overloaded. If one of the operand is of type String it performs concatenation.
1: System.out.println(" " +2 + 3);
If you take line number 1, associativity is from left to right so first it does " "+2 and the output will be string.that stirng again conatenated with 3.So output will be 23.
3: System.out.println(2 + 3 +"");
If you take line number 3,it does 2+3 =5 ,then 5+"" =5
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not an errata and could be useful to other people.
Moving this to the study forum...
[ February 28, 2002: Message edited by: Valentin Crettaz ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic