wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes shift operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "shift operator" Watch "shift operator" New topic
Author

shift operator

prateek narang
Greenhorn

Joined: Apr 04, 2001
Posts: 19
hi! all, the output of the following code is
33
0
18014398309481983
-1
-1
my question is that why the out put for short and byte is -1.

public class URShift {
public static void main(String[] args) {
char c='A';
c>>=33;
System.out.println(c+1);
int i = 1;
i >>>= 27;
System.out.println(i);
long l = -1;
l >>>= 10;
System.out.println(l);
short s = -1;
s >>>= 10;
System.out.println(s);
byte b = -1;
b >>>= 10;
System.out.println(b);
}
}
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Prateek
the byte and short both print -1 because when the operation is carried out they are both promoted to an int then shifted. Then the most significant bits are truncated to produce the correct type for the result. In both of these cases the -1 value looks like this as an int:
11111111 11111111 11111111 11111111
after performing the >>> 10 they would look like this:
00000000 00111111 11111111 11111111
the lefthand 16 bits are cut off so the result is
11111111 11111111
which is -1

Hope that helps
Dave


Dave
prateek narang
Greenhorn

Joined: Apr 04, 2001
Posts: 19
thanx Dave..i too thought the same thing but i've read in Thinking In Java that
"If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int.
So if the result is int then it should be the positive number.
Please clearify this .
thank you
prateek
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Prateek
I can't find the reference I'm looking for in the jls or elsewhere but I'm fairly sure that in this case the result of the shift is converted into the type of the left hand variable by just cutting off the appropriate number of significant bits. I'll keep looking for it, in the mean time maybe someone else will read this and answer it.
Dave
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4456
    
    6

With compound operators, there is an implied cast to the type of the left hand side (see JLS �15.26.2) thus, the result type will be the type of the left hand side (short or byte, in your code).
[This message has been edited by JUNILU LACAR (edited June 25, 2001).]


Junilu - [How to Ask Questions] [How to Answer Questions]
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Thanks Junilu I knew I'd seen it, just couldn't find it again.

Dave
prateek narang
Greenhorn

Joined: Apr 04, 2001
Posts: 19
thank you all, it is clear now.
prateek
 
 
subject: shift operator