This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
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


Win a copy of Head First Android this week in the Android forum!
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: 3896
    
  18

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.


The mind is a strange and wonderful thing. I'm not sure that it will ever be able to figure itself out, everything else, maybe. From the atom to the universe, everything, except itself.
Paul Clapham
Sheriff

Joined: Oct 14, 2005
Posts: 19693
    
  10

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."

 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Gotcha: Varargs spoofs method signature [from Sierra/Bates book]
 
It's not a secret anymore!