Get ready for your next Java data structures lesson! Today, we're delving into Primitive Types (int, float, char) and Class Types (Integer, Float, Character). This knowledge is crucial, as these types are used all over Java, and especially in handling Java collections.
Primitive types in Java are the most fundamental form of data. Here are some examples:
For each primitive type in Java, there's a corresponding class type. These instances convert regular data, such as int, float, or char, into objects with more capabilities:
They look similar to primitive types at first glance, huh? But they act almost entirely differently!
Primitive and class types may seem similar, yet they differ significantly in terms of memory usage, efficiency, and value comparisons. In fact, primitive type is just a value (5, 3.14, 'A'). Class type, however, is an object that holds the value. On top of holding the value, the object provides several additional properties, methods, and characteristics.
Here is a quick comparison of primitive and class types:
- Class types take more memory, as they not only hold a value but also hold a few additional properties
- Class types can be less time-effective
- Class types are more powerful, providing more functionality for each type instance
- Class types can hold an additional
nullvalue (meaning "no value") - Java is an Object-Oriented language, with class types allowing it to cover most of the needs, so they are more commonly used, especially in collections
Java compiler supports auto-boxing and auto-unboxing that allows seamless transitions between primitive types and class types. Let's observe below:
In this code, a auto-boxes from int to Integer, while bBoxed auto-unboxes from Integer to int. This saves us from manual conversions and calling .intValue() on class types in most places!
