0

I want to set a boolean execute as true by passing it into a method set_Execute.Can someone help on solving this?

Here is code:

 public boolean canExecute(){
    boolean execute=false;
    set_Execute(execute);
    log("can execute"+execute); //it is going inside method set_Execute but it is always printing execute as false
    return execute;
    }

    private boolean set_Execute(boolean setExecute){
    return setExecute=true;
    }
divya
  • 53
  • 1
  • 9

3 Answers3

1

you should set back the value to execute like below.

execute = set_Execute(execute);
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
0

Booleans in Java are immutable wrappers so they can't be set. What you can do is use an AtomicBoolean if you want to be able to edit the inner value from within a method.

public boolean canExecute(){
    AtomicBoolean execute = new AtomicBoolean(false);
    set_Execute(execute);
    log("can execute" + execute.get());
    return execute.get();
}

private void set_Execute(AtomicBoolean setExecute) {
    setExecute.set(true);
}
Emil Forslund
  • 549
  • 4
  • 12
  • 1
    Please don't confound immutability and variable assignment. Their example doesn't fail because anything is immutable. – Savior Apr 15 '16 at 05:36
0

You cannot do what you want directly because, as Pillar explained, Java passes variables by value, not by reference. So a change to method parameter never passes back to the caller.

A reference to an instance of a class is also passed by value, but the reference still points to the same instance as the one that the caller sees, so a good solution is to encapsulate your execute flag in a class and operate on an instance of it. That way you can change the value inside the instance.

In your case your flag represents a permission so it makes sense to create a class Permission.

I've left the rest of the code the same, but depending on the overall architecture of your application, it probably makes sense to make the set_Execute method into the Permission class as well.

public class Permission {
    private boolean allowed;

    public void setAllowed(boolean allowed) {
        this.allowed = allowed;
    }

    // Add getAllowed and toString methods
}
public Permission canExecute(){
    Permission execute = new Permission();
    set_Execute(execute);
    log("can execute"+execute); //it is going inside method set_Execute but it is always printing execute as false
    return execute;
}

private void set_Execute(Permission setExecute){
    setExecute.setAllowed(true);
}
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79