Swapping two numbers is a common and simple programming exercise, especially for beginners learning Java. It helps you understand how variables work and how logic is built inside a program. In this blog, we will learn two ways to swap numbers:
- Using a temporary (third) variable
- Without using a third variable
Java Program to Swap Two Numbers Using Third Variable
public class SwapNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
int temp = a;
a = b;
b = temp;
System.out.println(“After swapping:”);
System.out.println(“a = ” + a);
System.out.println(“b = ” + b);
}
}
Output:
- surya
- sury32@gmail.com