Home C C++ Java Python Perl PHP SQL JavaScript Linux Selenium QT Online Test

Home » Java » Programs » Swap two numbers

Java program to swap two numbers

public class Main {

	public static void main(String[] args) {
        int a = 97;
        int b = 32;
        
        System.out.println("----- Before swapping -----using temp variable:");
        System.out.println("Value of a is : " + a);
        System.out.println("Value of b is : " + b);
        System.out.println("----- After Swapping -----");
        int temp; temp = a; a = b; b = temp;
        System.out.println("Value of a is : " + a);
        System.out.println("Value of b is : " + b);
        
        System.out.println("----- Before swapping -----without using temp variable");
        System.out.println("Value of a is : " + a);
        System.out.println("Value of b is : " + b);
        System.out.println("----- After Swapping -----");
        a = a-b; // 97-32 = 65
        b = a+b; // 65+32 = 97
        a = b-a; // 97-65 = 32
        
        System.out.println("Value of a is : " + a);
        System.out.println("Value of b is : " + b);
	}
}