*
The moose likes Mock Exam Errata and the fly likes Majji Exam #24, Please help clarify Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Mock Exam Errata
Bookmark "Majji Exam #24, Please help clarify" Watch "Majji Exam #24, Please help clarify" New topic
Author

Majji Exam #24, Please help clarify

Mike Kelly
Ranch Hand

Joined: Jul 18, 2001
Posts: 78
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
rafa
Greenhorn

Joined: Feb 13, 2002
Posts: 6
are u sure that answer is b.
According to me it is c.
Raja Islam
Ranch Hand

Joined: Dec 07, 2001
Posts: 74
The answer B is a valid answer.
Mathew Sam
Ranch Hand

Joined: Dec 19, 2001
Posts: 124
+ 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
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Not an errata and could be useful for other people.
Moving this to the study forum...


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Majji Exam #24, Please help clarify
 
Similar Threads
The + operator is confusing, help!
Guess: Strings concat
Concatenation Question, Please help
Majji q#24
Majji Exam #24, Please help clarify