Swapping 2 integers with temporary variable
Swapping Technique:
Example:
Code
package com.allabtjava.alg;
/**
* @author Nagasharath K
*/
public class Swap_With_Temp {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("Variable a has " + a + "and b has " + b + "before swapping");
int temp = 0;
temp = a;
a = b;
b = temp;
System.out.println("After swapping variable a has " + a + " and b has " + b);
}
}
Output:
Variable a has 10 and b has 20 before swapping
After swapping variable a has 20 and b has 10
Swapping 2 integers without temporary variable
Example:
package com.allabtjava.alg;
/**
* @author NAGASHARATH K
*/
public class Swap_Without_Temp {
public static void main(String[] args) {
int a = 70;
int b = 50;
System.out.println("Variable a has " + a + " and b has " + b + " before swapping");
int c = b - a;
a = a + c;
b = b - c;
System.out.println("After swapping variable a has " + a + " and b has " + b);
}
}
Output:
Variable a has 70and b has 50 before swapping
After swapping variable a has 50 and b has 70