- swap() in Java
- How swap() works in Java?
- Examples of swap() in Java
- Example #1
- Example #2
- Conclusion
- Recommended Articles
- Swap Two Variables in Java
- Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
- > CHECK OUT THE COURSE
- 1. Overview
- 2. The Simple Way: Using a Temporary Variable
- 2.1. Why Not Swap in a Method?
- 3. Without Temporary Variable
- 3.1. Using Arithmetic Operations
- 3.2. Using Logical Operations
- 3.3. Single-line Variant
- 4. Performance Analysis
- 5. Conclusion
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.
Web development, programming languages, Software testing & others
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.
import java.util.*; public class Office < public static void main(String[] args) throws Exception < try < Listlist1 = new ArrayList(); 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 System.out.println("\nString After swap: " + list1); > catch (IndexOutOfBoundsException e) < System.out.println("\nExceptionthrown : " + e); >> >
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
Let us see one example to access an index in the list which is greater than the total number of elements in the list.
import java.util.*; public class Office < public static void main(String[] args) throws Exception < try < Listlist1 = new ArrayList(); 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 System.out.println("After swap: " + list1); > catch (IndexOutOfBoundsException e) < System.out.println("Exception thrown : " + e); >> >
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.
import java.util.*; public class Office < public static void main(String[] args) throws Exception < try < Listlist1 = new ArrayList(); 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 System.out.println("After swap: " + list1); > catch (IndexOutOfBoundsException e) < System.out.println("Exception thrown : " + e); >> >
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 –
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access
1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access
3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access
Swap Two Variables in Java
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
Sometimes, we may want to swap two variables in our code.
In this tutorial, we’ll see several ways to do that, depending on the types of variables we want to swap. Then, we will check the performances of each method.
2. The Simple Way: Using a Temporary Variable
The simplest way to swap two variables is to use a third variable as temporary storage:
Object a, b; Object temp; temp = a; a = b; b = temp;
This method is particularly easy to read and understand, even for beginners. Its primary disadvantage is that it requires a temporary variable.
We should keep in mind that this method is the only one that can swap Object variables.
2.1. Why Not Swap in a Method?
If we have to swap variables at several points in our code, it may sound attractive to create a method to swap variables like that:
public void swap(Object a, Object b)
Unfortunately, this won’t work in Java as references to objects are copied during method invocation.
If we really want to have a swap method, we have to use a wrapper class around your object and swap the object contained in the wrapper:
private static void swap(Wrapper a, Wrapper b)
With this method, enclosed Strings will remain swapped after the method returns.
3. Without Temporary Variable
If our variables are of primitive types, we can find ways to swap them without temporary variables.
Let’s see several examples.
3.1. Using Arithmetic Operations
We can use math to swap variables without temporary variables in several ways. For the following examples, let’s assume that we want to swap two integers a=5 and b=10.
We can use additions and subtraction for swapping:
a = a + b; // a = 15 b = a - b; // b = 5 a = a - b; // a = 10
Or, we can use multiplications and divisions:
a = a * b; // a = 50 b = a / b; // b = 5 a = a / b; // a = 10
We should keep in mind that this method doesn’t work if any of the numbers is 0 as the first operation will lead to storing a zero, making the rest of the algorithm useless. Moreover, if b=0, it will throw an ArithmeticException due to a division by zero.
We should also take care of primitives capacity as addition/multiplication can lead to numbers exceeding the maximum value of the primitive type. This may lead to errors after swapping without throwing any exception.
For example, if a = Integer.MAX_VALUE, then before swapping a=2147483647 and b=10 and after swapping, a=10, b=-1.
If we’re working with char, byte, or short types of data, an explicit cast is required as arithmetic operators result is a value of type int at least in Java:
a = (char)(a + b); b = (char)(a - b); a = (char)(a - b);
3.2. Using Logical Operations
If we’re working with integer data types (i.e., char, short, byte, int, long), we can use the exclusive OR bitwise operator (XOR). The “^” operator will process a bitwise XOR operation on all bits of our variables:
a = a ^ b; // a = 1111 (15) b = a ^ b; // b = 1010 (5) a = a ^ b; // a = 0101 (10)
We should be aware that, as for the arithmetic operators, the bitwise XOR operator returns at least int data type. So, we have to cast the result of the XOR for each line if we’re working with chars, bytes, or shorts variables.
3.3. Single-line Variant
We can use a single-line version of the swapping methods to reduce the code size:
b = (a + b) – (a = b); a += b – (b = a); a = a * b / (b = a); a = a ^ b ^ (b = a);
This works because expressions are evaluated with respect of the precedence of the operators. If a = 5 and b = 10 initially, the last expression is equivalent to a = 5 ^ 10 ^ (b = 5). The first operation (5 ^ 10) is exactly the first line of the multi-line algorithm, then we assign 5 to b (parenthesis have priority), and finally, we calculate 15 ^ 5 which is exactly the third line of the algorithm.
4. Performance Analysis
We just saw that there are several ways to swap two variables in Java, but which one is the more efficient? To give a tendency on performances of each algorithm, we performed loops of variable swapping methods and measured the time needed to swap two variables 100.000 times. We ran the test 10 times to calculate the average execution time of each algorithm. Here are the results:
The absolute time is not important here as it depends on the machine which is running the test. We only see that some algorithms are slower than others. It’s especially true for the multiplication/division one, which is significantly slower, either in its single-line version. On the opposite, the XOR algorithm is the most efficient in both multi and single-line versions.
Swapping Objects with a temporary variable is also quite efficient, which is quite understandable as only pointers are manipulated in that case.
5. Conclusion
In this article, we looked at how to swap two variables in Java, depending on the type of the variables.
We described how to swap Objects, and then we studied several ways to swap primitives types with several algorithms. Finally, we had a look at the performances of each method.
As always, the source code for all examples is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: