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;
-
no1is assigned the value 10 -
no2is 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,
no1becomes 20.
no2 = temp;
- Assign the value of
temp(10) tono2. - So,
no2becomes 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;
-
no1is 10 -
no2is 20
๐ง Swapping Logic (Without Temp Variable)
no1 = no1 + no2;
-
no1becomes10 + 20 = 30
no2 = no1 - no2;
-
no2becomes30 - 20 = 10
no1 = no1 - no2;
-
no1becomes30 - 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!
Top comments (0)