How do you swap two numbers in Java without using a temporary variable?

Prepare for your SDET Interview with comprehensive flashcards and challenging multiple-choice questions. Each question is designed with hints and detailed explanations to ensure your success. Start your journey to mastering the SDET Interview today!

Multiple Choice

How do you swap two numbers in Java without using a temporary variable?

Explanation:
Swapping two numbers in Java without using a temporary variable can indeed be accomplished through arithmetic operations. The basic idea is to use addition and subtraction to achieve the swap. Here’s how it works: 1. Assign the sum of both numbers to one of the original variables. For example, if you have two integers, `a` and `b`, you can do `a = a + b;`. 2. Then, subtract the new value of `a` (which is the sum) by `b` and assign it to `b`. This operation effectively sets `b` to the original value of `a` because now `b` is essentially `a + b - b`, which simplifies to `a`. 3. Finally, subtract the new value of `b` from the new value of `a` to recover the original value of `b` and assign it to `a`. Here's a simple example: ```java int a = 5; int b = 10; a = a + b; // Now a is 15 b = a - b; // Now b is 5 (original value of a) a = a - b; // Now a is 10 (original value of b)

Swapping two numbers in Java without using a temporary variable can indeed be accomplished through arithmetic operations. The basic idea is to use addition and subtraction to achieve the swap.

Here’s how it works:

  1. Assign the sum of both numbers to one of the original variables. For example, if you have two integers, a and b, you can do a = a + b;.

  2. Then, subtract the new value of a (which is the sum) by b and assign it to b. This operation effectively sets b to the original value of a because now b is essentially a + b - b, which simplifies to a.

  3. Finally, subtract the new value of b from the new value of a to recover the original value of b and assign it to a.

Here's a simple example:


int a = 5;

int b = 10;

a = a + b; // Now a is 15

b = a - b; // Now b is 5 (original value of a)

a = a - b; // Now a is 10 (original value of b)
Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy