Java : Operators and Typecasting

132 Views Asked by At
long value = 0x88888888 ;
int i = (int) (value & 0xff);

How does the above evaluation of expression take place? Is it

int i = (int)value & (int)0xff ;

or does the bitwise and operation gets evaluated first? I am getting confused :-|

3

There are 3 best solutions below

1
Eran On BEST ANSWER

First the bitwise operation is evaluated as an operation on longs (the parenthesis guarantee it). Then the result is cast to int.

0
Deepanshu J bedi On

First (value & 0xff); will be solved. i.e value(bitwise and)0xff. then the resultant will be converted to int value using type casting int i = (int) (value & 0xff);

0
Rod_Algonquin On

Lets take a look at the bytecode:

 public static void main(java.lang.String[]);
    Code:
    0: ldc2_w        #35                 // long -2004318072l
    3: lstore_1
    4: lload_1
    5: ldc2_w        #37                 // long 255l
    8: land
    9: l2i
   10: istore_3
   11: return
}

as you can see the hexadecimal 0xff is first converted to long and then use the bitwise and to the value by masking it with the 0xff after it is then converted to int

  • lload_1 load a long value from a local variable 1

  • ldc2_w push a constant #index from a constant pool (double or long) onto the stack

  • land bitwise and of two longs
  • l2i convert a long to a int