This week's giveaway is in the Spring forum.We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of REST with Spring (video course) this week in the Spring forum!

# Majji q#24

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.
Could someone pls explain me
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
and subsequently what is the o/p of the following code
System.out.println(5+4+6+"String"+5+4+6);
Uvnik Gupta
Ranch Hand

Joined: Jul 24, 2000
Posts: 32
Arithmatic operators have an associtivity of Left to Right hence:
1. " "+2+3 = " 2"+3 = " 23"
2. 2+3 = 5
3. 2+3+"" = 5+"" = "5"
4. 2+""+3 = "2"+3 ="23"
Similarly 5+4+6"String"+5+4+6 = "16String546".
Hope it's clear now.
Uvnik
Marcela Blei
Ranch Hand

Joined: Jun 28, 2000
Posts: 477
B) Prints 23, 5, 5 and 23 is the right answer.
Think about operator precedence (left to right) and the overload + for String literals
>1: System.out.println(" " +2 + 3);
((" " + 2) + 3)
>3: System.out.println(2 + 3 +"");
((2+3)+"")
>4: System.out.println(2 + "" +3);
((2+"")+ 3)
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Thanks Uvnik,
Its crystal clear now....

It is sorta covered in the JavaRanch Style Guide.

subject: Majji q#24