0
    public class sss {

  public static void main(String[] args) {
    int[] array = { 1, 2, 3 };
    change(array);

    for(int i=0;i<array.length;i++)
        System.out.println(array[i]);

  }

  public static void change(int [] array)
  {
      int[] temp = new int[4];
      for (int i =0; i<temp.length;i++)
          temp[i] = i;
      array =  temp;
  }

}

Im trying to change my array, Why is the output is 1,2,3 and not 0,1,2,3 ? Thanks.

NM2
  • 127
  • 6
  • becase array parameter is pass by value not pass by reference – newbieee Nov 13 '15 at 13:00
  • Thanks for the answer, but what do you mean ? – NM2 Nov 13 '15 at 13:04
  • The `array` reference in the method is just a copy of the `array` reference outside the method. Therefore changing it to a new value inside the method doesn't affect anything outside the method. – Keppil Nov 13 '15 at 13:07
  • If its just a coppy, Why, for example when I write array[0] = 1 in the method, it changes the terms outside the method ? – NM2 Nov 13 '15 at 13:11
  • Because both `array`s point to the same array, you can use either one to change the elements of it. Changing the `array` reference itself however does nothing. – Keppil Nov 13 '15 at 13:13
  • So.. There is any option to create a new array in some method outside the main , and change the reference of the original array to the new one ? – NM2 Nov 13 '15 at 13:17

0 Answers0