Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a simple question

 
ying yeh
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,
I have some doubt on the following outputs:
System.out.println( 1 + 2 + "3" );
the result printed is 33
System.out.println( "1" + 2 + 3 );
the result printed is 123
Can anyone explain this?
Thanks in advance!
 
mohd
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think this questions came from programmers guide to java certification by khlid mughal
When you say (1+2) this give you 3 plus the string that mean 3+�3� =3 for 1+2 and other 3 for string
When you say string plus number it will take it as string mean if you add string to variable it will as all string �1�+2 that give you 12 and +3 will give 123 all deal like string
 
Paul Villangca
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The important concept here is that operands are evaluated from left to right.
Case 1:
1 + 2 + "3"
(1 + 2)+ "3"
3 + "3"
"33"
The first + is an addition operator since the two operands are numeric type.

Case 2:
"1" + 2 + 3
("1" + 2)+ 3
"12" + 3
"123"
One of the first two operands is a String, so the + is a string concatenation operator.
[ June 13, 2002: Message edited by: Paul Villangca ]
 
Gautam Sewani
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi pohying hip,
As you know,expressions in java are evaluated from left to right,therefore the above output occurs.Lets examine it case by case:

In this case,first 1+2 is evaluated,which is equal to 3,then since the next argument is a string "3",therefore the previous 3 is converted to a string and joined to the String "3",which gives the output 33.

First "1"+2 is evaluated,which gives "12".Then "12"+3 is evaluated,which gives,123.
I hope that helps
Gautam
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
zagh,
Welcome to Javaranch
We'd like you to read the Javaranch Naming Policy and change your publicly displayed name to comply with our unique rule. Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic