Write a Java Program to swap two numbers using the third variable.Multi Line code example

Example 1: swap two variables in java in single line

// swap two variables in java in single line
public class SwapTwoVariablesInOneLine
{
   public static void main(String[] args)
   {
      int x = 23;
      int y = 75;
      System.out.println("Before swapping two numbers: x = " + x + " y = " + y);
      x = x ^ y ^ (y = x);
      System.out.println("After swapping two numbers: x = " + x + " y = " + y);
   }
}

Example 2: java program to swap two numbers

int a, b, c;
a = 5;
b = 3;
System.out.println("Before SWAP a = " + a + ", b = " + b);
c = a;
a = b;
b = c;
System.out.println("After SWAP a = " + a + ", b = " + b);

Tags:

Java Example