Home  • Programming • Java

Java program example to swap two numbers

This java program swaps two numbers using a temporary variable. To swap numbers without using extra variable see another code below. Code swapping using temporary or third variable
import java.util.Scanner;
 
class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y, temp;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);
 
      x = in.nextInt();
      y = in.nextInt();
 
      System.out.println("Before Swapping
x = "+x+"
y = "+y);
 
      temp = x;
      x = y;
      y = temp;
 
      System.out.println("After Swapping
x = "+x+"
y = "+y);
   }
}
Code swapping without temporary variable
import java.util.Scanner;
 
class SwapNumbers
{
   public static void main(String args[])
   {
      int x, y;
      System.out.println("Enter x and y");
      Scanner in = new Scanner(System.in);
 
      x = in.nextInt();
      y = in.nextInt();
 
      System.out.println("Before Swapping
x = "+x+"
y = "+y);
 
      x = x + y;
      y = x - y;
      x = x - y;
 
      System.out.println("After Swapping
x = "+x+"
y = "+y);
   }
}
Compile and Run: Swapping is frequently used in sorting techniques such as bubble sort, quick sort etc.

Comments 1


Carry on sir....

Share

Copyright © 2024. Powered by Intellect Software Ltd