aspose file tools*
The moose likes Beginning Java and the fly likes Output of the operations? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Output of the operations?" Watch "Output of the operations?" New topic
Author

Output of the operations?

Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
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

Joined: Aug 31, 2004
Posts: 11343

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.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19723
    
  20

+ 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"


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Output of the operations?