-2

Why is the output for the following code 11,21,31 11,21,31 and not 10,20,30 10,20,30?

public class Tp {

    public static void doChange(int a[])
    {
        for(int pos=0;pos<a.length;pos++)
        {
            a[pos]+=1;
        }
    }
    public static void main(String args[])
    {
        int arr[]= {10,20,30};
        doChange(arr);
        for(int x:arr)
        {
            System.out.print(x+",");
        }

        System.out.println(arr[0]+" "+arr[1]+" "+arr[2]);
    }
}
  • Why would it be either? Surely it is [`11,21,31,11 21 31`](https://ideone.com/xt9grA)? – Andy Turner Oct 25 '17 at 11:30
  • 1
    Because you modify the **content** of the array, not the array itself. The array itself is still the same on return. – fvu Oct 25 '17 at 11:31
  • 1
    this is clear. you write a[pos]+=1;, that is equal to a[pos] = a[pos] + 1. So you take the content and increment by 1 – Francesco Taioli Oct 25 '17 at 11:32
  • https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – Pavel Horal Oct 25 '17 at 11:33
  • `int a[]` is just like reference to `arr` array.So calling of method `doChange` is just like call by reference – Ganesh Patel Oct 25 '17 at 11:34
  • 3
    [Is Java “pass-by-reference” or “pass-by-value”?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Kaustubh Khare Oct 25 '17 at 11:34

4 Answers4

0

Because in java arrays are objects, when you pass the arr array to the doChange() method as argument, it actually copies the reference id of that array (not the elements).

In a simple way, you are updating the same array that you passed in the doChange() method, that's why it reflects to the original array.

Sandeep Rawat
  • 214
  • 2
  • 8
0

When you do

public static void doChange(int a[])    
{    
   for(int pos=0;pos<a.length;pos++)
   {
      a[pos]+=1;
   }
}

This line a[pos]+=1;, adds +1 to each value on the array, so the expect output is 11,21,31 11,21,31, if you want 10,20,30 10,20,30, delete or comment this line doChange(arr);

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
0

Obviously it prints "11, 21, 31, 11,21,31", with the method doChange you add 1 to every element of the array.

Writing:

a[pos]+=1;

is the same as writing:

a[pos]=a[pos]+1;
Jul10
  • 503
  • 7
  • 19
-1

int arr[]= {10,20,30}; Initializes array [0]=10, [1]=20, [2]=30

doChange called with a[] which is a reference of arr[]

for-loop adds +1 to every value in arr[] ( += is equal to x = x + ? )

Now you have [0]=11, [1]=21, [2]=31

Dinh
  • 759
  • 5
  • 16