beginnerFree

Variables & Primitive Types

The building blocks of Java data

Variables & Primitive Types

Java has 8 primitive types plus reference types like String. Every variable must declare its type.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:10

The Big Picture

Variables store data your program needs to work with. Java is statically typed - every variable declares its type at compile time, catching errors early.

  • Primitives: int, double, boolean, char (8 total)
  • References: String, arrays, objects, interfaces
  • Scope: local, instance (field), or class (static)

How It Works

Local primitives sit in the stack frame (fast, fixed size). Fields & array elements live on the heap with their object.

  • int: 32 bits, long: 64 bits, byte: 8 bits
  • float: 32-bit floating point, double: 64-bit floating point
  • Default values: 0 for numbers, false for boolean, null for refs

Local variables have no default - must initialize before use.

In the Java Landscape

Java 10+ adds var for local type inference:

  • var list = new java.util.ArrayList<String>();
  • Type inferred at compile time, still strongly typed

Wrapper classes bridge primitives and objects: Integer, Double Records (Java 16+) generate fields and accessors automatically. Pattern matching for instanceof (Java 16+) combines type check + variable.

Pitfalls and Best Practices

  • Use final for values that shouldn't change
  • Avoid float for money - use BigDecimal instead
  • Don't compare floats with == (precision issues)
  • Initialize variables close to first use
  • Prefer narrow types: int over long if range fits
  • Name clearly: userAge not x
#java#fundamentals#types