For working professionals
For fresh graduates
More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
Foreign Nationals
The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not .
Recommended Programs
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
46. Packages in Java
53. Java Collection
56. Generics In Java
57. Java Interfaces
60. Streams in Java
63. Thread in Java
67. Deadlock in Java
74. Applet in Java
75. Java Swing
76. Java Frameworks
78. JUnit Testing
81. Jar file in Java
82. Java Clean Code
86. Java 8 features
87. String in Java
93. HashMap in Java
98. Enum in Java
101. Hashcode in Java
105. Linked List in Java
109. Array Length in Java
111. Split in java
112. Map In Java
115. HashSet in Java
118. DateFormat in Java
121. Java List Size
122. Java APIs
128. Identifiers in Java
130. Set in Java
132. Try Catch in Java
133. Bubble Sort in Java
135. Queue in Java
142. Jagged Array in Java
144. Java String Format
145. Replace in Java
146. charAt() in Java
147. CompareTo in Java
151. parseInt in Java
153. Abstraction in Java
154. String Input in Java
156. instanceof in Java
157. Math Floor in Java
158. Selection Sort Java
159. int to char in Java
164. Deque in Java
172. Trim in Java
173. RxJava
174. Recursion in Java
175. HashSet Java
177. Square Root in Java
190. Javafx
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.
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.
Build the Skills for Tomorrow’s Tech Careers
Master the latest in Cloud Computing, DevOps, and AI-driven Full Stack Development with programs designed by leading institutions.
Also Read: How to Add Two Numbers in Java?
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;
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:
The simplest method used for value swapping operates frequently as an example of this technique.
This method enables value exchange without temporary variables yet its execution method is unclear and can produce issues during specific numeric type usage.
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.
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
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:
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:
Pros
Cons
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.
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:
Pros
Cons
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:
Pros
Cons
Performance Comparison
Also Read: What is a Switch Case in Java & How to Use It?
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:
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:
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 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:
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.
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.
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.
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 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:
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.
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:
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:
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:
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. |
Mistakes
The failure to save data in one of the temporary variables before swapping procedures causes information to disappear.
Swapping large numbers through arithmetic operations (a = a + b and b = a - b) creates problems because of integer overflow.
The exchange of references and objects excluding primitives becomes problematic when there is no null reference verification because it creates a path for NullPointerExceptions.
Skilled array element exchange requires proper indices since improper selection can result in wrong swaps and the potential ArrayIndexOutOfBoundsException.
Neglecting to manage edge cases, like arrays containing just one element or those that are empty, may lead to runtime errors.
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
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.
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.
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.
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.
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.
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.
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
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:
We begin by setting two integers, a and b. For instance, a equals 10 and b equals 20.
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.
Initially, we save the value of a in temp.
Output:
Before swapping:
a = 10
b = 20
After swapping:
a = 20
b = 10
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
The development of Java code which exchanges elements between two array locations requires this standard process:
Main Highlights:
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:
The integer array arr contains the values {10, 20, 30, 40, 50} as its elements.
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.
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
Swapping of two numbers in Java can be achieved in multiple ways, including using a temporary variable, arithmetic operations, bitwise XOR, arrays, and wrapper classes. Each method has its own advantages and limitations depending on the use case. While the temporary variable approach is simplest, arithmetic and XOR methods optimize memory usage. Wrapper classes and arrays provide flexibility for advanced scenarios.
Understanding these techniques strengthens problem-solving and prepares you for coding interviews. By mastering the swapping of two numbers in Java, you build a solid foundation for tackling more complex programming challenges with confidence.
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:
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:
Swapping two numbers is essential in programming for tasks like sorting, rearranging data, and algorithm design. It allows you to interchange variable values to achieve logical flow in programs. In Java, learning to swap builds problem-solving ability and introduces you to memory handling, arithmetic operations, and logical thinking, all of which are crucial for coding interviews and real-world applications.
In Java, swapping with a temporary variable is the simplest approach. First, assign the first number to a temporary variable. Then set the first number equal to the second number, and finally assign the temporary variable’s value back to the second number. This method is clear, beginner-friendly, and reduces logical errors, making it ideal for learning basic programming principles.
Yes, numbers can be swapped in Java without a temporary variable. The two common methods are arithmetic swapping, which uses addition and subtraction, and XOR swapping, which uses the XOR operator. Both avoid extra memory usage, making them more efficient. However, these methods may be less intuitive for beginners, and arithmetic swapping can sometimes cause overflow with large integer values.
Arithmetic swapping uses addition and subtraction to interchange numbers, while XOR swapping uses the bitwise XOR operator. Arithmetic swapping is simpler to understand but may cause overflow with large values. XOR swapping avoids overflow risks but can be harder for beginners to grasp. Both methods eliminate the need for a temporary variable, providing memory efficiency in Java programs.
For most cases, using a temporary variable is the most efficient and practical method in Java because it prioritizes readability and reduces the chance of errors. XOR and arithmetic swapping are faster in theory but rarely provide noticeable improvements in real-world Java applications. Developers typically choose the temporary variable method for its clarity, maintainability, and alignment with industry coding standards.
In Java, swapping doesn’t work inside a method for primitives because Java always uses pass-by-value. When a primitive is passed to a method, a copy of the value is made, not the original variable. Changes inside the method affect only the copy. This prevents direct swapping of primitive numbers within a separate method unless object wrappers are used.
No, Java does not support pass-by-reference. Instead, it always passes values by copy. For primitive data types, only copies of the values are passed, so swapping inside a method fails. For objects, Java passes the reference value by copy. While object properties can be changed inside methods, the reference itself cannot be reassigned for swapping variables directly.
Collections.swap() is a method in the java.util.Collections class that swaps two elements at specified positions in a list. It doesn’t work for primitive numbers directly but is extremely useful when manipulating ArrayLists or other list-based data structures. Developers use this method frequently in sorting, rearranging datasets, and implementing algorithms that require efficient element replacement within collections.
In most cases, swapping does not cause data loss. However, arithmetic swapping with large values may cause overflow, which results in incorrect outputs. For example, adding two very large integers may exceed the range of int. To avoid such issues, developers use temporary variable swapping or switch to larger data types like long when dealing with big numbers.
In arithmetic swapping, you add both numbers and assign the sum to one variable. Then subtract the other variable from the sum to get the first value, and finally subtract again to restore the second. Example:
a = a + b;
b = a - b;
a = a - b;
This avoids a temporary variable but risks overflow with large integers.
XOR swapping relies on bitwise logic. You perform XOR operations in sequence:
a = a ^ b;
b = a ^ b;
a = a ^ b;
This swaps values without extra memory and avoids arithmetic overflow. While efficient, it is less intuitive and harder for beginners to understand compared to the temporary variable approach. It’s mostly used for demonstrating bitwise operations.
Swapping primitive types involves directly exchanging numeric values, but Java passes them by value, limiting swapping inside methods. Swapping objects, however, deals with references. While you can modify an object’s fields inside a method, you cannot reassign the reference itself. This distinction is important in Java because it impacts how developers implement swapping logic in real-world programs.
Direct swapping of primitive numbers inside a Java function is not possible due to pass-by-value. However, you can achieve swapping by wrapping numbers in objects or using arrays. For example, passing an array of two elements allows changes inside a method to reflect outside. This is a common workaround for simulating swapping via functions in Java.
Yes, swapping of two numbers is a common Java interview question. Interviewers often ask candidates to demonstrate different methods—using temporary variables, arithmetic, or XOR. This tests logical reasoning, problem-solving ability, and understanding of Java’s pass-by-value nature. It’s a beginner-friendly but insightful exercise to evaluate a candidate’s coding fundamentals and ability to explain different approaches clearly.
Wrapper classes like Integer in Java can help simulate swapping by storing numbers as objects. By passing wrapper objects or using arrays, you can modify values inside methods. However, Integer is immutable, so changes require creating new objects. Alternatively, custom wrapper classes with mutable fields are often used to allow actual swapping behavior in Java applications.
Arrays allow you to swap numbers by holding values in a single structure. Passing an array of two integers to a method lets you modify values inside the array, reflecting changes outside due to reference handling. Example: swapping arr[0] and arr[1] achieves number swapping. This method bypasses the pass-by-value limitation with primitives in Java methods.
Yes, swapping numbers without operators is possible by using higher-level utilities or built-in methods. For example, numbers inside arrays or lists can be swapped using Collections.swap() or simple index reassignment. These methods avoid arithmetic or bitwise operations. Though less common in interviews, they provide practical ways to swap values when working with Java collections or data structures.
Generics allow developers to create reusable swap methods for objects. For example, you can design a generic method to swap two elements of any type within an array or list. While this doesn’t directly swap primitive integers, it’s useful for writing flexible code where the same swap logic works across multiple data types in Java.
Yes, efficient swapping is crucial in algorithms like bubble sort, quicksort, and selection sort. These algorithms rely heavily on value exchanges to reorder data. Understanding swapping in Java ensures developers can implement sorting logic effectively. While individual swaps may seem small, optimized and correct swapping techniques significantly affect algorithm performance, especially when handling large datasets in real applications.
For clarity and reliability, using a temporary variable is the best practice in Java. Avoid arithmetic swapping when dealing with large numbers to prevent overflow. Use XOR only when specifically asked or when demonstrating bitwise logic. For collections or arrays, rely on built-in methods like Collections.swap(). Always choose readability and maintainability over clever but confusing swapping tricks.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
FREE COURSES
Start Learning For Free
Author|900 articles published