• 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:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Majji Exam #24, Please help clarify

 
Ranch Hand
Posts: 78
  • 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.
B is correct answer, however I don't understand why the third line prints 5 instead of 23. What's the difference between line 1 and line 3?
Thanks Michael
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
are u sure that answer is b.
According to me it is c.
 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer B is a valid answer.
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
+ operator is overloaded. If one of the operand is of type String it performs concatenation.
1: System.out.println(" " +2 + 3);
If you take line number 1, associativity is from left to right so first it does " "+2 and the output will be string.that stirng again conatenated with 3.So output will be 23.
3: System.out.println(2 + 3 +"");
If you take line number 3,it does 2+3 =5 ,then 5+"" =5
 
Author & Gold Digger
Posts: 7610
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not an errata and could be useful for other people.
Moving this to the study forum...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!