Course contentsShow
← Java
Lesson 67 of 2,8702. Variables and Primitive TypesFree lesson

Default Values for Fields vs Local Variables

Understanding the difference: instance and static fields get default values, local variables do not.

Default Values for Fields vs Local Variables

What you'll learn: Why some variables get automatic default values in Java and others must be initialized manually.

The Core Difference

In Java, not all variables are treated equally when it comes to initialization. Fields (variables declared at the class level) receive automatic default values if you don't initialize them. Local variables (declared inside methods) do not — you must assign them a value before use, or the compiler will reject your code.

Why This Matters

Think of fields like a freshly formatted storage unit: Java fills each slot with a placeholder (0 for numbers, false for boolean, etc.) so nothing is truly "empty." Local variables, by contrast, are like sticky notes on your desk — Java won't write anything on them for you. You must write something yourself before reading them.

Fields get defaults:

  • int → 0
  • long → 0L
  • float → 0.0f
  • double → 0.0
  • boolean → false
  • char → '\u0000' (null character)

Local variables get nothing. If you declare an int inside a method and try to use it without assigning a value, the compiler throws an error: "variable might not have been initialized."

This design prevents accidental bugs. Java assumes you know exactly what value a local variable should start with, while fields often represent object state that can reasonably begin at zero or false.

Key Takeaway: Fields (class-level variables) automatically get default values; local variables (method-level) require explicit initialization before use.