Java uses pass by value for parameters - which means when you call
InsertElements
with
arr
as the parameter:
public static void main(String[] args) {
InsertElements(arr);
PrintUnsortedArray(arr);
}
the value in the variable is copied - null - and passed to the function.
The function then overwrites that value with the
new
array, fills it and returns - which doesn't affect the external variable at all.
If you think about it, that's the only sensible way to do it. What would happen if it didn't work like that, but the variable was passed instead?
void Foo(int x) {
x = x + 10;
}
...
int val = 56;
Foo(val);
System.out.println(val);
Would work fine - 66 would be printed.
But ... if we do this:
void Foo(int x) {
x = x + 10;
}
...
Foo(56);
System.out.println(56);
What happens? Does the value of a constant get changed? Logically, yes, it would - and that would make coding very, very difficult!
So just remember: Java always copies the content of a variable and passes that to a function, not the variable itself.