DEV Community

Guna Sekaran
Guna Sekaran

Posted on

Swapping The numbers in java

package array;

public class swapping_array {
    public static void main(String[] args) {
        int a=50,b=100;
        int temporary=a;//storing the a value into temporary variable for swapping. now it has 50 in it  

        a=b;     
        b=temporary;  
        System.out.println("a="+a);
        System.out.println("b="+b);
}
}

.........................................................................

OUTPUT:

a=100
b=50


Enter fullscreen mode Exit fullscreen mode

Another method for swapping the variables Without Creating new Variable.

package array;

public class swapping_array {
    public static void main(String[] args) {

    int a=5,b=6;
    a=a+b;//a=11
    b=a-b;//b=11-6 b=5 (b value changed into 5)
    a=a-b;//a=11-5 a=6 (a value changed into 6)

        System.out.println("a="+a);
        System.out.println("b="+b);
}
}

.........................................................................

OUTPUT:

a=6
b=5

Enter fullscreen mode Exit fullscreen mode

Top comments (0)