Java Program to swap two integer numbers using class


In this program, You will learn how to swap two integer numbers using the class in Java.


10 20 => 20 10


Example: How to swap two integer numbers using class in Java

Run it Now
import java.util.Scanner;

class Main {

    int a, b, temp;
    Scanner sc = new Scanner(System.in);

    void input() {
        System.out.print("Enter Two Numbers :");
        a = sc.nextInt();
        b = sc.nextInt();
    }

    void swap() {
        temp = a;
        a = b;
        b = temp;
    }

    void print() {
        System.out.println("\nAfter swap a is :" + a);
        System.out.println("After swap b is :" + b);

    }

    public static void main(String args[]) {
        Main obj = new Main();
        obj.input();
        obj.swap();
        obj.print();

    }
}

Output:

Enter Two Numbers :12 13
After swap a is :13
After swap b is :12