Answers for "swap two numbers in java without using third variable in java"

1

swap two variables without temporary java

import java.*; 
  
class noTemp { 
  
    public static void main(String a[]) 
    { 
        int x = 10; 
        int y = 5; 
        x = x + y; 
        y = x - y; 
        x = x - y; 
        System.out.println("After swaping:"
                           + " x = " + x + ", y = " + y); 
    } 
}
Posted by: Guest on January-22-2021
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

Code answers related to "swap two numbers in java without using third variable in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language