## Bitwise operation on byte type

Byte type is one of the important typesin Java. It is 8 bit long and is a signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type are often used in low level data processing ( could be audio data processing etc). They do save memory.

However, bitwise operation on byte type creates issues. Consider the following simple code snipped that is expected to bitwise AND two byte variables and produce the output in byte.

 `/*  ReferenceDesigner.com Tutorial for beginners  Bitwise operation on byte type */class bitwise{  public static void main (String args[]) { byte x, y; x = 0x0F; y = 0x1F; byte z; z = x & y; // Bitwise AND x and y System.out.println("z is " + z); // We expect output to be 0x0F or 15 in decimal}}`

However, If you compile and run this program, you will get following compile error.

 ```error: possible loss of precision z = x & y; // Bitwise AND x and y ^ required: byte found: int 1 error```

The Java compiler throws error because it upconverts any byte to int type before it applies any bitwise operation. The int type is 32 bits long ( 4 times that of the byte type). The solution to this problem is to declare z as int type.

int z ;

So basically, when you compute

z = x & y ;

x and y are upconverted to integer before bitwise AND operation is applied. Finally, it is a good idea to AND x and y with 0xFF and also the result with 0xFF.

 `/*  ReferenceDesigner.com Tutorial for beginners  Bitwise operation on byte type */class bitwise1{  public static void main (String args[]) { byte x, y; x = 0x0F; y = 0x1F; int z; z = ((x & 0xFF) & ( y & 0xFF)) & 0xFF ; // Bitwise AND x and y System.out.println("z is " + z); // We expect output to be 0x0F or 15 in decimal}}`