java

Swapping of Two Numbers in Java

In this tutorial, we are going to see how to write a java program to swap two numbers in two different ways. Either with or without a temporary variable.
 

Example 1: Swapping of Two Numbers in Java Using a Temporary Variable
import java.util.Scanner;

public class Main
{
   public static void main(String args[])
   {
      int a, b, tmp;
      System.out.print("Enter two numbers: ");
      Scanner sc = new Scanner(System.in);
     
      a = sc.nextInt();
      b = sc.nextInt();
     
      System.out.println("Before swapping: a = "+a+" and b = "+b);
     
      tmp = a;
      a = b;
      b = tmp;
     
      System.out.println("After swapping: a = "+a+" and b = "+b);
   }
}

Output:

Enter two numbers: 1 2
Before swapping: a = 1 and b = 2 
After swapping: a = 2 and b = 1

 

 

Example 2: Swapping of Two Numbers in Java Without Using a Temporary Variable
import java.util.Scanner;
 
class Main
{
   public static void main(String args[])
   {
      int a, b;
      System.out.print("Enter two numbers: ");
      Scanner sc = new Scanner(System.in);
 
      a = sc.nextInt();
      b = sc.nextInt();
 
      System.out.println("Before swapping: a = "+a+" and b = "+b);
 
      a = a + b;
      b = a - b;
      a = a - b;
 
      System.out.println("After swapping: a = "+a+" and b = "+b);
   }
}

Output:

Enter two numbers: 1 2
Before swapping: a = 1 and b = 2 
After swapping: a = 2 and b = 1
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *