Pages

Swap two number



```java

public class SwapNumbers {

    public static void main(String[] args) {

        int num1 = 5;

        int num2 = 10;


        System.out.println("Before swapping: ");

        System.out.println("num1 = " + num1);

        System.out.println("num2 = " + num2);


        // Swapping logic

        int temp = num1;

        num1 = num2;

        num2 = temp;


        System.out.println("After swapping: ");

        System.out.println("num1 = " + num1);

        System.out.println("num2 = " + num2);

    }

}

```


Description:

1. We start by declaring two integer variables, `num1` and `num2`, with initial values.

2. Before swapping, we print the values of `num1` and `num2`.

3. To swap the numbers, we use a temporary variable `temp` to hold one of the values temporarily.

4. We assign `num2` to `num1` and then assign the value in `temp` to `num2`.

5. After swapping, we print the values of `num1` and `num2` again.


Conclusion:

This code demonstrates a simple way to swap two numbers in Java using a temporary variable. Swapping values is a common operation in programming, and this method is straightforward and widely used. It works for variables of any numeric type and can be adapted for other data types as well.

No comments:

Post a Comment