Primitive Types
A primitive type is a fixed-size data type that is predefined and reserved
as a keyword. Primitive types serve as the building blocks for storing state in an
object. There are eight primitive types: boolean, byte, short, int, long,
float
, double, and char. Primitive types are not objects, but every
primitive type has a corresponding wrapper object.
The compiler can automatically convert primitive types into their wrapper
objects in a process called autoboxing. Conversely, the compiler can convert
wrapper objects into their primitive types in a process called unboxing.
One common pitfall from unboxing occurs when a null object reference
is unboxed into a primitive type, resulting in a NullPointerException.
Arrays
An array is an object that can hold a fixed number of values of a single type.
The capacity of an array is defined when the array is initialized, and its elements
can be accessed by a zero-based index. Arrays are covariant, meaning that
an array can be cast to an array of its superclass type. For example,
a String[] could be cast to an Object[], because the String class
extends the Object class.
Strings
Strings are unique objects that are used to represent text. String values can
be assigned without the use of the new keyword, although the compiler
is actually creating String objects internally. Strings can be concatenated via
the overloaded + operator, which the compiler converts into a chain of method
calls on a StringBuilder object. A StringBuilder (and thread-safe
alternative StringBuffer) improves performance by modifying a mutable
char[]
buffer before creating an immutable String instance. The immutable
property of strings allows the compiler to cache them in a process
called interning.
Enums
Enums, short for enumerated types, are special classes that represent a set
of single-instance constants. Practical applications include the days of the week,
the status levels of a task, or the roles of a security group. Enums were
introduced to replace String and Integer constants and they are far more
powerful because they can contain methods, implement interfaces, and provide
type safety. However, enums cannot be subclassed or extend any class besides
the implicitly extended Enum class.
|