wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Concatenation Question, Please help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Concatenation Question, Please help" Watch "Concatenation Question, Please help" New topic
Author

Concatenation Question, Please help

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
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
The operands are evaluated left to right. In line 1 , the first operand is a String, so the first + operation is going to be String concatenation.
In line 3, the first operand is an int, and the second operand is also an int, so the + operator is a numeric addition, so this gets performed first. Then the value of that expression, 5, is used as the left hand operand of another "+". This time however, the right-hand operand is a String " ", so the "+" is a concatenation operator.
[ February 21, 2002: Message edited by: Rob Ross ]

Rob
SCJP 1.4
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
You may read JLS 15.18.1 String Concatenation Operator + if you want to know more about those tricky String concatenations.
[ February 21, 2002: Message edited by: Valentin Crettaz ]

SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Mike Kelly
Ranch Hand

Joined: Jul 18, 2001
Posts: 78
Ah yes, precedence in operators, right here in my notes Thank-you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Concatenation Question, Please help
 
Similar Threads
The + operator is confusing, help!
Guess: Strings concat
Majji Exam #24, Please help clarify
Majji q#24
Majji Exam #24, Please help clarify