Saturday, 8 June 2013

Java code to swap two integer values

Code
-----------
class SwapDemo {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 numbers to swap");

int a = s.nextInt();
int b = s.nextInt();

swap(a, b);
}

public static void swap(int a, int b) {

// Store a in a temporary variable
int temp = a;

// Store b variable value in a
a = b;

// Store temp (a original) value in b
b = temp;

// Print the variables
System.out.println("a is " + a + " & b is " + b);
}
}

No comments:

Post a Comment