Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Swap Function in Java
2.1.
Syntax of Swap Function in Java
3.
Parameters and return types
4.
Some Examples To Illustrate Swap Function in Java
4.1.
Example 1
4.2.
Example 2
4.3.
Example 3
4.4.
Example 4
5.
Frequently Asked Questions
5.1.
How many ways can we swap two numbers in Java?
5.2.
Why doesn't swap work in Java?
5.3.
Is there any built-in swap function in Java?
5.4.
What are the problems with the swapping process?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Collections swap() method in Java with Examples

Author Akriti Bhan
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

We are very familiar with the programming language java and the swap method we usually use to swap particular elements in any array. In this blog, we will discuss the swap function in java. 

swap function in java

This requires some prerequisite knowledge of objectsmethods, and classes. We will look at them one by one and proceed by learning about the swap function along with the coded examples. Before proceeding with exploring the swap function in java, we must first understand what methods are in java.

What is Swap Function in Java

The Swap function in java as the name suggests is use to swap two values of a particular array with each other.In programming languages like Java we have to frequently use this swap function in different scenarios like when doing sorting or other complex operations.

Syntax of Swap Function in Java

The syntax for the swap function in java is as follows:

Collections.swap(List<data_type> list, int i, int j)  
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Parameters and return types

List<data_type> list This is a list where the data type is defined inside the template, this is where we want the swap operation to execute
i Index of one of the elements that you want to swap in the list
j Index of the other element you want to swap.

The swap function does not return anything, it has a void return type; it; this just swaps the indexes inside the list we pass it as parameters.

Some Examples To Illustrate Swap Function in Java

Example 1

import java.util.*;  
public class example1swap {  
    public static void main (String[] args) {
            ArrayList<String>  list = new ArrayList<String>();  
            list.add("cat");  
            list.add("dog");  
            list.add("rat");  
            list.add("mouse");  
            list.add("monkey");    
            System.out.println("List before swapping the elements is " +list);  
            /*calling the swap function */
            Collections.swap(list, 2, 3);  
            System.out.println("List after swapping the elements is :" +list);  
          }  
}  


Sample Output

output1

Example 2

In this section, we will take an example in which the indexes will be out of range.

import java.util.*;
public class example2 {
    public static void main(String[] argv) throws Exception
    {
        try {
            ArrayList<String>  list = new ArrayList<String>();  
            list.add("rat");
            list.add("monkey");
            list.add("mouse");
            list.add("rabbit");
            list.add("horse");
            System.out.println("Before swapping the elements of the list are: " + list);
            /*more than upper bound index */
            Collections.swap(list, 0, 5);
            System.out.println("After swapping the elements are: " + list);
        }
catch (IndexOutOfBoundsException e) {
            System.out.println("IndexOutOfBoundsException!!!!!!! : " + e);
        }
    }
}


Sample Output

output2

Example 3

import java.util.*;
public class Main {
   public static void main(String[] args) {
       // Create a Vector
       List<String> list = new Vector<>();
       list.add("Tom");
       list.add("Jerry");
       list.add("Spike");
       // Display the original list
       System.out.println("Original List: " + list);
       // Swap elements at positions 0 and 2
       Collections.swap(list, 0, 2);
       // Display the list after swapping
       System.out.println("After Swapping: " + list);
   }
}

 

Output

Original List: [Tom, Jerry, Spike]
After Swapping: [Spike, Jerry, Tom]

Example 4

import java.util.*;
public class Main {
   public static void main(String[] args) {
       // Create a Stack
       List<Integer> list = new Stack<>();
       list.add(100);
       list.add(200);
       list.add(300);
       list.add(400);
       // Display the original list
       System.out.println("Original List: " + list);
       // Swap elements at positions 1 and 3
       Collections.swap(list, 1, 3);
       // Display the list after swapping
       System.out.println("After Swapping: " + list);
   }
}

 

Output

Original List: [100, 200, 300, 400]
After Swapping: [100, 400, 300, 200]

We can see here that the index is out of bound thus, an exception is thrown. You can also find the output of this Java compiler code here.

We hope you are now well-versed in the swap function in Java.

Frequently Asked Questions

How many ways can we swap two numbers in Java?

There are multiple ways to swap two numbers in Java: using a temporary variable; through arithmetic operations such as addition/subtraction or multiplication/division without using a temporary variable; via the bitwise XOR operation; and finally, in a single statement employing addition, subtraction, and the assignment operator.

Why doesn't swap work in Java?

In Java, swapping doesn't work because Java is strictly pass-by-value. When primitive types or object references are passed to a method, the method gets a copy of them. Changes to these copies don't affect the original variables.

Is there any built-in swap function in Java?

Java does not have a built-in swap function for primitive types or object references due to its pass-by-value semantics. However, the Collections class in Java provides a swap() method to swap elements in a list or an array.

What are the problems with the swapping process?

Swapping in programming can face challenges such as potential data loss if not handled properly, issues with pass-by-value semantics in some languages like Java, or performance impacts if swapping requires additional temporary storage or complex operations.

Conclusion

In this blog, our prime focus was to learn about the swap function in Java. We started with understanding what objects and classes in java are. We further discussed methods in java. Then we finally addressed the swap function in java along with the coded examples.

You can refer to other similar articles as well 


Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, and Competitive Programming. Enroll in our courses and refer to the mock test and problems available.

Happy Learning Ninja! 

Live masterclass