Global Warrior
Global Warrior

Reputation: 5110

Changing boolean value in class function in java

Can we modify a Boolean value in class function in java, something like this wont work as the change is local to function. How can we make the following change passed variable reflect outside the method call?

public void changeboolean(Boolean b)
{
        if( somecondition )
        {
                b=true;
        }
        else
        {
                b=false;
        }
}

EDIT The code could be like this:

public String changeboolean(Boolean b,int show)
{
        if( somecondition )
        {
                b=true;
                show=1;
                return "verify again";
        }
        else
        {
                b=false;
                show=2;
                return "Logout";
        }
        show=3;
        return verifed;

}

I'm searching for something like this

b.setvalue(true);

Is it possible?

Upvotes: 15

Views: 38198

Answers (2)

kasongoyo
kasongoyo

Reputation: 1876

Boolean is immutable, like all the wrappers for the primitive types. Soln: Trying using MutableBoolean of apacheCommon http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableBoolean.html

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499770

Can we modify a Boolean value in class function in java

No, Boolean is immutable, like all the wrappers for the primitive types.

Options:

  • Return a boolean from your method (best choice)
  • Create a mutable equivalent of Boolean which allows you to set the embedded value. You would then need to modify the value within the instance that the parameter refers to - changing the value of the parameter to refer to a different instance wouldn't help you, because arguments are always passed by value in Java. That value is either a primitive value or a reference, but it's still passed by value. Changing the value of a parameter never changes the caller's variable.
  • Use a boolean[] with a single element as the wrapper type
  • Use AtomicBoolean as the wrapper type

Upvotes: 28

Related Questions