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.