• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Output of the operations?

 
Abhi vijay
Ranch Hand
Posts: 509
  • 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);

what is the difference between "" and " "??

when " " is used, then string concatenation is performed,why so?
[ October 04, 2008: Message edited by: Bear Bibeault ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both "" and " " are String literals. The difference is simply that " " is a space, and "" is an empty String (a String of zero length).

But this is not the cause of the behavior you are seeing in your code.

Basically, String concatenation with the + operator works from left to right, and the behavior you're seeing is due to where your String literal is placed in the expression. Your code happens to use the String " " as first term, but the String "" is used as a second and third term.

Try this...

System.out.println(1 + 2 + "" + 3 + 4);

You will find that 1 and 2 are evaluated as ints, resulting in addition. But once the String literal (in this case, an empty String) is encountered, the remaining terms in the expression are evaluated as Strings.
 
Rob Spoor
Sheriff
Pie
Posts: 20372
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
+ will do a String concatenation if at least one of its operands is a String. The other operand will be converted using one of the String.valueOf methods.

As Marc said, + evaluates from left to right. So let's look at your examples:
" " + 2 + 3
is
(" " + 2) + 3
is
" 2" + 3
is " 23"


2 + 3
is
5


2 + 3 + ""
is
(2 + 3) + ""
is
5 + ""
is
"5"


2 + "" + 3
is
(2 + "") + 3
is
"2" + 3
is
"23"
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic