0

The value of array elements are getting changed while calling a static method with the parameter passing the same array as argument but primitive value does not get changed

Is it work differently in the case of while we pass data structure as method argument ? Want to know why array element get changed after the method call with the array .. I was expecting value 0 in the last syso statement instead of 999

public class TestStatic {
    
    public static int square (int x)
    {
        x = x + 1;
        return x * x;       
    }

    public static int[] changeArr(int a[])
    {
        a[0] = 999;
        return a;
    }
    
    public static void main(String[] args)
    {
        int a = 10;

        System.out.println((square(a)));
        System.out.println(a);

        int arr[] = {0,0};
        changeArr(arr);
        System.out.println(arr[0]);
    }
}

Actual Output:

121
10
999

I was expecting

121
10
0

Qiniso
  • 2,587
  • 1
  • 24
  • 30
  • `changeArr(arr)` - `arr` is a reference to an array that you declared inside the `main` method. Since you passed reference to the `changeArr` method, when method changes the value at the first index, it changes the same array that you declared inside `main` method. – Yousaf Sep 29 '20 at 18:32
  • Probably, signature, which can be read as `a[]` item is of type `int`, is misleading a little bit. Change it to: `public static int[] changeArr(int[] a) { ... }` and read: `a` is a parameter of type `int[]`. So it is an object and objects are pass by reference not by type. – Michał Ziober Sep 29 '20 at 18:33

1 Answers1

-1

In Java, method parameters are by reference, not by value, which means you pass the reference to the object, not a copy of the object. Note that primitives are passed by value.