DEV Community

Sudhakar V
Sudhakar V

Posted on

programming - Swap With or Without Third Variable

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 {
Enter fullscreen mode Exit fullscreen mode

Defines a public class named Swap.

public static void main(String[] args) {
Enter fullscreen mode Exit fullscreen mode

The main method where the program starts.


๐Ÿงฎ Variable Initialization

int no1 = 10;
int no2 = 20;
Enter fullscreen mode Exit fullscreen mode
  • no1 is assigned the value 10
  • no2 is assigned the value 20

๐Ÿ” Swapping Logic Using a Temp Variable

int temp = no1;
Enter fullscreen mode Exit fullscreen mode
  • Store the value of no1 (10) in a temporary variable temp.
no1 = no2;
Enter fullscreen mode Exit fullscreen mode
  • Now assign the value of no2 (20) to no1.
  • So, no1 becomes 20.
no2 = temp;
Enter fullscreen mode Exit fullscreen mode
  • Assign the value of temp (10) to no2.
  • So, no2 becomes 10.

๐Ÿ–จ๏ธ Output

System.out.println(no1);
System.out.println(no2);
Enter fullscreen mode Exit fullscreen mode

This will print:

20
10
Enter fullscreen mode Exit fullscreen mode

โœ… 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
Enter fullscreen mode Exit fullscreen mode

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 {
Enter fullscreen mode Exit fullscreen mode

Defines a class called Swapwithout.

public static void main(String[] args) {
Enter fullscreen mode Exit fullscreen mode

Program starts here.


๐Ÿงฎ Variable Initialization

int no1 = 10;
int no2 = 20;
Enter fullscreen mode Exit fullscreen mode
  • no1 is 10
  • no2 is 20

๐Ÿง  Swapping Logic (Without Temp Variable)

no1 = no1 + no2;
Enter fullscreen mode Exit fullscreen mode
  • no1 becomes 10 + 20 = 30
no2 = no1 - no2;
Enter fullscreen mode Exit fullscreen mode
  • no2 becomes 30 - 20 = 10
no1 = no1 - no2;
Enter fullscreen mode Exit fullscreen mode
  • no1 becomes 30 - 10 = 20

โœ… Final Values

  • no1 = 20
  • no2 = 10
System.out.println(no1); // prints 20
System.out.println(no2); // prints 10
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Output:

20
10
Enter fullscreen mode Exit fullscreen mode

๐Ÿ“Œ 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)