Please tell me when I use swap(int a, int b) function it didn’t swap the values in original place but when I use sort(int[] ar) the changes are made in original array why?I know that
swap will not change the original values but why?
Please tell me when I use swap(int a, int b) function it didn't swap the values in original place but when I use sort(int[] ar) the changes are made in original array why?
Hey Piyush.
There are 2 types of memories present in Java. One is Stack Memory and the Other one is Heap Memory.
Stack memory is used to store items like primitive data types, a reference variable of objects(or the address of object present in heap), whereas Heap memory is used to store non primitive data types or in this case-the array.
Why didn’t the swap function swap values in the original place?
All the functions that are called occupy their area on the stack where all their variables are stored. The functions keep stacking one above the other, in order of their calls. When the function returns it is it is from this chat and all its local variables are destroyed. The variables that are present in one function or local to that function only. It cannot be accessed outside the function. The values of variables a and b in the main function are different from the values a and b of the swap function. In swap function, we interchange the values of a and b for that function and since they are different from a and b in main function, their value doesn’t get swapped in the main function.
Why was there a change in values in the original place in case of sort?
Any changes made in the heap memory are reflected back.
The array being a non primitive data type, is made in Heap Memory. The reference to the actual variable is stored in heap. Now when this variable is passed on to the function, the reference stored on the stack would be passed. Thus, the variable in the function would have same reference as that in the main function and both would point to the same variable present in the heap. If the function alters the value of variable in the heap it will be reflected in the variable of the main too. So, when we use sort on the array, we observe a change in the actual positions of the array in the heap memory.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.