Java: Method parameter default values

Discussion in 'Mac Programming' started by yg17, Nov 17, 2005.

  1. yg17
    Expand Collapse
    macrumors G5


    Aug 1, 2004
    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:

    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.
  2. nsutt22
    Expand Collapse
    macrumors regular


    May 5, 2005

    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
  3. therevolution
    Expand Collapse
    macrumors 6502

    May 12, 2003
    public void myFunction() {
    public void myFunction(boolean b) {
        // your code here
  4. gekko513
    Expand Collapse
    macrumors 603


    Oct 16, 2003
    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.
  5. plinden
    Expand Collapse
    macrumors 68040


    Apr 8, 2004
    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)
  6. jeremy.king
    Expand Collapse
    macrumors 603


    Jul 23, 2002
    Fuquay Varina, NC
    FWIW, the default value of an unitialized boolean will indeed be false.

Share This Page