Java program to swap two numbers using function

Let’s learn java program to swap two numbers using function.

java program to swap two numbers using function

Java program to swap two numbers using function

In swapping numbers in java using function first we have to write swap function which swaps two numbers. Later this function is called in “main” method.

Also read – garbage collection in java

Here’s the java program to swap two numbers using function,

// java swap
import java.util.Scanner;
// java swap function
public class SwapTwoNumberDemo 
{
   int numOne, numTwo;
   // swap function in java
   public  void swapNum(SwapTwoNumberDemo stn)
   {
      int temp;
      temp = stn.numOne;
      stn.numOne = stn.numTwo;
      stn.numTwo = temp;
   }
   public static void main(String[] args) 
   {
      SwapTwoNumberDemo obj = new SwapTwoNumberDemo();
      try
      {
         Scanner sc = new Scanner(System.in);             
         System.out.print("First  number : ");
         obj.numOne = sc.nextInt();

         System.out.print("Second number : ");
         obj.numTwo = sc.nextInt();

         obj.swapNum(obj);
         System.out.println("After swapping - numOne : " + obj.numOne + ", numTwo : " + obj.numTwo);
         sc.close();
      }
      catch(Exception ex)
      {
         System.out.println("Exception : " + ex.toString());
      }
   }
}



Output:

First number : 50
Second number : 100
After swapping – numOne : 100, numTwo : 50