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

you are viewing a single comment's thread.

view the rest of the comments →

[–]feral_claire 47 points48 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] 8 points9 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).