0
package basic;

class TestIt {

    static void doIt(int[] z) {
        z = null;
    }
}

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

        TestIt.doIt(myArray);

        for (int j = 0; j < myArray.length; j++)
            System.out.print(myArray[j] + " ");
    }

}

can any1 please explain why the output for code is 1,2,3,4,5. ....................................................................................................................................................................................................................

3 Answers3

2

Java is pass by value, which means that when you assign z = null it does not change myArray.

To set myArray to null you have to set it explicitely in main:

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

        myArray = null;                

}
Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63
2

In Java object references are passed by value. When you do this

static void doIt(int[] z) {
    z = null;
}

you set the value of object reference z to null. At this point, your doIt method can no longer reference myArray local variable from the main method, but the array stays unchanged, along with the myArray variable, which is referring to it.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

Because in java references to objects are passed by value. So TestIt.doIt(myArray); will only change the value of myArray to null in the doIt() method.

If you want the value to be changed in the calling method as well, use :

myArray = TestIt.doIt(myArray);

TheLostMind
  • 35,966
  • 12
  • 68
  • 104