Compiling 1

Interpreters and Compilers

The Java Virtual Machine

Operand Stack

Reverse Polish Calculator

Calling Functions

Parameters and Return Values

Local Variables

Lab

???

Step 1: The Operand Stack

  1. Compile this class
    public class Test
    {
       public static void main(String[] args)
       {
          int r = 3 + 4 * 5;
       }
    }

    Run it through javap -c. What do you get?

  2. That was disappointing. What can you do to see the operand stack in action? (Hint: Introduce a variable so the Java compiler can't precompute the result.)
  3. What is the javap output now?

Step 2: Parameter passing

  1. Compile this class:
    public class Test
    {
       public static void main(String[] args)
       {
          System.out.println(42);
       }
    }

    What byte codes do you get?

  2. How are the parameter and return types of println encoded? (Hint: Classes are encoded with the quaint Lname; notation.)
  3. How are the parameters of println supplied?

Step 3: Be the disassembler

  1. Consider this static mystery method:
       0:iload_1
       1:ifne 8
       4:iconst_1
       5:goto 17
       8:iload_0
       9:iload_0
       10:iload_1
       11:iconst_1
       12:isub
       13:invokestatic #2; //Method mystery:(II)I
       16:imul
       17:ireturn

    Translate it back into Java. What is your code? (You'll have to look up ifne in chapter 6 of the JVM spec.)

  2. When you compile your code and run it through javap, what output do you get? Where does it differ from the original?

Step 4: Be the assembler

  1. Consider this static method
    int fac(int n)
    {
       if (n == 0) return 1;
       else return n * fac(n - 1)
    }

    Translate it into byte codes by hand. What did you get?

  2. Now compile the code and run it through javap. What output do you get? Where does it differ from your hand-assembly?