JAVA Program 5: Swap two integer variables without using third variable

Problem: Write a java program to swap values of two integer variables without using third variable.

Solution:

Java Program:

import java.util.Scanner;

public class SwapingTwoNumbers {

	public static void main(String[] args) {
		
		// taking input from user
		Scanner in = new Scanner(System.in);
		System.out.println("Enter the 1st number: ");
		int x = in.nextInt();
		System.out.println("Enter the 2nd number: ");
		int y = in.nextInt();
		 
		// printing values before swap
		System.out.println("Before Swap: ");
		System.out.println("Value of x: "+x);
		System.out.println("Value of y: "+y);
		
		// swapping without using third variable
		x = x+y;
		y = x-y;
		x = x-y;
		 
		// printing values after swap
		System.out.println("After Swap: ");
		System.out.println("Value of x: "+x);
		System.out.println("Value of y: "+y);
	}
}

Output:
Enter the 1st number:
21
Enter the 2nd number:
33
Before Swap:
Value of x: 21
Value of y: 33
After Swap:
Value of x: 33
Value of y: 21

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning