How the Java virtual machine handles method invocation and return

A look under the hood at the bytecodes used for invoking and returning from methods

This month's Under The Hood focuses on method invocation and return inside the Java virtual machine (JVM). It describes the four ways Java (and native) methods can be invoked, gives a code sample that illustrates the four ways, and covers the relevant bytecodes.

Method invocation

The Java programming language provides two basic kinds of methods: instance methods and class (or static) methods. The difference between these two kinds of methods are:

  1. Instance methods require an instance before they can be invoked, whereas class methods do not.
  2. Instance methods use dynamic (late) binding, whereas class methods use static (early) binding.

When the Java virtual machine invokes a class method, it selects the method to invoke based on the type of the object reference, which is always known at compile-time. On the other hand, when the virtual machine invokes an instance method, it selects the method to invoke based on the actual class of the object, which may only be known at run time.

The JVM uses two different instructions, shown in the following table, to invoke these two different kinds of methods: invokevirtual for instance methods, and invokestatic for class methods.

1 2 Page
Recommended
Join the discussion
Be the first to comment on this article. Our Commenting Policies
See more