Swap two variables without using third variable

Below are java program to Swap two variables without using third variable . This program will swap two variable int and String.

public class SwapVariable {

	public static void main(String[] args) {

		// Swaping numbers
		int a = 10;
		int b = 20;
		a = a + b;
		b = a - b;
		a = a - b;

		System.out.println("a: = " + a);
		System.out.println("b: " + b);

		// Swaping String
		String value1 = "Java";
		String value2 = "Honk";

		value1 = value1 + value2;
		value2 = value1.substring(0, (value1.length() - value2.length()));
		value1 = value1.substring(value2.length(), value1.length());

		System.out.println("value1 = " + value1);
		System.out.println("value2 = " + value2);

	}

}

 

Output:
Swap two variables without using third variable

That’s it for Swap two variables without using third variable

Leave a Reply

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