Q. Write a Java program to swap two numbers.
Answer:
Program to swap two numbers using a temporary variable.
Output:

Q. Program to swap two numbers without using third variable.
Answer:
Output:

Answer:
Program to swap two numbers using a temporary variable.
Swap.java
class Swap
{
public static void main(String[] args)
{
int a = 5;
int b = 10;
int temp;
System.out.println("Before swapping, a: "+a+" b: "+b);
temp = a;
a = b;
b = temp;
System.out.println("After swapping, a: "+a+" b: "+b);
}
}
Output:

Q. Program to swap two numbers without using third variable.
Answer:
SwapNumber.java
class SwapNumber
{
public static void main(String[] args)
{
int a = 15;
int b = 17;
System.out.println("Before swapping a: "+a+", b: "+b);
a = a + b;
b = a - b;
a = a - b;
System.out.println("After swapping a: "+a+", b: "+b);
}
}
Output:



