Autoboxing (immutables) - 1

"Hi, Amigo!"

"Today I'll tell about autoboxing. AutoBoxing means to automatically put something into a box."

"You'll recall that Java has types that inherit the Object class, as well as primitive types. But it turns out that convenient things as collections and generics only work with types that inherit Object."

"Then the decision was made to make a non-primitive counterpart of every primitive type."

Primitive type Non-primitive counterpart
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
void Void

"But it's super inconvenient to convert between these types all the time:"

int x = 3;
Integer y = new Integer(x + 1);
int z = y.intValue();

"Especially when working directly with collections:"

Example
int[] numbers = new int[10];
ArrayList list = new ArrayList();
for (int i = 0; i < numbers.length; i++)
{
 list.add( new Integer(i));
}

"That's why Java's creators invented «autoboxing» of primitive types their and 'unboxing' to their non-primitive counterparts."

"Here's how it works:

What you see What really happens
int x = 3;
Integer y = x + 1;
int x = 3;
Integer y = Integer.valueOf(x + 1);
int z = y;
int z = y.intValue();
Boolean b = Boolean.FALSE;
boolean a = b;
Boolean b = Boolean.FALSE;
boolean a = b.booleanValue();
Integer x = null;
int y = x;
Integer x = null; int y = x.intValue(); //Throws an exception

"It's all simple. You can assign int and Integer types to each other, and the compiler takes care of everything else."

"That's very convenient."

"Yep. But there are nuances that I'll talk about later."