This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Question: Does Java support default parameter values?

I came across some Java code with the following structure:

public MyParameterizedFunction(String param1, int param2){ this(param1, param2, false); } public MyParameterizedFunction(String param1, int param2, Boolean param3){Copy the code

I know that in C++ you can assign default values to parameters. Here’s an example:

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

Is this also supported in Java? Why would this two-step syntax be preferable?

Answer 1:

This definition is not actually supported in Java, and the structure you encounter is the way Java handles it (that is, it uses overloads instead of default arguments).

For constructors, if overloading becomes complicated, see Tip 1 in Effective Java: A Programming Language Guide (consider static factory methods instead of constructors). For other methods, renaming some cases or using parameter objects can help. When you have enough complexity, it’s hard to tell the difference. One obvious case is that you must use the order of arguments to distinguish, not just numbers and types.

Answer 2:

This definition is not supported in Java, but you can use the builder pattern. See this answer.

As described in the linked answer, the Builder pattern allows you to write code like this:

Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
                 .name("Spicoli")
                 .age(16)
                 .motto("Aloha, Mr Hand")
                 .buildStudent();
Copy the code

Some of these fields can have default values or can be custom.

Reference:

Stack Overflow :Does Java Support default Parameter values?