Sub topic 1
Primitives and Objects: Why Java Has Both
Java has two families of types. Primitive types such as int and double hold raw values. Reference types such as String, ArrayList and Integer hold references to objects. Wrapper classes exist because the two families do not mix freely. This chapter explains why the split exists and what it costs. The rest of the tutorial builds on it.
Prerequisites
This chapter assumes you already know the following:
- The Java primitive types
int,long,double,booleanandchar, and how to declare variables of those types. - Basic class and object syntax: how to define a class, create an instance with
new, and call a method. - The difference between
==andequalswhen you compare objects. - Basic use of
ListandMapwith generics, such asList<String>.
You do not need to know anything about autoboxing yet. This chapter prepares you for it.
The Two Kinds of Types
Every type in Java is either a primitive type or a reference type. Java defines exactly eight primitive types. You cannot add a ninth. Every other type is a reference type: classes, interfaces, enums, records and arrays.
| Primitive | Size | Default value | Wrapper class |
|---|---|---|---|
| `byte` | 8 bits | `0` | `Byte` |
| `short` | 16 bits | `0` | `Short` |
| `int` | 32 bits | `0` | `Integer` |
| `long` | 64 bits | `0L` | `Long` |
| `float` | 32 bits | `0.0f` | `Float` |
| `double` | 64 bits | `0.0` | `Double` |
| `char` | 16 bits, unsigned | `'\u0000'` | `Character` |
| `boolean` | not precisely specified | `false` | `Boolean` |
The language fixes the size of every numeric primitive, so an int is 32 bits on every platform. The specification does not say how many bits a boolean occupies. The JVM decides, and many implementations use a full byte or even an int-sized slot.
Note that String is not on this list. It is a class, even though string literals look as simple as numbers.
What a Primitive Variable Holds
A primitive variable holds the value itself. If you copy it, you get an independent copy.
A reference variable holds a reference, which you can think of as an address that points to an object. Copying the variable copies the reference. Both variables then point to the same object.
public class ValueVsReference {
public static void main(String[] args) {
int a = 5;
int b = a; // copies the value 5
b = 10;
System.out.println(a + " " + b); // 5 10
int[] x = {1, 2, 3};
int[] y = x; // copies the reference, not the array
y[0] = 99;
System.out.println(x[0]); // 99
System.out.println(x == y); // true: same object
}
}Changing b did not affect a, because each variable owns its own value. Changing y[0] changed what x sees, because both variables refer to one array.
This difference also explains how == behaves. For primitives, == compares values. For references, == compares whether two variables point to the same object. That is why you use equals to compare the contents of two objects. Later chapters show how this causes surprising results with Integer.
Parameters Are Always Passed by Value
Java passes arguments by value for both families. For a primitive, the method receives a copy of the value. For a reference, the method receives a copy of the reference. The method can use that copy to modify the object, but it cannot make the caller's variable point somewhere else.
public class PassByValue {
static void bump(int n) {
n++; // changes only the local copy
}
static void fill(int[] arr) {
arr[0] = 42; // changes the shared object
}
public static void main(String[] args) {
int count = 1;
bump(count);
System.out.println(count); // 1
int[] data = new int[2];
fill(data);
System.out.println(data[0]); // 42
}
}This matters for wrappers later. An Integer is an object, but it is immutable, so a method that receives one cannot change the caller's number. You will see this in the chapter on comparing and passing wrappers.
Why Java Kept Primitives
Java could have made everything an object. Some languages do. Java kept primitives for three reasons.
- Memory. An
inttakes 4 bytes. AnIntegerobject carries an object header in addition to its 4-byte value. On a typical 64-bit HotSpot JVM with compressed references, anIntegertakes about 16 bytes. The exact figure depends on the JVM and its settings. - Speed. Arithmetic on primitives works directly on values. No allocation is needed, and no pointer must be followed to reach the number.
- Memory layout. An
int[]stores its numbers side by side in one block. AnInteger[]stores references, and each reference points to a separateIntegerobject somewhere on the heap. Walking the first array is cache-friendly. Walking the second means following a pointer for each element.
Why Java Also Needs Objects
If primitives are cheaper, why not use only primitives? Because several language features work only with reference types.
- Generics. A type argument must be a reference type.
List<Integer>is legal, andList<int>is not. Generics are implemented by type erasure, which means the compiled code treats a type argument asObjector as its bound. Anintis not anObject, so it cannot be a type argument. - Absence of a value. A reference can be
null. A primitive always holds a value. When you need "no value yet", such as a missing database column, you need a reference type. - Methods and interfaces. You cannot call a method on an
int. Writing5.toString()does not compile. A reference type can implementComparable<T>, be stored in aMap, or be passed where anObjectis expected. - Library APIs. Collections,
Optional<T>, and most framework APIs are written in terms ofObjector type parameters.
The following snippet shows the generics restriction.
import java.util.ArrayList;
import java.util.List;
public class GenericsNeedObjects {
public static void main(String[] args) {
// List<int> bad = new ArrayList<>(); // compile error: unexpected type
List<Integer> numbers = new ArrayList<>();
numbers.add(7);
System.out.println(numbers.get(0)); // 7
}
}The line numbers.add(7) passes an int to a method that expects an Integer. Java converts it for you. That conversion is the subject of the next chapters.
Defaults and null
The two families behave differently when you declare a field and do not assign it. A field of primitive type starts with its default value from the table above. A field of reference type starts as null. This applies to fields and array elements. Local variables get no default, and the compiler rejects reading one before it is assigned.
public class Defaults {
static int count;
static Integer boxedCount;
static boolean flag;
static String name;
public static void main(String[] args) {
System.out.println(count); // 0
System.out.println(boxedCount); // null
System.out.println(flag); // false
System.out.println(name); // null
}
}An int field can never be null. An Integer field starts as null, and that has consequences. If you later use boxedCount in arithmetic before assigning it, you will get a NullPointerException. The chapter on unboxing null covers this failure in detail.
Choosing Between the Two
Use these decision criteria when you pick a type for a field, a parameter or a return value.
| Situation | Prefer | Reason |
|---|---|---|
| Counters, loop indexes, arithmetic | Primitive | No allocation, no `null` |
| Value that may be absent | Wrapper | Can represent `null` |
| Element of a `List`, `Set` or `Map` | Wrapper | Generics require a reference type |
| Large numeric data, such as millions of values | Primitive array or primitive stream | Less memory, better locality |
| Field mapped to a nullable database column | Wrapper | Primitive cannot hold "no value" |
A good default is to use primitives and switch to a wrapper only when something in the table forces you to.
Common Errors at This Level
A few mistakes appear again and again when developers mix the two families.
- Assuming
==means the same thing everywhere. Onintit compares numbers. OnIntegerit compares references. The same symbol answers two different questions. - Assuming a method can swap or reset a caller's variable. Because arguments are passed by value, reassigning a parameter never changes the caller's variable.
- Forgetting that
Stringis a reference type. Strings are immutable objects. They are not primitives, and==on two strings compares references. - Using
Integerfor no reason. Declaring a loop counter asIntegercompiles and runs, but it adds hidden object work. You will measure this in the performance chapter. - Expecting a primitive to be nullable.
int x = null;does not compile.
Looking Ahead
Java keeps both families and bridges them with eight wrapper classes, one per primitive. The bridge has two parts.
- Each wrapper class holds a single primitive value inside an object, together with useful methods.
- The compiler inserts conversions between a primitive and its wrapper automatically. This is called autoboxing when it wraps and unboxing when it unwraps.
The convenience hides real work and some traps. Caching can make == give inconsistent answers. null can sneak into arithmetic. Overloaded methods can pick an unexpected version. Each of these gets its own chapter, and each one follows from the model in this chapter: a primitive is a value, and a wrapper is an object that holds a value.
Exercise
A class has the fields static int a; and static Integer b;, and nothing assigns to either. What do System.out.println(a) and System.out.println(b) print, and why can the statement int c = b + 1; fail at run time?
Show answer
The first prints 0 because a primitive field gets its default value. The second prints null because a reference field defaults to null. In b + 1, the compiler must unwrap b to an int, and unwrapping null throws a NullPointerException.
Exercise
Why does List<int> fail to compile, and what should you write instead if you need a list of whole numbers?
Show answer
Generic type arguments must be reference types, because generics are implemented through type erasure and an int is not an Object. Write List<Integer>. The compiler then converts between int and Integer where needed.
Exercise
After the code int[] x = {1, 2, 3}; int[] y = x; y[0] = 99;, what does x[0] contain, and what would happen to a in int a = 5; int b = a; b = 10;?
Show answer
x[0] is 99, because x and y hold references to the same array object. The variable a stays 5, because b is an independent copy of the value.