on Leave a Comment

Java Program to Swap Two Numbers

In this article, we will read about how to swap two numbers in java. We can swap two number using third variable or without using third variable. In this article, we will both methods.

Java Program to Swap Two Numbers

This java program swaps two numbers using third variable.

import java.util.Scanner;
class Swapping
{
 public static void main(String[] args) {
  int n1, n2, temp;
  Scanner read = new Scanner(System.in);

  System.out.print("Enter first number : ");
  n1 = read.nextInt();

  System.out.print("Enter second number : ");
  n2 = read.nextInt();
        
                /*Swapping two numbers using third variable*/
  temp = n1;
  n1 = n2;
  n2 = temp;
        
                System.out.println("\nAfter Swapping\n");
                System.out.println("First number : "+n1);
                System.out.println("Second number : "+n2);
 }
}

Output:

Enter first number : 5
Enter second number : 6

After Swapping

First number : 6
Second number : 5

Java Program to Swap Two Numbers without Using Third Variable

This java program swaps two numbers without using third variable.

import java.util.Scanner;
class Swapping
{
 public static void main(String[] args) {
  int n1, n2;
  Scanner read = new Scanner(System.in);

  System.out.print("Enter first number : ");
  n1 = read.nextInt();

  System.out.print("Enter second number : ");
  n2 = read.nextInt();
        
                /*Swapping two numbers without using third variable*/
                n1 = n1 - n2;
                n2 = n1 + n2;
                n1 = n2 - n1;
        
                System.out.println("\nAfter Swapping\n");
                System.out.println("First number : "+n1);
                System.out.println("Second number : "+n2);
 }
}

Output:

Enter first number : 10
Enter second number : 20

After Swapping

First number : 20
Second number : 10




0 comments:

Post a Comment