Swap two numbers without using third variable in java



In this core java programming tutorial we will write a program to Swap two numbers without using third variable in java.



Q. Write a program to swap two numbers without using third variable in java.


Full Program/SourceCode / Example to Swap two numbers without using third variable in java >
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
class SwapNumbersWithoutThirdVariableExample {
  
   public static void main(String[] args) {
          int n1 = 7, n2 = 5;
         
          System.out.println("before swapping, n1= " + n1 + " and n2= " + n2);
         
          n1 = n1 + n2;
          n2 = n1 - n2;
          n1 = n1 - n2;
         
          System.out.println("After swapping , n1= " + n1 + " and n2= " + n2);
         
   }
  
  
}
/*OUTPUT
before swapping, n1= 7 and n2= 5
After swapping , n1= 5 and n2= 7
*/


So in this core java programming tutorial we wrote a program to Swap two numbers without using third variable in java.

Previous program                                                                  Next program


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>

>Pattern/Pyramid generating program in java

77) write program to Customize Serialization process by defining writeObject()  method & DeSerialization process by defining readObject() method
78) wap to Serialize and DeSerialize object by implementing Externalizable interface- override writeExternal() and readExternal() methods
79) program to define Impact of not defining serialVersionUID in class and  avoiding InvalidClassException
80) If member of class does not implement Serializable interface - than  NotSerializableException is thrown
81) program to make subclass avoid Serialization if its superClass has implemented Serialization interface
82) Avoid Deserialization process from creating another instance of Singleton class
83) wap to Deep copy in java using Serialization and Deserialization
84) How to handle exception thrown from static block in java? Why throw not allowed in static block
85) program of Exception chaining in java
86) What are checked (compile time exceptions) in java
87) write Try-with-resources in java
88) write program to show Catch block and Automatic Resource Management in java 7 (Multi catch syntax)
eEdit
Must read for you :