Swap two numbers

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 5:- Swap two numbers

To swap two numbers, you need a temporary variable to hold one of the values while you interchange their positions. Here's a common method to swap two numbers in Java:

javaCopy code
public class SwapNumbers { public static void main(String[] args) { int num1 = 10; int num2 = 20; System.out.println("Before swapping:"); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); // Swapping logic using a temporary variable int temp = num1; num1 = num2; num2 = temp; System.out.println("\nAfter swapping:"); System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); } }

Output:

makefileCopy code
Before swapping: num1 = 10 num2 = 20 After swapping: num1 = 20 num2 = 10

In the code above, num1 and num2 are initialized with the values 10 and 20, respectively. The swapping logic uses the temporary variable temp to store the value of num1. Then, the value of num2 is assigned to num1, and finally, the value of temp (which was the original value of num1) is assigned to num2, completing the swap.

After the swap, the values of num1 and num2 have exchanged, and you can see the results in the "After swapping" section of the output.


Disclaimer:-

Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.

 

2. Variable And Data Types

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?