Is this pass by reference or pass by value

79 views Asked by At

so i was given this question in class.

consider the following method declaration:

       public static int method(int[] x)

Is the int[] x parameter passed by reference or by value?

To my understanding only primitives can be passed by value. This therefore is passed by reference? I read from here (Are arrays passed by value or passed by reference in Java?) that 'java can only pass by value' and that the reference pointing to the object array x is being passed as a value.

so what is the answer? Is the int[] x parameter passed by reference or by value?

Can someone also give me an example of a pass by reference since java can't do this?

many thanks

2

There are 2 answers

4
ha9u63a7 On

Everything in Java is pass-by-value. Consider your function:

public static int method(int[] x) {

// If you change x here, it won't get reflected in the x. Because you pass a copy of the 
// original x.

}
0
igorepst On

Java passes the reference by value, but the object itself is not passed by value, nor is copied. Just change something inside the array passed to some function and then look into it outside. You will see that it is changed