Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing boolean value in class function in java

Tags:

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?

like image 761
Global Warrior Avatar asked Apr 15 '12 12:04

Global Warrior


2 Answers

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
like image 124
Jon Skeet Avatar answered Nov 14 '22 16:11

Jon Skeet


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

like image 21
kasongoyo Avatar answered Nov 14 '22 15:11

kasongoyo