Skip to main content
PreparationZone Logo
PrepZone

Types, Variables and Wrappers

Primitives versus references, IEEE 754 float and double, autoboxing traps, enums, and operator families.

Pass checkpoint below

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.
Stack — per thread
main() frameuser → reference
greet() framecount = 3 (primitive)

Popped the moment a method returns.

Heap — shared
User objectname = "Asha"
String object"Asha"

Cleared by the garbage collector, not by returning.

The variable sits in the thread's stack frame. The object it names lives in the shared heap, which is why two variables can point at one object.

The eight primitives

Size, range and default

  • byte — 8 bits, −128 to 127, default 0. Used for raw binary data.
  • short — 16 bits, about ±32 thousand, default 0. Rarely used directly.
  • int — 32 bits, about ±2.1 billion, default 0. The default choice for whole numbers.
  • long — 64 bits, about ±9.2 quintillion, default 0L. Needed for timestamps in milliseconds.
  • float — 32-bit IEEE 754 binary floating point, default 0.0f. Roughly 7 significant digits.
  • double — 64-bit IEEE 754 binary floating point, default 0.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 — true or false, default false. Its size is not specified.

Overflow is silent

Arithmetic wraps around rather than failing, which is the single most dangerous default in the language.

Java
Loading compiler…

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.

Java
Loading compiler…
AspectPrimitiveReference
What the variable storesThe value itselfA pointer to a heap object, or null
Examplesint, double, boolean, charAny class, interface, array, enum or record
Default for a field0, 0.0, false, or the null characternull
AssignmentCopies the valueCopies the pointer — both names see one object
==Compares the valuesCompares identity
  • What the variable stores

    PrimitiveThe value itself
    ReferenceA pointer to a heap object, or null
  • Examples

    Primitiveint, double, boolean, char
    ReferenceAny class, interface, array, enum or record
  • Default for a field

    Primitive0, 0.0, false, or the null character
    Referencenull
  • Assignment

    PrimitiveCopies the value
    ReferenceCopies the pointer — both names see one object
  • ==

    PrimitiveCompares the values
    ReferenceCompares 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 own Order. The variable is never the object.
  • Interface types — a List variable may point at an ArrayList. The reference's compile-time type and the object's run-time class can differ.
  • Array types — int[] and String[] are objects with a length field. 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 throws NullPointerException.

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.

Java
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).

Java
Loading compiler…

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.0 and -0.0 as equal. Double.equals does 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.0 and by Math.sqrt(-1). Every comparison involving NaN is false, including NaN == NaN. Double.equals treats 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.

Java
Loading compiler…

That convenience has three sharp edges.

Java
Loading compiler…

The three edges

  • Cached range. Integer caches instances from −128 to 127, so == accidentally works there and silently stops working above it. Always compare wrapper values with .equals().
  • Unboxing null. A null wrapper unboxes by calling .intValue() on null, producing a NullPointerException at a line with no visible method call.
  • Boxing in loops. A long accumulator typed as Long allocates 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.

Java
Loading compiler…
Aspectint constantsenum
Type safetyAny int is accepted, valid or notOnly declared values compile
PrintingShows a meaningless numberShows the constant name
Can hold data or methodsNoYes — fields, constructors, methods
Works in switchYesYes, and the compiler can check exhaustiveness
Comparison==== is safe; instances are singletons
  • Type safety

    int constantsAny int is accepted, valid or not
    enumOnly declared values compile
  • Printing

    int constantsShows a meaningless number
    enumShows the constant name
  • Can hold data or methods

    int constantsNo
    enumYes — fields, constructors, methods
  • Works in switch

    int constantsYes
    enumYes, and the compiler can check exhaustiveness
  • Comparison

    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, so 7 / 2 is 3. Write 7 / 2.0 when you want 3.5. % keeps the sign of the left operand, so -7 % 3 is -1.
  • Unary — + - ++ -- ! ~. i++ yields the old value and then increments; ++i increments 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 why if (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 unboxing null throws.
  • instanceof — tests the run-time class. The pattern form (instanceof String s) is covered with the modern language features.
  • String + — if either operand is a String, + concatenates, and it associates to the left.
Java
Loading compiler…

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

  • "var makes Java dynamically typed." The type is fixed at compile time; only the writing is shorter.
  • "char can be negative." It is the one unsigned primitive, ranging from 0 to 65535.
  • "== works for Integer." It works accidentally inside the cache range, which makes the bug worse, not better.
  • "float saves meaningful memory." On modern hardware double is the sensible default; float mainly buys imprecision.
  • "float stores decimals." It stores a binary fraction. 0.1 is 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.equals is 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 L early in long expressions, or Math.addExact when wrapping would be a bug.
  • float is 1+8+23 bits with bias 127; double is 1+11+52 with bias 1023. 0.1 is not exact. Use BigDecimal from a string, or integer cents, for money.
  • NaN is not equal to itself. == treats +0.0 and -0.0 as equal; Double.equals does not.
  • Integer caches −128 to 127, so == works by accident there. Always use .equals() for wrapper values.
  • Unboxing a null wrapper throws NullPointerException at 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 + 1 is "211".

Test yourself

Answer these before moving on — recall is what makes it stick.

Checkpoint quiz

Pass 2 of 3 to verify this article on your path — scrolling alone does not count.

Question 1 of 3

How do you keep an order + payment + inventory flow consistent across services without distributed two-phase commit?