English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn two techniques to swap two numbers in Java. The first uses a temporary variable for swapping, and the second does not use any temporary variable.
fun main(args: Array<String>) { var first = 12.0f var second = 24.5f println("--Before swapping--) println("The first number = $first") println("The second number = $second") first = first - second second = first + second first = second - first println("--After swapping--) println("The first number = $first") println("The second number = $second") }
When running the program, the output is:
--Before swapping-- The first number = 1.2 The second number = 2.45 --After swapping-- The first number = 2.45 The second number = 1.2
In the above program, the two numbers to be swapped are1.20f and2.45f are stored in variables first and second.
Before swapping, use println() to print the variables to clearly see the result after swapping.
First, the value of first is stored in the temporary variable temporary (temporary = 1.20f) in.
Then, the value of second is stored in first (first = 2.45f).
And, the final value temporary is stored in second (second = 1.20f) in.
This completes the swapping process, and the variables are printed on the screen.
Remember, the only use of temporary is to save the value of first before swapping. You can also swap numbers without using temporary.
fun main(args: Array<String>) { var first = 12.0f var second = 24.5f println("--Before swapping--"); println("The first number = " + $first) println("The second number = " + $second) first = first - second second = first + second first = second - first println("--After swapping--"); println("The first number = " + $first) println("The second number = " + $second) }
When running the program, the output is:
--Before swapping-- The first number = 12.0 The second number = 24.5 --After swapping-- The first number = 24.5 The second number = 12.0
In the above program, we use simple math to swap numbers instead of using a temporary variable.
For the operation, store(first - second) is very important. It is stored in the variable first.
first = first - second; first = 12.0f - 24.5f
Then, we just addadding second(24.5f)-Calculated first(12.0f - 24.5f) to swap the numbers.
second = first + second; second = (12.0f - 24.5f) + 24.5f = 12.0f
Now, second holds12.0f(its original value). Therefore, we subtract the second(12.0f) minus the calculated first(12.0f - 24.5f) get another swapped number.
first = second - first; first = 12.0f - (12.0f - 24.5f) = 24.5f
The swapped numbers are printed on the screen using println().
This is the equivalent code in Java: In JavaSwap Two Numbers