File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on 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 "Question on shift operator" Watch "Question on shift operator" New topic

Question on shift operator

Anjana Ravindran
Ranch Hand

Joined: Aug 22, 2005
Posts: 76
What is the output of the following code block?
public class test {
public static void main(String args[]) {
int i = -1;
i = i >> 1;

i believe it is 0. it is a question from a site. it says the answer as -1. i doubt it. wat u say?
Sachin Dimble
Ranch Hand

Joined: Dec 07, 2005
Posts: 100
in java negative no represents with 2's complment form which means-

int -1-> java representation 0 001->1's compliment 1 110->2's compliment 1111 now this no will get rightshifted->0111->to get back apply rverse process i.e->1's compliment 1 000->2's compliment 1 001

in this no high order bit is 1 hence no will negative & no is 001 i.e->-1.

Hope will understand this!!

Sachin Dimble.
Enge Chall
Ranch Hand

Joined: Nov 22, 2005
Posts: 30
check for 2's complemen calculation link :

There is a little trick to calculate faster in the exam for -ve numbers:
If it's a odd number let's say (2n + 1) format, then add 1 and devide by 2.. ie your answer in -ve.

ie to get -15 >> 1, answer is -(15+1)/2 = -8
Similarly -16 >> 1, answer is 16/2=8.

Guys, thank me for saving ur binary calculation time
[ December 08, 2005: Message edited by: Enge Chall ]

Not everything that counts can be counted, and not everything that can be counted counts.
Naresh Gunda
Ranch Hand

Joined: Oct 15, 2005
Posts: 163

As the bits are shifted right, the sign bit(left most) is used to fill in from the left. So if the left hand operand is a positive value, zeros are filled in from the left, but if the operand is a negative value, ones are filled in from the left.

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

Hope this helps u
I agree. Here's the link:
subject: Question on shift operator
It's not a secret anymore!