Updated December 12, 2023
Introduction to swap() in Java
It refers to a method provided by java.util.Collections to swap the list elements present at 2 distinct positions in the List given as arguments while calling a method along with the collection reference, and gives the list with the elements interchanged, in case the two positions specified are the same. The list remains unchanged, and if the specified index in the argument exceeds the length of the list, it throws an IndexOutOfBoundsException.
Syntax:
public static void swap(List list1, int pos1, int pos2)
- list1: Represents the reference variable of java.util.List type having a number of elements.
- pos1: This variable represents the index of the first element.
- pos2: This variable represents the index of the second element.
Table of Contents
- Introduction
- How swap() works in Java?
- Examples
- Swapping of Two Numbers in Java
- Swapping of Three Numbers in Java
How swap() works in Java?
When calling the function, the swap method allows us to swap elements in a list at two different indexes specified in the arguments.
Let us see the working of the swap method using pseudocode:
- First, check the indexes of the arguments to ensure they are not null; otherwise, the system throws a compile-time error.
- The code checks and compares the list size with the given indexes. If the indexes do not fall within the bounds of the list size, it throws a runtime exception, specifically the IndexOutOfBoundsException, and exits.
- The list is traversed, and the list1[i] and list1[j] elements are taken and swapped.
Let us consider below list of elements and different scenarios in that:
Scenario 1: Swap elements at index 3 and 5.
Scenario 2: Swap elements at index 2 and 7.
Since we cannot find an element with index =7, the IndexOutOfBound exception is thrown.
Examples of swap() in Java
Here are the examples as follows:
Example #1
Let us see the example to check if a string is a palindrome or not using the swap() method.
Code:
import java.util.*;
public class Office {
public static void main(String[] args)
throws Exception
{
try {
List<String>list1 = new ArrayList<String>();
list1.add("R");
list1.add("E");
list1.add("P");
list1.add("A");
list1.add("P");
list1.add("E");
list1.add("R");
System.out.println("String Before swap: " + list1);
int n = list1.size();
for(int i=0;i<list1.size()/2;i++){
Collections.swap(list1, i, n-1-i);
}
System.out.println("\nString After swap: " + list1);
}
catch (IndexOutOfBoundsException e) {
System.out.println("\nExceptionthrown : " + e);
}
}
}
Output:
Explanation:
- In the above program, we employed the swap method to reverse the list to check if the current and reversed lists are identical, thereby determining if it is a palindrome string.
- Here, for loop is run upto the middle of the list and swapping ith element with the n-i-1th element in the list. As we can see, the string before and after the swap operation is the same; thus, it is a palindrome.
Example #2 – For IndexOutOfBoundsException
Let us see one example of accessing an index in the list that is greater than the total number of elements in the list.
Code:
import java.util.*;
public class Office {
public static void main(String[] args) throws Exception
{
try {
List<String>list1 = new ArrayList<String>();
list1.add("Lets");
list1.add("Start");
list1.add("our");
list1.add("Work");
list1.add("Now");
System.out.println("Before swap: " + list1);
System.out.println("\nLets reverse the list using swap elements ");
for(int i=0;i<list1.size();i++){
Collections.swap(list1, i, list1.size());
}
System.out.println("After swap: " + list1);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Output:
Explanation:
- Here while swapping the elements at positions I and list1.size() in the loop, we know the index for a list starts from 0 and ends up with an uptolist.size() -1, thus accessing the index out of these bounds eventually results in exceptions of IndexOutOfBound Exception as shown in the Output screen.
- A small tweak is required to make the above code work by changing the swap command to Collections.swap(list1,I,list.size() -1).
- Now, the index will not go out of the list size’s bounds; thus, no exception will be thrown.
Code:
import java.util.*;
public class Office {
public static void main(String[] args) throws Exception
{
try {
List<String>list1 = new ArrayList<String>();
list1.add("Lets");
list1.add("Start");
list1.add("our");
list1.add("Work");
list1.add("Now");
System.out.println("List Before swap: " + list1);
System.out.println("\nLets reverse the list using swap elements ");
for(int i=0;i<list1.size()/2;i++){
Collections.swap(list1, i, list1.size()-1-i);
}
System.out.println("After swap: " + list1);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception thrown : " + e);
}
}
}
Output:
Swapping of Two Numbers in Java
Let us take a look with the help of some examples.
Case 1: Swapping of numbers using the temporary variable
Code:
public class Swap2Numbers
{
public static void main(String[] args)
{
int num1=10;
int num2 =20;
// Printing values of numbers before swapping in order to see the change
System.out.println("Original values before swapping are:");
System.out.println("Value of number 1 is " +num1); System.out.println("Value of number 2 is " +num2);
// Value of num1, i.e. 10 is assigned to temp variable int temp = num1;
// Value of num2, i.e. 20 is assigned to num1 variable num1 = num2;
// Value of temp variable, i.e. 10 (assigned by num1) is assigned to num2
int temp = num1; num1 = num2;
num2 = temp;
// Printing values of numbers after swapping in order to see the change
System.out.println("Values after swapping are:");
System.out.println("Value of number 1 is " +num1);
System.out.println("Value of number 2 is " +num2);
}
}
Output:
Explanation:
In the above program, we had two variables named num1 and num2 with values of 10 and 20, respectively. Use a temporary variable named temp of the same data type as variables num1 and num2. The swapping is processed in 3 steps:
- The value of ‘num1’ (i.e., 10) is assigned to the temporary variable ‘temp’, so now the value of ‘temp’ is 10.
- The value of ‘num2’ (i.e. 20) is assigned to the ‘num1’ variable, i.e. now the value of the ‘num1’ variable is 20.
- The value of the ‘temp’ variable (i.e., 10) assigned in step 1 is now assigned to the ‘num 2’ variable, i.e., the value of the ‘num2’ variable becomes 10 now.
Finally, the values of the variables are swapped or interchanged, and the swapped values are printed on the console.
Case 2: Swapping of two numbers without using the temporary variable
Code:
public class SwapNumbers
{
public static void main(String[] args)
{
int num1=10;
int num2 =20;
// Printing values of numbers before swapping in order to see the change
System.out.println("Original values before swapping are:");
System.out.println("Value of number 1 is " +num1); System.out.println("Value of number 2 is " +num2);
num1 = num1- num2; num2 = num1+ num2; num1 = num2- num1;
// Printing values of numbers after swapping in order to see the change
System.out.println("Values after swapping are:");
System.out.println("Value of number 1 is " +num1);
System.out.println("Value of number 2 is " +num2);
}
}
Output:
Explanation:
The numbers are swapped using basic arithmetic operations in three steps in the example provided.
- Value of num1- num2 (i.e., 10- 20 = -10) is stored in the ‘num1’ variable. Now num1= -10.
- Value of num1+ num2 (i.e. -10+20 = 10) stored in the ‘num2’ variable. Now num2= 10.
- Value of num2- num1 (i.e. 10 – (-10))= 20) is stored in the ‘num1’ variable. Now, num1=20.
Swapping of Three Numbers in Java
Let us study swapping of three numbers with the help of some example
Case 1: Swapping of 3 numbers without using a temporary variable
Code:
public class Swap3Numbers
{
public static void main(String[] args)
{
int num1= 10; int num2= 20; int num3= 30;
// Printing values of numbers before swapping in order to see the change
System.out.println("Original values before swapping are:");
System.out.println("Value of number 1 is " +num1);
System.out.println("Value of number 2 is " +num2); System.out.println("Value of number 3 is " +num3);
num1 = num1+ num2+ num3; num2 = num1- (num2+ num3); num3 = num1- (num2+ num3); num1 = num1- (num2+ num3);
// Printing values of numbers after swapping in order to see the change
System.out.println("Values after swapping are:");
System.out.println("Value of number 1 is " +num1);
System.out.println("Value of number 2 is " +num2);
System.out.println("Value of number 3 is " +num3);
}
}
Output:
Explanation:
The above example follows simple mathematics to exchange the values of 3 variables. It includes four steps, which are as follows:
- Value of num1+ num2+ num3 (i.e. 10 + 20 + 30 = 60) is assigned to variable ‘num1’. So num1 = 60.
- Value of num1- (num2+ num3) (i.e. 60 – (20+30) = 10) is assigned to variable ‘num2’. So num2= 10.
- Value of num1- (num2+ num3) (i.e. 60 – (10+30) = 20) is assigned to variable ‘num3’. So num3= 20.
- Value of num1- (num2+ num3) (i.e. 60 – (10+20) = 30) is assigned to variable ‘num1’. So num1= 30.
The swapped values of the 3 variables are printed on the console.
Case 2: Swapping of 3 numbers using a temporary variable
Code:
public class Swap3Numbers
{
public static void main( String[] args)
{
int num1=10; int num2 =20; int num3 =30;
// Printing values of numbers before swapping in order to see the change
System.out.println("Original values before swapping are:");
System.out.println("Value of number 1 is " +num1);
System.out.println("Value of number 2 is " +num2); System.out.println("Value of number 3 is " +num3);
int temp = num1; num1 = num2; num2= num3;
num3= temp;
// Printing values of numbers after swapping in order to see the change
System.out.println("Values after swapping are:");
System.out.println("Value of number 1 is " +num1);
System.out.println("Value of number 2 is " +num2); System.out.println("Value of number 3 is " +num3);
}
}
Output:
Explanation:
In the above program, swapping of 3 numbers is performed in 4 simple steps, and a temporary variable ‘temp’ is used:
- The value of num1 (i.e. 10) is assigned to the temp variable. So, now the temp has a value of 10.
- Value of num2 variable (i.e. 20) is assigned to num1, so num1 value is 20 now.
- Value if num3 variable (i.e. 30 ) is assigned to num2 variable, so num2 has value 30.
- The value of the temp variable (i.e. 10) is assigned to the num3 variable, so num3 has value 10 now.
Values of the 3 numbers are swapped and printed on the console.
Conclusion
The swap method in the java.util.Collections class enables the interchange of values at specified indexes in a list. To use this method, you provide the list reference and the indexes of the values you want to swap as arguments. If both indexes are the same, the list will remain unchanged. This method throws IndexOutOfBoundsException in case the indexes specified are greater than the size of the list.
Recommended Articles
We hope that this EDUCBA information on “swap() in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.