• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shift operator

 
prateek narang
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
prateek narang
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7480
50
Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).]
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Junilu I knew I'd seen it, just couldn't find it again.

Dave
 
prateek narang
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you all, it is clear now.
prateek
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic