Passing Array to method

61 views Asked by At

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 ?

1

There are 1 answers

2
Vivin Paliath On BEST ANSWER

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.