How to swap two numbers without using temporary variable in java

/**
 * Program for swapping two numbers without using temporary variable
 * @author Technical Explorer
 */
package com.technicalexplorer;

import java.util.Scanner;

public class SwapNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int first, second;
System.out.print("Enter first number: ");
first = scanner.nextInt();
System.out.print("Enter second number: ");
second = scanner.nextInt();
//Away close scanner object after use in order to avoid resource leak.
scanner.close();
System.out.println("Before Swap - first: " + first + ", second: " + second);
first = first + second;
//first value assigned to second
second = first - second;
//second value assigned to first
first = first - second;
System.out.println("After Swap - first: " + first + ", second: " + second);
}

}

Sample Input and Output:
Input: 
Enter first number: 121
Enter second number: 15
Output: 
Before Swap - first: 121, second: 15
After Swap - first: 15, second: 121

Swap two numbers without temporary variable

Powered by Blogger.