Java program to swap two numbers using single level inheritance

Swap two numbers

This program illustrate how to swap two numbers using the concept single level inheritance without using third variable.We have made two classes.In first class i.e. “base” user will input a values using function “get()” and in second class i.e “scan” which extends the “base” class swaping of two numbers will be performed using function “swap()” and result will be displayed using function “display()”. The all three functions will be called by object of “scan” class i.e. “d1”.

Logic to swap two numbers without using third variable

    first number = first number  +  second number;
    second number = first number  -  second number;
    first number = first number  -  second number;
import java.util.*;
class base
{
 int x,y;
public void get()
{
 Scanner kb=new Scanner(System.in);
 System.out.println("Enter value of x:- ");
 x=kb.nextInt();
 System.out.println("Enter value of y:- ");
 y=kb.nextInt();
}
}
class scan extends base
{

	public void swap()
	{
		
		x=x+y;
		
		y=x-y;

		x=x-y;
	
    }
 
 public void display()
 {
	 System.out.println("value of x = "+x);
	 System.out.println("value of y = "+y);
 }
 
 public static void main(String arg[])
{
 scan d1=new scan();
 d1.get();
 d1.swap();
 d1.display();
}

}

OUTPUT:-

swap two numbers

Leave a Reply

Your email address will not be published. Required fields are marked *