Swapping the Variables Without Using Third Variables Using Java
In this post, we will see, how to swap the variables. There are different ways to swap the variables. The major swap algorithms are:
1) Swapping using the third varaibles.
2) Swapping using the Bitwise Operator. This is only for the Integer. This doesn't use the third variables.
3) Swapping using the Arithmetic Operations. This is also, only for the Integer. This also, doesn't use the
third variables.
4) Swapping the Strings without using the third variables. This is little bit tricky. The logic is similar to the
above one, i.e. Arithmetic Operations. But the Strings are immutable in the Java, so, externally we are not
using the third variables, but internally, this uses the third variables.
Below, we have the Java Program to discuss all the above methods in details.
/**
* This class will reverse the two variables.
* Here we will see how to swap the variables using or without using the third variables.
* @author Sonu Mishra
*/
public class SwapVariables {
/**
* Swapping using the third variable and without the third variables.
* Swap two variables using the temporary variables or the third variable.
* @param a The first variable.
* @param b The Second variable.
*/
In this post, we will see, how to swap the variables. There are different ways to swap the variables. The major swap algorithms are:
1) Swapping using the third varaibles.
2) Swapping using the Bitwise Operator. This is only for the Integer. This doesn't use the third variables.
3) Swapping using the Arithmetic Operations. This is also, only for the Integer. This also, doesn't use the
third variables.
4) Swapping the Strings without using the third variables. This is little bit tricky. The logic is similar to the
above one, i.e. Arithmetic Operations. But the Strings are immutable in the Java, so, externally we are not
using the third variables, but internally, this uses the third variables.
Below, we have the Java Program to discuss all the above methods in details.
/**
* This class will reverse the two variables.
* Here we will see how to swap the variables using or without using the third variables.
* @author Sonu Mishra
*/
public class SwapVariables {
/**
* Swapping using the third variable and without the third variables.
* Swap two variables using the temporary variables or the third variable.
* @param a The first variable.
* @param b The Second variable.
*/