In one of the previous tutorial, I have explained how to swap two numbers in java programming language. In this tutorial, I will share how to write a java program to swap number without a temporary variable.
Copy the below java program and execute it with the help Java compiler. At the end of this tutorial, I have shared the output of the following programs.
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 SwapNumbers { public static void main(String args[]) { int x, y; System.out.println("Enter the 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); x = x + y; y = x - y; x = x - y; System.out.println("After Swapping:\nx = "+x+"\ny = "+y); } } |
Enter the number x and y:
30
10
Before Swapping:
30
10
After Swapping:
10
30
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: java program after swap two numbers, Java programming, Java programs, Java programs with examples, Java programs with output, java tutorial, Java tutorials