Pass by Value Meaning in Java
In Java, when you pass a parameter to a method, a copy of the value of that parameter is passed to the method, rather than the original object itself. This is what is meant by "Java is pass by value".
For example, suppose you have a method like this:
public void myMethod(int x) {
x = x + 1;
}
If you call this method like this:
int a = 5;
myMethod(a);
Then the value of a
remains unchanged because myMethod
only operates on a copy of a
.
Similarly, if you have a method like this:
public void myMethod(MyObject obj) {
obj.setValue(10);
}
And you call this method like this:
MyObject myObj = new MyObject();
myObj.setValue(5);
myMethod(myObj);
Then myObj
still has a value of 5 because the obj
parameter in myMethod
only points to a copy of the reference to myObj
, not to myObj
itself. However, the state of the object pointed to by myObj
has been changed to have a value of 10.
Here's a more detailed example:
public class PassByValueExample {
public static void main(String[] args) {
int x = 5;
System.out.println("Before calling myMethod: x = " + x);
myMethod(x);
System.out.println("After calling myMethod: x = " + x);
}
public static void myMethod(int x) {
x = x + 1;
System.out.println("Inside myMethod: x = " + x);
}
}
In this example, we define a method called myMethod
that takes an integer parameter x
. The method simply adds 1 to x
and prints out its value.
In the main
method, we create an integer variable x
and assign it a value of 5. We then print out the value of x
, call the myMethod
method, and print out the value of x
again.
When we run this code, we get the following output:
Before calling myMethod: x = 5
Inside myMethod: x = 6
After calling myMethod: x = 5
As you can see, the value of x
inside the myMethod
method is 6, but the value of x
outside of the method is still 5. This is because the myMethod
method only operates on a copy of the value of x
, not on the original x
variable.