Swap two numbers in Java example shows how to swap two numbers using a temp variable and without using the third temp variable.
How to swap two numbers using a temp variable in Java?
The logic of swapping two numbers using the temp variable in Java is simple. We use a temp variable to hold the value of the first variable, assign the second variable to the first, and then assign temp to the second variable. Please see below the given code example to do that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package com.javacodeexamples.basic; import java.util.Scanner; public class SwapTwoNumbersWithoutTempExample { public static void main(String[] args) { //create a scanner Scanner s = new Scanner(System.in); System.out.println("Input two numbers"); //get the int values from the console int a = s.nextInt(); int b = s.nextInt(); //swap numbers using a temp variable //1. assign a to temp variable int temp = a; //2. assign b to a, now a contains value of b a = b; //3. assign temp to b (temp contains original a value) b = temp; System.out.println("Values after number swap"); System.out.println("a: " + a); System.out.println("b: " + b); } } |
Output
1 2 3 4 5 6 |
Input two numbers 25 75 Values after number swap a: 75 b: 25 |
How to swap without using a third temp variable in Java?
Swapping two numbers without using a temp variable is a bit tricky. We need to use some math to do that. First, we add both the numbers and assign the sum to the first variable. Now we subtract the second variable from the sum and assign it to the first variable (so that the second variable contains the value of the first and that is half job done). Then we again subtract the value of the second variable from the sum and assign it to the first variable (it will give the value of the first variable because now the second variable contains the value of the first variable).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.javacodeexamples.basic; import java.util.Scanner; public class SwapTwoNumbersWithoutTempExample { public static void main(String[] args) { //create a scanner Scanner s = new Scanner(System.in); System.out.println("Input two numbers"); //get the int values from the console int a = s.nextInt(); int b = s.nextInt(); //swap numbers without temp variable //1. add a and b, assign it to a a = a + b; //2. now subtract b from a, that will give us value of a b = a - b; //3. Subtract updated b (which now contain value of a) from a a = a - b; System.out.println("Values after number swap"); System.out.println("a: " + a); System.out.println("b: " + b); } } |
Output
1 2 3 4 5 6 |
Input two numbers 15 27 Values after number swap a: 27 b: 15 |
Please also check out the Java Math Tutorial with examples to know more about arithmetic operations.
This example is a part of the Java Basic Examples.
Please let me know your views in the comments section below.