void truifier (boolean bool) {
if (bool == false) {
bool = true;
}
}
void demo () {
boolean test = false;
truifier (test);
// test is still false
System.out.println (test);
}
You know you can call the function with a literal constant - what should be modified here?
void demo2 () {
truifier (false);
}
Or with a final local variable
void demo2 () {
final boolean b = false;
truifier (b);
}
Or with Attributes from a class:
class X {
private boolean secret = false;
void demo3 () {
truifier (secret);
}
}
In all these calls, truifier
gets a local copy of the reference to the object in question.
boolean b = false;
// b -> false
b is a reference to the object "false" - or in this case primitive value.
boolean c = b;
// c -> false, not: c-> b -> false
c = true;
// c -> true
c is changed, but not b. c isn't an alias for b, but a copy of the reference, and now the copy references a true
. There are only 2 real objects (primitives) here: true and false.
In a method call, a copy of the reference is made and passed, and changes on that reference affect only this. However, there is no deep copying. With a class, for which you change an attribute, will have that attribute changed outside, but you can't replace the class itself. Or Arrays: You may change the content of the array (the reference-copy points to the same array) but not the array itself (the size, for instance). Well - you can change it in the method, but the outer reference is independent, and not changed.
k = [a, b, c, d]
l = k;
l [2] = z;
// l=k=[a, b, z, d]
l = [p, q, r]
// k = [a, b, z, d]