Monday, May 13, 2013

Is it possible to write a method in Java which swaps two int or Integer ?

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).
/** This code will never work as intended  **/
public void swap(Integer x, Integer y) {
    Integer tmp = x;
    x = y;
    y = tmp;

The only way to have this possible was using some kind of setter on Integer class which could have modified the underlying value. But Java declares all Wrapper classes as Immutable for thread-safety perspective, thus there is no way to swap Integers in Java.

TIP-The called method can't change the caller's variable, although for object reference variables, the called method can change the object the variable referred to.

No comments:

Post a Comment

Your comment will be published after review from moderator