← Back to context

Comment by U1F984

6 hours ago

Java does use dup in some cases, e.g.

   public static void test() { 
      new Object();
   }

         0: new           #2                  // class java/lang/Object
         3: dup
         4: invokespecial #1                  // Method java/lang/Object."<init>":()V
         7: pop
         8: return

This `dup` seems entirely useless it actually supports the case for omitting it fron the instruction set.

  • The only reason it is useless in this (arguably ill-chosen) example is because the result of “new Object()” is not used (hence the pop), which is an uncommon case. If test() instead returned the new object, or would use it in some other way after the initialization, then the dup would be needed. Invokespecial consumes the object reference on the stack, hence if you want to use it after invokespecial, you have to copy or duplicate it before.