Hello Everybody,


please explain me what is pass by reference ,i know what does it mean but i could not find any of its simple example that differentiate between pass by reference and pass by value :(

please help me i have spent almost 4 hours searching for it but didn't find example that i could understand as i am a beginner,
please provide me with the beginner example of pass by reference.

Have you Googled this: pass by reference java

Frankly speaking i searched and read more than 20 different website , but many of them just provided the basic difference between Pass by reference and pass by value,
i know that
Pass by Reference means passing the address , and Strings and Array are both pass by reference and pass by value means passing a copy of the value as an argument.

i don't understand that what does that mean because i didn't find any suitable example that i could understand, what does mean by "passing a copy of the value as an argument" and "passing the value itself", i just need simplest example that could make me understand it, the example available on google search are pretty tough for a guy like me that is why i asked it here.

actually i learned the basics of java 8 month ago in university but they only taught as the basics, nothing more than it...! now i am using internet to learn java, i don't know anything about using GUI in java that is why first i am trying to learn the basics.

passing a copy of the value: you won't change the value of the original object in the 'parent' or calling method. let's say method a calls method b, with a copy of the value of object c, which is used in both method a and b. if you alter this value in method b, the value in method a will not change, unless you have

c = performMethodB(c);


pass by reference, you're passing on a reference to the same object you use in your calling method. if you change the value of this referenced object, whether you return int as a result of your method or not, the value of the original object will be altered as well.

example available on google search are pretty tough

Copy and paste some of them here with your questions about them. We'll try to help you understand them.

Copy and paste some of them here with your questions about them. We'll try to help you understand them.

OK, here is the one i tried to understand.

public void tricky(Point arg1, Point arg2)
{
  arg1.x = 100;
  arg1.y = 100;
  Point temp = arg1;
  arg1 = arg2;
  arg2 = temp;
}
public static void main(String [] args)
{
  Point pnt1 = new Point(0,0);
  Point pnt2 = new Point(0,0);
  System.out.println("X: " + pnt1.x + " Y: " +pnt1.y); 
  System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
  System.out.println(" ");
  tricky(pnt1,pnt2);
  System.out.println("X: " + pnt1.x + " Y:" + pnt1.y); 
  System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);  
}

the output of this program is

X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0

what is arg1.x , arg1.y ??

i didn't understand what they tried to explain through it ?

Source: javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html

Let me try explaining it another way.
You understand that the computer's memory has addresses for all the bytes in it starting at 0 and going to Gigabytes. Exact details are not important. What you need to understand is that every variable is associated with ONE memory address.

Say there is a variable at location 1200 with a value 123.

First we'll do call by value.
If we call a method and pass that variable as an argument, the compiler will find another location in memory, say 1700 and copy the contents/value of location 1200(123) to location 1700.
When the method starts executing it is given the location 1700 to work with. It can change the contents of location 1700 and never change the contents of 1200 where the variable's data started from. When the method returns, the contents of 1700 is destroyed to be used again by another method. The contents of 1200 is unchanged. It is still 123.

Now call by reference:
When the method is called it is given the location 1200 to work with. Now if the method changes the contents of location 1200, the original contents are changed. When the method returns the contents of 1200 will be as the method left it. The original value can be changed.

commented: you're incredible !! Xufyan +3

what is arg1.x , arg1.y ??

arg1 is a Point. Look at the API doc for Point - you will see that it has two public variables x and y representing the x and y coordinates of the Point. By changing them you prove that the calling program's variable can be changed using the parameter - which is a (copy of a )reference to the original object.

The point of the rest of the code is that lines 5-7 are swapping over arg1 and arg2 - but what that means to the calling program depends on whether those two args are passed by reference or by value. If its by ref then the two variables in the calling code will be swapped. If it's by value then only the copies in the method will be swapped and the two variables in the calling code will be unaffected.

OK thanks alot , i understand that,
in pass by value the original value remain unaffected while the copy of that value affected , like you've said,

int a =120;
public abc (int a){
this.a = a;
return a;
}

if we later call this method in another class then compiler will store that variable in any other location in memory and only that value will be affected while the original value remain unchanged..!

but why it is useful, why do we need to change the value ??

why do we need to change the value

The arguments for a method can be considered the same as any of the local variables in the method. When the method exits, the variable goes away.
You can use the argument variable the same as you use any of the other local variables in the method. If it is convenient to change it, you can change it, just like you can change any variable.

The arguments for a method can be considered the same as any of the local variables in the method. When the method exits, the variable goes away.
You can use the argument variable the same as you use any of the other local variables in the method. If it is convenient to change it, you can change it, just like you can change any variable.

thanks a alot !!! :D
i've understood what pass by value is, but how pass by reference is useful ??? can you provide 2 to 3 lines example program ?

