0
Is it possible to swap two numbers using function in Java?
5 Answers
+ 3
Prokopios Poulimenos
A method can not return two values, so I would use an array for the two numbers:
https://code.sololearn.com/cb2en41ZAjw7/?ref=app
+ 1
Solution 1 :
Use a third variable and do the following :
temp = x;
x = y;
y = temp;
-- -----------------------
Solution 2 : Without temporary variable
x = x + y;
y = x - y;
x = x - y;
-- -----------------------
Solution 3 : With bitwise operator
x = x ^ y;
y = x ^ y;
x = x ^ y;
+ 1
Prokopios Poulimenos:
solution 1 is correct
solution 2 may cause operator overflow (it's computer algebra, not math - range is limited) and x,y might be objects?
solution 3 - no idea why this should work (e.g. x = 1 and y = 0) and depends on number encoding, but what if y,x are no numbers?
0
Sorry but I am asking about using function I mean
pass two variables to function to get swapped