Sahi Papers: Sample Questions 7 - 7 of 7

Examrace Placement Series prepares you for the toughest placement exams to top companies.

Question number: 7

» Languages » Java

Short Answer Question▾

Write in Short

Swap two variables without using 3rd variable.

Explanation

public class SwapElementsWithoutThirdVariableExample

  1. {
  2.     public static void main(String[] args)
  3.     {
  4.         int a = 2;
  5.         intb = 4;
  6.         System.out.println("Before Swapping");
  7.         System.out.println("nValue of num1 is :" +a);
  8.         System.out.println("nValue of num2 is :" +b);
  9.         //add both the numbers and assign it to first
  10.         a = a + b;
  11.         b = a - b;
  12.         a = a - b;
  13.         System.out.println("nAfter Swapping");
  14.         System.out.println("nValue of num1 is :" +a);
  15.         System.out.println("nValue of num2 is :" +b);
  16.     }
  17. }

Output:

Before Swapping

Value of num1 is: 2

Value of num2 is: 4

After swapping

Value of num1 is: 4

Value of num2 is: 2