Pedantic
Pedantic

Reputation: 1378

Pass by value and pass by reference in java

I am reading about Pass by Value and Pass by reference in java, I got many articles,some of them saying Java is following only 'Pass by value " and some of them saying some difference between primitive and object. so I wrote following sample code. and putting output also. Please comment and share what is exactly the answer is.

I checked for Int, String , StringBuffer and Employee class, now Its working as pass by reference for Employee class only.

package test;
class Emp {
    public String name="";
    public int age=0;

    public Emp(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public String toString() {
        return "Name: "+ this.name + "....Age: "+ this.age;

    }
}
public class Class1 {
    public Class1() {
        super();
    }

    public void doChange(int i) {
        i = i +10;
        System.out.println("Value of Integer in Method:>"+ i);
    }

    public void doChange(Emp i) {
        i.age=29;
        i.name="rishu";
        System.out.println("Value of Employee In Method "+i.toString());
    }

    public void doChange(String i) {
        i = i + " Hello";
        System.out.println("value of i->"+ i);
    }


    public static void main(String[] args) {
        int i =10;
        String str="XXX";
        Class1 c= new Class1();
        StringBuffer sb= new StringBuffer();
        Emp e= new Emp("abhi",28);       

        sb.append("ABC ");
        System.out.println("");
        System.out.println("Value of Integer before Method:->"+ i);
        c.doChange(i);
        System.out.println("Value of Integer after Method:->"+ i);
        System.out.println("");
        System.out.println("Value of String before Method:->"+ str);
        c.doChange(str);
        System.out.println("Value of Integer after Method:->"+ str);
        System.out.println("");
        System.out.println("Value of StringBuffer before Method:->"+ sb);
        c.doChange(sb.toString());
        System.out.println("Value of StringBuffer after Method:->"+ sb);
        System.out.println("");

        System.out.println("Value of Employee before Method:->"+ e.toString());
        c.doChange(e);
        System.out.println("Value of Employee after Method:->"+ e.toString());
    }
}

Output:

Value of Integer before Method:->10
Value of Integer in Method:>20
Value of Integer after Method:->10

Value of String before Method:->XXX
value of i->XXX Hello
Value of Integer after Method:->XXX

Value of StringBuffer before Method:->ABC 
value of i->ABC  Hello
Value of StringBuffer after Method:->ABC 

Value of Employee before Method:->Name: abhi....Age: 28
Value of Employee In Method Name: rishu....Age: 29
Value of Employee after Method:->Name: rishu....Age: 29

Upvotes: 0

Views: 3776

Answers (5)

Arpit Soni
Arpit Soni

Reputation: 101

We can do both in java "Pass by value" as well as "Pass by reference" here the example of both.

Pass by Value example

class PassByValue{
String name="java";
void display(String name)
{
    name="Java Programming";
}
public static void main(String arg[])
{
    PassByValue p=new PassByValue();
    System.out.println("Before changes : "+p.name);
    p.display("C++");
    System.out.println("After changes : "+p.name);
}}

Pass by reference example

class PassByReference{
String name="Java";
void display(PassByReference p)
{
    name="Java Programming";
}
public static void main(String arg[])
{
    PassByReference p=new PassByReference();
    System.out.println("Before changes : "+p.name);
    p.display(p);
    System.out.println("After changes : "+p.name);
}}

You can check returning value and returning object in java by click here: return value and return object in java

Upvotes: 1

HJW
HJW

Reputation: 23453

There is no pass by reference in Java, only pass by value.

When this method exits, employee will not be chin boon, but something else you set it to before you entered this method.

public void doChange(Emp i) {
    i = new Emp("chin boon", 42);
}

When this method exits, employee will have the name chin boon.

public void doChange(Emp i) {
    i.setName("chin boon");
}

Upvotes: 2

Michael Borgwardt
Michael Borgwardt

Reputation: 346536

Java is pass-by-value only.

However, for objects, what is passed by value is a reference to the object. No, that's not the same as pass-by-reference. The difference is this:

If in you do this:

public void doChange(Emp i) {
    i = new Emp("changed!", 42);
}

It has absolutely no effect outside the method - because the reference i is a copy of the reference used outside the method. However, it refers to the same object, so if you use the reference to change fields of the object, these changes are visible outside the method.

Upvotes: 10

Kushan
Kushan

Reputation: 10703

Java passes parameters to methods using pass by value semantics. That is, a copy of the value of each of the specified arguments to the method call is passed to the method as its parameters.

Note very clearly that a lot of people confuse the "reference" terminology with respect to Java's references to objects and pass by reference calling semantics. The fact is, in dealing with Java's references to objects, a copy of the reference's value is what is passed to the method -- it's passed by value. This is, for example, why you cannot mutate the (original, caller's) reference to the object from inside the called method.

For example:

Dog aDog = new Dog("Max");

you are defining a pointer to a Dog aDog object, not a Dog object itself.

public void foo(Dog d) {
   d = new Dog("Bingo");
}

the variable passed in is not modified! After calling foo, aDog still points to the "Max" Dog. Passes the value of d to foo, the value of a pointer is similar to a memory address.

Upvotes: 1

ŁukaszBachman
ŁukaszBachman

Reputation: 33743

Value of Integer before Method:->10 Value of Integer in Method:>20 Value of Integer after Method:->10

No surprise here. You pass value of 10 to the method, it's incremented and displayed properly. After you get back from method call the i variable stays intact.

Value of String before Method:->XXX value of i->XXX Hello Value of Integer after Method:->XXX

Strings are immutable classes, so there is no way to change it. You can only reassign value, as you did in your example. The trick here is to understand, that you receive a copied value of reference leading to object XXX. Now, you are creating new object i + "Hello" and overriding previous reference i. So the object XXX don't change, however within the method you are not printing it - you are printing the object that you created within the method.

Value of StringBuffer before Method:->ABC value of i->ABC Hello Value of StringBuffer after Method:->ABC

This is the same case as in the code above, since toString() yields a new String object.

And finally:

Value of Employee before Method:->Name: abhi....Age: 28 Value of Employee In Method Name: rishu....Age: 29 Value of Employee after Method:->Name: rishu....Age: 29

This is the perfect showcase of PASS BY VALUE You are creating object Employee, but you are passing a REFERENCE to this object as a method parameter. Now, remember this for life, this reference is COPIED, so you will receive a copy of reference available for you to work with inside the method. THAT IS WHY JAVA IS ALWAYS PASS BY COPY. However, this copied reference is pointing still to the same object Employee, which you have created earlier. So if you will use that reference to modify the object pointed by it, you modify original Employee. That is why you can see change effect in the output.

Bruce Eckel has a nice example of references and objects in Java. Think of Object as of TV and a reference as a remote control. If you pass reference to other method as an argument, you will have a copied remote control within this method. If you press "turn off" button within the method, the TV will still end up being off, even though you didn't use the original remote ;)

Upvotes: 1

Related Questions