Java program to swap two numbers
Sure, here's a Java program to swap two numbers:
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); int temp = num1; num1 = num2; num2 = temp; System.out.println("After swapping:"); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); } }
In this program, we first define two integer variables num1
and num2
to represent the numbers to swap. We then print out the values of num1
and num2
before swapping.
We then define a third integer variable temp
and assign num1
to it. We can think of this as temporarily storing the value of num1
so that we don't lose it when we overwrite num1
with num2
.
We then assign num2
to num1
and temp
to num2
, effectively swapping the values of num1
and num2
.
Finally, we print out the values of num1
and num2
after swapping.
Note that we can also swap two numbers without using a temporary variable by using arithmetic operations, as follows:
num1 = num1 + num2; num2 = num1 - num2; num1 = num1 - num2;
However, this method is less readable and may be less efficient on some platforms.