-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
  • 135
  • 1
  • 10

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
  • 62,771
  • 5
  • 54
  • 92
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
  • 35,854
  • 3
  • 28
  • 38