public static void main(String[] args) {
Integer i = new Integer(0);
int[] arr = {1};
p1(i);
p2(arr);
System.out.println(i);
System.out.println(arr[0]);
}
public static void p1(Integer i) {
i = 2;
}
public static void p2(int[] i) {
i[0] = 2;
}
//output: 0, 2
How can I change the value of i like I change the value of arr?
You can't change the value of the variable i
in main
from within the p1
method, because the argument is passed by value: the parameter i
in p1
is entirely separate from the i
variable, it's just that they have the same value at the start of the method. Java always uses pass-by-value semantics - but when the parameter type is a class, it's a reference that is passed by value.
In fact, you're not changing the value of arr
, either - it's a reference to the same array as before, but the value in the array has been changed. And that's what you can't do with Integer
, because Integer
is an immutable type.
If you want a mutable class like Integer
, you could use AtomicInteger
instead:
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger(0);
modify(i);
System.out.println(i);
}
private static void modify(AtomicInteger x) {
x.set(2);
}
I would usually not do this, however - I usually try not to modify the objects that method parameters refer to. Instead, I write methods which compute a single result, and return that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With