One more common interview questions you might have faced in Java interviews.Swapping of numbers is possible in Java by using two methodologies. Either you can do it through a third variable or without third or temporary variable.
Lets have a look on those two types of swapping through Java code.
Swapping two numbers without using third variable
Suppose you have two variables 'a' and 'b' and you need to swap the value of 'b' to 'a' and the 'a' to 'b'.
We cant use any third variable so we have to swap it between these two variables only. Here is the code for doing so.

There are other ways too for doing the above apart from addition and subtraction.
Now lets look at the code for using a temporary or third variable to swap two numbers. No trick in this.
Swapping two numbers by using a third variable
Now lets look at the sample code for swapping two numbers by using a third or temporary variable.
Lets have a look on those two types of swapping through Java code.
Swapping two numbers without using third variable
Suppose you have two variables 'a' and 'b' and you need to swap the value of 'b' to 'a' and the 'a' to 'b'.
We cant use any third variable so we have to swap it between these two variables only. Here is the code for doing so.

There are other ways too for doing the above apart from addition and subtraction.
Now lets look at the code for using a temporary or third variable to swap two numbers. No trick in this.
Swapping two numbers by using a third variable
Now lets look at the sample code for swapping two numbers by using a third or temporary variable.

No comments:
Post a Comment