In this blog, we will look at various approaches to swapping two numbers in Java, discussing their significance and providing practical examples.
What does “Swap of Two Numbers in Java” mean?
The process of changing the values of two variables is referred to as “Swap of Two Numbers in Java.” Swapping two numbers in Java entails exchanging the values stored in variables without losing or changing their original values. Programmers frequently use this operation to efficiently rearrange data, sort arrays, or perform mathematical calculations.
Example of swapping two numbers in Java:
public class NumberSwapExample { public static void main(String[] args) { int a = 10; int b = 20; System.out.println("Before swapping:"); System.out.println("a = " + a); System.out.println("b = " + b); // Swapping logic int temp = a; a = b; b = temp; System.out.println("After swapping:"); System.out.println("a = " + a); System.out.println("b = " + b); } }
In this example, two variables, ‘a’ and ‘b,’ are set to the values 10 and 20, respectively. We use a temporary variable, ‘temp,’ to store the value of ‘a‘ in order to swap these numbers. Then we assign the value ‘b‘ to ‘a‘ and the value ‘temp‘ to ‘b‘. After performing the swapping operation, we swap the values of ‘a’ and ‘b’. The program’s output will show the numbers before and after swapping:
``` Before swapping: a = 10 b = 20 After swapping: a = 20 b = 10 ```
Using this swapping technique, we can effectively manipulate variable values in Java programs.
Know the nth Prime Number in Java here!
Swapping of two numbers using a third variable
//Java Program to Swap Two Numbers import java.util.*; class swapNumEx { // Function to swap two numbers // Using temporary variable static void swapValue(int a, int b) { // Swapping the values int temp = a; a = b; b = temp; System.out.println("Value of a is " + a + " and Value of b is " + b); } // Main driver code public static void main(String[] args) { System.out.print("Enter a value for a: "); Scanner sc = new Scanner(System.in); int a = sc.nextInt(); System.out.print("Enter a value for b: "); int b = sc.nextInt(); // Calling above function to reverse the numbers swapValue(a, b); } }
Explanation of the Code:
The below provided code explains how to use a temporary variable to swap the values of two numbers in Java:
1. The code begins by importing the necessary Java utilities.
2. Consequently the class ‘swapNumEx’ contains the swap logic.
3. The ‘swapValue‘ function is used to swap the values of two numbers. It accepts two integer parameters, ‘a‘ and ‘b‘.
4. The function declares a temporary variable ‘temp’ and assigns it the value ‘a’ to save the original value of ‘a’ before overwriting it.
5. We update the value of ‘a’ by assigning it the value of ‘b’. This effectively swaps the values of ‘a‘ and ‘b‘.
6. Similarly, the value of ‘b’ is updated by assigning the value of ‘temp’ to it. This step assigns the original value of ‘a‘, which is stored in ‘temp.’ to `b`, completing the swapping process.
7. Finally, the function prints the updated values of ‘a‘ and ‘b’, displaying the result of the swapping operation, using the ‘System.out.println’ statement.
8. In the main method, the ‘Scanner’ class prompts the user to enter values for ‘a’ and ‘b’.
9. The ‘Scanner’ method uses the ‘nextInt’ to read user input and assign it to variables ‘a’ and ‘b’.
10. The function ‘swapValue’ swaps the values ‘a’ and ‘b’ when called as arguments.
11. Following the function call, the program prints the updated values of ‘a’ and ‘b,’ indicating that the values were successfully swapped.
In summary, This code demonstrates Java swapping two numbers using a temporary variable, with the `swapValue` function encapsulating logic.
Output:
Enter a value for a: 5
Enter a value for b: 10
Value of a is 10 and Value of b is 5
Swapping the Values Without Using a Third Variable by using sum and differences concepts of maths
// Java Program to Swap Two Numbers import java.util.*; class swapNoEx2 { // Function to swap values of two numbers without creating temp variable static void swapValues(int a, int b) { // Difference of 2nd from 1st is stored in first variable a = a - b; // Sum is stored in second variable b = a + b; // Difference of 1st from 2nd is replaced in first variable a = b - a; // Print numbers System.out.println("Value of a is " + a + " and Value of b is " + b); } // Main driver method public static void main(String[] args) { System.out.print("Enter a value for a: "); Scanner sc = new Scanner(System.in); int a = sc.nextInt(); System.out.print("Enter a value for b: "); int b = sc.nextInt(); // Above function is called in main to print swapped values of numbers swapValues(a, b); } }
Get complete Best Python Books for Programmers here!
Explanation of the code:
Below code provided illustrates yet another method for swapping the values of two numbers in Java without the use of a temporary variable:
1. The code starts by importing the required Java utilities.
2. The class ‘swapNoEx2’ defines the swap logic.
3. Simultaneously the ‘swapValues‘ function swaps the values of two numbers without the use of a temporary variable. It requires two integer parameters, a and b.
4. The function updates the value of ‘a’ by subtracting the value of ‘b’ from it. This step computes and stores the difference between the two numbers in ‘a‘.
5. Finally, we add the original value of ‘a’ (before subtraction) to ‘b’ to update its value. This step computes and stores the sum of the original two numbers in ‘b‘.
6. The value of ‘a‘ is then updated again by subtracting the new value of ‘a‘ from it (which is the updated value of ‘b‘). This step replaces the difference between the two numbers in ‘a’.
7. The swapping process is now complete, and the function uses the ‘System.out.println‘ statement to print the updated values of ‘a‘ and ‘b‘.
8. In the main method, the ‘Scanner’ class prompts the user to enter values for ‘a’ and ‘b’.
9. The ‘Scanner‘ method ‘nextInt‘ is used to read user input and assign it to variables ‘a‘ and ‘b‘.
10. The function ‘swapValues’ swaps the values when called with the arguments ‘a’ and ‘b’.
11. The program prints the updated values of ‘a’ and ‘b,’ indicating that it successfully swapped the values, following the function call.
In summary, this code offers a Java method for swapping two numbers without using a temporary variable, using the `swapValues` function.
Output:
Enter a value for a: 8
Enter a value for b: 4
Value of a is 4 and Value of b is 8
Swapping the Values Using Operator
// Java Program to Swap two Numbers import java.io.*; import java.util.*; class swapNumEx3 { // Function to swap values of two numbers using XOR operator static void swapValues(int x, int y) { // Logic of XOR operator x = x ^ y; y = x ^ y; x = x ^ y; System.out.println("Value of x is " + x+ " and Value of y is " + y); } // Main driver method public static void main(String[] args) { System.out.print("Enter a value for x: "); Scanner sc = new Scanner(System.in); int x = sc.nextInt(); System.out.print("Enter a value for y: "); int y = sc.nextInt(); // Calling the function in main method to get above integer numbers swapped swapValues(x, y); } }
Explanation of the code:
The below code shows another method for swapping the values of two numbers in Java using the XOR operator:
- The code imports Java libraries and defines swap logic in class “swapNumEx3”.
- Afterward the ‘swapValues’ function uses the XOR operator to swap the values of two numbers. ‘x’ and ‘y’ are two integer parameters that it accepts.
- The function performs swapping using the XOR operator (“). This strategy’s reasoning is as follows:
– “x = x y” combines “x” and “y” using an XOR operation, then stores the outcome in “x”.
– The statement “y = x y” performs an XOR operation on the newly updated value of “x” and “y” (which is the original value of “x”) and stores the outcome in “y”.
– “x = x y” performs an XOR operation on the updated values of “x” and “y” (which are, respectively, their original values) and stores the outcome in “x.”
Without the use of a temporary variable, these XOR operations effectively swap the values of ‘x’ and ‘y’.
- The function then uses the “System.out.println” statement to print the updated values of “x” and “y.”
- The “Scanner” class prompts the user to enter values for “x” and “y” using the “main” method.
- And then the “Scanner” class’s “nextInt” method reads the user input and assigns it to the variables “x” and “y”.
- Subsequently the method “nextInt” of the “Scanner” class reads the user input and assigns it to the variables “x” and “y”.
- The program prints the updated values of “x” and “y” after calling the function to show that the values have been successfully switched.
In summary, this code offers a Java method for swapping two numbers using XOR, with the `swapValues` function implementing swap logic.
Learn How to Palprime Number in Java, Here!
Output:
Enter a value for x: 6
Enter a value for y: 7
Value of x is 7 and Value of y is 6
Using Arithmetic operators
// Java Program to Swap two Numbers import java.util.*; public class swapNumEx4{ public static void main(String []args){ System.out.print("Enter a value for a: "); Scanner sc = new Scanner(System.in); int a = sc.nextInt(); System.out.print("Enter a value for b: "); int b = sc.nextInt(); System.out.println("Before swapping Value of a is " + a + " and Value of b is " + b +"\n"); a = (a + b) - (b = a); System.out.println("After Swapping Value of a is " + a + " and Value of b is " + b); } }
Explanation of the code:
Below mentioned code demonstrates another approach to swap the values of two numbers in Java without using a temporary variable:
- The code imports Java libraries and defines a swapping logic class, `swapNumEx4.
- While the user is prompted to enter values for “a” and “b” using the “Scanner” class in the “main” method.
- The “Scanner” method called “nextInt” reads the user input and assigns it to the variables “a” and “b”.
- The program then uses the “System.out.println” statement to print the initial values of “a” and “b.”
- One line of code is all that is required to swap the values:
– “(a + b)” computes the product of “a” and “b.”
– “(b = a)” effectively stores the original value of “a” in “b” by assigning “a value “‘s to “b.”
– The final step is to evaluate the whole expression “(a + b) – (b = a)“, which deducts the original value of “a” (stored in “b“) from the sum of “a” and “b” and effectively assigns the original value of “b” to “a“.
- The program then displays the updated values of ‘a’ and ‘b, showing that the values have been switched using the ‘System.out.println’ statement.
In summary, this Java code demonstrates a concise method for swapping two numbers using a single expression, interacting with the user.
Output:
Enter a value for a: 10
Enter a value for b: 20
Before swapping Value of a is 10 and Value of b is 20
After Swapping Value of a is 20 and Value of b is 10
In conclusion, swapping numbers in Java is a common task, with various techniques like temporary variables, arithmetic operations, bitwise XOR, and single expressions. Understanding these techniques helps developers choose the most suitable method for specific requirements, aiding in sorting, data manipulation, and algorithmic problem-solving.
We hope that our blog post on “Swap Two Numbers in Java” will answer any queries you may have about Java. As you continue to develop your coding skills, visit the Newtum’s website to learn more about our online coding courses in Java, Python, PHP, and other topics. With practice and dedication, you can master Java development and learn new programming concepts.