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.

2. Variable And Data Types

0 Comments

Start the conversation!

Be the first to share your thoughts

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support