I\'m a programming beginner and I have question regarding a return value from a function.
I´m studying Java.
I have attached code from my book that features a cl
You are touching upon a concept in programming languages named pass by reference vs pass by value.
When you "pass an object by value" to a method, a copy of that object is taken and that copy is passed to the method. So in the called method, when you modify the object, the modification does not get reflected in the caller method.
When you "pass an object by reference" to a method, only a pointer to the actual object that it is referring to is passed to the method. So in the called method, when you modify the object, the modification does get reflected in the caller method.
In Java, all method arguments are "passed by value". It is easier to think that it is pass by reference but it is not the case.
Now, all object variables are references in Java. So in this case, the array is a reference. Java passes that array reference by value i.e it takes a copy of the "reference" and passes it.
So you can now imagine two pointers to the same array - original one named "args" in main() and the new one named "a" in sort()
Since the underlying array is the same, it does not matter if you modify the array using the pointer "args" in the main() or the pointer "a" sort(). They both will see the change.
It is also the reason - why a swap will not work as you would expect.
void main()
{
badSwap(arr1, arr2);
// arr1 and arr2 will still point to same values as the prior line
// because only the reference pointers are getting swapped
// however, arr1[0] will be -99
}
void badSwap(int[] a, int[] b)
{
a[0] = -99;
int[] temp = a;
a = b;
b = temp;
}