In Java, you can swap two numbers using a temporary variable to store the value of one of the numbers before swapping them.
Here’s an example Java program that swaps two numbers:
public class SwapNumbers { public static void main(String[] args) { int num1 = 10; int num2 = 20; System.out.println("Before swapping:"); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); // swap the numbers int temp = num1; num1 = num2; num2 = temp; System.out.println("After swapping:"); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); } }
Here, we declare two integer variables num1
and num2
, and initialize them with the values 10 and 20, respectively.
We then print the values of num1
and num2
before swapping them.
To swap the two numbers, we declare a third integer variable temp
and store the value of num1
in it.
We then assign the value of num2
to num1
and finally assign the value of temp
(which is the original value of num1
) to num2
.
Finally, we print the values of num1
and num2
after swapping them.
The output of the above program will be:
Before swapping: num1 = 10 num2 = 20 After swapping: num1 = 20 num2 = 10
In summary, to swap two numbers in Java, you need to use a temporary variable to store the value of one of the numbers before swapping them.