Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Majji q#24  RSS feed

 
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);
 
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
 
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....
 
Put the moon back where you found it! We need it for tides and poetry and stuff. Like this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!