Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Guess: Strings concat

 
Anonymous
Ranch Hand
Posts: 18944
  • 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.
 
Roll
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its B).
 
Ray Marsh
Ranch Hand
Posts: 458
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is (2 + 3 + "" ) = 5 and ( " " + 2 + 3 ) = 23?
What is the trigger to make the answer a string or integer?
 
Tony Alicea
Desperado
Sheriff
Posts: 3226
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The way I see it is that the expression is evaluated from left to right, 3+3 is 5 and then it is made a string.
In: " " + 2 + 3
first 2 is made a string because of the ""+... and then 3 is made "3" and is concatenated to "2".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic