In this article I would like to share with you a program that will ask the user to give two integer numbers and then our program will swap or interchange the arrangement of two numbers without using third variable in Java. The code is very easy simple and easy to understand. I am using TextPad as my text editor in this sample program. Thank you.
My email address are the following jakerpomperada@gmail.com and jakerpomperada@yahoo.com.
My mobile number here in the Philippines is 09173084360.
Sample Program Output
Program Listing
swap.java
import java.util.Scanner;
class swap {
public static void main(String args[])
{
int num1=0, num2=0;
Scanner s = new Scanner(System.in);
System.out.println();
System.out.println("=== Swap of Two Numbers Without Using Third Variable in Java === ");
System.out.println();
System.out.print("Enter First Value : ");
num1 = s.nextInt();
System.out.print("Enter Second Value : ");
num2 = s.nextInt();
System.out.println();
System.out.println("===== BEFORE SWAPPING ======");
System.out.println();
System.out.println(num1 + " " + num2);
num1 = (num1+num2);
num2 = (num1-num2);
num1 = (num1-num2);
System.out.println();
System.out.println("===== BEFORE SWAPPING ======");
System.out.println();
System.out.println(num1 + " " + num2);
System.out.println();
System.out.println("===== END OF PROGRAM ======");
System.out.println();
}
} // End of Code