How do you swap two numbers without using a third variable in Java?
- User
How do you swap two numbers without using a third variable in Java?
Assistant
In Java, you can swap two numbers without using a third variable by using arithmetic operations. Here's how:
public class SwapWithoutTemp { public static void main(String[] args) { int a = 5; int b = 10; System.out.println("Before swap: a = " + a + ", b = " + b); // Swap without using a third variable a = a + b; // a now contains sum of both b = a - b; // b now contains original value of a a = a - b; // a now contains original value of b System.out.println("After swap: a = " + a + ", b = " + b); } }Would you like me to explain how this code works?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.