Reputation: 6158
I am currently working on atomic classes and I am unable to track whether it is "call by value" or "call by reference". I understand that Java does not allow call by reference and that it is only and only call by value. But in case of atomic classes, it seems to be call by reference. Can you share your thoughts with me?
Upvotes: 0
Views: 202
Reputation: 33171
In Java, method calls are pass by value. But when you pass an object to a function, you are actually passing a reference to the object by value. This means that if you do something like
public static int f(AtomicInteger x){
x=new AtomicInteger(4);
return x.get();
}
public static int g(AtomicInteger x){
x.set(5);
return x.get();
}
public static void main(String[] args){
AtomicInteger y=new AtomicInteger(3);
System.out.println(f(y));
System.out.println(y.get());
System.out.println(g(y));
System.out.println(y.get());
}
You will get the result
4
3
5
5
Because you passed y by value. f
did not change the value of the object y
, nor did g
. However g
did change the internal state of y
.
See Parameter passing in Java for more details.
Upvotes: 0
Reputation: 147164
Java passes references by value. Your variable is of type reference to AtomicInteger
. So when you call a method the reference is copied, but the object is not. Indeed, Java has no standard way of copying objects (there is the protected Object.clone
, but that is evil).
Upvotes: 1
Reputation: 597106
It's called pass by value/reference, and it concerns passing arguments to methods.
Atomic classes are no exception to the pass-by-value:
public void method1() {
AtomicInteger atomic = new AtomicInteger(5);
method2(atomic);
System.out.println(atomic.get()); // prints 5
}
public void method2(AtomicInteger atomic) {
atomic = new AtomicInteger(7); // reassign, but this does not affect metod1
}
Upvotes: 3