by Dinesh Thakur Category: Data Type

This Swap Numbers Java Example program prints exchange number i.e. if the input is n1 is 100 and n2 is 200 then after swaping output will be n1 is 200 and n2 is 100. You should use any temporary variable to swap the numbers.

Here is the Java Example for the program SwapNumberExample :

import java.util.Scanner;

public class SwapNumberExample
{
             private static void swap(int n1, int n2)
        {
            int temp = n1;
            n1 = n2;
           n2 = temp;
           System.out.println("After Swapping");
           System.out.println("Value of number1 is :" + n1);
           System.out.println("Value of number2 is :" +n2);
        }
public static void main(String[] args)
    {
     try
          {
           System.out.println("Enter the First Number ");
           Scanner first = new Scanner(System.in);
           int n1 = first.nextInt();
           System.out.println("Enter the Second Number");
           Scanner second = new Scanner(System.in);
           int n2 = second.nextInt();
           System.out.println("Before Swapping");
           System.out.println("Value of number1 is :" + n1);
           System.out.println("Value of number2 is :" +n2);
           swap(n1, n2);
      }
           catch (Exception e){}
   }
}

Swap Numbers Java Example



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.