Swap Two Numbers in Java

Java Program to Swap two Numbers

Swapping is the process of exchange the values of two variables with each other. For example variable num1 contains 20 and num2 contains 40 after swap their values are num1 contains 40 and num2 contains 20. In below code i will show exchange values of two variable using third variable and without sing third variable.

Java Program to Swap two Numbers using third variable

```import java.util.Scanner;
class Swapnumber
{
public static void main(String[] args)
{
int a, b, c;
Scanner s=new Scanner(System.in);
System.out.println("Enter Value in a :");
a=s.nextInt();
System.out.println("Enter Value in b :");
b=s.nextInt();
c=a;
a=b;
b=c;
System.out.println("Values in a:" +a);
System.out.println("Values in b:" +b);
}
}
```

Output

```Enter Value in a : 10
Enter Value in b : 20
Value in a : 20
Value in b : 10
```

Java Program to Swap two numbers without using third variable

```import java.util.Scanner;
class Swapnumber
{
public static void main(String[] args)
{
int a, b;
Scanner s=new Scanner(System.in);
System.out.println("Enter Value in a :");
a=s.nextInt();
System.out.println("Enter Value in b :");
b=s.nextInt();
a=a+b;
b=a-b;
a=a-b;
System.out.println("Values in a:" +a);
System.out.println("Values in b:" +b);
}
}
```

Output

```Enter Value in a :
10
Enter Value in b :
20
Value in a : 20
Value in b : 10
```

Syntax

```for compile -> c:/javac Swapnumber.java
for run -> c:/java Swapnumber
```

Explanation of Code

• Scanner s=new Scanner(System.in): are used for receive input from keyboard.
• nextInt(): method are used for get integer type value from keyboard.
• System.out.println("....."): are used for display message on screen or console.