Swap Two Numbers

Swap the values of two variables using a temporary variable.

BeginnerTopic: Module 1: Basic Java Programs
Back

Java Swap Two Numbers Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
public class Main {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        System.out.println("Before swap: a = " + a + ", b = " + b);

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

        System.out.println("After swap: a = " + a + ", b = " + b);
    }
}
Output
Before swap: a = 5, b = 10
After swap: a = 10, b = 5

Understanding Swap Two Numbers

We use a temporary variable to store one value while we perform the swap:

temp = a → a = b → b = temp

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents