Java Primitive types vs Java Classes (int vs Integer)

Java Primitive types vs Java Classes (int vs Integer)

In Java you have what are called primitive types. In very simplistic terms, these are keywords that help to identify a variable. For example, let's say I want a variable that can store an integer, a number with no decimal:

int x = 5;

In Java I just created a variable x that is of type int, a primitive type which stands for integer. It happens to store the number 5. This is pretty easy to understand and beginners using Java can easily use and understand this Java code.
Did you know that Java also has a class called Integer? The Integer class starts with a capitalized I (because it's a class) and can be used to create variables that store integers. This is just like using the primitive type int, but a lot more powerful. Here are a couple of reasons why:
If you know about collections, you will have come across certain kinds such as the ArrayList. An ArrayList can store objects without bounds (unlike an array which has a fixed size). However, a variable with the int type is not an object, and cannot be stored this way. So, using our example, change:
int x = 5;
to
Integer x = 5;
It's that easy, and because Java knows you're talking about integers, it knows how to set a number to the Integer object x.
Another thing you can do with Integer that you can't with int, is serialize it on its own. Serializing objects is a very advanced topic that has to do with networking, and I don't want to get into it here, but basically to pass data over a network in Java such as with RMI (Remote Method Invocation), you cannot send the int by itself. It needs to belong to a class which can be serialized. With an Integer, because it already is a class, can potentially be sent over the network as a serialized object.
There are advantages to using just the primitive type int, speed being one of the important points, but it's nice to know you can have an object version of it as well.
And int is not the only primitive type to have a class equivalent! You can do the same with byte, double, boolean, float, long, and char! The equivalents are Double, Boolean, Float, Long, and Character, respectively.