Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 12: Write a Java program to swap two numbers.

Swapping.java

import java.util.Scanner;

public class Swapping
{
	// sumOfDigits - A method to swap two numbers
	static void swap()
	{
		Scanner s =new Scanner(System.in);
		int n1,n2;
		
		System.out.println("Enter the number n1");
		n1=s.nextInt();
		
		System.out.println("Enter the number n2");
		n2=s.nextInt();
		
		System.out.println("\nBefore Swaping");
		System.out.println("Values of n1 and n2");
		System.out.println("n1: s"+n1+"\n"+"n2: "+n2);
		
		int temp;
		temp=n1;
		n1=n2;
		n2=temp;
		
		System.out.println("\nAfter Swaping");
		System.out.println("Values of n1 and n2");
		System.out.println("n1: "+n1+"\n"+"n2: "+n2);
	}
	
	//main method
	public static void main(String[] args) 
	{
		//call to the method swap().
		swap();
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.