Swapping means inter changing. Swapping two numbers or two variables is nothing but sending the value of one variable to another variable and vice-versa. For instance, consider two variables i=2 and j=4. Now swapping these two variables gives i=4 and j=2. This is what is called as swapping. Now i think, it is obvious for you and that you can do this. Let's see the example.
import java.util.*;
class SwapDemo
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter 2 numbers to
swap");
int a=s.nextInt();
int b=s.nextInt();
swap(a,b);
}
public static void swap(int a,int b)
{
// Store a in a temporary variable
int temp=a;
// Store b variable value in a
a=b;
// Store temp (a original) value in b
b=temp;
// Print the variables
System.out.println("a is "+a+" & b is "+b);
}
}
Sample Output
Enter 2 numbers to swap
8
7
a is 7 & b is 8
Explanation
The logic is very simple. Everything here is done in the swap() method which take two parameters of type int (here) [You can take variables of any type and swap]. From the comments, it is obvious that first, the value in he variable a is stored in temp and the value of b is stored in a. Now a contains the value in b and temp contains the value in a. Now all that is left is store the value of a in b. For this we'll use the initially stored value of a which is in temp and assign the value to b.
When we print the variables we'll find that the variables are swapped i.e. their values are interchanged. Note that, as call-by-value takes place here the effect is circumscribed with in the
swap()
method only. The original a & b are not swapped. For that to be done, write the swap code in the main()
itself.
No comments:
Post a Comment