top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Swapping of Two Numbers in Java

Introduction

Swapping of two numbers in Java is one of the first programs taught to beginners when they start out learning Java programming. It is a program where the values inside two variables are swapped with each other. It is important to learn how values can be swapped, as this concept is used in many algorithms and programs.

Overview

This tutorial aims to provide a detailed guide on swapping two numbers in Java. We will discuss the various ways in which two numbers can be swapped in Java through examples. Studying these examples will provide a better understanding of this concept.

Program to Swap Two Numbers

Algorithm

We can follow a general algorithm that we can use to write a program in any programming language for swapping two numbers. The specific implementation may vary based on the programming language syntax and conventions.

Algorithm:

  1. Start

  2. Declare and initialize two integer variables, num1, and num2, with the desired values.

  3. Print the values of num1 and num2 before swapping.

  4. Declare an additional integer variable, temp.

  5. Assign the value of num1 to temp to preserve it.

  6. Assign the value of num2 to num1.

  7. Assign the value stored in temp (the original value of num1) to num2.

  8. Print the values of num1 and num2 after swapping.

  9. End.

C Program

#include <stdio.h>


void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}


int main() {
    int num1 = 10;
    int num2 = 20;


    printf("Before swapping:\n");
    printf("num1 = %d\n", num1);
    printf("num2 = %d\n", num2);


    swap(&num1, &num2);


    printf("After swapping:\n");
    printf("num1 = %d\n", num1);
    printf("num2 = %d\n", num2);


    return 0;
}

The above C program defines a swap function that takes two integer pointers as parameters and swaps their values using a temporary variable. Inside the main function, two integer variables num1 and num2 are declared and initialized with values 10 and 20, respectively.

The program prints the values of num1 and num2 before swapping.

Then, the swap function is called, passing the addresses of num1 and num2 as arguments.

After the swapping operation, the program prints the values of num1 and num2 to verify the swapping. The program finally returns 0, indicating successful execution.

Python Program

def swap_numbers(a, b):
    a, b = b, a
    return a, b

num1 = 10
num2 = 20

print("Before swapping:")
print("num1 =", num1)
print("num2 =", num2)

num1, num2 = swap_numbers(num1, num2)

print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)

This Python program defines a function swap_numbers that takes two parameters, a and b, and swaps their values using tuple assignment. Two variables num1 and num2 are declared and assigned values 10 and 20 respectively. The program prints the values of num1 and num2 before swapping.

Then, the swap_numbers function is called, passing num1 and num2 as arguments, and the returned values are assigned back to num1 and num2. After the swapping operation, the program prints the values of num1 and num2 to verify the swapping.

PHP Program

<?php

function swapNumbers(&$a, &$b) {
    $temp = $a;
    $a = $b;
    $b = $temp;
}

$num1 = 10;
$num2 = 20;

echo "Before swapping:\n";
echo "num1 = " . $num1 . "\n";
echo "num2 = " . $num2 . "\n";

swapNumbers($num1, $num2);

echo "After swapping:\n";
echo "num1 = " . $num1 . "\n";
echo "num2 = " . $num2 . "\n";
?>

The PHP program defines a function swapNumbers that takes two variables by reference (&$a and &$b) and swaps their values using a temporary variable. Two variables $num1 and $num2 are declared and assigned values 10 and 20 respectively.

The program echoes the values of $num1 and $num2 before swapping. Finally, the swapNumbers function is called, passing $num1 and $num2 as arguments, and the values are swapped in place. After the swapping operation, the program echoes the values of $num1 and $num2 to verify the swapping.

C# Program

using System;

class Program
{
    static void Swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;
    }

    static void Main(string[] args)
    {
        int num1 = 10;
        int num2 = 20;

        Console.WriteLine("Before swapping:");
        Console.WriteLine("num1 = " + num1);
        Console.WriteLine("num2 = " + num2);

        Swap(ref num1, ref num2);

        Console.WriteLine("After swapping:");
        Console.WriteLine("num1 = " + num1);
        Console.WriteLine("num2 = " + num2);
    }
}

The C# program defines a Swap method that takes two integer parameters using the ref keyword and swaps their values using a temporary variable. Inside the Main method, two integer variables, num1 and num2, are declared and initialized with values 10 and 20, respectively.

The program writes the values of num1 and num2 before swapping using Console.WriteLine.

