Question #40MediumGeneral

If A =0 , B=1 , how to assign A value in B , B value in A

Answer

Overview

Swapping two variables without a temporary variable is a classic programming challenge. Dart supports multiple approaches.


Method 1: Destructuring Assignment (Dart 3+)

dart
int A = 0, B = 1;

// Dart 3 record / destructuring swap
(A, B) = (B, A);

print('A = $A'); // A = 1
print('B = $B'); // B = 0

Method 2: Using a Temporary Variable (Classic)

dart
int A = 0, B = 1;

int temp = A;  // temp = 0
A = B;         // A = 1
B = temp;      // B = 0

print('A = $A'); // A = 1
print('B = $B'); // B = 0

Method 3: Arithmetic (Integers Only)

dart
int A = 0, B = 1;

A = A + B; // A = 1
B = A - B; // B = 0
A = A - B; // A = 1

print('A = $A'); // A = 1
print('B = $B'); // B = 0

Method 4: XOR (Integers — Bitwise)

dart
int A = 5, B = 10;

A = A ^ B; // A = 15
B = A ^ B; // B = 5
A = A ^ B; // A = 10

print('A = $A'); // A = 10
print('B = $B'); // B = 5

Comparison

MethodWorks ForDart Version
text
(A, B) = (B, A)
Any typeDart 3+ ✅ (Best)
text
temp
variable
Any typeAll versions
ArithmeticNumbers onlyAll versions
XORIntegers onlyAll versions

Best Dart Practice: Use

text
(A, B) = (B, A)
— clean, readable, type-safe, and works for any variable type (not just integers).