This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes A question about >"" title="" /> Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A question about ">>"" Watch "A question about ">>"" New topic

A question about ">>"

jeff yashero

Joined: Sep 24, 2003
Posts: 5
If I wrote some codes like bellow...
//A program about shift">>"
public class Test1{
public static void main(String[] args){
int num=100;
System.out.println("The result is:"+num);

Why the result equal to zero??
However I try this : " num=num>>(-2) " ,and I got the same answer...
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24195

Hi Jeff,
Welcome to JavaRanch!
Please have a look at our naming policy -- I think "Jeff Jeff" falls under "obviously fictitious." Thanks. We try to keep things respectable 'round these parts.
Anyway, as to your question: from the Java Language Specification:

If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance. It is as if the right-hand operand were subjected to a bitwise logical AND operator & (�15.22.1) with the mask value 0x1f. The shift distance actually used is therefore always in the range 0 to 31, inclusive.

So, since -2 & 0x1f is 0x1e, or 30, >> -2 is equal to right-shifting by 30 bits; enough to annihilate all the nonzero bits of decimal 100!

[Jess in Action][AskingGoodQuestions]
jeff yashero

Joined: Sep 24, 2003
Posts: 5
Thanks Ernest ^^
It is sorta covered in the JavaRanch Style Guide.
subject: A question about ">>"
It's not a secret anymore!