How to Accept Two Values of a & b and Swap their Values in Java

The program allows users to input two numbers and then swaps the values of these two numbers. 

It provides a practical illustration of how to exchange the values of two variables in a program

How to Accept Values of Two Numbers and Print their Addition

In this program:

  1. User Input: Prompt the user to enter two numbers (a and b).
  2. Swapping: Swap the values of a and b using a temporary variable (temp).
  3. Display Results: Show the values of a and b both before and after the swap.

import java.util.Scanner;

public class SwapValues {
    public static void main(String[] args) {
        int a, b, temp;
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter 1st number: ");
        a = scanner.nextInt();

        System.out.print("Enter 2nd number: ");
        b = scanner.nextInt();

        System.out.println("\nBefore Swapping...");
        System.out.println("A=" + a + ", B=" + b);

        temp = a;
        a = b;
        b = temp;

        System.out.println("\nAfter Swapping...");
        System.out.println("A=" + a + ", B=" + b);
    }
}
Join Now


Previous Year Questions Now to Boost Your Exam Performance

LOADS OF LOGIC