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



No comments:

Post a Comment