Java Boolean value not changing in the called method

I have a scenario where I want to set a Boolean object and then use its booleanValue() in the constructor later in the method. However, the area in which the object is installed is different. It is set in the method called by the method in which the object is first created. Based on my understanding of how Java passes primitive and object arguments and reads several messages on the Internet (like this ), when an object is passed to a method, its properties are passed by reference and any change to the called method should be reflected in the calling method after how the called method completed execution. However, I notice that when the called method is completed, any change in it does not work in the calling method.

Here is a snapshot of my script:

 private CustomObject1 callingMethod(){ Boolean b = Boolean.TRUE; List<CustomObject2> list = this.calledMethod(b); //Create CustomObject1 with b.booleanValue() as one of the arguments in the constructor } private List<CustomObject2> calledMethod(Boolean b){ ... ... if(condition){ b = Boolean.FALSE; } ... ... } 

By the time the CustomObject code is CustomObject creation of b.booleanValue() always true, even if the if-statement in callingMethod() is true and Boolean in this method is set to false.

I don’t want to change the return type of the calling method as Boolean , because this will require changes in other bits of the code that can cause this method. Currently, they only need to change the signature, but changing the type of return will require additional work, since the logic must be supported (for example, filling out a list and then doing something with it).

+6
source share
2 answers

Firstly, there is a lot of misinformation about passing parameters in Java, for example, "objects are passed by reference, primitives are passed by value", which is not true . Everything is passed by value .

You do not pass an object by reference in Java, you pass a reference to an object by value. Boolean b does not contain a Boolean object; it contains a link (pointer) to a Boolean object.

Here is a good article about it: http://javadude.com/articles/passbyvalue.htm

Secondly, Boolean (like other wrapper objects as well as String ) are immutable objects. Thus, with an immutable object, and since they are passed by value (better to say, their links are passed by value), you cannot achieve what you want. Instead, you will need to replace a mutable object, such as @rob.

Or use the MutableBoolean from Apache Commons Lang .

+14
source

The problem is that you are reassigning b to namedMethod. The redistribution in callMethod only reassigns the variable declared in this method parameter list; it does not change the variable declared in the call area.

To do what you want to achieve, you can either convert b to a field or create a MutableBoolean class that allows you to do something like b.setValue(false) .

+2
source

All Articles