Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Swapping without temporary variable in Java

  1. import java.util.Scanner;
  2. class SwapNumbers
  3. {
  4. public static void main(String args[])
  5. {
  6. int x, y;
  7. System.out.println("Enter x and y");
  8. Scanner in = new Scanner(System.in);
  9. x = in.nextInt();
  10. y = in.nextInt();
  11. System.out.println("Before Swapping\nx = "+x+"\ny = "+y);
  12. x = x + y;
  13. y = x - y;
  14. x = x - y;
  15. System.out.println("After Swapping\nx = "+x+"\ny = "+y);
  16. }
  17. }