File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Concatenation Question, Please help

 
Mike Kelly
Ranch Hand
Posts: 78
  • 0
  • 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
 
Rob Ross
Bartender
Posts: 2205
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Mike Kelly
Ranch Hand
Posts: 78
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah yes, precedence in operators, right here in my notes Thank-you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic