Answers for "write a java program to swap two variables"

2

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());
      }
   }
}
Posted by: Guest on February-08-2021
0

java program to swap two numbers

int a, b, c;
a = 5;
b = 3;
System.out.println("Before SWAP a = " + a + ", b = " + b);
c = a;
a = b;
b = c;
System.out.println("After SWAP a = " + a + ", b = " + b);
Posted by: Guest on November-11-2020
0

java swap variables

// a, b can be a numeric value
a += b; // a = a + b
b = a - b; // b = (a + b) - b = a  ---> b=a
a -= b; // a = (a + b) - (a) = b  ---> a=b
Posted by: Guest on April-28-2021

Code answers related to "write a java program to swap two variables"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language