-1

There're 2 kinds of function declarations:

void f(String ... s) {
    System.out.println(s.length);
}
void g(String [] s){
    System.out.println(s.length);
}

Both are ok, I would guess "f()" is only a form of syntax sugar of g()?

When using f(), java compiler will still create an internal array of s, right or wrong? ---- I checked the class file inside Intellij, seems the disassembly code for f() is still String... not String[]

Would you kindly help to clarify? Thanks a lot.

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119

1 Answers1

1

Q: What's difference between java vararg array param and normal array param?

See https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments. Varargs can be used only in the final argument position.

Q: Both are ok, I would guess "f()" is only a form of syntax sugar of g()?

Yes.

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process.

Q: When using f(), java compiler will still create an internal array of s, right or wrong? ---- I checked the class file inside Intellij, seems the disassembly code for f() is still String... not String[]

It is handles as array, see How does JVM implement the varargs?

Also I fully support the final statement of the reference:

So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.

leonardkraemer
  • 6,573
  • 1
  • 31
  • 54