Skip to main content
GameDev.net gamedev.net
🔒 Locked

Java Double not working right

Started by Sagar_Indurkhya Mar 14, 2005 at 6:41 PM 2 replies 500+ views
Original Post
Sagar_Indurkhya
Sagar_Indurkhya
I have:

public class Calculator
{
    public static void main(String args[])
    {

        Double c = null;
        test(c);

        System.out.println(c);
    }

    public static void test(Double b)
    {
        b = new Double("5");
        int i = 5;
    }
}

now the output is: null this is because apparently, java is not treating Double as a reference! Double is derived from Objects, so shouldn't it be treated as a reference?
Zahlman
Zahlman
Yep. The solutions for "out parameters" in Java are basically:

1) wrap the parameter in an object, and set the data member.
2) wrap the parameter in an array of size 1, and set the 0th element. (Arrays are objects, more or less anyway.) Or if there are several "out parameters" of the same type, pass them in a single array. This may well be good design; there could be a good reason to group those parameters in a particular order throughout the system.

The behaviour is actually quite nice and consistent, and IMHO coheres well with the Java object model; I feel rather like this is somewhere that the C# language developer(s) don't Get It. The Java behaviour upholds the Principle of Least Astonishment; if you pass something mutable to a function, it may be changed in some way, but you will get the same thing back.

It wouldn't make as much sense in C++ where there is less emphasis on "everything is an object" and more emphasis on being able to copy and destruct objects properly, do RAII etc., such that the C++ reference system makes more sense for C++, but would seem out of place in Java. (I would say it *does* seem out of place in C#, but I can't fairly assert that, since, well, I haven't used C#.)

OTOH, it's sometimes aggravating not to have something equivalent to the "copy constructor/assignment operator" concept.

OTGH, because of the garbage collection, Java's design inherently encourages aliasing objects and NOT copying them, whenever possible - this actually allows for some optimizations that people wouldn't bother with in C++ because the memory management would get too tricky.

(E.g. an object has a data member which is of a polymorphic, but immutable type; you don't really need to clone it in a C++ copy constructor, but if you don't, then you have a nasty object ownership problem on your hands and will probably have to resort to smart pointers.)

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.