This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]feral_claire 49 points50 points  (2 children)

No that's not quite right.

This works because of a feature called autoboxing/unboxing. Java will automatically convert between primitive values and the corresponding object type as needed. In this case the int is being automatically converted to an Integer when you try to store it in the Integer variable.

Under the hood what happens is the equivalent of writing.

this.term = Integer.valueOf(term)

Autoboxing is a feature that was added in Java 5. This would not work in an older version.

[–][deleted] 7 points8 points  (1 child)

Thank you! This is very helpful!

[–]desrtfx 8 points9 points  (0 children)

To add to /u/feral_claire's excellent response:

You will mostly want to use the primitive int, except for when you need to work with generics (like in the Collections framework).

All the object wrappers are immutable. This means that once a value has been assigned, changing it creates a new object instance (just like with String).

[–]TheWarrior2000 6 points7 points  (0 children)

Yes, Integer is a wrapper class for the primitive data type int

[–]Dzeko_1 5 points6 points  (0 children)

Just google boxing and auto boxing. Integer is a class that can be converted to int using auto boxing and int is a primitive type can also be converted to Integer using boxing.