DOES JAVA PASS BY REFERENCE OR PASS BY VALUE?

It was the most confusing topic for me, whether java passes references to functions or values or both. Well, later on when I studied the theory of java, I found out some interesting things that I would like to share here.

java


class A{

void sort(int arr){
 arrays.sort(arr)
}

public static void main(String args[]){
int arr[5]={3,6,8,5,2};
sort(arr);
}  //main
} //class

Looking at it one would easily identify from syntax that java is pass by value. But when you inspect that array it is completely modified to a sorted array.
But why this happened?
Well to understand this first it is important to tell you that Java doesn't allow users to make references i.e references are not allowed in java. Thought it internally references the data with the help of JVM.
It is to be noted that if references are not allowed in java, then it is obvious that we cant pass references in java to its methods.

But then why original array is changed?
Here also we passed value in method sort. This value is the array's address. the var arr holds the memory address of array 'arr'. So that's why modifications got reflected in the original array.

2 Comments