File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Majji q#24 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Majji q#24" Watch "Majji q#24" New topic
Author

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....
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Majji q#24
 
Similar Threads
Guess: Strings concat
Concatenation Question, Please help
The + operator is confusing, help!
Majji Exam #24, Please help clarify
+ overloded operator