Reputation: 166
I have a method:
public static void MutableInt (int newValue) {
AtomicInteger atomicInteger;
atomicInteger = new AtomicInteger(10);
newValue = atomicInteger.get();
}
And then invocation in main:
int x=3;
MutableInt(x);
System.out.println("After invoking MutableInt method, x = " + x);
Result is still 3. Is it possible to mutate the int this way?
Upvotes: 1
Views: 503
Reputation: 356
FIst of all, you're passing a primitive to the method, not a reference to an instance of an object. Even with autowiring, if you set the int variable to something else inside the method, since your not returning anything, the variable outside the scope of the method won't be changed.
If you passed an Integer object instead, the value of the Integer outside the method would be modified if you changed it inside the method, as long as it was not final in the signature of the method.
The fact that your creating an intermediate AtomicInteger inside the method isn't important, since it only exists on the scope of the method.
Upvotes: 0
Reputation: 1769
Not really. Java arguments are passed by value not by reference, so modifying the variable inside the method does nothing to the variable declared outside it. You could do something like
public static int MutableInt (int newValue) {
AtomicInteger atomicInteger;
atomicInteger = new AtomicInteger(10);
return atomicInteger.get();
}
int x = MutableInt(3);
System.out.println("After invoking MutableInt method, x = " + x);
Upvotes: 0
Reputation: 73528
Nope. No matter what you do inside mutableInt()
the value of x
will stay 3
. The only way to change it is to make the method return an int and assign it to x
, or change x
itself to a mutable object (like AtomicInteger
).
Upvotes: 1