Java Program to Swap Two Numbers

You are currently viewing Java Program to Swap Two Numbers

Hey guys! If you are looking to know the concept of the “Java Program to Swap Two Numbers” then read this tutorial to learn about it. Initially, We will discuss the swapping numbers and how to do a task? Let’s see the possibilities here.

Interchanging the values of two variables with each other is called the swapping numbers. For example, If we can assign “a=2”, “b=4” then the output will be like “a=4”, “b=2”.

Java Program to Swap Two Numbers

We can swap two numbers using java in the below example program.

import java.util.*;  
class Swap_With {  
    public static void main(String[] args) {  
       int x, y, t;// x and y are to swap   
       Scanner sc = new Scanner(;  
       System.out.println("Enter the value of X and Y");  
       x = sc.nextInt();  
       y = sc.nextInt();  
       System.out.println("before swapping numbers: "+x +"  "+ y);  
       /*swapping */  
       t = x;  
       x = y;  
       y = t;  
       System.out.println("After swapping: "+x +"   " + y);  
       System.out.println( );  

Source Code Explanation

Initially, We have to import the java.util.scanner class into this program. Secondly, We need to declare the respective variables for both input and output values.

After running this program, The program asks you to enter the input values. The output of swapping numbers will be displayed on the output screen after applying the values and clicking on the enter button.

Finally, The system.out.printIn() function will help to show the result on the output screen.

Read Also : Remove Vowels From String in Java


We can also Swap Two Numbers in PHP and Swap Two Numbers in Python. We have already shared those articles on our webpage. Please check and learn about it.

Output of Java Program to Swap Two Numbers

The output of the java program to swap two numbers will be given below for your reference. The input values will be either a user’s choice or your wish.

Enter the value of X and Y
before swapping numbers: 5  8
After swapping: 8   5


I hope this article helps you to swap two numbers in the Java program. If you face any issues please let me know via the comment section. Share this article with other Java program developers via social networks. Thank You!

Manoj S

Hi, I'm Manoj working as a part-time blogger in Coding Diksha. Here, I post about programming to help developers.

Leave a Reply