can we write a java method that swaps two integers

Carvia Tech | December 04, 2019 | 1 min read | 108 views


The answer is No.

For knowing the exact answer you must be knowing how Parameter Passing works in Java.

Incase of primitive int

Parameters to the method are passed by value in Java. In case of primitive data types, a copy of the value is passed to the method, so any changes in the method will not reflect in the calling code.

Incase of Integer Wrapper Class

For objects, the reference to the Object are copied by value to the calling method. If we reassign these reference copies then the changes will not be reflected to the method calling this swap(x,y).

Swap method: will never work as intended
public void swap(Integer x, Integer y) {
       Integer tmp =x;
       x=y;
       y=tmp;
 }

Top articles in this category:
  1. Can two threads call two different synchronized instance methods of an Object?
  2. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
  3. Given a collection of 1 million integers, all ranging between 1 to 9, sort them in Big O(n) time
  4. What do you understand by Java Memory Model?
  5. Factorial of a large number in Java BigInteger
  6. What is AtomicInteger class and how it works internally
  7. Diamond Problem of Inheritance in Java 8

Find more on this topic:

Recommended books for interview preparation: