Can objects be passed by value rather than by reference in Java?
<p>Let's consider the following code in Java.</p>

<pre><code>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);
    }
}
</code></pre>

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

<hr>

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

<hr>

<p>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)</p>
