Java: Swap two variables
Swap Variables
Write a Java program to swap two variables.
Java: Swapping two variables
Swapping two variables refers to mutually exchanging the values of the variables. Generally, this is done with the data in memory.
The simplest method to swap two variables is to use a third temporary variable :
define swap(a, b) temp := a a := b b := temp
Pictorial Presentation:
Sample Solution-1
Java Code:
Explanation:
In the exercise above -
- Initialize two integer variables, 'a' with the value 15 and 'b' with the value 27.
- Prints the original values of 'a' and 'b' before swapping.
- Use a temporary variable temp to temporarily store the value of 'a'.
- Assign the value of 'b' to 'a'.
- Assign the value stored in temp (originally from a) to 'b'.
- Finally, it prints the values of 'a' and 'b' after the swapping operation.
Without using third variable.
Sample Solution-2
Java Code:
Explanation:
In the exercise above -
- Initialize two integer variables, 'a' with the value 15 and 'b' with the value 27.
- Prints the original values of 'a' and 'b' before swapping.
- Use arithmetic operations to swap values without using a temporary variable:
- a = a + b adds 'a' and 'b' and stores the sum in 'a'. Now, 'a' contains the sum of the original 'a' and 'b'.
- b = a - b subtracts the original 'b' from the updated 'a' and stores the result in 'b'. Now, 'b' contains the original value of 'a'.
- a = a - b subtracts the updated 'b' (which now contains the original value of 'a') from the updated 'a' and stores the result in 'a'. Now, 'a' contains the original value of 'b'.
- Finally, it prints the values of 'a' and 'b' after the swapping operation.
Sample Output:
Before swapping : a, b = 15, 27 After swapping : a, b = 27, 15
Flowchart:
Sample Solution (Input from the user):
Java Code:
Sample Output:
Input the first number: 36 Input the second number: 44 Swapped values are:44 and 36
Flowchart:
For more Practice: Solve these Related Problems:
- Swap two variables without using a temporary variable.
- Swap three variables in a circular fashion.
- Write a program that swaps two numbers but does not allow direct arithmetic operations.
- Swap two strings instead of integers.
Java Code Editor:
Previous: Write a Java program to print an American flag on the screen.
Next: Write a Java program to print a face.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.