Swap two numbers with and without a third variable
Description: Swap the values of a = 10 and b = 25. First use a third variable. Then do it without a third variable.
Hint:
- With three variables:
temp = a; a = b; b = temp; - Without: use addition and subtraction.
Solution
public class Main {
public static void main(String[] args) {
int a = 10, b = 25;
int temp = a; // way 1: a third variable
a = b;
b = temp;
System.out.println("a = " + a + ", b = " + b);
a = a + b; // way 2: no third variable
b = a - b;
a = a - b;
System.out.println("a = " + a + ", b = " + b);
}
}
Output
a = 25, b = 10
a = 10, b = 25
How it works
- The first way keeps one value safe in
tempbefore it is replaced. - In the second way,
abecomes the sum, and then each variable gets the other value by subtraction. (Be careful: with very big numbers the sum can overflow.)
Read Java Operators.
Learn more about the similar topics:
| Tutorials |
|---|
| Java Variables |
| Java Data Types |
| Java Type Casting |
| Java Operators |
| Java User Input with Scanner |
| Java Math Class |
| Exercises & Assignments |
|---|
| Print your name and age with variables |
| Swap two numbers with and without a third variable |
| Convert Celsius to Fahrenheit |
| Interview Questions & Answers |
|---|
| What are the primitive data types in Java? |
| What are autoboxing and unboxing in Java? |