swap two numbers in java without using third variable in java code example

Example 1: swap two variables without temporary java

import java.*; 
  
class noTemp { 
  
    public static void main(String a[]) 
    { 
        int x = 10; 
        int y = 5; 
        x = x + y; 
        y = x - y; 
        x = x - y; 
        System.out.println("After swaping:"
                           + " x = " + x + ", y = " + y); 
    } 
}

Example 2: swap 2 integers without using temporary variable

using System;

class MainClass {
  public static void Main (string[] args) {
    int num1 = int.Parse(Console.ReadLine());
    int num2 = int.Parse(Console.ReadLine());
      num1 = num1 + num2; 
      num2 = num1 - num2; 
      num1 = num1 - num2; 
      Console.WriteLine("After swapping: num1 = "+ num1 + ", num2 = " + num2); 
    Console.ReadLine();
  }
}

Tags:

Misc Example