5

I have some function in java and i want this function to have a parameter with a default value that is set to variable if no value sent, look like following:

private void test(int count=5)
 {
 }

So i can call the function with 2 ways: test(); and test(10);
how do i do it?

3
  • 2
    Use overloading. Commented Oct 30, 2018 at 9:28
  • or use Integer --> if null then initialize variable to 5 Commented Oct 30, 2018 at 9:29
  • 1
    @LaurentB That still requires that a null be passed ..? Commented Feb 7, 2021 at 2:56

1 Answer 1

6

You could have two overloaded methods. The version with no parameters would call another version accepting an int input, passing a default value of 5.

private void test() {
    test(5);
}

private void test(int count) {
    // rest of method
}
Sign up to request clarification or add additional context in comments.

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.