Skip to main content

How to Swap two numbers without using third variable in Java

How to Swap two numbers without using third variable in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package logic;
 
import java.util.Scanner;
 
public class SwapWithoutThird 
{
	 static void swap(int arg1,int arg2)
	 {
		 arg1=arg1+arg2;
		 arg2=arg1-arg2;
		 arg1=arg1-arg2;
 
		 System.out.println("after Swapin value of n1= "+arg1);
		 System.out.println("after Swapin value of n2= "+arg2);
 
	 }
 
	public static void main(String[] args) 
	{
		Scanner c=new Scanner(System.in);
		System.out.println("enter a first number");
		int n1=c.nextInt();
 
		System.out.println("enter second number");
 
        int n2=c.nextInt();
        System.out.println("value of n1= "+n1);
        System.out.println("value of n2= "+n2);
        swap(n1,n2);
 
	}
 
}

output:

1
2
3
4
5
6
7
8
enter a first number
10
enter second number
20
value of n1= 10
value of n2= 20
after Swapin value of n1= 20
after Swapin value of n2= 10