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

Majji q#24

 
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.
Could someone pls explain me
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 477
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Uvnik,
Its crystal clear now....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic