Saturday, April 6, 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;

No comments:

Post a Comment

Your comment will be published after review from moderator