Friday, 1 April 2016

Swap Numbers Without Using Third Variable Java Example

Java program to Swap Numbers Without Using Third Variable

Program:


public class SwapElement {  

    public static void main(String[] args) {
        
        int num1 = 10;
        int num2 = 20;
        
        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: 


Before Swapping
Value of num1 is :10
Value of num2 is :20
Before Swapping
Value of num1 is :20

Value of num2 is :10

No comments :

Post a Comment