aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Gotcha: Varargs spoofs method signature [from Sierra/Bates book] Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Gotcha: Varargs spoofs method signature [from Sierra/Bates book]" Watch "Gotcha: Varargs spoofs method signature [from Sierra/Bates book]" New topic
Author

Gotcha: Varargs spoofs method signature [from Sierra/Bates book]

Steven Elliott
Greenhorn

Joined: Mar 28, 2002
Posts: 14
The subject line is the best I could do to describe something that caught me out in the first series of self-tests, question 3 in the SCJP Sierra/Bates book.

Given:


So you have the same method called with two different method signatures.
The test question is:
Which, inserted independently at line 6, will compile? (Choose all that apply.)
A. static void doStuff(int... doArgs) { }
B. static void doStuff(int[] doArgs) { }
C. static void doStuff(int doArgs...) { }
D. static void doStuff(int... doArgs, int y) { }
E. static void doStuff(int x, int... doArgs) { }

I answered A as the only correct answer and was surprised to find that E also is correct! The reason I didn't pick E was in the first case, doStuff(1), would not compile because it would be missing the varargs argument (there is only one argument, 1, after all). Surprisingly, though, not only does the code compile but it runs.

Can someone enlighten me why doStuff(1) (w/one argument) will compile and run with E which requires two arguments?
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  17

A vararg parameter can take any amount of arguments, even zero.

Not only does the method foo(int... values) allow the method call foo(1), it will even allow the method call foo(), in which case values will hold an empty array.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18650
    
    8

There's a general high-level rule related to the design of the Java language, which can be stated roughly as "We don't need no stinkin' special cases".

So in this case that rule says "There can be any number of parameters for a vararg. Does that mean any number higher than 1? No, that would make 0 and 1 be special cases. We don't need that. Just any number."

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Gotcha: Varargs spoofs method signature [from Sierra/Bates book]