Java, call by value or call by reference
Java programming is call by value or call by reference. What is call by value ?, what is call by reference ? , what is argument ? , what is parameter ?, what is stack memory ? what is heap memory. There are some questions should be answered before going further. An argument is a value passed to a function when the function is called. A parameter is a variable used to define a particular value during a function definition. Call by value means arguments value will be copied by function parameter. Call by reference means arguments reference will copied by function parameter.
A.1.1 Java memory
The JVM divided the memory into some section : stack, heap static
Stack memory : stack memory is memory that contains methods (include method parameter), local variables and reference variable
Heap memory : heap memory is memory that contains object include instance variable. Instance variable may be reference to another object.
Static memory : Static memory is memory that contains static variable or method or class
The picture above illustrates the connection of variable, reference value and object. The box is variable, the remote is reference value and the TV is object. Mostly variable and reference value reside in stack memory, while created object resides in heap memory.
A.1.2 Method block
Method is heart of java application logic. Method blocks reside in stack memory. Why logic should be put in method, because when every thread trigger a method then JVM will create separated block of the method in stack memory. Actually method is thread safe it depends on variable and process inside the method.
A.1.2.1 Method without reference variable
The code above will be transformed in memory, look like this :
Based on above picture, method and primitive local variables live in stack memory.
A.1.2.1 Method with reference variable
The code above will be transformed in memory, look like this :
Based on above picture, method and reference local variables live in stack memory while the objects live in heap memory. objA is reference variable that point to object A in heap memory. Instance variables live in heap memory too. Object A has some instance variable and the name are objB and a. ObjB is reference variable while a is primitive variable both of them live in heap memory. ObjB variable has reference to object B and object B has 2 instance variable.
A.1.3 Java call by value or reference
Based on before explanation , java can accommodate call by value and call by reference. Java is call by value when function parameter is primitive value and java is call by reference when function parameter is object type.