View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Swapping of Two Numbers in Java

Updated on 20/03/20258,021 Views

Swapping two numbers is a basic principle in programming, frequently employed to organize values in algorithms, data structures, and beyond. In Java, several techniques exist for swapping two numbers, ranging from utilizing temporary variables to more efficient methods that do not require any variables.

Programming relies heavily on swapping functions because it creates an essential basis for various algorithms that solve multiple distinct problems successfully. Data management through the exchange concept allows users to modify data arrangements in multiple ways to handle sorting functions and execute searching operations and improve algorithm performance.

The process of Swapping of Two Numbers in Java can be achieved through four methods which include temporary variable usage and arithmetic operations, bitwise XOR operations and a single expression combination of addition, subtraction and assignment operators.

Sharpen your Java programming skills through our Software Development courses and advance your learning journey!

This blog will walk you through various methods for Swapping of Two Numbers in Java, addressing both conventional and enhanced strategies.

What is Swapping of Two Numbers?

Swapping denotes the action of exchanging the values of two variables. In Java programming, it pertains to swapping the values of two numeric variables, typically integers or floating-point numbers. The variable values are exchanged, meaning the initial value of the first variable takes on the value of the second variable, and the second variable's value becomes that of the first.

Also Read: How to Add Two Numbers in Java?

Situations Where Swapping is Useful

In Java swapping serves various purposes by exchanging variable values, particularly during sorting operations and data structure algorithm processing where value and element rearrangement exists.

1. Sorting Algorithms

Situation: In many sorting algorithms, such as Bubble Sort, Selection Sort, and Quick Sort, swapping is used to arrange elements in the desired order.

Why Useful: Swapping allows elements to be rearranged efficiently without losing any data. For instance, in Bubble Sort, two adjacent elements are swapped if they are in the wrong order, helping to sort the entire array.

Example:

Java
// Example: Bubble Sort - Swap adjacent elements if needed
if (arr[i] > arr[i + 1]) {
    int temp = arr[i];
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
}

2. Shuffling Arrays or Lists

Situation: Swapping is essential when shuffling elements in a list or array, such as in a card game or a random selection algorithm.

Why Useful: It allows for the random reordering of elements to ensure each element has an equal chance of being selected.

Example:

java
// Example: Shuffling cards or items in an array
int i = 0, j = (int)(Math.random() * arr.length);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

3. Finding Minimum or Maximum Element

Situation: In algorithms like Selection Sort or when finding the minimum/maximum in an array, swapping helps move the smallest/largest element to the desired position.

Why Useful: The algorithm swaps the current element with the smallest/largest element found during the iteration, efficiently organizing the data.

Example:

java
// Example: Swapping the minimum element with the first element
if (arr[i] < arr[minIndex]) {
    minIndex = i;
}
// Swap arr[minIndex] with arr[i]

4. Two Pointer Technique

Situation: In problems that use a two-pointer approach (like partitioning an array or reversing a sequence), swapping elements at different pointers is essential.

Why Useful: It allows for efficient manipulation of elements from both ends of the array or list, especially in algorithms like QuickSort or two-sum problems.

Example:

java
// Example: QuickSort - Swap to partition the array
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

5. Reversing Arrays or Strings

Situation: When you need to reverse the order of elements in an array or string, swapping is often used to achieve this.

Why Useful: Swapping elements from both ends of the array reduces the space complexity, as no additional arrays or lists are needed.

Example:

java
// Example: Reversing an array using swapping
int start = 0, end = arr.length - 1;
while (start < end) {
    int temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    start++;
    end--;
}

6. Solving Puzzles (e.g., Sudoku, 8-Puzzle)

Situation: Swapping is commonly used in solving puzzle problems like 8-Puzzle, Sudoku, or Sliding Puzzle, where you need to move tiles or elements into a desired arrangement.

Why Useful: Swapping allows elements to be moved around in a controlled manner, helping to achieve the target configuration.

Example:

java
// Example: 8-Puzzle - Swap tiles to reach the target arrangement
int temp = puzzle[x1][y1];
puzzle[x1][y1] = puzzle[x2][y2];
puzzle[x2][y2] = temp;

7. Data Swapping in Cryptography

Situation: In encryption and decryption algorithms, swapping is used to obfuscate the data during the encryption process.

Why Useful: Swapping helps in creating complex transformations of the data, making it more difficult to decode without the correct key.

Example:

java
// Example: Swapping for cryptographic data manipulation
byte temp = encryptedData[i];
encryptedData[i] = encryptedData[j];
encryptedData[j] = temp;

