Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does JVM implement the varargs?

Tags:

java

internals

I recently got interested in such a feature in Java, as functions with variable number of arguments. This is a very cool feature. But I'm interested:

void method(int x, String.. args) {
  // Do something
}

How is this actually implemented on the runtime level? What comes to my mind, is that when we have a call:

method(4, "Hello", "World!");

The last two arguments are internally transformed into an array, that is passed to the method. Am I right about this, or the JVM actually pushes in the stack refereneces to the strings, not just one reference to the array?

like image 313
SPIRiT_1984 Avatar asked Feb 13 '14 06:02

SPIRiT_1984


1 Answers

It is implemented at compile time level. You method is compiled to bytecode as

varargs method(I[Ljava/lang/String;)V
...

which is equivalent to

void method(int x, String[] args) {
...

with varargs flag.

And

method(4, "Hello", "World!");

is compiled as

method(4, new String[] {"Hello", "World!"});
like image 100
Evgeniy Dorofeev Avatar answered Oct 06 '22 14:10

Evgeniy Dorofeev