Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-7-sonnet-20250219· AnthropicHugging Face LMArena Human Preference 140K

How do you swap two numbers without using a third variable in Java?

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-pro’s answer.
  1. User

    How do you swap two numbers without using a third variable in Java?

  2. Claude 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?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.