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.