8. Swap Nodes in Linked Lists (Swap Elements)

Situation: When working with linked lists, you may need to swap the positions of two nodes. This operation is useful in various algorithms like sorting or partitioning a linked list.

Why Useful: Swapping nodes allows for effective reordering of data without needing to traverse the entire list or use additional space.

Example:

java
// Example: Swapping two nodes in a linked list
Node temp = node1.next;
node1.next = node2.next;
node2.next = temp;

9. Exchange Rates and Financial Transactions

Situation: Swapping is used in financial transactions where you need to exchange one type of currency for another. In this case, the data of one type of currency is swapped with another in financial systems.

Why Useful: It helps handle transactions efficiently, ensuring accurate rates and values are maintained during the exchange process.

Example:

java
// Example: Swap two currency values (simplified)
double temp = currency1Amount;
currency1Amount = currency2Amount;
currency2Amount = temp;

10. Swapping in Games and Simulations

Situation: In game development (e.g., for swapping items in an inventory system, characters in positions, etc.), swapping helps manage game states, player actions, and environmental changes.

Why Useful: Swapping elements such as positions, items, or players enhances the gaming experience and interaction, making gameplay more dynamic.

Example:

java
// Example: Swapping player positions in a game
Player temp = player1;
player1 = player2;
player2 = temp;

Different Techniques Available for Swapping in Java

In Java, swapping refers to the process of exchanging the values of two variables. There are several techniques to achieve this in Java, depending on whether you want to use additional memory or work within constraints like immutability. Here are the different techniques available for swapping values in Java:

  • Employing a Temporary Variable:

The simplest method used for value swapping operates frequently as an example of this technique.

  • Employing Arithmetic Functions (Addition/Subtraction):

This method enables value exchange without temporary variables yet its execution method is unclear and can produce issues during specific numeric type usage.

  • Employing the Bitwise XOR Operation:

This method functions as a value transfer mechanism that works without temporary variables yet its execution requires additional learning and not all data types can benefit from it.

  • Employing the Collections.swap() method:

The Collections.swap() method functions as the best option for moving List elements between specific index positions.

Here is a quick summary of techniques:

Technique

Requires Extra Memory

Pros

Cons

Using a Temporary Variable

Yes

Simple and easy to understand.

Requires extra memory.

Using Arithmetic Operations

No

Efficient for swapping numbers.

Risk of overflow with large numbers.

Using XOR

No

Very efficient and avoids extra memory.

Can be hard to understand for beginners.

Using Collections.swap()

Yes (for objects)

Great for object-based collections.

Limited to collections like lists.

Also Read: Bitwise Operators in Java: Types, Implementation and Advantages

Swapping Using a Temporary Variable

Java programmers utilize temporary variables for swapping because this method represents an efficient and basic technique to exchange two values efficiently. The swapping process benefits from using a third variable to store the temporary value of one of the elements being exchanged.

Steps:

  • The first step requires creating a temporary storage variable to copy one of the original variables' values.
  • At the second step of the process, the initial value gets assigned to the temporary storage variable.
  • The next process should assign the initial variable value to the second variable.
  • The fourth step involves moving the temporary variable content to the second variable.

Code:

public class SwapExample {
   public static void main(String[] args) {
       // Initial values of a and b
       int a = 5, b = 10;
       // Step 1: Use a temporary variable to hold one of the values
       int temp = a;  // Store the value of a in temp
       // Step 2: Swap the values
       a = b;          // Assign the value of b to a
       b = temp;       // Assign the value stored in temp (which is the original a) to b
       // Display the swapped values
       System.out.println("After swapping:");
       System.out.println("a = " + a);  // Output: a = 10
       System.out.println("b = " + b);  // Output: b = 5
   }
}

Output:

After swapping:
a = 10
b = 5

Explanation:

  • At first, a = 5 and b = 10.
  • During the operation the value of variable a is stored in the temporary variable temp (temp = 5).
  • Following the assignment b is given to a (a = 10).
  • The temporary storage of temp contains the initial a value at 5 before it is assigned to b (b = 5).
  • The most conventional method to swap variables uses a temporary storage element. This technique operates effectively because it uses simple language to perform efficiently across different conditions.

Pros

  • Straightforward and easy to comprehend
  • No chance of losing data
  • A direct exchange operation exists between parties that clearly understand their intentions to swap values.
  • This method functions with every data type without exception.

