Sunday, 14 January 2018

Swapping of Two Numbers in Java

1.Swapping with using third variable : -

package com.tutorial4u;

public class SwapTwoNumber {
       public static void main(String[] args) {
             int n1 = 4;
             int n2 = 5;
             int temp;
             System.out.println("Before swapping n1 = "+n1+" and n2 = "+n2);
             temp = n1;
             n1 = n2;
             n2 = temp;
             System.out.println("After swapping n1 = "+n1+" and n2 = "+n2);
       }

}


Output :

Before swapping n1 = 4 and n2 = 5
After swapping n1 = 5 and n2 = 4

2.Swapping without using third variable :-


package com.tutorial4u;

public class SwapTwoNumber {
       public static void main(String[] args) {
             int n1 = 4;
             int n2 = 5;
             int temp;
             System.out.println("Before swapping n1 = "+n1+" and n2 = "+n2);
             n1 = n1+n2;
             n1 = n1-n2;
             n2 = n1=n2;
             System.out.println("After swapping n1 = "+n1+" and n2 = "+n2);
       }

}


Output :

Before swapping n1 = 4 and n2 = 5
After swapping n1 = 5 and n2 = 4

No comments:

Post a Comment

No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...