Passing primitives by reference in Java

  Some person, that might have long experience with C++ or C (as in my case) in the past, when coming to the world of Java might be stumbled for a sec, when he or she needs to pass primitives to a function by reference (e.g. to be able to change their values). Some small example is under the cut.


  Ok, you might already know, that in Java (with all it's OOP concepts and other cool stuff) parameters are always passed by values. Actually, the reference to object is passed by value, but not the object itself, and this gives you the possibility to make changes with objects within function, where these references were passed to. But what would you do in a case with primitives? In "good-old" C (or C++) you would use some address arithmetic and use pointers (or references, if you want to look cool in front of your C++ co-workers). In Java you do not have pointers (hurray!). But there is one solution to given problem -- object wrappers. Each primitive type in Java has it's Object representation. In case with int it is Integer. Plus there is such a cool thing as autoboxing that allows you to convert between primitive <---> object without any additional body movements.

  So, from words to action. I'll give you some small example of Evklid algorithm for getting greatest common divisor of two integers.


public class EvklidGCD {
    public static void main(String[] args) {
        int i1 = 50;
        int i2 = 80;
        System.out.println("GCD for " + i1 + " and " + i2 + " --> " + Evklid.getGCD(i2, i1));
    }
}


/**
 * Evklid algorithm for determining GCD
 */

class Evklid {

    /**
     * @param x First number
     * @param y Second number
     */

    public static int getGCD(final int x, final int y) {
        int a = x;
        int b = y;
        int R = 0;

        if (a < b) {
            swap(a, b);
        }

        while (a % b > 0) {
            R = a % b;
            a = b;
            b = R;
        }

        return R;
    }

    private static void swap(Integer a, Integer b) {
        Integer tmp;
        tmp = a;
        a = b;
        b = a;
    }
}


 In this example the swap() function is using object wrapping for integer type. As you also can see autoboxing and autounboxing is *hidden* from the developer, so when you call swap() function you simply pass two int's and all other job is done under the hood.

0 comments:

Post a Comment