The Swap method is called, passing num1 and num2 as ref arguments. After the swapping operation, the program writes the values of num1 and num2 again to verify the swapping using Console.WriteLine.

Swapping Two Numbers in Java

The different methods in which string inputs can be swapped in Java are:

  • Swapping two numbers using a third variable in Java:

In this method, a third variable is added to temporarily hold the value of any one variable while the values of the two variables are switched. The variables can be switched out successfully by sequentially assigning values.

  • Swapping two numbers without using a third variable in Java:

You can switch numbers without a temporary variable by using the XOR (^) operator. The bits are switched by using the XOR operator to combine two variables, which causes their values to change.

Example 1: Swap Two Numbers in Java Using a Temporary Variable

public class upGradTutorials {
    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("After swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
    }
}

This program demonstrates how to swap the values of two numbers in Java using a temporary variable. Initially, we have two variables, num1, and num2, with values of 10 and 20, respectively. We print the values of num1 and num2 before the swapping operation.

To swap the values, we introduce a third variable called temp. We store the value of num1 in temp to preserve it. Then, we assign the value of num2 to num1. Finally, we assign the value stored in temp (the original value of num1) to num2.

Example 2: Swap Two Numbers in Java Without Using a Temporary Variable

public class upGradTutorials {
    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);

        num1 = num1 + num2;
        num2 = num1 - num2;
        num1 = num1 - num2;

        System.out.println("After swapping:");
        System.out.println("num1 = " + num1);
        System.out.println("num2 = " + num2);
    }
}

Like the previous example, this Java program initializes two integer variables, num1, and num2, with values 10 and 20, respectively. Before swapping, the program prints the values of num1 and num2 using System.out.println.

To swap the values without using a temporary variable, the program performs the following steps:

  • Add num1 and num2 and assign the result back to num1.

  • Subtract num2 from the updated value of num1 and assign the result back to num2.

  • Subtract the updated value of num2 from the updated value of num1 and assign the result back to num1.

After the swapping operation, the program prints the values of num1 and num2 again to verify the swapping. The program outputs the final swapped values of num1 and num2.

Swapping of Two Numbers in Array in Java

public class ArraySwapExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20};

        System.out.println("Before swapping:");
        System.out.println("numbers[0] = " + numbers[0]);
        System.out.println("numbers[1] = " + numbers[1]);

        swap(numbers, 0, 1);

        System.out.println("After swapping:");
        System.out.println("numbers[0] = " + numbers[0]);
        System.out.println("numbers[1] = " + numbers[1]);
    }

    public static void swap(int[] arr, int index1, int index2) {
        int temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
    }
}

The above program initializes an array named numbers with two elements: 10 and 20. Before swapping, the program prints the values at index 0 and index 1 of the numbers array using System.out.println. The swap method is called passing the numbers array along with the indices of the elements to swap (0 and 1).

Inside the swap method, a temporary variable temp is used to store the value at index1.

The value at index2 is assigned to index1, effectively swapping the values. Finally, the value stored in temp is assigned to index2, completing the swap operation. After the swapping operation, the program prints the updated values at index 0 and index 1 of the numbers array to verify the swapping.

Conclusion

Swapping numbers in Java frequently comes up in interviews and discussions programming. It entails converting the values of two variables or array members. Using a temporary variable is the simplest method, although bitwise operators can swap values without needing a second variable. Alternating the indices of the numbers in an array also allows for number switching.

When performing swaps, it is crucial to consider the extent of the variables and their possible influence on performance, especially when many swaps are involved. You can check out courses from upGrad to master concepts like swapping of two numbers in Java.

FAQs

  1. Is it possible to perform a swapping of two numbers using scanner?

Yes, the scanner class can swap two numbers in Java. In this case, the input for the number is taken from the users, after which the normal swapping methods are applied, as discussed in this tutorial.

  1. Is it viable to swap the values of two numbers stored in an array in Java?

Yes, by switching the indices of two numbers stored in an array, you can change the values of the numbers.

  1. Are there any performance factors to take into account when Java swaps numbers?

Using a temporary variable or bitwise operator to swap two numbers in Java is typically effective and has little effect on performance. It's crucial to remember that frequent Using a temporary variable or bitwise operator to swap two numbers in Java is typically effective and has little effect on performance. It's crucial to remember that frequent swapping within a loop or extensive swapping operations may significantly affect performance.

Leave a Reply

Your email address will not be published. Required fields are marked *