Sponsored Link •
This article takes a look at how method invocation and return is handled by the Java virtual machine, with a close inspection of the relevant bytecodes is included. The article ends with a source-code example of method invocation.
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.
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:
Instancemethods require an instance before they can be invoked, whereas
classmethods do not.
Instancemethods use dynamic (late) binding, whereas
classmethods 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
instance methods, and invokestatic for
||pop objectref and args, invoke method at constant pool index|
||pop args, invoke static method at constant pool index|