Cons

  • Needs additional memory for the temporary variable.
  • Somewhat less effective in memory-limited settings.
  • The approach appears less advanced to programmers who have worked with this code before.

Swapping Without Using a Temporary Variable

Exchanging values without a temporary variable can be accomplished through two primary techniques: arithmetic operations and bitwise XOR. Both techniques enable you to exchange values without requiring an additional storage variable.

Exchanging Values Through Arithmetic Operations

  • This technique employs fundamental addition and subtraction (or multiplication and division) to exchange values. This is how it functions:
  • Combine the two numbers and save the result in one of the variables.
  • Next, take away the second number from the total to obtain the original value of the first number.
  • Lastly, take the new value of the first number away from the total to find the initial value of the second number.

Code (Arithmetic Method):

public class SwapExample {
   public static void main(String[] args) {
       int a = 5, b = 10;
       // Step 1: Add the two numbers
       a = a + b;  // a becomes 15 (5 + 10)
       // Step 2: Subtract the second number from the sum
       b = a - b;  // b becomes 5 (15 - 10)
       // Step 3: Subtract the new value of b from the sum
       a = a - b;  // a becomes 10 (15 - 5)
       // Display the swapped values
       System.out.println("After swapping:");
       System.out.println("a = " + a);  // Output: a = 10
       System.out.println("b = " + b);  // Output: b = 5
   }
}

Output:

After swapping:
a = 10
b = 5

Explanation:

  • a = a + b (The value of a is updated to include b).
  • b = a - b (Now b takes on the initial value of a).
  • a = a - b (Ultimately, a changes to the initial value of b).

Pros

  • Easy to execute
  • No additional memory consumption

Cons

  • Can lead to overflow with large values.
  • Not as comprehensible
  • Not appropriate for floating-point values.

Swapping Through XOR (Bitwise XOR)

  • Another frequent technique involves utilizing the XOR (exclusive OR) bitwise operation. XOR exhibits a fascinating trait: if you XOR a number with itself, the outcome is 0, and if you XOR any number with 0, that number does not change.
  • The XOR technique allows for value swapping without the requirement of a temporary variable. Here’s the way it operates:
  • Apply XOR to the initial variable and the second one.
  • XOR the outcome of the last operation with the second variable to retrieve the initial value of the first variable.
  • Apply XOR between the outcome of the second operation and the first variable to retrieve the original value of the second variable.

Code (XOR Method):

public class SwapExample {
   public static void main(String[] args) {
       int a = 5, b = 10;
       // Step 1: XOR a and b, and store the result in a
       a = a ^ b;  // a becomes 15 (0101 ^ 1010 = 1111)
       // Step 2: XOR the new value of a with b, and store the result in b
       b = a ^ b;  // b becomes 5 (1111 ^ 1010 = 0101)
       // Step 3: XOR the new value of a with the new value of b, and store the result in a
       a = a ^ b;  // a becomes 10 (1111 ^ 0101 = 1010)
       // Display the swapped values
       System.out.println("After swapping:");
       System.out.println("a = " + a);  // Output: a = 10
       System.out.println("b = " + b);  // Output: b = 5
   }
}

Output:

After swapping:
a = 10
b = 5

Explanation:

  • a = a ^ b (This saves the XOR result of a and b in a).
  • b = a ^ b (This obtains the initial value of a and saves it in b).
  • a = a ^ b (This gets back the original value of b and saves it in a).

Pros

  • No additional memory consumption
  • More effective for whole numbers
  • No risk of overflow

Cons

  • More difficult to comprehend
  • Restricted to whole number types
  • Decreases clarity for newcomers.

Performance Comparison

  • The bitwise XOR operator receives superior performance from the compiler because it accepts direct hardware support.
  • The process of arithmetic XOR involves multiple operations thus making it run slower than native bitwise XOR operations.

Also Read: What is a Switch Case in Java & How to Use It?

Swapping Using Functions

Functions form an effective Java approach to develop reusable code while improving its organizational structure. Because Java uses pass-by-value for primitive types, directly swapping values within a function involving primitive types needs a bit of a workaround. Here’s a method to exchange values using functions in Java:

Swapping Primitive Types Through Functions

Java passes primitive types (e.g., int, char, double) by value, which means modifications to the values within the function will not impact the original variables. Consequently, when exchanging primitive types, you usually have to return the exchanged values.

Example: Swapping Two Integers Using a Function

