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
?