Pass optional parameters to Methods?

I know there’s got to be an easy way to do this, but I can’t find it for the life of me.

When I build a new method, I want to be able to make it so that the first parameter is always required, but the second is optional. i.e.:

public void calculate(int firstnum, Object objpass) {
…do something with firstnum…
…do something with objpass as pertaining to firstnum calculation if objpass exists…
}

Any way to do this? If I specify the the second parameter in the method parameter list, it requires it when called. Help?

Just write a second calculate that only accepts an int, and have it delagate to your actual calculate method to do the actual heavy lifting (with the default arg). Slightly more bulky code, but as far as I’m aware the only way to get C++ style default args.

Murphy’s Law strikes again…right after I posted, I found my answer! So, if anything, thank you all for being subjected to a truly Murphy-ized Newbie. :stuck_out_tongue:

For those wondering…when calling the method, you just have to specify somemethod(integerofsomesort, null);

Thank you for those who were so speedy to reply (I’ve already gotten a reply while composing this message). You folks are fantastic!

…or wait until 1.5 goes gold (it supports method signatures with variable numbers of parameters).

[quote]…or wait until 1.5 goes gold (it supports method signatures with variable numbers of parameters).
[/quote]
How will THAT work?

The term they’re using for that feature is “varargs”. You can look up the spec for it at jcp.org. It works by letting you annotate a method as accepting a variable number of arguments. The compiler automatically boxes arguments to any method that is tagged with a VARARGS access modifier.

Personally, I preferred concise object array literals, but it’s looking too late for that change to take place.

God bless,
-Toby Reyelts

You can define a method method(type... name) which is equivalent to method(type[] name) and then call it with method(a, b, c) instead of using method(new type[]{a, b, c}). Because Java 1.5 will automatically convert primitive data into instances of Wrapper classes, stuff looks much nicer, for example

format("%1 = %2", "3+4", 3+4);

instead of

format("%1 = %2", new Object[]{"3+4", new Integer(3+4)});

:o

That is neat

More feature rich = less noob friendly

The explicitness (is that a word???) of Java was, IMHO 1 of its benefits.
All the added syntactic sugar is only going to further confuse newbies to the language.

Think about how many Java noobies actually understand what is happening behind the scenes with string concatenation,
And how often the question, ‘my String concatenation is realy slow!’ is asked…

Variable argument lists & especially Autoboxing is going to multiply that problem 100fold.