- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Program To Swap Two Number
Swapping two variables is a fundamental logic exercise that every developer encounters early in their journey. Whether you are reordering elements in a list or implementing a sorting algorithm like Bubble Sort, understanding how to exchange values between two memory locations is essential.
In Java, because we typically work with primitive types like int, swapping requires a specific logical flow to ensure no data is lost during the transition. Here is the most common and readable way to achieve this using a temporary variable.
public class SwapNumbers {
public static void main(String[] args) {
// Step 1: Initialize two integer variables
int a = 5;
int b = 10;
System.out.println("--- Before Swapping ---");
System.out.println("Value of a: " + a);
System.out.println("Value of b: " + b);
// Step 2: Perform the swap using a third (temporary) variable
// Imagine 'temp' as a placeholder to prevent 'a' from being overwritten
int temp = a; // temp now holds 5
a = b; // a now holds 10
b = temp; // b now holds 5
System.out.println("\n--- After Swapping ---");
System.out.println("Value of a: " + a);
System.out.println("Value of b: " + b);
}
}
a and b are fine for tutorials, in a real application, you might use currentPrice and previousPrice to make the code self-documenting.
How the Logic Works
If you try to swap values by simply writing a = b; b = a;, you will find that both variables end up with the same value. This happens because the moment you assign b to a, the original value of a is overwritten and lost forever.
To visualize this, imagine you have a Glass of Orange Juice (A) and a Glass of Apple Juice (B). If you want to put the Apple Juice into Glass A, you first have to pour the Orange Juice into an Empty Third Glass (Temp). Once Glass A is empty, you can move the Apple Juice over, and finally, pour the Orange Juice from the Third Glass into Glass B.
temp = a; a = b; but then forget to finish the process with b = temp;, leaving the second variable unchanged.
Swapping Without a Temporary Variable
While the temporary variable method is the most readable and "standard" way to swap, you might encounter scenarios in interviews where you are asked to swap numbers without using a third variable. This can be done using simple arithmetic:
// Arithmetic Swap Logic
a = a + b; // a becomes 15 (5 + 10)
b = a - b; // b becomes 5 (15 - 10)
a = a - b; // a becomes 10 (15 - 5)
a + b exceeds Integer.MAX_VALUE (2,147,483,647), it will cause an integer overflow, potentially leading to incorrect results.
Practical Real-World Example
In software development, swapping is rarely done in isolation. A classic example is the Selection Sort algorithm. When the algorithm finds the smallest number in an array, it must "swap" it with the element currently at the front of the list. Without the logic shown above, the algorithm would accidentally delete data instead of reordering it.
By mastering this simple three-step process, you have learned how to safely manipulate data in memory—a skill that will serve you throughout your entire career as a Java developer.