Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes a simple question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "a simple question" Watch "a simple question" New topic
Author

a simple question

ying yeh
Greenhorn

Joined: Apr 23, 2002
Posts: 3
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

Joined: May 28, 2002
Posts: 2
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

Joined: Jun 04, 2002
Posts: 133
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

Joined: Apr 19, 2002
Posts: 93
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

Joined: Aug 26, 2001
Posts: 7610
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.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
wood burning stoves
 
subject: a simple question