Question

Let's say I have the following code:

class Msg {
    private Object msg;
    public byte[] getMsg() {
        return (byte[]) msg;
    }
    public void setMsg(byte[] msg) {
        this.msg = msg;
    }
}

Does setting and then getting the message involve autoboxing?

Was it helpful?

Solution 2

No. Auto-boxing doesn't apply to arrays, at any time.

Even if it did, the array is an object, and it's the reference to array object you're casting, not the elements within it.

OTHER TIPS

Auto-boxing only occurs when you assign a primitive (byte) value (or variable) to a reference (Byte) variable.

Assigning an array (byte[]) to an Object variable only involves casting. That would be a static or implicit casting. Whereas the other way around involves an explicit (dynamic) casting.

Boxing each element of the array would require creating a whole new array (i.e. Byte[]). And in this case, that's not what's happening. You have only chosen to refer to the same array (byte[]) just using a variable of type Object.

No. A primitive array is an object. Both the byte[] and Object references point to the same object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top