Assign value to the variable in the method declaration

4

Is it possible to assign the default value of a variable within the method declaration, the same as in PHP ? If so, how?

Ex: I want the test function, when called, if no parameter is passed, has the value of b false and true if called this.teste(true);

public function teste(Boolean b = false){

}
    
asked by anonymous 19.10.2016 / 15:45

3 answers

5

No, in java you can not assign a default value that way.

Now you can get this "default value" behavior in a method in other ways. Example:

public void teste(Boolean b){
      if(b == null){
             b = false;}

Or if the interest is simply to make the parameter not mandatory, you can use overhead by creating two methods:

public void teste(){
     teste(false);
}



public void teste(Bollean b){}

I hope you have helped.

    
19.10.2016 / 15:54
2

As you are using an object as a parameter, the Optional class can be useful to check if the value is null (and if it is, use a "default value"):

public void teste(Boolean b){
  b = Optional.ofNullable(b).orElse(false);

  System.out.println("Valor de 'b': " + b);
}
teste(true);  // Valor de 'b': true
teste(false); // Valor de 'b': false
teste(null);  // Valor de 'b': false

Or, as mentioned in the comments, make use of varargs :

public static void teste(Boolean... b){
   boolean value = b.length > 0 ? b[0] : false;
   System.out.println("Valor de 'b': " + value);
}
teste(true);  // Valor de 'b': true
teste(false); // Valor de 'b': false
teste();      // Valor de 'b': false
    
18.11.2016 / 16:18
1

If you are looking for an optional parameter, use method overloading.

public void teste() {
    teste(false);
}

public void teste(boolean b) {
    //executa ação aqui
}

This works for simple methods. I would not recommend using more than two or three versions of the same method and only when there are no more than two or three parameters involved, because overhead can lead to bizarre situations and confusion when passing parameters.

If you have multi-parameter methods, pass an object as a parameter by implementing builder pattern .

For example, instead of doing so:

void fazerPizza(boolean mussarela, boolean oregano, boolean calabreza, boolean tomate, String nome) {
    //...
}

...  

fazerPizza(true, false, true, false, "Calabreza");

It could look like this:

void fazerPizza(PizzaBuilder b) {
    //...
}

fazerPizza(new PizzaBuilder("Calabreza")
    .mussarela()
    .calabreza());

With this pattern, you can auto-complete the possible parameters without getting confused, omit what you do not want, and still leave default values on the object PizzaBuilder if you want.

Read more at Building Objects Smart Builder Pattern and Fluent Interfaces .

    
20.10.2016 / 02:27