Change boolean Values?

Viewed 19466

I have a question about boolean values in Java. Let's say I have a program like this:

boolean test = false;
...
foo(test)
foo2(test)

foo(Boolean test){
  test = true;
}
foo2(Boolean test){
  if(test)
   //Doesn't go in here
}

I noticed that in foo2, the boolean test does not change and thereby doesn't go into the if statement. How would I go about changing it then? I looked into Boolean values but I couldn't find a function that would "set" test from true to false. If anyone could help me out that would be great.

5 Answers

Here is a good explanation.

http://www.javadude.com/articles/passbyvalue.htm

Java has pointers, and the value of the pointer is passed in. There's no way to actually pass an object itself as a parameter. You can only pass a pointer (value) to an object.

And my solution

   public static class MutableBoolean {
        public boolean value;

        public MutableBoolean(boolean value) {
            this.value = value;
        }
    }

usage:

MutableBoolean needStop = new MutableBoolean(false);
call( new Listener(needStop){
   void onCallback(){
      needStop.value = true;
   }

})
Related