
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Swap Two Integers in Java
In this article, we will learn to swap two numbers using Java. We will use the Scanner class to get the user input and perform the swapping temporary variable. Read integers from users using the nextInt() method of the Scanner class.
Steps to swap two integers
Following are the steps to swap two numbers in Java?
- Import the Scanner class.
- Create a variable (temp), and initialize it with 0.
- Assign 1st number to temp.
- Assign the 2nd number to the 1st number.
- Assign temp to the second number.
- Print the swapped values of the two numbers
Java program to swap two integers
Below is the Java program to swap two integers ?
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
Code Explanation
In the above code, we will start by importing the Scanner class from the java.util package, which lets us take input from the user. Inside the main method, we create a Scanner object named sc to read integers using the nextInt() method. We ask the user to enter two numbers, which are stored in the variables num1 and num2. To swap them, we declare a temporary variable temp to hold num1's value. We then assign num2 to num1 and finally store temp (original num1) in num2. After the swap, we printed the new values, confirming the swap was successful.