Java Array Question

Asked 2 years ago, Updated 2 years ago, 26 views

Java, let me ask you a quick question.

static void test (int[] array, intk) {
        array[1]=100;
        k =100;
    }
    public static void main(String[] args) throws IOException {
        int[] in = new int[] {1,2,3,4,5,6};
        int a = 4;
        System.out.println(in[1]);
        System.out.println(a);
        test(in,a);
        System.out.println(in[1]);
        System.out.println(a);
    }

There is a simple Java code like above. Why does the value of a not change, but the array value can be changed from test to output?

java

2022-09-22 19:53

1 Answers

Java has reference types and primitive types.

There are integers (int, byte, short, long, char, logical (boolean, and real (byte.

The reference type is all objects except the primitive type, and it also includes an array of primitives.

When calling a function, the primitive type is passed through a copy of the value, and the reference type is passed through the reference value, as the name implies.

Reference values refer to the address of the object, and different variables can refer to the same object through reference values.

int[] a = {1, 2, 3};
int[] b = a;

As shown above, a and b are reference types, so the reference value is copied through a substitution operation, and the two variables have the same reference value. The same reference value means that you are referring to the same object. Therefore, if you change the element value through b, the contents of the a variable referring to the same object will also change.

In contrast, for a primitive, each variable has the value that the primitive wants to represent, not the reference value (address).

int c = 10;
int d = c;

According to the above, c and b have the same value as 10, but changing the value of d does not change the value of c. This is because c and d do not share the same address.

Tidy up, in Java, variables store values. A variable in the reference type stores the reference value and accesses the object to which it points. A primitive variable stores the values that each primitive type represents, which is not an address, so even variables with the same values do not affect each other.

Therefore, array of void test(int[] array, intk) has the same reference value as int[] in = new int[] {1,2,3,4,5,6}, so changing array points to the object.

For your information, we have explained above that primitive variables store values for that type, but you might think that reference values for an Impossible object are stored.


2022-09-22 19:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.