0

i know that java is call by reference, i have a question about these code

public class test {

public static void main(String[]  argv){


    ArrayList<Integer>  a = new ArrayList<Integer>();
    int aa = 5;
    int[] aaa ={0,1,2};
    a.add(1);
    aaa[0]=999;
    System.out.println("ArrayList "+ a.toString());
    System.out.println("int "+ aa);
    System.out.println("Array "+ Arrays.toString(aaa));

    add2(a,aa,aaa);


    System.out.println("ArrayList"+ a.toString());
    System.out.println("int "+ aa);
    System.out.println("Array "+ Arrays.toString(aaa));
}

private static  void add2(ArrayList<Integer> a1,int aa1,int[] aaa1)
{
    a1.add(2);
    aa1=aa1+10;
    aaa1[2]=999;
}

the result is

ArrayList: [1]

int:       5

Array:     [999, 1, 2]

ArrayList: [1, 2]

int:       5

Array:     [999, 1, 999]

why ArrayList and Array will change when i call function and "int" won't change

Can someone explain to me these situation , thanks a lot

Damodaran
  • 10,882
  • 10
  • 60
  • 81
cihm
  • 71
  • 9

1 Answers1

1

You are partially right about Java being pass-by-reference (well not really, but that's a different topic); however, this is only true when passing objects.

According to The Java Tutorials:

Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to them are lost.

As the quote states, primitive types (like int) are passed to the function by value. A copy of the primitive is given to the function when it is called, and thus any changes made by the function have no effect on the original data.

Community
  • 1
  • 1
Kyle
  • 374
  • 1
  • 11