swap() numbers java code example

Example 1: Java program to swap two numbers using function

import java.util.Scanner;
// java swap function
public class SwapTwoNumberDemo 
{
   int numOne, numTwo;
   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.println("First number : ");
         obj.numOne = sc.nextInt();
         System.out.println("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());
      }
   }
}

Example 2: swapping values in java using a function not working

#include <stdio.h>

int main() {
   int a = 23, b = 47;
   int t;
   printf("Before. a: %d, b: %d\n", a, b);
   t = a;
   a = b;
   b = t;
   printf("After.  a: %d, b: %d\n", a, b);
   return 0;
}

Tags:

Java Example