33

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?

4
  • 2
    No that is not possible in Java. Commented Apr 15, 2014 at 20:01
  • 5
    This is usually solved with method overloading. Commented Apr 15, 2014 at 20:01
  • What you want to achieve? Commented Apr 15, 2014 at 20:02
  • See this: stackoverflow.com/a/47441378/4217744 Commented Nov 22, 2017 at 18:45

2 Answers 2

62

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

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

public void test(String name)
{

}
Sign up to request clarification or add additional context in comments.

Comments

16

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

public void test() {
    test("exampleText");
}
public void test(String name) {
    //logic here
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.