Swapping of two numbers

This Java programming tutorial will teach you the
methods for writing program to calculate swap of two numbers. Swapping
is used where you want to interchange the values. This program will help
you to increase your programming ability.
In this program we will see how we can swap two
numbers. We can do this by using a temporary variable which is used to store
variable so that we can swap the numbers. To swap two numbers first we have to
declare a class Swapping. Inside a class declare one static method swap(int i,
int j) having two arguments, the value of these arguments will be swapped. Now
declare one local variable temp which will help us to swap the values. At last
call the main method inside of which you will call the swap method and the
result will be displayed to you.
Code of the program is given below
public class Swapping{
static void swap(int i,int j){
int temp=i;
i=j;
j=temp;
System.out.println("After
swapping i = " + i + " j = " + j);
}
public static void main(String[] args){
int i=1;
int j=2;
System.out.prinln("Before swapping
i="+i+" j="+j);
swap(i,j);
}
}
|
Output of this program is given below:
C:\java>java Swapping
Before swapping i = 1 j = 2
After swapping i = 2 j = 1 |
Download this example

|