public class SwapExample {
   // Function to swap two integers and return them in an array
   public static int[] swap(int a, int b) {
       int temp = a;  // Temporary variable to hold one value
       a = b;         // Swap the values
       b = temp;
       return new int[] {a, b};  // Return swapped values as an array
   }
   public static void main(String[] args) {
       int a = 5, b = 10;
       // Call the swap function and get swapped values
       int[] swappedValues = swap(a, b);
       // Unpack the swapped values into a and b
       a = swappedValues[0];
       b = swappedValues[1];
       // Display the swapped values
       System.out.println("After swapping:");
       System.out.println("a = " + a);  // Output: a = 10
       System.out.println("b = " + b);  // Output: b = 5
   }
}

Output:

After swapping:
a = 10
b = 5

Explanation:

  • The swap function receives integers from another function for exchanging variables through a temporary value which it then outputs in an array.
  • The main method obtains the swapped values as returned results which get assigned to variables a and b.

Swapping Wrapper Classes (Objects) Through Functions

Java passes objects such as Integer, and Double along with other classes through reference so you can make direct modifications when accessing methods. Within the method the Integer objects can be exchanged by changing their content directly.

Example: Swapping Two Integer Objects Using Functions

public class SwapExample {
   // Function to swap two Integer objects
   public static void swap(Integer a, Integer b) {
       // Here, swapping won't persist in the main method since Integer is immutable
       Integer temp = a;
       a = b;
       b = temp;
       System.out.println("Inside swap method:");
       System.out.println("a = " + a);  // Output: a = 10
       System.out.println("b = " + b);  // Output: b = 5
   }
   public static void main(String[] args) {
       Integer a = 5, b = 10;
       // Call the swap function
       swap(a, b);
       // Display the swapped values
       System.out.println("After swap in main method:");
       System.out.println("a = " + a);  // Output: a = 5
       System.out.println("b = " + b);  // Output: b = 10
   }
}

Output:

Inside swap method:
a = 10
b = 5
After swap in main method:
a = 5
b = 10

Explanation:

  • The modification attempt to swap Integer values within the swap function fails to maintain changes because wrapper classes cannot be changed due to their reference-based operation although their references behave as values in the main method thus preventing a and b from reflecting method updates.
  • The original values need to be modified by providing new exchanged values.

Swapping Custom Wrapper Class Through Functions

The issues from using wrapper classes can be avoided through custom-designed classes that handle value exchange within the method. Your method can display external modification results because you use mutable objects in this approach.

Example: Swapping Using a Custom Wrapper Class

class Pair {
   int first;
   int second;
  
   // Constructor to initialize values
   public Pair(int first, int second) {
       this.first = first;
       this.second = second;
   }
  
   // Method to swap the values
   public void swap() {
       int temp = first;
       first = second;
       second = temp;
   }
  
   @Override
   public String toString() {
       return "first = " + first + ", second = " + second;
   }
}
public class SwapExample {
   public static void main(String[] args) {
       // Create a Pair object to hold two values
       Pair pair = new Pair(5, 10);
      
       System.out.println("Before swap: " + pair);  // Output: first = 5, second = 10
      
       // Call the swap method on the Pair object
       pair.swap();
      
       System.out.println("After swap: " + pair);   // Output: first = 10, second = 5
   }
}

Output:

Before swap: first = 5, second = 10
After swap: first = 10, second = 5

Explanation:

  • In this instance, the Pair class holds two values (first and second), and the swap method interchanges these values within the Pair object.
  • Because objects are passed by reference in Java, any modifications made within the method affect the original Pair object, resulting in the swap lasting beyond the function call.

Limitations Due to Java’s Pass-By-Value Nature

  • Altering Basic Types:

The by-value feature of Java prohibits direct modification of primitive types both inside and outside methods. The method needs a return value system to transmit the modified information outside the method boundary.

  • Altering Citations:

The ability to modify object state proves useful but redirection of references away from their original objects within the method cannot transmit modifications to the original reference. Supplement the new reference point to demonstrate the made modifications in your method.

  • Unchangeability of Wrapper Classes:

The Java wrapper classes including Integer, Double, Character and others have immutable nature. Despite being transmitted by value the values of these items remain unalterable without direct modification. The process of modifying a wrapper class value requires you to create a new object which you return to the method for updating purposes.

  • No Pass-by-Reference:

Java implements reference passing differently from several programming languages including C++ because it lacks conventional pass-by-reference functionality. The calling method allows only value return or new object return to activate variable changes in the calling instance.

Also Read: Wrapper Classes in Java: What is it, Why do we need it?

