If you search for Java Interview Questions on Google then you will find this question most from top questions. In Java what are the best way to Swap Two Members Without using Temp Variable?
In this tutorial we will solve this problem by two different ways:
- Using
addition
andsubtraction
method - Using
multiplication
anddivide
method
Here is a complete code:
package com.crunchify.tutorials; /** * @author Crunchify.com */ public class CrunchifySwapVariables { public static void main(String[] args) { int a = 20; int b = 30; int c = 3; int d = 4; CrunchifySwapVariables.SwapVairablesMethod1(a, b); CrunchifySwapVariables.SwapVairablesMethod2(c, d); } public static void SwapVairablesMethod1(int a, int b){ System.out.println("value of a and b before swapping, a: " + a +" b: " + b); //swapping value of two numbers without using temp variable a = a + b; //now a is 50 and b is 20 b = a - b; //now a is 50 but b is 20 (original value of a) a = a - b; //now a is 30 and b is 20, numbers are swapped System.out.println("Result Method1 => a: " + a +" b: " + b); } public static void SwapVairablesMethod2(int c, int d){ System.out.println("\nvalue of c and d before swapping, c: " + c +" d: " + d); //swapping value of two numbers without using temp variable using multiplication and division c = c*d; d = c/d; c = c/d; System.out.println("Result Method2 => c: " + c +" d: " + d); } }
Output:
value of a and b before swapping, a: 20 b: 30 Result Method1 => a: 30 b: 20 value of c and d before swapping, c: 3 d: 4 Result Method2 => c: 4 d: 3
List of all Java Tutorials.