LARA

Compiled Factorial Example

Factorial example:

class Factorial {
    public int fact(int num){
	int num_aux;
	if (num < 1)
	    num_aux = 1 ;
	else 
	    num_aux = num * (this.fact(num-1));
	return num_aux;
    }
}

Result of compilation with javac:

public int fact(int);
  Code:
   0:   iload_1
   1:   iconst_1
   2:   if_icmpge       10
   5:   iconst_1
   6:   istore_2
   7:   goto    20
   10:  iload_1
   11:  aload_0
   12:  iload_1
   13:  iconst_1
   14:  isub
   15:  invokevirtual   #2; //Method fact:(I)I
   18:  imul
   19:  istore_2
   20:  iload_2
   21:  ireturn

Note: a non-static method has a receiver parameter (this), which is parameter in the slot 0. The bytecode can therefore refer to the receiver object by using aload_0 instruction to put it onto the stack and then use instructions to invoke methods, read fields, and write fields.