-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?

Ziv Sion
  • 165
  • 1
  • 11

2 Answers2

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);
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
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 ... }
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40