Lion
Lion

Reputation: 19037

Can objects be passed by value rather than by reference in Java?

Let's consider the following code in Java.

package obj;

final class First
{
    public int x;

    public First(int x)
    {
        this.x=x;
    }
}

final class Second
{        
    public Second(First o)
    {
        o.x=10;
    }
}

final public class Main
{
    public static void main(String[] args)
    {
        First f=new First(50);

        Second s=new Second(f);

        System.out.println("x = "+f.x);
    }
}

In the above code, we are supplying a value 50 through the statement First f=new First(50); which is being assigned to a class member x of type int in the constructor body in the class First.


In the class Second, the object f of the class First is being passed through the statement Second s=new Second(f); and we are modifying the value of the instance variable x held in that object to 10 which will affect the original object f because in Java objects are always passed by reference and not by value.


In some specific situations, it may be crucial not to allow such changes to the original objects. Is there any mechanism in Java that may allow us to prevent such modifications? (that might allow us to pass objects by value)

Upvotes: 2

Views: 166

Answers (3)

Sumit Singh
Sumit Singh

Reputation: 15896

 First f=new First(50);
 Second s=new Second(f);  

in first line you are create a reference variable of Object type First and in 2nd line it is pass to Class Second
So as Jon Skeet say in java "Java always uses pass-by-value, but the value of any expression is only ever a primitive type or a reference - never an object."
And if if u don't want to change the value of property then u must be pass new object of class First
Because if u have a reference of any class then u can change the property of that class ..
Or u can create a copy of that object which is at the end creating a new object of First Class

Upvotes: 0

Nicola Musatti
Nicola Musatti

Reputation: 18228

No, there aren't. I would say that your example is not a very good one: if you want to ensure that something doesn't change, don't provide ways to change it. Causing the change to be lost afterwards is misleading at best.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1501886

No, the object isn't being passed at all in Second. The reference is being passed by value.

Java always uses pass-by-value, but the value of any expression is only ever a primitive type or a reference - never an object.

It sounds like you want to create a copy of an existing object, then pass a reference to that new object to the method (by value). Quite what constitutes a "copy" will depend on the data in the class. (You may be able to get away with a shallow copy, or you may need to go deeper etc.)

Upvotes: 9

Related Questions