This is a very basic program in Java programming language. If you are a Java beginners or want to start learning Java programming language, then this program will help you to understand the basic Java programming. In this post, I will explain about a Java program to swap two numbers with an example.
Before executing this program I assume you have configured Java in your computer.
Copy the below program and create a file “SwapNumberProgram.java” and execute it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | import java.util.Scanner; class SwapNumberProgram { public static void main(String args[]) { int x, y, temp; System.out.println("Enter number x and y"); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); System.out.println("Before Swapping\nx = "+x+"\ny = "+y); temp = x; x = y; y = temp; System.out.println("After Swapping\nx = "+x+"\ny = "+y); } } |
Enter number x and y
10
20
Before Swapping
x value: 10
y value: 20
After Swapping
x value: 20
y value: 10
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: code snippet in java for swapping, java program after swap two numbers, java program before swap and after swap, java tutorial, Java tutorials, sample swapping of 2 numbers, swapping using third variable