Although you can change the value of a parameter, it's actually quite rare for anyone to do that.
It can be very confusing. People tend to assume that a parameter is "someone else's" value that has been passed in, and isn't yours to change. If you do assign a new value then there's a real danger that a less experienced programmed will think this is changing the original value, not just the copy in the parameter.
I don't think I've ever done that in a decade and a half of Java programming, and I would be very suspicious if I saw it in anyone else's code.

how pass by reference is useful ???

The designers of Java decided it was not very useful, which is why they left it out of the language. (Some C coders will disagree!)

Java does not pass by reference.
An example in c;
AClass* pCls;
aMethod(pCls); // method changes the value of pCls to point to another AClass object

In java:
AClass aClass;
aClass = aMethod(aClass); // method returns pointer/reference to a new AClass object

The change of pCls taking place in the c code is hidden from the caller of aMethod.
In java, the caller does the change.

The thing that needs to be point out is that Java is strictly pass-by-value. When you encounter a method which has primitive arguments:

public void display(int a){
    System.out.println("An integer: "+a);
}

The Java Virtual Machine allocates a temporary memory address(Ex. 1200) for that variable which holds a copy of the value that was passed to the method. Now you are free to do as you which with the variable a in the method's body because it won't affect the original variable since we are now dealing with two different addresses of memory.

However, when you are dealing with objects as arguments:

public void display(Point a){
    System.out.println("X: "+a.x+" Y: "+a.y);
}

The Java Virtual Machine does not create an exact copy of the original object and give it to a(that would be too expensive) instead the JVM passes the value of the address of the original variable(Ex. 1200) to the variable in the parameter in this case a. This where people get confuse because they think that because the reference of the original variable(Ex. 1200) was passed to variable a that Java is pass-by-reference when in reality this value was pass-by-value. Thus, now you have two variables that point to the same memory address and so if you alter the variable in any way(which points to an object that has x and y) inside the method, the original variable will be affected too.

Hope that clears up the difference between pass-by-value and pass-by-reference.

so if you alter the variable in any way (which points to an object that has x and y) inside the method, the original variable will be affected too.

The use of the word variable here is misleading. The variable is what holds the address of the object. The contents of the object can be changed and everyone would see this change, but the value of the variable can not be changed for the caller because the compiler copied the variable's value to a new variable that is used by the method.

The use of the word variable here is misleading. The variable is what holds the address of the object. The contents of the object can be changed and everyone would see this change, but the value of the variable can not be changed for the caller because the compiler copied the variable's value to a new variable that is used by the method.

Alright so replace the last sentence with:

"Thus, now you have two variables that point to the same memory address and so if you alter the variable a(which points to an object that has x and y) in any way inside the method, the original variable will be affected too."

Bottom line: Variable -> Address -> Object! Where different variables can have the same address thus modify the same object.

f you alter the variable a(which points to an object that has x and y) in any way inside the method, the original variable will be affected too."

I'm quibbling I suppose. I think of the variable as a pointer to an object. Any changes the method makes to the variable it receives is not passed on to the caller. Changes made to the object pointed to by the variable are seen by all.

AClass aCls = new AClass();  // create a variable that points to an object
method(aCls);  // call a method and pass it the variable aCls
// Here the value of aCls is NOT changed
...
public void method(AClass somePtr) {
   somePtr.setValueMethod(33); // this could change the contents of AClass object 
   somePtr = null;  // Change the value of the variable passed to the method
    // this change to the variable will not be seen outside of the method
}

OK I get what you are I saying and you are partially right, here is an example:

public class Point {
    int x;
    int y;
    
    public Point(){
        x = 0;
        y = 0;
    }
    public Point(int x, int y){
        this.x = x;
        this.y = y;
    }
    public String toString(){
        return ("X: "+x+" Y: "+y);
    }
}

and...

public class UserClass {
    
    private void test() {
        Point myPoint = new Point(1, 1);
        modify(myPoint);
        System.out.println("Outside the method: "+myPoint.toString());
    }
    private void modify(Point mPoint){
        System.out.println("Inside the method: "+mPoint.toString());
        mPoint.x = 10;
        mPoint.y = 10;//Changes the object's instances
        mPoint = null;//Gives up the memeory address, but there is still one 
                      //other variable with reference to that object myPoint, thus
                      //the object is not GC and holds it's new modified state.
    }
    
    public static void main(String[] args){
        new UserClass().test();
    }
}

output:

Inside the method: X: 1 Y: 1
Outside the method: X: 10 Y: 10

So yes the call to mPoint = null; is not seen outside of the method because since multiple variables can hold the same memory address which in turn reference the same object when this line of code is reached only the mPoint variable gives up it's memory address value, thus not being able to reference that object. But since the myPoint variable still has a reference to that same object, that object is not GC as expected.

you are partially right

Sorry, what about the other part?

The part where I show why it is that it works that way, your reasoning is right, I was just backing up your statement with proof. :)

Sorry, I was an assembler coder for years. Pointers and memory are second nature and I might not explain it correctly.

No need to apologize, just trying to help out :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.