Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

yg17

macrumors Pentium
Original poster
Aug 1, 2004
15,028
3,003
St. Louis, MO
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:

PHP:
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.
 

nsutt22

macrumors regular
May 5, 2005
177
0
parameters?

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
 

therevolution

macrumors 6502
May 12, 2003
468
0
Code:
public void myFunction() {
    myFunction(false);
}

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

gekko513

macrumors 603
Oct 16, 2003
6,301
1
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.

Code:
public void foo(Object param) {
    if (param==null)
        param = "asdf";
    ...
}

Edit: therevolution's solution is better.
 

plinden

macrumors 601
Apr 8, 2004
4,029
142
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)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.