Why this matters
- The
==versus.equals()question is the most common source of silent bugs for new Java developers, and autoboxing is why. - Integer overflow and floating-point imprecision cause money and timing bugs that no test catches unless you know to look.
- Enums replace a whole category of bug-prone integer constants, and most people under-use them.
Popped the moment a method returns.
Cleared by the garbage collector, not by returning.
The eight primitives
Size, range and default
byte— 8 bits, −128 to 127, default0. Used for raw binary data.short— 16 bits, about ±32 thousand, default0. Rarely used directly.int— 32 bits, about ±2.1 billion, default0. The default choice for whole numbers.long— 64 bits, about ±9.2 quintillion, default0L. Needed for timestamps in milliseconds.float— 32-bit IEEE 754 binary floating point, default0.0f. Roughly 7 significant digits.double— 64-bit IEEE 754 binary floating point, default0.0d. The default choice for fractional values, about 15 digits.char— 16 bits, a single UTF-16 unit, default'\u0000'. Unsigned, unlike the rest.boolean—trueorfalse, defaultfalse. Its size is not specified.
Overflow is silent
Arithmetic wraps around rather than failing, which is the single most dangerous default in the language.
The third line is the classic trap. Every operand is an int, so the multiplication happens in
32 bits and overflows before the result is widened to long. Marking the first operand L
forces the whole expression into 64-bit arithmetic.
What a reference variable holds
After the eight primitives, every other variable is a reference: a name for an object on the heap, or null when it names nothing.
| Aspect | Primitive | Reference |
|---|---|---|
| What the variable stores | The value itself | A pointer to a heap object, or null |
| Examples | int, double, boolean, char | Any class, interface, array, enum or record |
| Default for a field | 0, 0.0, false, or the null character | null |
| Assignment | Copies the value | Copies the pointer — both names see one object |
| == | Compares the values | Compares identity |
What the variable stores
PrimitiveThe value itselfReferenceA pointer to a heap object, or nullExamples
Primitiveint, double, boolean, charReferenceAny class, interface, array, enum or recordDefault for a field
Primitive0, 0.0, false, or the null characterReferencenullAssignment
PrimitiveCopies the valueReferenceCopies the pointer — both names see one object==
PrimitiveCompares the valuesReferenceCompares identity
A method receives a copy of whichever kind you pass. That is why Java is always pass-by-value.
The reference types worth naming
- Class types —
String,ArrayList, your ownOrder. The variable is never the object. - Interface types — a
Listvariable may point at anArrayList. The reference's compile-time type and the object's run-time class can differ. - Array types —
int[]andString[]are objects with alengthfield. An array of objects stores references, not the objects inline. - Enum types — a closed set of instances, covered later in this lesson.
==is the right comparison for them. null— legal for every reference type and for no primitive. Calling a method through it throwsNullPointerException.
How float and double are stored
float and double are IEEE 754 binary floating-point values: a sign bit, a biased exponent, and a fraction. They are not decimal types.
float (32 bits): 1 sign | 8 exponent | 23 fraction bias 127
double (64 bits): 1 sign | 11 exponent | 52 fraction bias 1023
A normal number is decoded as (-1)^sign × 1.fraction × 2^(storedExponent − bias). The leading 1 is implicit, so a float has 24 bits of significand (about 7 decimal digits) and a double has 53 (about 15).
0.1 has no exact binary representation, the same way 1/3 has no exact decimal one. The stored value is the nearest representable double, so sums drift.
The four special patterns
- Signed zero — exponent and fraction all zeros.
==treats+0.0and-0.0as equal.Double.equalsdoes not, because it compares the raw sign bit. - Infinity — exponent all ones, fraction all zeros. A finite overflow, or a non-zero number divided by zero.
- NaN — exponent all ones and a non-zero fraction. Produced by
0.0 / 0.0and byMath.sqrt(-1). Every comparison involving NaN is false, includingNaN == NaN.Double.equalstreats two NaNs as equal. - Subnormals — exponent all zeros, fraction non-zero. Values too small for the implicit leading 1, so the gap around zero shrinks gradually instead of snapping to zero.
Wrappers and autoboxing
Each primitive has an object counterpart — int/Integer, double/Double and so on —
because collections and generics can only hold objects. The compiler converts automatically.
That convenience has three sharp edges.
The three edges
- Cached range.
Integercaches instances from −128 to 127, so==accidentally works there and silently stops working above it. Always compare wrapper values with.equals(). - Unboxing null. A
nullwrapper unboxes by calling.intValue()onnull, producing aNullPointerExceptionat a line with no visible method call. - Boxing in loops. A
longaccumulator typed asLongallocates a new object on every iteration. In a hot loop this is a real cost.
Enums instead of constants
An enum is a class with a fixed set of instances. It gives you type safety, readable output, and a natural place to attach behaviour.
| Aspect | int constants | enum |
|---|---|---|
| Type safety | Any int is accepted, valid or not | Only declared values compile |
| Printing | Shows a meaningless number | Shows the constant name |
| Can hold data or methods | No | Yes — fields, constructors, methods |
| Works in switch | Yes | Yes, and the compiler can check exhaustiveness |
| Comparison | == | == is safe; instances are singletons |
Type safety
int constantsAny int is accepted, valid or notenumOnly declared values compilePrinting
int constantsShows a meaningless numberenumShows the constant nameCan hold data or methods
int constantsNoenumYes — fields, constructors, methodsWorks in switch
int constantsYesenumYes, and the compiler can check exhaustivenessComparison
int constants==enum== is safe; instances are singletons
Enum is one of the highest-value, lowest-effort upgrades in everyday Java.
Operators
Every operator belongs to a small family. The bugs come from precedence, from short-circuiting, and from + meaning two different things.
The families
- Arithmetic —
+ - * / %. Integer division truncates toward zero, so7 / 2is3. Write7 / 2.0when you want3.5.%keeps the sign of the left operand, so-7 % 3is-1. - Unary —
+ - ++ -- ! ~.i++yields the old value and then increments;++iincrements and then yields the new value. Keep either one out of a larger expression. - Relational —
== != < > <= >=. On primitives this compares values. On references==compares identity. - Logical —
&&and||stop evaluating as soon as the result is fixed.&and|on booleans evaluate both sides.!negates.if (list != null && !list.isEmpty())is safe only because of the short-circuit. - Bitwise and shift —
& | ^ ~and<< >> >>>on integers.>>copies the sign bit in from the left.>>>shifts in zeros. - Assignment —
=and the compounds+=,-=,*=and the rest. An assignment is an expression, and its value is whatever was assigned. That is whyif (b = false)compiles. - Ternary —
condition ? whenTrue : whenFalse. The two branches are checked as one type. Mixing a primitive with a wrapper can force unboxing, and unboxingnullthrows. instanceof— tests the run-time class. The pattern form (instanceof String s) is covered with the modern language features.- String
+— if either operand is aString,+concatenates, and it associates to the left.
Precedence, from tighter to looser
- Postfix
++and--, then unary+ - ! ~and prefix++--. - Multiplicative
* / %, then additive+ -(including string concatenation). - Shifts
<< >> >>>, then relational< <= > >= instanceof, then equality== !=. - Bitwise
&, then^, then|. These bind tighter than&&and||. - Logical
&&, then||, then the ternary?:, then assignment. Assignment associates to the right.
var infers the type of a local variable from its initialiser. The variable is still statically typed. Use it when the right-hand side already shows the type. The dedicated lesson on var covers the cases where inference is illegal.
Common misreadings
- "
varmakes Java dynamically typed." The type is fixed at compile time; only the writing is shorter. - "
charcan be negative." It is the one unsigned primitive, ranging from0to65535. - "
==works for Integer." It works accidentally inside the cache range, which makes the bug worse, not better. - "
floatsaves meaningful memory." On modern hardwaredoubleis the sensible default;floatmainly buys imprecision. - "
floatstores decimals." It stores a binary fraction.0.1is already rounded before you add anything. - "A reference variable contains the object." It contains a pointer. The object is on the heap, and assignment copies the pointer.
- "
NaN == NaN." The comparison is false.Double.equalsis the method that treats two NaNs as equal. - "Local variables default to zero." Fields do. Locals must be assigned before use, enforced at compile time.
Quick recall
Everything you need if you only revisit this box.
- Eight primitives hold values directly; everything else is a reference — a pointer to a heap object, or
null. Fields get defaults, locals do not. - Assignment of a reference copies the pointer. Both variables then name one object.
- Integer arithmetic wraps silently. Use
Learly in long expressions, orMath.addExactwhen wrapping would be a bug. floatis 1+8+23 bits with bias 127;doubleis 1+11+52 with bias 1023.0.1is not exact. UseBigDecimalfrom a string, or integer cents, for money.NaNis not equal to itself.==treats+0.0and-0.0as equal;Double.equalsdoes not.Integercaches −128 to 127, so==works by accident there. Always use.equals()for wrapper values.- Unboxing a
nullwrapper throwsNullPointerExceptionat a line with no visible call. - Enums give type safety, readable names and attached behaviour;
==is the correct comparison for them. &&and||short-circuit;&and|evaluate both sides. Integer/truncates,%follows the left operand's sign, and string+associates left, so"2" + 1 + 1is"211".
Test yourself
Answer these before moving on — recall is what makes it stick.