How can swap two variables without using third variable
Answer : Please have example below to swap string and int variable:
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 :