I read a few articles and similar question in Stackoverflow; however, I did not quite get an answer to my question. Here is the code:
public class CoinFlipping {
Random random = new Random();
Boolean head = null;
public void flip(Boolean b){
b = random.nextBoolean();
// head = b;
}
public static void main(String [] args){
CoinFlipping cf = new CoinFlipping();
cf.flip(cf.head);
System.out.println("Head: "+cf.head);
}
}
I refer to this arcticle: Is Java "pass-by-reference" or "pass-by-value"?
I can understand why that piece of code behaves as it does. When we call new dog()
we basically create a new Dog object. I get it. However, the example that I provided seems to be confusing a bit. I am not creating an object in this case (aren't I?). I am changing a value. Then why in this case when I print results, I get null
and not true
or false
?
The parameter b
is passed by value, even though b
is itself a reference. Thus, when you call flip
, the flip
method treats b
as a local variable that is a copy of what you pass into it. Changing this copy doesn't change cf.head
.
If b
were a reference to a mutable object, you could change the object b
refers to, and that change would be seen by the rest of the program after flip
returns. But a change to b
itself is a change to a copy, and any such change will not be seen by the rest of the program. (Boolean
is not mutable.)