2

If we have to swap two elements in java then we can swap them using a temporary variable.

  int temp=a;
  a=b;
  b=temp;

Also, we can do it by using different ways also but is there any predefined method like C++ that have std::swap()?

In the collection, we have swap() but it only works for the list.

1

2 Answers 2

4

No, there is no pre-defined function that swaps two elements. And for good reason. Java is always pass-by-value. Not like C++, where you can choose whether to give the value or the reference of the variable to the function.

If you want to read more about pass-by-value / pass-by-reference, this answer covers pretty much everything.

1

No, there is no way to do that without using a temporary variable.
Even C++ implementation of std::swap() uses a temporary variable inside, see here.

If you really want to you can wrap this code in a method and just call it.

This is just for fun but if you really want to swap integers, you can do it like so:

int a = 100;
int b = 25;
a = a + b;
b = a - b;
a = a - b;
1
  • 3
    Or, using the xor operator: a = a ^ b; b = a ^ b; a = a ^ b;
    – MC Emperor
    Oct 29, 2021 at 6:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.