In this post, we will see how to swap two numbers without using temporary variables.
There are three ways to do it.
Java program:
Java program:
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package org.arpit.java2blog; class SwapingTwoNumbers { public static void main(String args[]){ int a = 5; int b = 10; // First way System.out.println("First way"); System.out.println("Before swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); a = a+b; b = a-b; a = a-b; System.out.println("After swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); // Second way System.out.println("****************"); System.out.println("Second way"); System.out.println("Before swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); a = a*b; b = a/b; a = a/b; System.out.println("After swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); //Third way System.out.println("****************"); System.out.println("Third way"); System.out.println("Before swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); a = a^b; b = a^b; a = a^b; System.out.println("After swap:"); System.out.println("a value: "+a); System.out.println("b value: "+b); } } |
When you run above program, you will get following output:
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 |
First way Before swap: a value: 5 b value: 10 After swap: a value: 10 b value: 5 **************** Second way Before swap: a value: 10 b value: 5 After swap: a value: 5 b value: 10 **************** Third way Before swap: a value: 5 b value: 10 After swap: a value: 10 b value: 5 |
Please go through Interview programs in java  for more such programs.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.