Section 3.5 Interlude: Java Primitives
Before we wrap up this section, it is worth mentioning Java primitives. In Java there are two kinds of values. One we have seen already, namely objects. Either objects of a class we created, or one of the built-in objects.
But there is another common type of values, namely primitive values. Primitive values are pure values, like numbers or booleans. Their types are written with all lowercase letters, for example:
double PI = 3.14159;
boolean isSaved = false;
Here are some important things to know about primitive values:
- Primitive values are not objects.
- In particular, a variable with primitive type cannot be assigned the value
null
, becausenull
can only be used with object types. - A primitive type will always have an actual value, and a default value appropriate for the type if you forgot to initialize it.
- Primitive types cannot be used in lists, maps, or in general any place that expects a generic type.
- When a primitive value is used in a context that expects an object, the primitive value will be automatically converted to a corresponding object type. For example a
double
is converted to a typeDouble
. Each primitive type has a corresponding object type "wrapper". - To obtain a primitive value out of a corresponding object wrapper value, we must take care to account for the possibility of
null
.