Search code examples
javapass-by-referenceprimitivepass-by-value

Why can I pass a primitive to a method that takes an object?


Why is it possible to pass a primitive to a method that takes an object? Is the primitive turned into an object? like int = Integer and boolean = Boolean?

I can call the following function:

hash(41, 0);

    public static int hash(int seed, Object object)
    {
        int result = seed;
        if(object == null)
        {
            return hash(result, 0);
        }
        else if(!isArray(object))
        {
            result = hash(result, object.hashCode());
        }
        else
        {
            int length = Array.getLength(object);
            for(int index = 0; index < length; ++index)
            {
                Object item = Array.get(object, index);
                // prevent looping if item in array references the array itself
                if(!(item == object))
                {
                    result = hash(result, item);
                }
            }
        }
        return result;
    }

Solution

  • Yes, this is called a boxing conversion. The int value is "boxed" into an Integer, which is an Object. It has been available in Java since 1.5.

    The JLS, Section 5.1.7 lists available boxing conversions:

    Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:

    • From type boolean to type Boolean

    • From type byte to type Byte

    • From type short to type Short

    • From type char to type Character

    • From type int to type Integer

    • From type long to type Long

    • From type float to type Float

    • From type double to type Double

    • From the null type to the null type

    Additionally, the boxing conversion is allowed during method invocation conversion, which is really what's going on here. The value is being converted to another type because the int 0 is being passed to a method that expects an Object. The JLS, Section 5.3, lists boxing conversion as one method of method invocation conversion:

    Method invocation contexts allow the use of one of the following:

    • an identity conversion (§5.1.1)

    • a widening primitive conversion (§5.1.2)

    • a widening reference conversion (§5.1.5)

    • a boxing conversion (§5.1.7) optionally followed by widening reference conversion

    • an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.