0

When passing the array of integer to a method and assigning it to different variables. Eg: to a=c,b=c; values changes in both a and b.

public static void main(String[] args) {
    int arr[] = new int[]{1,2,3,4,5};

 miniMaxSum(arr);
  }

static void miniMaxSum(int[] arr) {
int[] a = arr;
int[] b =arr;

b[2] = 3;

//but here value changes in a also.
}
Daya Nithi
  • 117
  • 1
  • 10
  • @MensurQulami Sorry for being annoying, but Java is *always* pass-by-value. You are passing the value of a reference. This is why if you'd anything else to `arr` inside the above method, the original array passed to the method wouldn't change. – bkis Jul 17 '19 at 10:25
  • 1
    When passing an array to a function, it passes a reference to the array. You need to do a deep copy instead of a shallow copy to make it not change the original. You could try `System.arraycopy();` – DenverCoder1 Jul 17 '19 at 10:26
  • I have updated the question. I am not sure how to solve it. – Daya Nithi Jul 17 '19 at 10:29
  • @MensurQulami That's not what i said. If the method assigns a different array to the method parameter variable, the original reference (the one you give the value of to the method) stays the same. See: [Is Java “pass-by-reference” or “pass-by-value”?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – bkis Jul 17 '19 at 10:43
  • @MensurQulami Thats the issue. – Daya Nithi Jul 17 '19 at 10:44
  • @eyl327 System.arraycopy() done the trick. Could you explain in detail. – Daya Nithi Jul 17 '19 at 10:46
  • 1
    `System.arraycopy()` copies the actual data in memory. Passing an array to a function just passes the value of a reference to the array meaning if you use regular assignment, it will only copy the place in memory which has the data and not the actual data itself. So you have multiple references to the same array. – DenverCoder1 Jul 17 '19 at 11:04

0 Answers0