Alex Rivera | Logout

Does Java support default parameter values?

Asked 2009-06-15T18:04:28.277
2195

I came across some Java code that had the following structure:

public MyParameterizedFunction(String param1, int param2)
{
    this(param1, param2, false);
}

public MyParameterizedFunction(String param1, int param2, boolean param3)
{
    //use all three parameters here
}

I know that in C++ I can assign a parameter a default value. For example:

void MyParameterizedFunction(String param1, int param2, bool param3=false);

Does Java support this kind of syntax? Are there any reasons why this two step syntax is preferable?

Edit
Report

2 Answers

20

I might be stating the obvious here but why not simply implement the "default" parameter yourself?

public class Foo() {
        public void func(String s){
                func(s, true);
        }
        public void func(String s, boolean b){
                //your code here
        }
}

for the default, you would either use

func("my string");

and if you wouldn't like to use the default, you would use

func("my string", false);
answered 2013-02-18T13:59:18.373
6

No. In general Java doesn't have much (any) syntactic sugar, since they tried to make a simple language.

answered 2009-06-15T18:49:17.523

Your Answer