0

I am a bit confused about assignment operations in Java. After changing y[] and 'a', x[] changes together with y[] while b remains as it is. Could somebody clarify the mechanism of "pass by value of the reference of a variable"?

class numTest {
    public static void main(String[] args) {
        int x[] = new int[]{1, 2, 3};
        int y[] = x;
        double a = 10.0;
        double b = a;
        int i;

        y[2] = 100; // substitute element in array y
        for(i = 0; i < x.length; i++)
            System.out.print(x[i] + " ");
        System.out.println();
        for(i = 0; i < y.length; i++)
            System.out.print(y[i] + " ");
        System.out.println();

        a += 1.0; // increment value of a by 1
        System.out.println(a);
        System.out.println(b);
    }
}

Is it because Java treats primitive and reference data types differently?

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • 2
    Yes. Primitives and reference types are indeed treated differently. And unlike an `int`, an `int[]` is a reference type. All arrays are objects. By assigning `y` to `x`, you have two variables pointing to the same object. – MC Emperor Feb 06 '22 at 15:06
  • 1
    Take a look at: [What is the difference between a variable, object, and reference?](https://stackoverflow.com/q/32010172). After reading it you know that objects (and arrays are also objects) have unique identifiers (numbers) which we call *references* and can store those numbers/references in *reference variables*. So code like `int x[] = new int[]{1, 2, 3};` will declare reference variable `x`, create array holding `1 2 3`, and assigns its identifier (lets say it is 42) to `x`. Then with `int y[] = x;` you declare reference variable `y` and assign to it *value* held by `x` which is 42. – Pshemo Feb 06 '22 at 15:16
  • 1
    Now both `x` and `y` hold reference to same object (they "*point to*" same array), so regardless if we use `x[2]=...` or `y[2]=...` we end up modifying internal state of that one array (or to be more precise, value of *internal variable* held by array which we access via `[index]` syntax, and that variable is different/separate from `x` or `y` which is why they don't change and still hold reference to same array). – Pshemo Feb 06 '22 at 15:16
  • I see. Thank you all. – XinyangFeng Feb 07 '22 at 00:46

0 Answers0