Search code examples
javabytecode

Understand ByteCode which print something


Please help what this bytecode will print

BIPUSH 10
BIPUSH 7
IXOR
ISTORE 1
IINC 1 19
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
ILOAD 1
INVOKEVIRTUAL java/io/PrintStream.println (I)V

Solution

  • I would strongly recommend reading the JVM specification, which explains everything.

    Going through your specific example

    BIPUSH 10
    

    This pushes 10 onto the stack

    BIPUSH 7
    

    This pushes 7 onto the stack. The stack is now 10 7

    IXOR
    

    This xors the top two elements. The stack is now 10^7 = 13

    ISTORE 1
    

    This stores the top element in local variable slot 1. The stack is now empty, while the locals are [INVALID, 13]

    IINC 1 19
    

    This increments local 1 by 19. The locals are now [INVALID, 32]

    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    

    This pushes System.out onto the stack

    ILOAD 1
    

    This loads the variable onto the stack

    INVOKEVIRTUAL java/io/PrintStream.println (I)V
    

    And this prints it. So the final result is printing 32.

    This bytecode was probably generated by Java code along the lines of the following

    int x = 10 ^ 7;
    x += 19;
    System.out.println(x);