This is a simple Java program that swaps the values of two numbers using a temporary variable. Let me explain it line by line:
🔄 Swap Program Explanation
public class Swap {
Defines a public class named Swap
.
public static void main(String[] args) {
The main method where the program starts.
🧮 Variable Initialization
int no1 = 10;
int no2 = 20;
-
no1
is assigned the value 10 -
no2
is assigned the value 20
🔁 Swapping Logic Using a Temp Variable
int temp = no1;
- Store the value of
no1
(10) in a temporary variabletemp
.
no1 = no2;
- Now assign the value of
no2
(20) tono1
. - So,
no1
becomes 20.
no2 = temp;
- Assign the value of
temp
(10) tono2
. - So,
no2
becomes 10.
🖨️ Output
System.out.println(no1);
System.out.println(no2);
This will print:
20
10
✅ Values have been successfully swapped!
🔧 Bonus: Swap Without Temp Variable (Just for Fun)
int a = 10, b = 20;
a = a + b; // a = 30
b = a - b; // b = 10
a = a - b; // a = 20
Nice one, Sudhakar! This is a classic example of swapping two numbers without using a temporary variable. Let's break it down step by step:
🔁 Code Explanation:
public class Swapwithout {
Defines a class called Swapwithout
.
public static void main(String[] args) {
Program starts here.
🧮 Variable Initialization
int no1 = 10;
int no2 = 20;
-
no1
is 10 -
no2
is 20
🧠 Swapping Logic (Without Temp Variable)
no1 = no1 + no2;
-
no1
becomes10 + 20 = 30
no2 = no1 - no2;
-
no2
becomes30 - 20 = 10
no1 = no1 - no2;
-
no1
becomes30 - 10 = 20
✅ Final Values
-
no1
= 20 -
no2
= 10
System.out.println(no1); // prints 20
System.out.println(no2); // prints 10
💡 Output:
20
10
📌 Summary:
You've swapped two numbers without using a third variable—just by using arithmetic. Great job!
Let me know if you want to try the same using bitwise XOR method too—it’s another cool trick!