• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Right Shift Operator >>

 
sai kumar
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So what's your question, Sai? Have you compiled and executed it? What did it produce? Did the output confuse you?
Corey
 
fethi makhlouf
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 !
 
j zaal
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>> is signed shift operator!!
so -1 >>31 = -1
>>> is unsigned operator
-1 >>> 31 =1
 
Vineela Devi
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic