Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Right Shift Operator >> Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Right Shift Operator >>" Watch "Right Shift Operator >>" New topic
Author

Right Shift Operator >>

sai kumar
Ranch Hand

Joined: Mar 31, 2004
Posts: 72
Hi all,
A question from a mock exam:
What happens when we attempt to compile and run the follwoing code?
public class Logic{
static int minusOne=-1;
static public void main(String args[]){
int N=minusOne >> 31;
System.out.println("N ="+N);
sai kumar
Ranch Hand

Joined: Mar 31, 2004
Posts: 72
Sorry for the incomplete question, Here it is:
What happens when we attempt to compile and run the follwoing code?

Edited by Corey McGlone: Added CODE Tags
[ March 31, 2004: Message edited by: Corey McGlone ]
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
So what's your question, Sai? Have you compiled and executed it? What did it produce? Did the output confuse you?
Corey


SCJP Tipline, etc.
fethi makhlouf
Ranch Hand

Joined: Feb 16, 2004
Posts: 50
HI Kumar
If you look for the result, it should be cmpilation and runtime without error,
it will also print 1

Look :

public class Logic{
static int minusOne=-1; // binary 1111 1111 1111 1111 1111 1111 1111 1111
static public void main(String args[]){
int N=minusOne >> 31; // it becomes 0000 0000 0000 0000 0000 0000 0000 0001
System.out.println("N ="+N); // it means 1 !


SCJP 1.4
j zaal
Greenhorn

Joined: Apr 01, 2004
Posts: 5
>> is signed shift operator!!
so -1 >>31 = -1
>>> is unsigned operator
-1 >>> 31 =1
Vineela Devi
Ranch Hand

Joined: Dec 20, 2003
Posts: 191
Hi,
As Zaal has correctly pointed out ,>> is signed rigth shift operator and
-1>>31 results in -1 , but not 1.
when >> is applied on a number, the sign bit of the no is always preserved and the result will have the same sign as tht of the original number.
Vineela.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Right Shift Operator >>