Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

shift operators

 
anushree ari
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ranchers,
In dan's operators topic exam i came through this questions,
byte b=0;
b+=~b>>>1;
System.out.println(b);
the ans is -1
the exp is b=b+~b>>>1;
==> b=0+ -1>>>1;
so the result is -1.
but if i compile sepreately -1>>>1,the result is
2147483647,why is that?
anybody could ans me,
yhx
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by anushree ari:
...but if i compile sepreately -1>>>1,the result is
2147483647,why is that?

Yes, but if you cast that result to a byte then the result will be -1.
The compound assignment operator casts the result to the type of the left hand operand. If all of the 8 least significant bits are set to one then the result of a cast to a primitive byte is -1.
 
anushree ari
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thx dan,i got it,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic