Java: Method parameter default values

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

  1. macrumors G5

    yg17

    Joined:
    Aug 1, 2004
    Location:
    St. Louis, MO
    #1
    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.
     
  2. macrumors regular

    nsutt22

    Joined:
    May 5, 2005
    #2
    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
     
  3. macrumors 6502

    Joined:
    May 12, 2003
    #3
    Code:
    public void myFunction() {
        myFunction(false);
    }
    
    public void myFunction(boolean b) {
        // your code here
    }
    
     
  4. macrumors 603

    gekko513

    Joined:
    Oct 16, 2003
    #4
    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.
     
  5. macrumors 68040

    plinden

    Joined:
    Apr 8, 2004
    #5
    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. macrumors 603

    jeremy.king

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

Share This Page