Changing boolean value in class function in java

Can we change the boolean value in a class function in java, something like this will not work, since the change is local to the function. How can we make the next variable that has passed the variable outside of the method call?

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

EDIT The code could be:

 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 looking for something like this

 b.setvalue(true); 

Is it possible?

+8
java
source share
2 answers

Can we change the boolean value in a class function in java

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

Options:

  • Return a Boolean from your method (best choice)
  • Create a mutable Boolean equivalent that allows you to set an inline value. Then you will need to change the value inside the instance to which the parameter refers - changing the parameter value to refer to another instance will not help you, because the arguments are always passed by value in Java. This value is either a primitive value or a reference, but it is still passed by value. Changing a parameter value never changes the caller's variable.
  • Use boolean[] with one element as a shell type
  • Use AtomicBoolean as a Shell Type
+18
source share

Boolean is immutable, like all wrappers for primitive types. SOLN: Attempting to use MutableBoolean from apacheCommon http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/mutable/MutableBoolean.html

0
source share

All Articles