Swapping means exchanging the values of two variables.
For example:
Before swap: a = 10, b = 20
After swap: a = 20, b = 10
public class Swapping {
int a ;
int b ;
Swapping (int a , int b ){
this.a = a;
this.b = b;
}
public void swap(){
int temp;
temp = a ;
a = b ;
b = temp ;
}
public static void main(String[] args) {
Swapping big = new Swapping (10,20);
System.out.println("before swap");
System.out.println(big.a);
System.err.println(big.b);
big.swap();
System.out.println("after swap");
System.out.println(big.a);
System.err.println(big.b);
}
}
Explanation
int a, b: These are instance variables used to store the values.
Swapping(int a, int b): This is a constructor that sets the initial values of a and b.
swap(): A method that uses a temporary variable to swap the values of a and b.
main(): The program execution starts here. It creates an object and demonstrates the swap.
Output
Before swap:
a = 10
b = 20
After swap:
a = 20
b = 10
Top comments (0)