I read many articles and all says Java is pass by value. But i still don’t construe the difference between pass by value and reference. I wrote a sample program and it executes like this..
public class PassByValue {
private int a;
private int b;
public PassByValue(int a, int b) {
this.a = a;
this.b = b;
}
public static int mul(int a, int b) {
int z = a * b;
System.out.println("The Value of Z inside mul: " + z);
return z;
}
public static void main(String args[]) {
int z = 100;
int x = 40;
int y = 20;
mul(x,y);
PassByValue pass = new PassByValue(x,y);
mul(pass.a,pass.b);
System.out.println("The Value of Z" + z);
}
}
Execution
800
800 and
100
Can anyone explain me these questions…
- What is Pass By Value means…
Answer: Its just passing the numbers or value stored in the variable to a function. Am i right or wrong.
- How do you say Java is Pass By Value?
- Why is Java is Pass By Value and not by reference?
- Does the above program Tries shows an example of Pass by value and Reference… but still does things via Pass by Value only… I wrote that program.
You are right in your answer, but you are lacking detail. If you do
Dog d = new Dog()dis a reference to an instance of Dog, i.e. What pass by value means is that you when passdinto a methodwalkDog(d);the a copy of the reference (i.e. the value of the reference, not the reference itself) to the Dog is passed into the method. So you have 2 references to the one instance of the Dog, the one in the calling scope, and the one in the called scope. Lets say in the
walkDogmethod there is a lined = new Dog();the
dreference in the method only points to the new Dog. The original reference where the method was first called still points to theoriginalDog. If Java had pass by reference, the same reference, not a copy of the reference would be used in the method, and so changing the value of the reference would affect the reference in both the calling and the called scope.EDIT — based on your comment, I want to make on thing clear. Since the reference in the original scope and the method scope both point to the same object, you can still change things on that object in both scopes. So if you do
d.drinkWater();in the
walkDogmethod, anddrinkWaterchanges some variable on the dog object, then since both references point to the same object, which was changed.It’s only a distinction between what the references actually are in each scope. But it does come up a lot.