File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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: 24199

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 ^^
I agree. Here's the link:
subject: A question about ">>"
It's not a secret anymore!