Hi All, What are the widening rules regarding shift operation?
I know byte/short/char will be widened to an int. But if we are shifting an int by a long, wont int be widened to a long? Thanks.
Harwinder Bhatia
Ranch Hand
Joined: Oct 17, 2003
Posts: 150
posted
0
Hi Cathy This is from the JLS:
The type of each of the operands of a shift operator must be a primitive integral type, or a compile-time error occurs. Binary numeric promotion (�5.6.2) is not performed on the operands; rather, unary numeric promotion (�5.6.1) is performed on each operand separately. The type of the shift expression is the promoted type of the left-hand operand.
Cheers Harwinder
Vad Fogel
Ranch Hand
Joined: Aug 25, 2003
Posts: 504
posted
0
Hi Cathy, I'd like to add my 2cents to what Harwinder mentioned. You must've followed one angry thread where somebody upset asked how come this code
produces a negative result. Make sure you've examined what's going on in there because K&B overlooked this scenario. I didn't have a question like that, but who knows...
Vishy Karl
Ranch Hand
Joined: Sep 08, 2003
Posts: 116
posted
0
Hi Vad, Your example of byte b=-128; System.out.println(b>>>3); gave me output of 536870896 Why is it coming so ? Should is not be 16 ?? as 128 / 2 raised to 3 is 16 and the sign is changed to positive as operator >>> is used. Plz. explain ?
"The man who can drive himself further once the effort gets painful is the man who will win." <br />Roger Bannister
Sunder Ganapathy
Ranch Hand
Joined: Apr 01, 2003
Posts: 120
posted
0
When you write 'System.out.println(b>>>3)' the result is printed as int. If you store the result in a byte field and then print it, you would get the negative value .
Sunder Ganapathy
Ranch Hand
Joined: Apr 01, 2003
Posts: 120
posted
0
While printing it as byte it is accessing the least significant eight bits .
Vishy Karl
Ranch Hand
Joined: Sep 08, 2003
Posts: 116
posted
0
HI Sunder, I am still not getting your point. If i try to store the result of b>>>3 in a byte it gives me compiler error saying possible loss of precision . Even on casting it gives me the same error. Can u explain with example ? Thanks,
Sunder Ganapathy
Ranch Hand
Joined: Apr 01, 2003
Posts: 120
posted
0
I am giving below the code for your benefit . I 've also given the output as it appears on the console . class page172{ public static void main(String[] args) {
I apologize, what I really meant in the first place was
And right, when you apply a shift operator, the left operand is promoted to the type of the shift expression, and the result is at least int or wider, so b>>>3 is not tricky.