In Java an xor statement is used to interchangebetween two variables

  • 2020-04-01 03:57:41
  • OfStack

A third variable is usually used for interchanging between two variables, which is fine, but creating new variables adds overhead. You can use a more efficient method if you want to swap variables that are of two integer types. For example, the ^(or) operation is as follows:


import java.util.Scanner; 
public class VariableExchange { 
  public static void main(String args[]){ 
    Scanner scan = new Scanner(System.in); 
    System.out.println(" Please enter the first integer variable :"); 
    long A = scan.nextLong(); 
    System.out.println(" Please enter a second integer variable :"); 
    long B = scan.nextLong(); 
    System.out.println("A="+A+"tB="+B); 
    System.out.println(" After performing the variable swap ......"); 
    A = A^B; //Perform variable swap
    B = B^A; 
    A = A^B; 
    System.out.println("A="+A+"tB="+B); 
  }  
} 

Output results:


run: 
 Please enter the first integer variable : 
100 
 Please enter a second integer variable : 
200 
A=100  B=200 
 After performing the variable swap ...... 
A=200  B=100 
BUILD SUCCESSFUL (total time: 5 seconds) 


Related articles: