Win a copy of Head First Android this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Output of the operations?

 
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 22508
122
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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"
 
reply
    Bookmark Topic Watch Topic
  • New Topic