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.

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("After 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:10 20
After swap a is:20
After swap b is:10