1
public class Foo {
public static void change(int[] arr){
    arr = null;
}
public static void change2(int[] arr){
    arr[0] = 99;
}
public static void main (String[] args){
    int[] arr = {1,2,3,4,5};
    change(arr);
    System.out.println("it should null: "+Arrays.toString(arr));
    change2(arr);
    System.out.println("updated array : "+Arrays.toString(arr));
}   }

CONSOLE OUTPUT

it should null: [1, 2, 3, 4, 5]
 updated array: [99, 2, 3, 4, 5]

I need to get understanding about pass by reference as i passed int[ ] to first method i.e change() it does not null the array as per my understanding it should change to NULL as array references are pass by reference but if i pass array to second method i.e change2() it changed the value at specific index. It means that reference is being passed.

Syed Umar
  • 91
  • 7

2 Answers2

3

It is because the Array in java are objects, and the array reference variable is passed by value in public static void change(int[] arr){ , hence you cannot change the reference variable by doing:-

arr = null;
//or
arr=new int[10];

But you can change the object pointed by the copy of array reference variable (i.e arr passed to the method):-

arr[0]=1
Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
2

This is not pass by reference. In Java everything is passed by value. What gets passed to the method is copy of the reference. Since this new reference is also pointing (referencing) the same object, you can manipulate the object using new reference.

But if you assign a different object to this new reference, it will not change which object is pointed (referenced) by the old reference. Old reference still points the same object, which it used to point. So no problem for old reference.

So the outputs are perfectly fine.

C# allows pass by ref. Though to mention this.

Master Chief
  • 2,520
  • 19
  • 28