Introduction to swap() in Java
It refers to a method provided by java.util.Collections to swap the elements of a list 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 same then the list remains unchanged and in case the index specified in the argument is greater than the length of the list IndexOutOfBoundsException is thrown.
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.
How swap() works in Java?
The swap method is functionality provided to us to swap the elements of a list at 2 different indexes provided in the arguments to while calling the functions.
Let us see the working of the swap method using pseudocode:
- First, the arguments’ indexes are checked if they are not null; otherwise, a compile-time error is thrown .
- The size of the list is checked and compared with the indexes given if they lie in the bounds of list size or not; in case no, then IndexOutOfBounds run time exception is thrown and exit.
- The list is traversed, and list1[i], list1[j] element is 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.
Here, since we cannot find an element with index =7, the IndexOutOfBound exception is thrown.
Examples of swap() in Java
Given below are the examples mentioned:
Example #1
Let us see the example to check if a string is a palindrome or not using the swap() method.

4.8 (13,870 ratings)
View Course
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 used the swap method to reverse the list to see if the current and reversed list is the same or not, thus called 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 swap operation is the same; thus, it is a palindrome.
Example #2
For IndexOutOfBoundsException.
Let us see one example to access an index in the list which 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 index out of these bounds eventually results in exceptions of IndexOutOfBound Exception as shown in Output screen.
- To make the above code working a small tweak is required 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:
Conclusion
Swap method is a functionality given by java.util.Collections class to interchange the values present at different indexes in the list, which are specified in the arguments while calling the method along with reference to the list. In case both the indexes are the same, the list will remain unchanged. This method throws IndexOutOfBoundsException in case indexes specified are greater than the size of the list.
Recommended Articles
This is a guide to swap() in Java. Here we discuss the introduction to Swap(), how swap() works in java with programming examples. You may also have a look at the following articles to learn more –