My code is:
public class MyProgram {
public void start() {
int a = 1;
int[] b = { 1, 2, 3};
int[] c = { 1, 2, 3};
method1(a, b[0], c);
System.out.println("a = " + a);
System.out.println("b[0] = " + b[0]);
System.out.println("c[0] = " + c[0]);
}
private void method1(int x, int y, int[] z) {
x++;
y = 10;
if ( z.length >= 1 ) {
z[0] = 100;
}
System.out.println(x);
System.out.println(y);
}
}
The output is
a = 1
b[0] = 1
c[0] = 100
I really have no idea why only c[0] has changed.
private void method1(int x, int y, int[] z)
Note that int
type is a primitive, so it's passed by value (value is copied over)
And int[]
type is an array, so it's passed by reference (reference to the array is passed over)
So when you modify the int
variables, you are changing the copies - they don't affect the variables outside of the scope of that function
When you modify the array, it's done through the reference passed in - so the changes persist.
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