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.

Saurabh Dhage
  • 1,478
  • 5
  • 17
  • 31

2 Answers2

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.

Renis1235
  • 4,116
  • 3
  • 15
  • 27
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;
Two Horses
  • 1,401
  • 3
  • 14
  • 35