F JAVA Program To Swap Value Without Help Of Third Variable | CodeTheta

JAVA Program To Swap Value Without Help Of Third Variable

August 06, 2016

Code :
import java.util.Scanner;
class Swapping_without_third {
 public static void main (String args[])
 {
  int FirstNumber, SecondNumber;
  Scanner sobject=new Scanner(System.in);
  System.out.println("Enter Two Numbers: ");
  FirstNumber = sobject.nextInt();
  SecondNumber = sobject.nextInt();
  System.out.println("Before swapping Method: \n FirstNumber = "+FirstNumber +"\n SecondNumber = "+SecondNumber);
  FirstNumber = FirstNumber+SecondNumber;   //10+20=30
  SecondNumber = FirstNumber-SecondNumber;  //30-20=10
  FirstNumber = FirstNumber-SecondNumber;   //30-10=20
  System.out.println("After swapping Method: \n FirstNumber = "+FirstNumber +"\n SecondNumber = "+SecondNumber);  
 }
}

Output :
Enter Two Numbers:
10
20
Before swapping Method:
 FirstNumber = 10
 SecondNumber = 20
After swapping Method:
 FirstNumber = 20
 SecondNumber = 10

IDE Used To Test This Code : Dr Java

Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us.We will reply you as soon as possible.

Post a Comment