This program demonstrates how you can swap values in 2 variables by different methods.
public class Swap extends Object { public static void main(String args[]) { int a = 123; int b = 345; System.out.println(a + " : " + b); //Swapping using temporary variable : straight-forward method int temp = a; a = b; b = temp; System.out.println(a + " : " + b); //Swapping using arithmetic operations : saves memory a = a + b; //You can use a += b; b = a - b; a = a - b; //You can use a -= b; System.out.println(a + " : " + b); //Swapping using bitwise operations : avoids arithmetic overflow a = a ^ b; //You can use a ^= b; b = a ^ b; //You can use b ^= a; a = a ^ b; //You can use a ^= b; System.out.println(a + " : " + b); } }
Copyright © 1999-2008 Krishna Kumar, All Rights Reserved.