Thursday, October 11, 2012

Swap Numbers Java Example



  public class SwapElementsExample {
   
          public static void main(String[] args) {
                 
                  int num1 = 10;
                  int num2 = 20;
                 
                  System.out.println("Number Before Swapping");
                  System.out.println("Value of num1 is :" + num1);
                  System.out.println("Value of num2 is :" +num2);
                 
                  //swap the value
                  swap(num1, num2);
          }
   
          private static void swap(int num1, int num2) {
                 
                  int temp = num1;
                  num1 = num2;
                  num2 = temp;
                 
                  System.out.println("Number After Swapping");
                  System.out.println("Value of num1 is :" + num1);
                  System.out.println("Value of num2 is :" +num2);
                 
          }
  }
   
 
  Output
  Number Before Swapping
  Value of num1 is :10
  Value of num2 is :20
  Number After Swapping
  Value of num1 is :20
  Value of num2 is :10

No comments:

Post a Comment