---
title: "How to swap two numbers without using a third variable?"  
description: "How to swap two numbers without using a third variable?"  
author: "Mukul Goenka"  
published: 2021-11-16  
canonical: https://www.mindstick.com/interview/33827/how-to-swap-two-numbers-without-using-a-third-variable  
category: "java"  
tags: ["javascript", "programming language"]  
reading_time: 1 minute  

---

# How to swap two numbers without using a third variable?

```
public class SwapNumberWithoutThierdVariable{public static void swapNumbers(int a, int b) {
    b = b + a;
 a = b - a;
 b = b - a;
}
public static void main(String[] args) {
 int a = 10;
 int b = 20;
 swapNumbers(a, b);
 System.out.printf("a is %d, b is %d", a, b); // a is 10, b is 20
}}
```

## Answers

### Answer by Mukul Goenka

```
public class SwapNumberWithoutThierdVariable{public static void swapNumbers(int a, int b) {
    b = b + a;
 a = b - a;
 b = b - a;
}
public static void main(String[] args) {
 int a = 10;
 int b = 20;
 swapNumbers(a, b);
 System.out.printf("a is %d, b is %d", a, b); // a is 10, b is 20
}}
```


---

Original Source: https://www.mindstick.com/interview/33827/how-to-swap-two-numbers-without-using-a-third-variable

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
