Write a java program to swap two variable

To swap two variables in Java, you can use a temporary variable to hold the value of one of the variables before swapping. Here's an example Java program that swaps the values of two variables: 

 

public class SwapVariables {
    public static void main(String[] args) {
        int a = 5;
        int b = 10;

        System.out.println("Before swapping: a = " + a + ", b = " + b);

        int temp = a;
        a = b;
        b = temp;

        System.out.println("After swapping: a = " + a + ", b = " + b);
    }
}

In this program, we declare two integer variables a and b with initial values of 5 and 10 respectively. We then print out the values of a and b before swapping.

We then declare a temporary variable temp to hold the value of a. We then assign the value of b to a, and finally assign the value of temp (which is the original value of a) to b.

Finally, we print out the values of a and b after swapping.

When we run this program, the output should be: 

 

Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

 

Submit Your Programming Assignment Details