Swapping of Two Numbers in Java

package com.java.programs;
public class SwapNumbers {
	
	public static void swapUsingThirdVariable(int x, int y) {
		System.out.println("Before Swapping: x = "+x+" , y = "+y);
		int temp;
		temp = x;
		x = y;
		y = temp;
		System.out.println("After Swapping: x = "+x+" , y = "+y);
	}
	
	public static void swapWithoutUsingThirdVariable(int x, int y) {
		System.out.println("Before Swapping: x = "+x+" , y = "+y);
		x = x + y;
		y = x - y; // => y = (x + y) - y => y = x
		x = x - y; // => x = (x + y) - x => x = y
		System.out.println("After Swapping: x = "+x+" , y = "+y);
	}
	
	public static void main(String[] args) {
		swapUsingThirdVariable(5,6);
		swapWithoutUsingThirdVariable(4,5);
	}
}
Before Swapping: x = 5 , y = 6
After Swapping: x = 6 , y = 5
Before Swapping: x = 4 , y = 5
After Swapping: x = 5 , y = 4

Related Article

Simple Java Programs asked in Interviews

Leave a Reply

Your email address will not be published. Required fields are marked *