Quick links: C-Tricks HR Interview Que. Code Snippets C Programs C++ Programs Java Programs PHP Examples

Home » Java programs

Java program to swap two integer numbers using class

Submitted by BalRam Dixit, on May 19, 2017
Learn: How to read and swap two integer numbers in Java language using class, that means swapping of numbers operations will be performed using class.

In this Java program, we are going to read two integer numbers and swap them, program is implemented using class that means, there will be methods to read integer numbers, to display numbers and two swap the numbers.

Note: This program is not using temporary variable to swap the numbers.

Consider the program

import java.util.Scanner;

public class Swap{
	private int num1;
	private int num2;
	public void setNum1(int num){
		this.num1=num;
	}
	public int getNum1(){
		return this.num1;
	}
	public void setNum2(int num){
		this.num2=num;
	}
	public int getNum2(){
		return this.num2;
	}
	public void swapNumber(){
		setNum1(getNum1()+getNum2());
		setNum2(getNum1()-getNum2());
		setNum1(getNum1()-getNum2());
	}
	public void inputNumber(){
		//temp variable to store num
		int num;
        Scanner sc  =   new Scanner(System.in);
        System.out.print("Enter first number: ");
        num =   sc.nextInt();
        setNum1(num);
        
        System.out.print("Enter second number: ");
        num =   sc.nextInt();
        setNum2(num);        

	}
	public void printNumber(){
		System.out.println("First Number is --> "+getNum1());
		System.out.println("Second Number is --> "+getNum2());
	}
	public static void main(String[] ar){
		Swap ob = new Swap();
		ob.inputNumber();
		ob.swapNumber();
		ob.printNumber();
		
	}
}

Output

Enter first number: 10
Enter second number: 20
First Number is --> 20
Second Number is --> 10






COMMENTS


Love this website?
please like to get updates...