Question

I have looked all over the internet to try and solve this problem. Can anyone answer this correctly and explain why? Thank you so much!

Look at the following code.

Integer myNumber;
myNumber = 5;

Which of the following is true about the second statement?

  1. The statement performs unboxing

  2. The statement performs autowrapping.

  3. The statement performs autoboxing.

  4. It results in an error because you cannot assign a primitive type to a wrapper class object.

Was it helpful?

Solution

This would be considered autoboxing. It takes the int value 5 and puts it in an Integer object.

Unboxing would be int myInt = myNumber as it assigns an Integer to an int. (Note that autoboxing is the opposite of unboxing. Technically, unboxing and boxing are opposites. Autoboxing is when the JVM takes care of the boxing for us. The way to manual-box (if that can be taken as a word) is myNumber = Integer.valueOf(5);

Autowrapping seems like a made up term to trick you by your professor.

Some languages will throw an error in cases like this. Java does in most similar situations, but for primitives it has special exceptions.

OTHER TIPS

It depends on what version of Java you are using. If it's anything prior to 1.5, the second statement will result in a compile time error. The concept of autoboxing was only introduced from Java 1.5.

So, if it's Java 1.5 and above, the second statement performs autoboxing.

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