Swapping Two Variables in One Line in Java7 Jan 2025 | 3 min read Swapping two variables is a common task in programming, typically involving three steps: storing one variable's value in a temporary variable, assigning the second variable's value to the first, and then assigning the temporary variable's value to the second. However, in some programming languages and scenarios, it can be done more concisely in a single line. In Java, it can be achieved using arithmetic or bitwise operations. In this section, we will discuss how to swap two variables in one line. Using Arithmetic OperationsThe idea behind using arithmetic operations to swap two variables without a temporary variable is based on the properties of addition and subtraction. File Name: SwapWithArithmetic.java Output: Before swap: a = 5 b = 10 After swap: a = 10 b = 5 ExplanationThe swap is done in a single line using the phrase a = a + b - (b = a). Initially, the numbers 5 and 10, respectively, are assigned to a and b. Three steps are involved in the operation of the expression: The sum of a and b is first calculated using a + b, yielding 15, which is then assigned to a. Concurrently, b is given the value of a prior to the addition (5) since (b = a). As a result, a now holds 15 and b holds 5. At the last stage, a = 15 - 5 gives a the initial value of b (10). Following the trade, b holds 5 and a holds 10. Using Bitwise XOR OperationAnother method involves the bitwise XOR operation, which can also swap two integers without needing a temporary variable: File Name: SwapWithXOR.java Output: Before swap: a = 5 b = 10 After swap: a = 10 b = 5 ExplanationXOR is used to carry out the swap in the statement a = a ^ b ^ (b = a). At first, an is five and b is ten. The following is how the XOR operation works: Initially, a ^ b calculates the XOR of a and b, yielding 15, which is saved in a momentarily. At the same time, (b = a) gives b the initial value of a (5). As a result, a now holds 15 and b holds 5. The original value of b (10) is assigned to an in the final step, which involves recalculating the XOR using a = 15 ^ 5. Following the trade, b holds five and a holds ten. This approach circumvents the overflow problems that arise during arithmetic operations and works well for integer types. Time ComplexityThe time complexity of above methods for swap operation are O(1) . The XOR operation and arithmetic operations, is a constant-time operation. The series of XOR operations and assignments each take a fixed amount of time, independent of the input values. Space ComplexityThe space complexity of above methods are O(1). Both approaches do not require any extra memory beyond the input variables a and b. The swap is performed in-place, and no additional variables or data structures are used. ConclusionIn Java, bitwise XOR operations or arithmetic operations can be used to swap two variables in one line. These techniques offer a succinct means of carrying out the swap without using a temporary variable; but, they have certain drawbacks and require careful consideration of readability and type safety. As with any programming approach, maintaining manageable and comprehensible code requires striking a balance between cleverness and clarity. Next TopicCodility-passing-car-problem-in-java |
JFileChooser is a class that is present in the java Swing package. The java Swing package is essential for JavaTM Foundation Classes(JFC). JFileChooser contains many elements that assist in building a graphical user Interface in java. Java Swing gives components like buttons, panels, dialogs, etc. JFileChooser...
5 min read
Given a 2D array grid of positive integers measuring m x n. We have to move in a zigzag path across the grid, avoiding each other cell. The following stages are used to define the zigzag pattern. Start in cell (0, 0) on the upper left. When...
6 min read
The XOR bitwise operator, indicated by the symbol "^", is a binary operator in Java that performs a bitwise XOR operation between two operands. The XOR operation returns a value in which each bit in the result is set to 1 if and only if precisely...
3 min read
Java is a widely-used programming language known for its versatility and ability to handle complex tasks. One of the fundamental concepts in Java programming is the use of iterative constructs that allows us to repeat a set of instructions multiple times. In this section, we will...
5 min read
Dijkstra algorithm is one of the prominent algorithms to find the shortest path from the source node to a destination node. It uses the greedy approach to find the shortest path. The concept of the Dijkstra algorithm is to find the shortest distance (path) starting from...
8 min read
to extensive library support. These libraries, organized as packages, provide a rich set of tools and functions that simplify development, increase code reuse, and encourage maintenance. In this comprehensive section, we will explore Java packages, their purpose, special features, and how they contribute to the overall...
8 min read
Stackers are linear data structures in principle. A simple Load-In-First-Out (LIFO) set is the last item added to the stack and the first item to be removed. The basic operations in a stack include push, pop, and peek. However, manipulating the middle element of a stack-such...
5 min read
Dead code is a common issue that developers encounter in their programming journey. It refers to lines or blocks of code that are written but never executed during the program's runtime. While this may seem harmless, dead code can clutter a codebase, making it harder to...
3 min read
Swapping corner words and reversing middle characters in Java exemplify a creative approach to string manipulation, a fundamental programming aspect. The task involves altering the positions of the first and last words in a string while inverting the order of the characters nestled between them. Example 1: Input:...
8 min read
Minecraft is a sandbox video game developed by Mojang Studios. It is written in Java programming language. It is developed by Markus Persson. In May 2009, it was released for personal computers. The Minecraft Java edition is a cross-platform play between Windows, Linux, and macOS. It...
4 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India