For working professionals
For fresh graduates
More
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.
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.
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:
#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.
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
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.
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.
The different methods in which string inputs can be swapped in Java are:
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.
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.
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.
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:
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.
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.
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.
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.
Yes, by switching the indices of two numbers stored in an array, you can change the values of the 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.
Take the Free Java Quiz & See Your Rank!
Pavan Vadapalli
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.