-4

I tried to do something like C++:

public void function(int x = 10) { // If user did not give an parameter, parameter= 10
    }

How can I set the parameter in case he did not get?

2
  • 1
    Java doesn't support that. You should use method overloading Commented Dec 17, 2020 at 20:50
  • Can you show me how? I tried before Commented Dec 17, 2020 at 20:51

2 Answers 2

1

You'd overload it with a method that doesn't receive a parameter, then call it with the one that you want:

public void function() { function(10); }

Your original function would then just be:

public void function(int x) { // ... body ... }
Sign up to request clarification or add additional context in comments.

Comments

1

In Java, you can achieve it using method overloading

public void function(int x) {

}

public void function() { 
    int x = 10;// If user did not give an argument, argument = 10
    function(x);
}

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.