Advertisement
Shailrshah

Swapping numbers using Call by Value and Call by Reference

Nov 3rd, 2014
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. import java.util.Scanner;
  2. class Numbers{
  3.     int a, b;
  4. }
  5. class Swapping{
  6.     public static void swap_by_ref(Numbers n){
  7.         System.out.println("[swap_by_ref(), at start]n.a = "+n.a+" and n.b = "+n.b);       
  8.         int temp = n.a;
  9.         n.a = n.b;
  10.         n.b = temp;
  11.         System.out.println("[swap_by_ref()], at end]n.a = "+n.a+" and n.b = "+n.b);
  12.     }
  13.     public static void swap_by_val(int a, int b){
  14.         System.out.println("[swap_by_val()], at start]a = "+a+" and b = "+b);
  15.         int temp = a;
  16.         a = b;
  17.         b = temp;
  18.         System.out.println("[swap_by_val()], at start]a = "+a+" and b = "+b);
  19.     }
  20.     public static void main(String args[]){
  21.         Scanner sc = new Scanner(System.in);
  22.         System.out.println("Enter two numbers.");      
  23.         Numbers n = new Numbers();
  24.         n.a = sc.nextInt();
  25.         n.b = sc.nextInt();
  26.         int x = n.a;
  27.         int y = n.b;
  28.        
  29.         System.out.println("\n\n[main(), before swap_by_val()]x = "+x+" and y = "+y);  
  30.         swap_by_val(x, y);
  31.         System.out.println("[main(), after swap_by_val()]x = "+x+" and y = "+y+"\n\n");
  32.  
  33.         System.out.println("[main(), before swap_by_ref()]n.a = "+n.a+" and n.b = "+n.b);      
  34.         swap_by_ref(n);
  35.         System.out.println("[main(), after swap_by_ref()]n.a = "+n.a+" and n.b = "+n.b);
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement