Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to declare default argument in Java in String? [duplicate]

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?

like image 985
user3455638 Avatar asked Apr 15 '14 20:04

user3455638


People also ask

Can we give default value to arguments in Java?

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.

How do you pass a default argument in Java?

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.

Can we give default value to arguments?

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.

Can a method have multiple arguments?

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.


Video Answer


2 Answers

No, the way you would normally do this is overload the method like so:

public void test()
{
    test("exampleText");
}

public void test(String name)
{

}
like image 140
MrLore Avatar answered Oct 16 '22 11:10

MrLore


No, it is not. However, the following is possible:

public void test() {
    test("exampleText");
}
public void test(String name) {
    //logic here
}
like image 16
nanofarad Avatar answered Oct 16 '22 12:10

nanofarad