Home > database >  Why is the following Output the right one?
Why is the following Output the right one?

Time:01-20

public class Alle {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        int [] y = arr;
        y[0] = 15;
        System.out.println(Arrays.toString(arr));
    }

}

The Output is 15,2,3,4 but why? I never changed "arr".

CodePudding user response:

In Java, arrays are objects, not primitive types. When you are assigning link to arr to the new variable, y still points to arr, so you are actually changing arr. Thats it. But if you want to copy the array, you can use this method: Arrays.copyOf(int[] original, int newLength)

CodePudding user response:

Let's assume you have a son, named jackson. You introduce him to your friend, "Hey Friend, meet my son Jackson". The friend says, "Hi Jackson, I'll call you jake." Later that friend calls him and says, "Hey Jake, here take a handful of candies". your son Jackson comes to you, and you see he has a handful of candies. But how ? You never gave jackson candies. But your friend gave to jake. Makes sense ?

In your code, the arr, and the y are exactly the same entity, not equal, not copy, but the exact same Object. So you make changes at one place, it'll show at the other one as well.

CodePudding user response:

When you initialized the integer array viz arr in your case, it allocated a space in the heap to your reference variable arr when you executed the following code:

int[] arr = {1,2,3,4};

This arr is referring to an integer array in heap as arrays are objects in java.

Now when you performed the following code:

int [] y = arr;

This created one more reference variable y which is referring to the same object in the heap that your reference variable arr was referring to, that is why whatever changes you make through your reference variable y or reference variable arr will reflect the changes of the object created in the heap as they are referring to the same object.

If you want a new object allocated to your reference variable y that resembles the elements of your arr array then you can clone it. The following code represents it:

public class Alle {
    public static void main(String[] args) {
        int[] arr = {1,2,3,4};
        int [] y = arr.clone(); //change here
        y[0] = 15;
        System.out.println(Arrays.toString(arr));
    }

}

This gives an output:

[1, 2, 3, 4]

Hence your arr array is not affected this time.

  • Related