- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements