Java program to swap two integers


Read integers from users using the nextInt() method of the Scanner class.

To swap them −

  • Create a variable (temp), initialize it with 0.
  • Assign 1st number to temp.
  • Assign 2nd number to 1st number.
  • Assign temp to second number.

Example

import java.util.Scanner;
public class SwapTwoNumbers {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter first number :: ");
      int num1 = sc.nextInt();
      System.out.println("Enter second number :: ");
      int num2 = sc.nextInt();

      int temp = 0;
      temp = num1;
      num1 = num2;
      num2 = temp;

      System.out.println("After swapping ::");
      System.out.println("Value of first number ::"+ num1);
      System.out.println("Value of first number ::"+ num2);
   }
}

Output

Enter first number ::
22
Enter second number ::
33
After swapping ::
Value of first number ::33
Value of first number ::22


Updated on: 13-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements