ForInfinity ForInfinity - 1 year ago 93
Java Question

Is it possible to mutate an int through a method using AtomicInteger?

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;
System.out.println("After invoking MutableInt method, x = " + x);

Result is still 3.
Is it possible to mutate the int this way?

Answer Source

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).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download