If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To swap two numbers, you need a temporary variable to hold one of the values while you interchange their positions. Here's a common method to swap two numbers in Java:
javaCopy code
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);
// Swapping logic using a temporary variable
int temp = num1;
num1 = num2;
num2 = temp;
System.out.println("\nAfter swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
Output:
makefileCopy code
Before swapping:
num1 = 10
num2 = 20
After swapping:
num1 = 20
num2 = 10
In the code above, num1
and num2
are initialized with the values 10 and 20, respectively. The swapping logic uses the temporary variable temp
to store the value of num1
. Then, the value of num2
is assigned to num1
, and finally, the value of temp
(which was the original value of num1
) is assigned to num2
, completing the swap.
After the swap, the values of num1
and num2
have exchanged, and you can see the results in the "After swapping" section of the output.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform