Script Valley
Java: Complete Language Course
Java FundamentalsLesson 1.2

Java primitive data types and variable declaration

int, long, double, float, boolean, char, byte, short, variable declaration, type sizes, default values

Primitive Data Types

Java has eight primitive types — values stored directly on the stack, not as objects. Choosing the right type avoids silent overflow and wasted memory.

The Four You Will Use Most

int age = 30;           // 32-bit, range ±2.1 billion
long population = 8_000_000_000L; // 64-bit, suffix L required
double price = 19.99;  // 64-bit IEEE 754 decimal
boolean active = true; // true or false only

The Other Four

byte b = 127;           // 8-bit, range -128 to 127
short s = 32_000;       // 16-bit, range ±32,767
float f = 3.14f;        // 32-bit decimal, suffix f required
char c = 'A';           // 16-bit Unicode character

Key declaration rules:

  • Declare type before name: int count = 0;

  • Java is statically typed — you cannot assign a String to an int variable after declaration.

  • Integer literals default to int; floating-point literals default to double.

  • Use underscores in large numbers (1_000_000) for readability — the compiler ignores them.

Uninitialized local variables cause a compile error in Java. Class-level fields get zero-equivalent defaults (0, false, \u0000), but relying on defaults is considered poor practice because it obscures intent.

Widening vs narrowing: Java automatically widens smaller types to larger ones (e.g., int to long), but narrowing requires an explicit cast: (int) myLong. Narrowing truncates — data loss is possible and the compiler makes you acknowledge it.

Up next

Java operators and expression evaluation order

Sign in to track progress