0

it's Trumpy again!

Here is the code:

public static void main(String[] ar){
    int[] a={1,2,3};
    int x=3;
    foo1(a);
    foo2(x);
    System.out.println(a[0]);
    System.out.println(x);
}
public static void foo1(int[] a){
    a[0]=55;
}
public static void foo2(int x){
    x=77;
}

The output:

55
3

Trumpy's question: when I call to foo2 function it doesn't change the x variable, the change remained in the scope of the function. but when I call foo1 it changes the array itslef, am I right?

hnefatl
  • 5,860
  • 2
  • 27
  • 49
Trumpy
  • 13
  • 3
  • It doesn't change the array, it changes one of the elements of the array. The array is still the same. if you do `a = new int[4]` you'll observe the exact same behaviour you see with `foo2` (`a` doesn't change in `main`). – BackSlash Dec 25 '17 at 00:11
  • In `foo1` you're changing a value in the array pointed to by the reference. In `foo2` you're changing the reference (and as it's passed by value this doesn't last outside the function). – hnefatl Dec 25 '17 at 00:11
  • Dammm 4896 upvotes and I have zero – Trumpy Dec 25 '17 at 00:14
  • why closing so fast? what's bothering you?@BackSlash – Trumpy Dec 25 '17 at 00:19
  • @Trumpy Because some answers provided in the duplicate question already address your issue. You can take a look at [this one](https://stackoverflow.com/a/40523/1759845), for example. – BackSlash Dec 26 '17 at 09:00

0 Answers0