---
title: "Write a program in java to swap two numbers without using third variable and with third variable."  
description: "Write a program in java to swap two numbers without using third variable and with third variable."  
author: "Nitin Kushwaha"  
published: 2019-07-12  
updated: 2019-07-16  
canonical: https://www.mindstick.com/forum/55171/write-a-program-in-java-to-swap-two-numbers-without-using-third-variable-and-with-third-variable  
category: "java"  
tags: ["swapping of two number."]  
reading_time: 1 minute  

---

# Write a program in java to swap two numbers without using third variable and with third variable.

with example...

## Replies

### Reply by Anonymous User

**Swapping with the third variable**:-

```
Class mobile

{

public static void main(String args[])

{

int x = 10, int y = 21, int temp;

System.out.println("Before swapping "+x+", "+ + y);

temp=x;

x=y;

y=temp;

System.out.println("After swapping "+x+", "+ + y);

}

}

Output-

x=21

y=10.
```

```
Without third variable-

Class student

{

public static void main(String args[])

{

int x = 60;

 int y = 40;

System.out.println("Before swapping "+x+", "+ + y);

x=x+y;

y=x-y;

x=x-y;

System.out.println("After swapping "+x+", "+ + y);

}

}

Output-

x=40

y=60.
```


---

Original Source: https://www.mindstick.com/forum/55171/write-a-program-in-java-to-swap-two-numbers-without-using-third-variable-and-with-third-variable

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
