Java Program to Swap Two Numbers

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:

After swapping:
a = 20
b = 10
 

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *