How to Swap two numbers without using third variable in Java?
This is the JavaScript forum - a completely different programming language from java.
Also there is no way to swap two numbers without using a temporary field of some sort to hold one of the numbers during the swap in any language at all - unless the two numbers are the same even before you overwrite one with the other.
You can do this using destructuring, where two variables values can be swapped in one destructuring expression.
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
You can also do this without the ES6 destructuring technique, only using normal JavaScript.
var a = 3;
var b = 5;
b = a + b; // 8
a = b - a; // 5
b = b - a; // 3
@Arshi_Bano can you clarify whether are you asking about Java or Javascript?
As felgall has pointed out, they are two different things.
Since you say “Java” and that appears to be your main area of interest, I moved this from the JS forum after it was flagged by another user.
Though because you posted in the JS forum, some have assumed that you actually meant JavaScript.
The code Paul posted should also work in Java.
It will not. There is no var
keyword in Java. It’s a strongly typed language.
int a = 3;
int b = 5;
b = a + b;
a = b - a;
b = b - a;

It will not.
So if the code you just posted (the Java equivalent of the JavaScript) doesn’t do the same thing then why did you post iit.
Make up your mind - does that combination of additions and subtractions work in all languages (as I said) or doesn’t it.
It isn’t so much the operations.
The main difference is that Java is strictly typed and the declaration of variables syntax is different,
i.e. you don’t say “var”, you say “int”, “array” etc. depending on the datatype.
As for the math itself, that’s OK for both

As for the math itself, that’s OK for both
That is the part of the code I was referring to (obviously syntax varies between languages)
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.