Is it possible to use default argument in the method with String. The code is shown below:
public void test(String name="exampleText") {
}
The code above generate error. Is it possible to correct it?
Short answer: No. Fortunately, you can simulate them. Many programming languages like C++ or modern JavaScript have a simple option to call a function without providing values for its arguments.
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.
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.
Multiple ArgumentsYou can actually have your variable arguments along with other arguments. That is, you can pass your method a double, an int, and then a String using varargs. It might seem silly to have multiple arguments in a method that already takes multiple arguments.
No, the way you would normally do this is overload the method like so:
public void test()
{
test("exampleText");
}
public void test(String name)
{
}
No, it is not. However, the following is possible:
public void test() {
test("exampleText");
}
public void test(String name) {
//logic here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With