1

I have simple code Scenario:

class Demo
{ 
  static void check(int z[])
 {
   z=null;
 } 

}

class arrNullCheck
{
  public static void main(String args[])
 {
    int arr[]={2,3,4,5};

    Demo.check(arr);

    for(int i=0;i<4;i++)
     {
       System.out.print(arr[i]);

      }     
  }
}

According to me this program should throw null pointer exception at runtime as z is equal to null,But output is as follows:

Output: 2 3 4 5

If i update method like:

 static void check(int z[])
 {
   z[0]=9;
 } 

then it will update array with value 9 as expected. why doesn't null work here then ?

Abin Lakhanpal
  • 380
  • 2
  • 15

1 Answers1

1

No, it won't throw an exception. Java is a pass by value language, and references are also passed by value. You cannot reseat references either. The z is a copy of a reference to arr, and when you reassign to null in your method, you are only changing the value of the local copy and not of the original arr.

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • Then what about 'z[0]' element in updated method, it should not update 'arr' too. – Abin Lakhanpal Jun 09 '15 at 16:45
  • 1
    Yes it will. `z` points to the same thing that `arr` points to. When you do `z[0] = 9`, you're not modifying `z` at all. You're modifying the value at location `0` in the array that `z` points to. – Vivin Paliath Jun 09 '15 at 16:57