For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. 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.
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
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:
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.
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.
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.
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.
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.
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.
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.
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.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.