call by value call by refrence in java code example

Example: call by value and call y refrence in java

/*call by refrence doesnot change the value of parameters(a and b ) in
main function but where as passing the values by refrence changes the values 
of and b in the main function
*/
//CALL BY REFERENCE
public class JavaTester {
   public static void main(String[] args) {
      IntWrapper a = new IntWrapper(30);
      IntWrapper b = new IntWrapper(45);
      System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);
      // Invoke the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping values will be different here**:");
      System.out.println("After swapping, a = " + a.a + " and b is " + b.a);
   }
   public static void swapFunction(IntWrapper a, IntWrapper b) {
      System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);
      // Swap n1 with n2
      IntWrapper c = new IntWrapper(a.a);
      a.a = b.a;
      b.a = c.a;
      System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);
   }
}
class IntWrapper {
   public int a;
   public IntWrapper(int a){ this.a = a;}
}
/*
------------------------------------OUTPUT--------------------------------------
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be different here**:
After swapping, a = 45 and b is 30
--------------------------------------------------------------------------------
*/
//CALL BY VALUE
public class Tester{
   public static void main(String[] args){
      int a = 30;
      int b = 45;
      System.out.println("Before swapping, a = " + a + " and b = " + b);
      // Invoke the swap method
      swapFunction(a, b);
      System.out.println("\n**Now, Before and After swapping values will be same here**:");
      System.out.println("After swapping, a = " + a + " and b is " + b);
   }
   public static void swapFunction(int a, int b) {
      System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
      // Swap n1 with n2
      int c = a;
      a = b;
      b = c;
      System.out.println("After swapping(Inside), a = " + a + " b = " + b);
   }
}
/*
-----------------------------------OUTPUT---------------------------------------
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45
--------------------------------------------------------------------------------
*/

Tags:

Java Example