Hi, I got one ques. frm Marcus Green Mock Test that says Given the following variables which of the following lines will compile without error? String s = "Hello"; long l = 99; double d = 1.11; int i = 1; int j = 0; 1) j= i <<s; 2) j= i<<j; 3) j=i<<d; 4)j=i<<l;
ans given is 2)j= i<<j; 4)j=i<<l; I can understand option 2) but in option 4) how a int(32 bits) can be shifted to 99 places? is it something wrong with my understanding please correct me?
Rikin Asher
Greenhorn
Joined: Jul 30, 2003
Posts: 5
posted
0
To answer your question, it is valid to do something like say " 8 << 97 ". This is the same as writing 8 << 1 . What you do is take the mod of 97 % 32 (which gives you the remainder of 1) .. and you left shift by the remainder value. Try writing a sample program, and you'll see.
Ross Goldberg
Ranch Hand
Joined: Jul 09, 2003
Posts: 63
posted
0
I thought bitshifts had to be with integers or those types that can be implicitly cast UP to integers (32 bits). In that case, l = 99 is a long, so shouldn't it croak? After all, it doesn't actually check to see that long l fits in an int bucket...or is the long actually converted to 32 bits (chopping off anything left of 32 bits)? Ross
Barkat Mardhani
Ranch Hand
Joined: Aug 05, 2002
Posts: 787
posted
0
Hi Ross: Quot from JLS:
The type of each of the operands of a shift operator must be a primitive integral type, or a compile-time error occurs.