Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I cant figure out how this void method works

Tags:

java

arrays

void

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.

like image 704
user1776095 Avatar asked Oct 26 '12 04:10

user1776095


1 Answers

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.

like image 76
sampson-chen Avatar answered Nov 07 '22 02:11

sampson-chen