Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# doubt in majji

bala_chocos
Ranch Hand
Posts: 48
int i = 1;
2: i <<= 31;<br /> 3: i >>= 31;
4: i >>= 1;
5:
6: int j = 1;
7: j <<= 31;<br /> 8: j >>= 31;
9:
10: System.out.println("i = " +i );
11: System.out.println("j = " +j);
A) i = 1
j = 1
B) i = -1
j = 1

C) i = 1
j = -1

D) i = -1
j = -1

ans d
: public class Q8
2: {
3: int i = 20;
4: static
5: {
6: int i = 10;
7:
8: }
9: public static void main(String[] args)
10: {
11: Q8 a = new Q8();
12: System.out.println(a.i);
13: }
14: }
A) Compilation error, variable "i" declared twice.
B) Compilation error, static initializers for initialization purpose only.
C) Prints 10.
D) Prints 20.
ans d

Anonymous
Ranch Hand
Posts: 18944
Hi bala,
I had problem with same questions in majji's test.
int i=1;
i<<=31;<br /> i>>=31 ;
i>>=1;
Here since int i is a positive no. and shifting 1 to 31 places to left and then to same no of places to right brings it to its original position. Then shifting right place to 1, results in 1 falling off. And since rightshifts extends the sign, so the result cannot be negative. so Accd. to me i=0.
Similarly for
int j=1;
j<<=31;<br /> j>>=31;
The right and left shift would result in 1 coming to its original positon. So j=1.
If any body has some other explanation , please post it.
Thanks,
Preeti.

Stephen Pride
Ranch Hand
Posts: 121
Q1: Answer D is correct: i = -1, j = -1.
i = 1; // bits: 00000000000000000000000000000001
i <<= 31; // bits: 10000000000000000000000000000000<br /> i >>= 31; // bits: 11111111111111111111111111111111
1 >>= 1; // bits: 11111111111111111111111111111111
111111111111111 in 2's compliment is -1.
Same thing occurs with the "j" variable.
Q2: Answer D is correct: 20.
Static blocks are read-in at class load time (i.e., before main() method gets loaded). Therefore, initially, "i" will be 10 when the class loads. Upon instantiation in the line "QB a = new QB()", the non-static variable "i" gets initialized. Therefore, when a call is made which references the variable "i", the non-static variable is used.

Sanjeev Verma
Ranch Hand
Posts: 87
Dear Guys
you have said it all. but i disagree with what Stephen has to say about Q2. I think it is more of a "scope" problem we are seeing here. the int i declared inside static block is a different variable altogether which has a local scope and only shadows the instance variable int i, which remains unaffected by the happenings inside the static block.
correct me if i am wrong.
also, can we initialize a non static variable inside a static block? can someone clarify?
regards
Sanjeev

vidhya Ramachandran
Greenhorn
Posts: 13

You cannot make a static reference to nonstatic variable i.

Kiran Ingale
Greenhorn
Posts: 15