I have referred to the various explanations around here on SO about pass by value and pass by reference in Java. So far the notion is that incase of primitive datatypes it goes pass by value and incase of reference and user defined datatypes it is pass by reference. I also read that arrays are always pass by reference. However, when I try to execute the following program why the outputs are different in both these methods? The location of the object is called the reference. So if I am passing by value to demoByValue_
it should return 90
or 91
? What am I missing here? Also, will it help to start fiddling with first pointers from C/C++ in order to get an abstract picture of this idea or what could be a real life analogy to grasp thi concept for a beginner? I did look into the analogy of house addresses and if the person wants to go to a specific house it needs the address etc. But, I want to know here that why I am failing to understand this concept? How to access the reference to the value of a primitve data type to see whats going on?
public class Misc {
public static void main(String[] args) {
int a = 91;
System.out.println(a); //prints 91
demoByValue(a);
System.out.println(a); //prints 91
a = demoByValue_(a);
System.out.println(a); //prints 90 -- Why??
}
public static void demoByValue(int a){
a = 90;
}
public static int demoByValue_(int a){
a = 90;
return a;
}
}