Java program to swap two integers

Java Programming Java8Object Oriented Programming

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


raja
Published on 26-Apr-2018 08:55:52
Advertisements