Call By reference in java.

Call by Reference in java

Many of the writer  said only call by value is possible in java not call by reference but i read call by reference:
class CallByRef {   static int a, b;
  public CallByRef() {
   a = 10;
   b = 20;
  }
static void swap(CallByRef obj) {
   int temp;
  temp = CallByRef.a;

CallByRef.a=CallByRef.b;
CallByRef.b=temp;

System.out.println("In the swap() method obj has the value of and b are:");
System.out.println("a=" + CallByRef.a + "\t" + "b=" + CallByRef.b);
}
public static void main(String[] args) {
CallByRef obj1 =  new CaallByRef();

System.out.println("Before swapping value of a and b in obj1");
System.out.println("a=" + CallByRef.a + "," + "b=" + CallByRef.b);


swap(obj1);

System.

out.println("After swapping value of a and b in obj1");


System.

out.println("a=" + CallByRef.a + "," + "b=" + CallByRef.b);




}

}


/*

Before swapping value of a and b in obj1

a=10,b=20

In the swap() method obj has the value of and b are:

a=20 b=10

After swapping value of a and b in obj1

a=20,b=10

*/
Here value of obj is changed then value of obj1 is also changed.
So it is call by Reference.

Comments

Popular posts from this blog