File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Guess: Strings concat Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Guess: Strings concat" Watch "Guess: Strings concat" New topic
Author

Guess: Strings concat

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Jan 20, 2000
Posts: 52
Its B).
Ray Marsh
Ranch Hand

Joined: Jan 12, 2000
Posts: 458
Why is (2 + 3 + "" ) = 5 and ( " " + 2 + 3 ) = 23?
What is the trigger to make the answer a string or integer?


Anxiety does not empty tomorrow of its sorrows, but only empties today of its strength. – Charles Spurgeon
Tony Alicea
Desperado
Sheriff

Joined: Jan 30, 2000
Posts: 3222
    
    5
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".


Tony Alicea
Senior Java Web Application Developer, SCPJ2, SCWCD
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Guess: Strings concat