Lesson Overview

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.

Dive into Primitive Types in Java

Primitive types in Java are the most fundamental form of data. Here are some examples:

int myAge = 10; // integer
float pi = 3.14f; // decimal number
char firstInitial = 'A'; // single character

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:

Integer ageObject = 10;
Float piObject = 3.14f;
Character initialObject = 'A';

They look similar to primitive types at first glance, huh? But they act almost entirely differently!

Unlocking Differences: Comparisons

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 null value (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
Quick Dive: Auto-boxing & Auto-unboxing

Java compiler supports auto-boxing and auto-unboxing that allows seamless transitions between primitive types and class types. Let's observe below:

int a = 10; // this is a primitive `int` type
Integer aBoxed = a; // auto-boxing: int to Integer
System.out.println(aBoxed); // prints: 10

Integer bBoxed = 20; // this is a class type
int b = bBoxed; // auto-unboxing: Integer to int
System.out.println(b); // prints: 20

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!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal