# Simple example explaining the Java bytecode operands

Here is the simple java code, which we will convert into byte code instructions

class GoodArithmetic {

byte addOneAndOne() {

byte a = 1;

byte b = 1;

byte c = (byte) (a + b);

return c;

}

}

Here is the bytecode which will get generated for the above class

iconst_1 // Push int constant 1.

istore_1 // Pop into local variable 1, which is a: byte a = 1;

iconst_1 // Push int constant 1 again.

istore_2 // Pop into local variable 2, which is b: byte b = 1;

iload_1 // Push a (a is already stored as an int in local variable 1).

iload_2 // Push b (b is already stored as an int in local variable 2).

iadd // Perform addition. Top of stack is now (a + b), an int.

int2byte // Convert int result to byte (result still occupies 32 bits).

istore_3 // Pop into local variable 3, which is byte c: byte c = (byte) (a + b);

iload_3 // Push the value of c so it can be returned.

ireturn // Proudly return the result of the addition: return c;

Here is another example :

class Diversion {

static void Convert() {

byte imByte = 0;

int imInt = 125;

while (true) {

++imInt;

imByte = (byte) imInt;

imInt *= -1;

imByte = (byte) imInt;

imInt *= -1;

}

}

}

Here is the byte code :

iconst_0 // Push int constant 0.

istore_0 // Pop to local variable 0, which is imByte: byte imByte = 0;

bipush 125 // Expand byte constant 125 to int and push.

istore_1 // Pop to local variable 1, which is imInt: int imInt = 125;

iinc 1 1 // Increment local variable 1 (imInt) by 1: ++imInt;

iload_1 // Push local variable 1 (imInt).

int2byte // Truncate and sign extend top of stack so it has valid byte value.

istore_0 // Pop to local variable 0 (imByte): imByte = (byte) imInt;

iload_1 // Push local variable 1 (imInt) again.

iconst_m1 // Push integer -1.

imul // Pop top two ints, multiply, push result.

istore_1 // Pop result of multiply to local variable 1 (imInt): imInt *= -1;

iload_1 // Push local variable 1 (imInt).

int2byte // Truncate and sign extend top of stack so it has valid byte value.

istore_0 // Pop to local variable 0 (imByte): imByte = (byte) imInt;

iload_1 // Push local variable 1 (imInt) again.

iconst_m1 // Push integer -1.

imul // Pop top two ints, multiply, push result.

istore_1 // Pop result of multiply to local variable 1 (imInt): imInt *= -1;

goto 5 // Jump back to the iinc instruction: while (true) {}