Swap Two Numbers Without Using Third Temporary Variable | Java Programs

Output:

*** Swap Two Numbers Without Using Third Variable ***

*** Before swapping ***
a = 123
b = 456
*** After swapping ***
a = 456
b = 123

Click Here For Java Online Compiler

Solution:

public class SwapTwoNumbers2 {

    public static void main(String[] args) {
        int a = 123;
        int b = 456;
        System.out.println("*** Swap Two Numbers Without Using Third Variable ***" + "\n");
        System.out.println("*** Before swapping ***");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        a = a + b;
        b = a - b;
        a = a - b;
        System.out.println("*** After swapping ***");
        System.out.println("a = " + a);
        System.out.println("b = " + b);
    }
}
Share This :

Related Post

avatar

Can we do the same using division operation?
Java Code Korner

delete 10 January 2019 at 00:35



sentiment_satisfied Emoticon