0
public class Passing_Objects_to_Methods 
{
int id;
public Passing_Objects_to_Methods(int id) 
{
    this.id=id;
}
public static void swap(Passing_Objects_to_Methods b1,Passing_Objects_to_Methods b2)
{
    Passing_Objects_to_Methods temp;
    temp=b1;
    b1=b2;
    b2=temp;
}
public static void main(String []args)
{
    Passing_Objects_to_Methods obj1=new Passing_Objects_to_Methods(2);
    Passing_Objects_to_Methods obj2=new Passing_Objects_to_Methods(1);
    System.out.println("Before Swapping");
    System.out.println("Id of obj1 "+obj1.id);
    System.out.println("Id of obj2 "+obj2.id);
    swap(obj1, obj2);
    System.out.println("After Swapping");
    System.out.println("Id of obj1 "+obj1.id);
    System.out.println("Id of obj2 "+obj2.id);
}   

When I pass object and try to interchange it wont change outside the block since java is pass-by-value But

public class Passing_Objects_to_Methods_Part2 {
    int id;
    public Passing_Objects_to_Methods_Part2(int id) 
    {
        this.id=id;
    }
        
    public static void Swap(Passing_Objects_to_Methods_Part2 b1,Passing_Objects_to_Methods_Part2 b2)
    {
        int temp;
        temp=b1.id;
        b1.id=b2.id;
        b2.id=temp;
    }
    public static void main(String[] args)
    {
        Passing_Objects_to_Methods_Part2 obj1=new Passing_Objects_to_Methods_Part2(2);
        Passing_Objects_to_Methods_Part2 obj2=new Passing_Objects_to_Methods_Part2(1);
        System.out.println("Before Swapping");
        System.out.println("Id of obj1 "+obj1.id);
        System.out.println("Id of obj2 "+obj2.id);
        Swap(obj1, obj2);
        System.out.println("After Swapping");
        System.out.println("Id of obj1 "+obj1.id);
        System.out.println("Id of obj2 "+obj2.id);

    }
}

As I try to interchange The variables of objects it does change them Outside the block also.Please Tell me the reason.

Progman
  • 16,827
  • 6
  • 33
  • 48
  • 4
    [You just asked a very similar question](https://stackoverflow.com/questions/67656997/tell-now-i-have-learnt-that-java-is-pass-by-value-but-at-this-moment-i-am-bit-co). if you want to clarify some things in that question such as explaining why it wasn't a duplicate, you should edit it, not post a new one. – Sweeper May 23 '21 at 08:43
  • 1
    Only the object reference is passed by-value. Java does not create a copy of your (full) object (tree). You cannot switch the object reference to a new one (as you discovered), but you can change anything "inside" the object (because it is not a copy). – knittl May 23 '21 at 09:28

0 Answers0