Updated November 29, 2023
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 the 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 a functionality provided to us to swap the elements of a list at 2 different indexes provided in the arguments 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 the IndexOutOfBounds run time exception is thrown and exits.
- 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
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 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 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 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:
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. A temporary variable with the name temp is used of the same data type of the 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:
In the above example, simple mathematics is followed to swap the numbers, which is done in 3 steps:
- 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:
In the above example, simple mathematics is followed to exchange the value of 3 variables. It involves 4 steps which are mentioned below:
- 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
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
We hope that this EDUCBA information on “swap() in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.