Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

right shift opeartors  RSS feed

 
Rally Krish
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the result of compiling and running the following program. Select one correct answer.

public class test {
public static void main(String args[]) {
int i = -1;
i = i >> 1;
System.out.println(i);
}
}


ans is -1

need explanation
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, the Java representation of -1 is 11111111111111111111111111111111 - basically all ones. (again, this is
two's complement)

Second, in a right shift (>>), the sign bit is retained. So no matter how often you right shift, the value will not change.

Henry
[ July 22, 2006: Message edited by: Henry Wong ]
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But there is also the >>> operator, which does not retain the sign bit. So -1>>>1 is Integer.MAX_VALUE (or something like that).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!