Java: Pass By Value or Pass By Reference
Table of contents
Java: Pass By Value or Pass By Reference
Many programmers often confuse between Java being Passed By Value or Pass By Reference. If only we could visualize our code, this won’t seem too big a problem. Let’s start with the basics. Data is shared between functions by passing parameters. Now, there are 2 ways of passing parameters:
Pass By Value: The pass by value method copies the value of actual parameters. The called function creates its own copy of argument values and then uses them. Since the work is done on a copy, the original parameter does not see the changes.
Pass By Reference: The pass by reference method passes the parameters as a reference(address) of the original variable. The called function does not create its own copy, rather, it refers to the original values only. Hence, the changes made in the called function will be reflected in the original parameter as well.
Java follows the following rules in storing variables: Local variables like primitives and object references are created on Stack memory. Objects are created on Heap memory.
Now coming to the main question: ## Is Java Pass by Value or Pass by Reference?
package communaute_java;
public class Test1 {
public static void main(String... args) {
int data = 100;
System.out.print( data + " " );
processData(data);
System.out.print( data);
}
private static void processData(int data) {
data=data * 2;
}
}
Comment your answers below.
And If you like to read articles like this then hitting the follow button would be valuable.
Subscribe to my newsletter
Read articles from Niraj Kumar Gupta directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Niraj Kumar Gupta
Niraj Kumar Gupta
B.tech student with great fundamentals in Core programming & love to talk everything about data, DevOps, and cloud