Swapping Using Java Collections

Swapping elements in an ArrayList in Java can be achieved using a method akin to how you exchange elements in a regular List. Here’s an illustration of how to interchange two elements in an ArrayList by utilizing the Collections.swap method.

Using an ArrayList:

Code:

import java.util.*;
public class ArrayListSwapExample {
   public static void main(String[] args) {
       // Create an ArrayList of integers
       ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(10, 20, 30, 40, 50));
      
       // Display the original ArrayList
       System.out.println("Before swapping: " + numbers);
      
       // Swap elements at index 1 and index 3
       Collections.swap(numbers, 1, 3);
      
       // Display the ArrayList after swapping
       System.out.println("After swapping: " + numbers);
   }
}

Output:

Before swapping: [10, 20, 30, 40, 50]
After swapping: [10, 40, 30, 20, 50]

Explanation:

  • The ArrayList includes five integers which are initialized at the values 10, 20, 30, 40, 50.
  • The Collections.swap(numbers, 1, 3 operation swaps the elements present at positions 1 and 3 inside the numbers ArrayList. Index positions 1 and 3 contain respectively 20 and 40 thus the values are exchanged.

Using an array-based approach

In Java, swapping elements in an array can be easily done with a temporary variable, or you could explore alternative methods such as XOR swapping or performing it without a temporary variable.

Let’s explore the typical array-based methods for exchanging elements in an array.

  • Swapping Values with a Temporary Variable

Arrays usually swap two elements in this familiar manner. A variable of temporary use stores one array element while the index elements are undergoing swapping.

Code:

public class ArraySwapExample {
   public static void main(String[] args) {
       // Initialize an array
       int[] arr = {10, 20, 30, 40, 50};
       // Display the original array
       System.out.println("Before swapping:");
       printArray(arr);
       // Swap elements at index 1 and 3 (i.e., 20 and 40)
       int temp = arr[1];  // Store the value at index 1 (20)
       arr[1] = arr[3];    // Assign the value at index 3 (40) to index 1
       arr[3] = temp;      // Assign the stored value (20) to index 3
       // Display the array after swapping
       System.out.println("After swapping:");
       printArray(arr);
   }
   // Helper method to print the array
   public static void printArray(int[] arr) {
       for (int i : arr) {
           System.out.print(i + " ");
       }
       System.out.println();
   }
}

Output:

Before swapping:
10 20 30 40 50
After swapping:
10 40 30 20 50

Explanation:

  1. Temporary Variable: The value located at index 1 (20) is saved in a temporary variable named temp.
  2. The value located at index 3 (40) is shifted to index 1.
  3. Ultimately, the value held in temp (which is 20) is set at index 3.
  • Swapping Values Without a Temporary Variable

You can swap elements without needing an extra temporary variable by employing arithmetic operations (addition and subtraction) or bitwise XOR. Nevertheless, this approach is generally shunned in numerous situations because of possible problems with overflow (regarding arithmetic) and clarity.

Code (Using Arithmetic):

public class ArraySwapExample {
   public static void main(String[] args) {
       // Initialize an array
       int[] arr = {10, 20, 30, 40, 50};
       // Display the original array
       System.out.println("Before swapping:");
       printArray(arr);
       // Swap elements at index 1 and 3 without using a temporary variable (using arithmetic)
       arr[1] = arr[1] + arr[3]; // arr[1] = 20 + 40 = 60
       arr[3] = arr[1] - arr[3]; // arr[3] = 60 - 40 = 20
       arr[1] = arr[1] - arr[3]; // arr[1] = 60 - 20 = 40
       // Display the array after swapping
       System.out.println("After swapping:");
       printArray(arr);
   }
   // Helper method to print the array
   public static void printArray(int[] arr) {
       for (int i : arr) {
           System.out.print(i + " ");
       }
       System.out.println();
   }
}

Output:

Before swapping:
10 20 30 40 50
After swapping:
10 40 30 20 50

Explanation:

  1. We employ arithmetic operations (+ and -) to exchange the values. The important point is that the addition and subtraction operations change the values directly without needing a temporary variable.
  2. Possible Concern: This method might lead to integer overflow if the values being exchanged are excessively large.
  • Swapping With XOR (Without Utilizing a Temporary Variable)

Code:

public class ArraySwapExample {
   public static void main(String[] args) {
       // Initialize an array
       int[] arr = {10, 20, 30, 40, 50};
       // Display the original array
       System.out.println("Before swapping:");
       printArray(arr);
       // Swap elements at index 1 and 3 without using a temporary variable (using XOR)
       arr[1] = arr[1] ^ arr[3]; // arr[1] = 20 ^ 40
       arr[3] = arr[1] ^ arr[3]; // arr[3] = (20 ^ 40) ^ 40 = 20
       arr[1] = arr[1] ^ arr[3]; // arr[1] = (20 ^ 40) ^ 20 = 40
       // Display the array after swapping
       System.out.println("After swapping:");
       printArray(arr);
   }
   // Helper method to print the array
   public static void printArray(int[] arr) {
       for (int i : arr) {
           System.out.print(i + " ");
       }
       System.out.println();
   }
}

Output:

Before swapping:
10 20 30 40 50
After swapping:
10 40 30 20 50

Explanation:

  • XOR Swapping: The XOR operation is used to swap the elements without a temporary variable.
  • First XOR: arr[1] = arr[1] ^ arr[3] gives arr[1] = 20 ^ 40.
  • Second XOR: arr[3] = arr[1] ^ arr[3] retrieves the original value of arr[1] (i.e., 20).
  • Final XOR: arr[1] = arr[1] ^ arr[3] gives the original value of arr[3] (i.e., 40).

Difference Between Swapping Using Temp Variable and Without Temp Variable

Swapping values in programming can be done in different ways, with two common approaches being using a temporary variable and without using one. The method chosen can impact the simplicity, efficiency, and memory usage of the operation. Below is a comparison between swapping using a temporary variable and without it, highlighting their differences.

Aspect

Using Temp Variable

Without Temp Variable

Method

Basic assignments

Deploys Arithmetic Operations and Bitwise XOR

Uses Temp Variable

Requires an extra variable (temporary variable)

No extra memory required

Performance

Slightly less efficient due to the extra variable.

Can be more efficient, as no extra memory is used.

Complexity

Simple, easy to understand and implement.

Slightly more complex, especially with XOR.

Common Mistakes and Best Practices

Mistakes

  • Misuse of Temporary Variable:

The failure to save data in one of the temporary variables before swapping procedures causes information to disappear.

  • Excess with Mathematical Exchange

Swapping large numbers through arithmetic operations (a = a + b and b = a - b) creates problems because of integer overflow.

  • Swapping Null References (For Objects)

The exchange of references and objects excluding primitives becomes problematic when there is no null reference verification because it creates a path for NullPointerExceptions.

  • Incorrectly Swapping Arrays

Skilled array element exchange requires proper indices since improper selection can result in wrong swaps and the potential ArrayIndexOutOfBoundsException.

  • Swapping Without Considering Edge Cases

Neglecting to manage edge cases, like arrays containing just one element or those that are empty, may lead to runtime errors.

  • Misinterpretation of Object References

In Java, when working with arrays or objects, you are exchanging references instead of the real objects. The reference-changing behavior remains unknown to you without the proper understanding that references are transforming rather than the actual objects.

Best Practices

  • A separate variable should be established to simplify understanding of the program

Making use of a temporary variable stands as the easiest approach to safely exchange two numbers between each other. A temporary variable serves to simplify the process while protecting against the errors that might occur through the use of XOR operators or mathematical expressions.

  • Prevent Overflow through Arithmetic

When performing arithmetic swaps during optimization it is essential to watch out for integer overflow because it can happen with large numbers. XOR swapping provides a solution to prevent overflow during calculations.

  • Manage Edge Cases

All edge scenarios must be verified regularly including empty arrays combined with arrays having only one element and arrays containing null values. Such circumstances result in the occurrence of errors including IndexOutOfBoundsException or NullPointerException.

  • Grasp Object References

Objects and arrays become interchangeable by reference during code execution. The process of changing references affects the pointer system because it redirects which objects link to which reference but does not modify the actual objects.

  • Think About Code Clarity

The development of easily understandable code should be a persistent practice. Using temporary swap variables together with Collections.swap() methods improves both code readability and maintenance quality.

  • Steer clear of needless Swapping

If both values are identical, there's no need to exchange them. Enhance the logic by verifying if the values are not the same before continuing with the swap.

Common Interview Questions on Swapping

Q: How can you swap two numbers without causing an overflow?

A: Use a temporary variable to ensure that no overflow occurs when adding or subtracting large numbers.

int a = Integer.MAX_VALUE, b = Integer.MIN_VALUE;
int temp = a;
a = b;
b = temp;

Q: How would you swap two numbers in a List using Java's Collections.swap() method?

A:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
Collections.swap(list, 1, 3);  // Swap elements at index 1 and 3

Q: How would you swap two nodes in a single linked list?

Approach:

Swapping nodes in a singly linked list is more complicated than swapping values in an array, as you have to adjust pointers. You cannot directly access nodes by index.

A:

Find the nodes to swap (and their previous nodes).

Adjust the next pointers of the previous nodes to point to the new nodes.

Swap the next pointers of the nodes to be swapped.

Q: How would you swap two numbers using a stack?

A: Using a stack, you can store both values and then pop them back in swapped order.

int a = 10, b = 20;
Stack<Integer> stack = new Stack<>();
stack.push(a);
stack.push(b);

b = stack.pop();
a = stack.pop();

Q: How would you swap two numbers using constant space?

A: You can use arithmetic or XOR to swap without using any extra space.

Using Arithmetic:

a = a + b;

b = a - b;

a = a - b;

Using XOR:

a = a ^ b;

b = a ^ b;

a = a ^ b;

Also Read: 50+ Top Programming Interview Questions and Answers to Succeed in 2025

Practice Exercise Suggestion

Exercise 1: Swap Two Integers Using a Temporary Variable

To swap two integers with the help of a temporary variable, you can adhere to these steps in Java. Here’s the code that shows how to accomplish it:

Code:

public class SwapTwoIntegers {
   public static void main(String[] args) {
       // Initialize two integers
       int a = 10;
       int b = 20;
       // Display original values
       System.out.println("Before swapping:");
       System.out.println("a = " + a);
       System.out.println("b = " + b);
       // Swap using a temporary variable
       int temp = a;  // Store the value of 'a' in temp
       a = b;         // Assign the value of 'b' to 'a'
       b = temp;      // Assign the value of temp (which is the original 'a') to 'b'
       // Display swapped values
       System.out.println("\nAfter swapping:");
       System.out.println("a = " + a);
       System.out.println("b = " + b);
   }
}

Explanation:

  • Initial setup:

We begin by setting two integers, a and b. For instance, a equals 10 and b equals 20.

  • Temporary Variable:

We present a new variable named temp to temporarily hold the value of a. This enables us to maintain the value of a while we replace a with b.

  • Swapping Logic:

Initially, we save the value of a in temp.

  • Next, we set the value of b to a.
  • Lastly, we allocate the value kept in temp (which reflects the initial value of a) to b.

Output:

Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10

Exercise 2: Swap Two Numbers Using Bitwise XOR

Here’s a method for Swapping of Two Numbers in Java using the bitwise XOR operation. This technique does not need a temporary variable and is a well-known method for swapping values in a low-level manner.

Steps for XOR Swap:

𝐴 ⊕ 𝐴 = 0

A⊕A=0 and

𝐴 ⊕ 0 = 𝐴

A⊕0=A.

By using this property, you can swap two numbers without using an additional variable.

Bitwise XOR Swap Formula:

a = a ⊕ b

a =a ⊕b

b = a ⊕ b

b=a⊕b (Now b holds the original value of a)

a = a ⊕ b

a=a⊕b (Now a holds the original value of b)

Code for XOR Swap:

public class XORSwap {
   public static void main(String[] args) {
       // Initialize two integers
       int a = 10;
       int b = 20;
       // Display original values
       System.out.println("Before swapping:");
       System.out.println("a = " + a);
       System.out.println("b = " + b);
       // Swap using bitwise XOR
       a = a ^ b;  // Step 1: a = a XOR b
       b = a ^ b;  // Step 2: b = (a XOR b) XOR b = a
       a = a ^ b;  // Step 3: a = (a XOR b) XOR a = b
       // Display swapped values
       System.out.println("\nAfter swapping:");
       System.out.println("a = " + a);
       System.out.println("b = " + b);
   }
}

Explanation:

Step 1:

Execute the XOR operation on a and b, and save the result again in a. Now a contains the XOR of a and b (a ^ b).

Step 2:

Apply XOR to the new value of a and b. As a currently possesses a ^ b, this will allow us to retrieve the initial value of a and set it to b.

Step 3:

Ultimately, perform an XOR operation between the new value of a (which is a ^ b) and the updated value of b (which is now the initial a). This will provide the initial value of b and allocate it to a.

Output:

Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10

Exercise 3: Implement A Method That Swaps Two Elements In An Array

The development of Java code which exchanges elements between two array locations requires this standard process:

Main Highlights:

  • This method receives an array as well as two indices before performing a swap operation on the element positions represented by the indices.
  • A temporary variable plays an essential role in the swap operation by temporarily holding one of the elements.

Code:

public class ArraySwap {
   public static void main(String[] args) {
       // Initialize an example array
       int[] arr = {10, 20, 30, 40, 50};
       // Display the original array
       System.out.println("Before swapping:");
       printArray(arr);
       // Swap elements at index 1 and 3 (i.e., swap 20 and 40)
       swap(arr, 1, 3);
       // Display the array after swapping
       System.out.println("\nAfter swapping:");
       printArray(arr);
   }
   // Method to swap two elements in the array at specified indices
   public static void swap(int[] array, int index1, int index2) {
       // Check if indices are within bounds of the array
       if (index1 >= 0 && index1 < array.length && index2 >= 0 && index2 < array.length) {
           // Perform the swap using a temporary variable
           int temp = array[index1];
           array[index1] = array[index2];
           array[index2] = temp;
       } else {
           System.out.println("Invalid indices.");
       }
   }
   // Helper method to print the array
   public static void printArray(int[] array) {
       for (int num : array) {
           System.out.print(num + " ");
       }
       System.out.println();
   }
}

Explanation:

  • Array Setup:

The integer array arr contains the values {10, 20, 30, 40, 50} as its elements.

  • Swapping Technique:

The swap() function processes both an array and two index integers as parameters.

The function checks if the selected indices exist within the array dimensions.

The correct execution of this technique requires the usage of a temporary variable during index-based data item exchange.

  • Array Displaying:

The printArray() provides a display function that shows the array data before and after the swap operation takes place.

Output:

Before swapping:
10 20 30 40 50
After swapping:
10 40 30 20 50

Accelerate Your Learning with upGrad

The practical learning available through upGrad courses gives students an excellent opportunity to strengthen their understanding of Java and develop their problem-solving skills. The Java programming courses at upGrad provide practical activities that help students understand Swapping of Two Numbers in Java and teach advanced topics.

The upGrad courses enable students to learn:

  • Real-world assignments help you practice Java principles by working directly on operating tasks.
  • Industry professionals can provide professional guidance which shares their domain-specific knowledge to students.
  • Participate in activities together with quizzes and problem-solving exercises which provide immediate feedback to develop your coding competencies.
  • The career support of upGrad assists students in their software development career transition by developing the specific skills needed for success.

Whether you are a novice wanting to grasp the fundamentals or an intermediate coder seeking to enhance your abilities, upGrad offers a variety of courses tailored for every skill level. Therefore, advance in your educational journey and discover upGrad's Java courses to acquire a strong base in programming, covering topics like number swapping and other crucial methods!

Some courses that you can explore are:

Get free counselling session from experts at upGrad, and to know more visit the upGrad center near you.

Similar Reads:

FAQs

1. Why do we need to swap two numbers?

Programming and algorithms require number value swapping between variables to achieve basic operations that include sorting mechanisms as well as data manipulation and data reordering needs.

2. How do you swap two numbers using a temporary variable?

To swap two numbers with a temporary variable, first save the value of the first number in that variable, then set the first number to the value of the second number, and ultimately, assign the temporary variable's value to the second number.

3. What is the difference between arithmetic swapping and bitwise XOR swapping?

Arithmetic swapping involves using addition and subtraction operations or multiplication and division operations to swap data while bitwise XOR swapping uses the XOR operator to achieve the same outcome without requiring a temporary variable.

4. Can we swap two numbers without using a third variable?

The exchange of numbers through arithmetic swapping requires basic arithmetic operations and bitwise XOR swapping achieves comparable results through the XOR operator without depending on a third variable.

5. Which method is most efficient for swapping numbers?

The swap between numbers is commonly achieved through temporary variables or std::swap() in C++ because compilers optimize such techniques and makes them easy to understand.

6. Why doesn’t swapping work inside a method in Java?

Within the swap method Java passes the numeric values of objects instead of their reference which prevents alterations inside the method from affecting variables a and b.

7. What is the use of Collections.swap() in Java?

The Collections.swap() function inside Java enables users to swap elements within lists at precise locations. The Collections utility class of Java.util contains this swap method among its suite of functions that modify various Java collection types.

8. Does Java support pass-by-reference for swapping?

Contrary to C++ Java lacks a way to execute pass-by-reference parameter passing. Java adopts pass-by-value mechanisms for method parameters while the results depend on parameter types.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.