aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A question ... Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "A question ..." Watch "A question ..." New topic
Author

A question ...

Ira Jain
Ranch Hand

Joined: Sep 06, 2000
Posts: 70
Hi,
Can somebody please explain me the output of the following question-
class MyClass{
public static void test(int i, String exp) {
if((i>>1)!=(i>>>1)) System.out.println(exp);
}
public static void main(String[] args){
test(1<<32,"1<<32");
test(1<<31,"1<<31");
test(1<<30,"1<<30");
test(1,"1");
test(0,"0");
test(-1,"-1");
}
}
The given ouput is : 1<<31 and -1.
thanx in advance
Ira
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 2547
This is actually quite simple. The point is, >> and >>> produce the same resule EXCEPT for the -ive integers. (And of course, if the RHS is not a multiple of 32/64)
Here, only two are -ive 1 << 31 and -1! Hence, the answer.<br /> 1<< 31, puts 1 on the 32nd bit which is a sign bit making it -ive.<br /> I hope you know why >> and >>> produce different result for -ive integers.
HTH,
Paul.

------------------
Get Certified, Guaranteed!
(Now Revised for the new Pattern) www.enthuware.com/jqplus
[This message has been edited by Paul Anil (edited October 17, 2000).]


Enthuware - Best Mock Exams and Questions for Oracle/Sun Java Certifications
Quality Guaranteed - Pass or Full Refund!
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
Paul is right, and just in case someone doesn't know why >> and >>> produce different answers for negative numbers, it is because >> looks at the highest bit value and that is what it adds to the beginning of the bit pattern, and >>> always adds 0's. Since negative numbers have a 1 at the highest bit value, they stay negative, while >>> doesn't.
[This message has been edited by bill bozeman (edited October 17, 2000).]
Ira Jain
Ranch Hand

Joined: Sep 06, 2000
Posts: 70
Thanks a lot Bill and Paul for clearing my doubts.
 
 
subject: A question ...
 
Threads others viewed
shift operators
right & left shifts
Shift Operators ??????????
shift Operators
Question from Khalidmughal for >>> operator
developer file tools

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture