Page

Swap Numbers Without Using Third Variable in Java


public class SwapElementsWithoutThirdVariableExample {

        public static void main(String[] args) {
               
                int num1 = 12;
                int num2 = 15;
               
                System.out.println("Before Swapping");
                System.out.println("Value of num1 is :" + num1);
                System.out.println("Value of num2 is :" +num2);
               
              
                num1 = num1 + num2;
                num2 = num1 - num2;
                num1 = num1 - num2;
               
                System.out.println("Before Swapping");
                System.out.println("Value of num1 is :" + num1);
                System.out.println("Value of num2 is :" +num2);
        }


}

/*
Output of Swap Numbers Without Using Third Variable example would be
Before Swapping
Value of num1 is :12
Value of num2 is :15
After Swapping
Value of num1 is :15
Value of num2 is :12
*/

No comments:

Post a Comment