Skip to content
Advertisement

What is the use of the “dup2_x2” instruction in JVM bytecode?

Java has a dup2_x2 instruction which, according to the documentation, has the following behavior:

Duplicate the top one or two values on the operand stack and insert the duplicated values, in the original order, into the operand stack.

Does javac produce bytecode with this instruction? What are its potential use cases?

Advertisement

Answer

For example, the following code

public static Long example1(Long[] array, int i, long l) {
    return array[i]=l;
}
public static long example2(long[] array, int i, long l) {
    return array[i]=l;
}

compiles to

  public static java.lang.Long example1(java.lang.Long[], int, long);
    Code:
       0: aload_0
       1: iload_1
       2: lload_2
       3: invokestatic  #1        // Method java/lang/Long.valueOf:(J)Ljava/lang/Long;
       6: dup_x2
       7: aastore
       8: areturn

  public static long example2(long[], int, long);
    Code:
       0: aload_0
       1: iload_1
       2: lload_2
       3: dup2_x2
       4: lastore
       5: lreturn

See, demo on Ideone

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement