0

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

Community
  • 1
  • 1
Crazypigs
  • 87
  • 3
  • 13

2 Answers2

2

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

igorepst
  • 1,230
  • 1
  • 12
  • 20
0

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.

}
ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
  • 1
    _If you change x here, it won't get reflected in the x_ Not exactly. If you _reassign_ x, this won't modify the original x. If you change any of the element into x, they will be saved. – BackSlash Nov 15 '14 at 14:40
  • 1
    Yes. See [this demo](http://ideone.com/dIFZ1z). – BackSlash Nov 15 '14 at 14:42
  • @BackSlash I think it needs to be clarified regarding static/non-static scopes. You can demonstrate this yes, but only because you are calling a static method from a another static method. This will not be true for non-static context. – ha9u63a7 Nov 15 '14 at 14:47
  • 2
    [Are you sure?](http://ideone.com/LvB4Zd) You can have static or non static context, my example will work. That's how java works. When you pass an object to a method, a copy of the object's ***reference*** gets created, not a copy of the object itself. So you won't be able to change the object's reference, but you will be able to change the object's attributes. That's why you can't _reassign_ x but you can _change its contents_. – BackSlash Nov 15 '14 at 15:04