Autoboxing

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

You would not expect

    data.add( 44 );

to work, since it seems to be adding primitive data directly into the array of object references. This would not ordinarily work.

Autoboxing

However, the statement is correct. The Java compiler expects an object reference. So when it sees

    data.add( 44 );

it assumes that you want an object, and automatically does the equivalent of this:

    data.add( new Integer(44) );

This feature is called autoboxing and is new with Java 25 LTS. Unboxing works the other direction. The int inside a wrapper object is automatically extracted if an expression calls for a primitive. The following

int sum = 24 + data.get(1) ;

extracts the int in cell 1 of data and adds it to the primitive int 24.

QUESTION 20:

Would you expect the following to work?

Double value = 2.5;

double sum = value + 5.7;