- Does Java support default parameter values?
- Does Java have default parameters?
- 1. Java default parameters in practice
- 1.1. Java default parameters with method overloading
- 1.2. Allowing Nulls as method parameters
- 1.3. Varargs parameter
- 2. Java default parameters in long parameter list
- 2.1. Solving Java default parameters with Parameter Object
- 2.2. … and Builder patterns
- Conclusion
- Java Default Parameters
- Default Parameters in Java
- Set Default Parameters using var-args in Java
- Set Default Parameters as Empty String in Java
- Set Default Parameters using var-args with any number of arguments in Java
- Related Article — Java Method
Does Java support default parameter values?
Java does not have built-in support for default parameter values like some other programming languages. However, you can achieve a similar effect by using method overloading or by providing a default value for the parameter inside the method body.
Here’s an example using method overloading:
public void print(int value) < print(value, 1); > public void print(int value, int count) < for (int i = 0; i < count; i++) < System.out.println(value); >>
In this example, the print(int) method overloads the print(int, int) method, and calls it with a default value of 1 for the count parameter.
Here’s an example using a default value in the method body:
public void print(int value, int count) < if (count 0) < count = 1; > for (int i = 0; i < count; i++) < System.out.println(value); >>
In this example, the count parameter is given a default value of 1 if it is not positive.
Note that both of these techniques have some limitations compared to true default parameters. For example, you cannot use them to specify different default values for different parameters, and you cannot use them to specify default values for parameters of different types.
Does Java have default parameters?
Many programming languages like C++ or modern JavaScript have a simple option to call a function without providing values for its arguments. In Java, default method parameters require a bit more typing to achieve this effect in comparison to other languages. From this article, you will learn how the default method parameters work in Java.
1. Java default parameters in practice
The syntax of Java language doesn’t allow you to declare a method with a predefined value for a parameter. Fortunately, you can achieve the same effect with simple code constructions.
There are several options that you may use to simulate behavior known from other programming languages. You can:
- use method overloading
- allow nulls as an input
- declare a method with Java Varargs
Let’s take a closer look at these options.
1.1. Java default parameters with method overloading
Probably the best option to achieve default method parameters in Java is by using the method overloading. Method overloading allows you to declare several methods with the same name but with a different number of parameters.
How to use method overloading to simulate default method parameters?
By calling a more complex method by a simpler one.
Here is a practical example of a method which allows you to query for an optional number of some documents:
List search(String query) < return search(query, 10, 0); >List search(String query, Integer limit, Integer offset) < // method implementation >
The only required parameter is a query string. As you can see, you only have to implement the method with the highest number of parameters. To clarify, the simple method is just a proxy that passes its parameter to the more complex method and provides default parameter values for the optional arguments.
In comparison to other options, the main advantage of method overloading is the simplicity for the client code. You can easily read what set of parameters is allowed for a given method.
Although method overloading is strongly recommended, it’s worth knowing about other possibilities.
1.2. Allowing Nulls as method parameters
Another option is to declare a single method that accepts all possible parameters. Next, in the body of the method, you can check which parameters are nulls and assign them default values.
In this approach, our previous example looks as follows:
List search(String query, Integer limit, Integer offset) < if (limit == null) < limit = 10; >if (offset == null) < offset = 0; >// method implementation >
There are two main disadvantages to this approach. First, you still need to pass all arguments in client code. Even if some of them are nulls. Second, you need to know which parameters are nullable as you can’t tell that just by looking at the method declaration.
What is more, many developers consider reassinging method parameters as bad practice as it makes the code harder to follow. With this in mind, many static code analysis tools allow you to check for this kind of code smell.
1.3. Varargs parameter
The Varargs option is limited only to arguments of the same type and meaning. Therefore, it doesn’t actually solve the problem of default parameters in Java methods. But you may consider it in some cases.
User createUser(String login, Right. rights) < rights = User.DEFAULT_RIGHTS; // implementation >
Technically, it’s even possible to use Varargs as a single optional parameter. In this case, you don’t have to pass null in the client code to use the default value. Yet, it rather feels like an awful hack. I recommend sticking to method overloading.
2. Java default parameters in long parameter list
The main problem with method overloading as a solution for default parameter values reveals itself when a method accepts multiple parameters. Creating an overloaded method for each possible combination of parameters might be cumbersome.
Simply put, the Parameter Object is a wrapper object for all parameters of a method.
But wait! Aren’t we just moving the problem of the long parameter list from a method to the constructor of the new class?
Indead, we are. But class constructors give us one additional solution for the problem which is the Builder pattern.
2.1. Solving Java default parameters with Parameter Object
As mentioned before, the first thing you need is a parameter object class that wraps the list of method parameters. Let’s see how it can look like for a method from the previous example:
As you can see, the implemented parameter object is nothing more than just a regular POJO. The advantage of the Parameter Object over a regular method parameter list is the fact that class fields can have default values. Just like in the above example.
That’s it. Now you have all default parameters in a single place.
2.2. … and Builder patterns
Once you create a wrapper class for the method parameter list you should also create a corresponding builder class. Usually, you’ll do it as an inner static class.
But don’t type builders alone, automate this work!
Popular Java IDEs provide plugins that generate builder classes.
In our example the builder will look as follows:
class SearchParams < // getters . private SearchParams(Builder builder) < query = builder.query; limit = builder.limit; offset = builder.offset; >public static Builder newBuilder() < return new Builder(); >public static final class Builder < private String query; private int limit; private int offset; private Builder() < >public Builder withQuery(String val) < query = val; return this; >public Builder withLimit(int val) < limit = val; return this; >public Builder withOffset(int val) < offset = val; return this; >public SearchParams build() < return new SearchParams(this); >> >
The final step is to use the builder to construct a new parameter object. In this case, you assign only selected parameters. For those parameters you skip, their default values are going to be used. Here’s an example:
SearchParams params = SearchParams.newBuilder() .withQuery("gold") .withOffset(20) .build(); // params.limit = 10 by default
Our example is really simple as the method has only three parameters so it might look like overengineering. In fact, the solution for default parameters using Parameter Object and Builder shines when the list of method parameters is much longer.
Conclusion
Java doesn’t have a simple solution for default method parameters as available in other common programming languages. Yet, you can simulate it using other Java constructions and patterns. In addition, you learn a simple approach with method overloading which works for methods with a short parameter list. For complex methods, the Parameter Object pattern is more flexible.
If you find the article useful, please share it with your friends. Don’t forget to subscribe so I can notify you about other similar posts.
Java Default Parameters
- Default Parameters in Java
- Set Default Parameters using var-args in Java
- Set Default Parameters as Empty String in Java
- Set Default Parameters using var-args with any number of arguments in Java
This tutorial introduces how to implement default parameters in Java.
A default parameter is used when no value is passed. It is helpful when we want to pass limited arguments while the method accepts multiple arguments. For example, a method accepts three arguments, but if we wish to pass only two arguments during the method call, then the Java compiler uses the default value of the third argument to avoid any compilation error.
Java does not support default parameters value, but we can achieve it using some built-in solutions such as var-args or method overloading. Let’s see some examples.
Default Parameters in Java
In this example, we use the method overloading approach to set the default parameter value. However, this is not a fine solution but can be used as an alternative. Notice, we pass 0 as the default value while calling the add() method.
This approach doesn’t work if we have two optional parameters of the same type, and any of them can be omitted.
public class SimpleTesting int add(int a, int b) return a+b; > int add(int a, int b, int c) return a+b+c; > public static void main(String[] args) SimpleTesting test = new SimpleTesting(); int val1 = 10; int val2 = 20; int result1 = test.add(val1, 0); int result2 = test.add(val1, 0, val2); System.out.println("resutl1 : "+ result1); System.out.println("resutl2 : "+result2); > >
Set Default Parameters using var-args in Java
This is another approach where we use the variable args feature to set default parameters. The var-args allows passing a variable length of arguments of the same type. See the example below.
public class SimpleTesting int add(int a, int. b) int b2 = b.length>0?b[0]:0; return a+b2; > int add(int a, int b, int c) return a+b+c; > public static void main(String[] args) SimpleTesting test = new SimpleTesting(); int val1 = 10; int val2 = 20; int result1 = test.add(val1); int result2 = test.add(val1, 0, val2); System.out.println("resutl1 : "+ result1); System.out.println("resutl2 : "+result2); > >
Set Default Parameters as Empty String in Java
In the case of string parameters, we can set an empty string to the parameters; however, this string holds null as the default value. See the example below.
public class SimpleTesting String defaulPara(int a, String str1, String str2) return str1+str2+a; > public static void main(String[] args) SimpleTesting test = new SimpleTesting(); int val1 = 10; String result1 = test.defaulPara(val1,"","second"); String result2 = test.defaulPara(val1,"first",""); System.out.println("resutl1 : "+ result1); System.out.println("resutl2 : "+result2); > >
resutl1 : second10 resutl2 : first10
Set Default Parameters using var-args with any number of arguments in Java
In the case of var-args, we are free to provide any number of arguments while calling the method. So, if you want to provide only limited arguments, then it will work fine. See the example below.
public class SimpleTesting int defaulPara(int. a) int sum = 0; for (int i : a) sum+=i; > return sum; > public static void main(String[] args) SimpleTesting test = new SimpleTesting(); int val1 = 10; int val2 = 20; int result1 = test.defaulPara(); int result2 = test.defaulPara(val1); int result3 = test.defaulPara(val1, val2); System.out.println("resutl1 : "+ result1); System.out.println("resutl2 : "+result2); System.out.println("resutl3 : "+result3); > >
resutl1 : 0 resutl2 : 10 resutl3 : 30