I used to think Java supports both pass by value and passby reference but i came accross many discussions like
- Java is always pass by value, with no exceptions, ever .
- Java is always pass-by-value
- Java always passes arguments by value NOT by reference.
- Java passes references by value.So you can't change the reference that gets passed in.
If java only supports pass by value
how does java.util.Array.sort()
or Collections.sort(unsortList)
work?
int iArr[] = {2, 1, 9, 6, 4};// sorting array
Arrays.sort(iArr);
System.out.println("The sorted int array is:");
for (int number : iArr) {
System.out.println("Number = " + number);
}
Update: What passing a reference (by value) Actually mean? How does it differ from passing by reference behaviour of Arrays in C or C++?
Update:
Please correct me if I am wrong. In C we pass the address of variables when passing by reference.In Java we pass the reference to the object (or value).As long as the variable in the method is pointing to the Object the value of the object changes with the varible in the method invoked.
There is no copy of Object or reference made!, I could see only 2 different variables pointing to the same Object as in pass by reference.Similar in C++ pass by reference two different variables points to the same address.