| Author |
operators and precedence
|
Leandro Oliveira
Ranch Hand
Joined: Nov 07, 2002
Posts: 298
|
|
about this: int a=1; int b=2; String s= b+a-- +((b=(b+10))+" "+a++); System.out.println(s); don't u think it should appear "1412 1" on the screen??? Because: first ((b=(b+10))+" "+a++) will be evaluated then b=(b+10) will be evaluated and result in 12 then it will be 12+" " + a++ then a++ will be evaluated and result in 1 all will be, then, "12 1" then a-- will be evaluated and result in 2 then b + a will be evaluated and result in 14 then 14+"12 1" will be evaluated and result in "1412 1"!!! BUT IT DOES NOT HAPPEN THIS WAY THE END RESULT IS "312 0" WHY???
|
 |
Sridhar Srikanthan
Ranch Hand
Joined: Jan 08, 2003
Posts: 366
|
|
Dear leandro,
String s= b+a-- +((b=(b+10))+" "+a++);
b=2 , a =1 a couple of points to remember Java evaluates an expression from left to rightIf there is a string on either side of the "+" operator, the other operand is converted to a string ++ and -- if applied as prefix like ++a increment the value of a immediately ++ and -- if applied as suffix like a++ increment of the value happens in the next expression using the opearnad(i,e a) now, a = 1; b=2; String s= b+a-- +((b=(b+10))+" "+a++); as java evaluates from left to right , the above expression is calculated as s = (b=2) + (a--) + ((b=12)+" " + (a++)); b=2 is because left-to-right evaluation a-- evaluates to 1 and changes a to 0 after a-- is used. similarly a++ (as a has become 0 because of previous expression) is zero but after this expression, increments by 1. so finally s = (2+ 1 + (12+" "+0)); => s = (3 + (12 0); => s = 312 0; Hope this helps Sri b+ a-- + ( [ February 15, 2003: Message edited by: Sri Sri ]
|
 |
Leandro Oliveira
Ranch Hand
Joined: Nov 07, 2002
Posts: 298
|
|
|
thanks!!! u are right!!! I did not pay atention to the left to right evaluation of things!!!
|
 |
 |
|
|
subject: operators and precedence
|
|
|