• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

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....
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!