View Full Version : Java: Method parameter default values

Nov 17, 2005, 12:31 PM
PHP has this, and I'm pretty sure C++ also has it for functions, where you can specify a default parameter value for a function so if it's not given in the function call, it takes a default value. Like in PHP, the syntax I believe is:

function myFunction($blah="asdf")

So, if you call the function using myFunction(), inside the function, $blah will have the value of "asdf". But, if you call it using myFunction("qwerty"), $blah takes on "qwerty". I tried using the same syntax in Java, and javac doesn't like it. Does anyone know what the correct syntax, if such a thing even exists, in Java is? Thanks.

BTW, if it matters, in my case, the parameter is a boolean and by default, i want it to be false unless true is passed in the method call.

Nov 17, 2005, 12:44 PM
Your are calling the function myFunction() or making it?
What is the parameters of the function?

you may have to declar your variable outside the function

can i see the functions code too

Nov 17, 2005, 12:58 PM
public void myFunction() {

public void myFunction(boolean b) {
// your code here

Nov 17, 2005, 12:59 PM
Java doesn't have optional parameters. Just as well in my opinion. To get a similar behaviour, you must check for null values in the beginning.

public void foo(Object param) {
if (param==null)
param = "asdf";

Edit: therevolution's solution is better.

Nov 17, 2005, 01:02 PM
therevolution is right. Java doesn't have this syntax. You have to write a method whose signature matches what you want to call (actually that's the wrong way to think of it - API comes before app so you have to call exactly what your method is defined as)

Nov 17, 2005, 01:29 PM
FWIW, the default value of an unitialized boolean will indeed be false.