Language Fundamentals

Primitive Types & Variables

Java has exactly eight primitive types with fixed, platform-independent sizes. Everything else is an object reference. Choosing the right numeric type — and knowing where precision and overflow bite — is foundational.
  • Eight primitives: byte, short, int, long, float, double, char, boolean — sizes are identical on every platform
  • Integer overflow is silent — it wraps around with no exception
  • double cannot represent most decimal fractions exactly — never use it for money (EJ 60)
  • Conversions that can lose information require an explicit cast
  • Local variables must be initialized before use; fields get default values
  • Prefer primitives to boxed types (Integer, Long…) wherever possible (EJ 61)
The eight primitive types
TypeSizeRange / valuesLiteral examples
int4 bytes−2,147,483,648 … 2,147,483,64742, 1_000_000, 0xFF, 0b1010
long8 bytes±9.2 × 10¹⁸42L, 9_000_000_000L
short2 bytes−32,768 … 32,767(short) 12
byte1 byte−128 … 127(byte) 0x1F
double8 bytes~15–16 significant digits3.14, 2.5e3, 1e-9
float4 bytes~6–7 significant digits3.14F
char2 bytesUTF-16 code unit'A', '\u2122'
booleantrue / falsetrue

Underscores in literals (1_000_000) are purely visual. Hexadecimal (0x), binary (0b) and octal (leading 0) literals exist — octal is a well-known trap, so avoid leading zeros. Since Java 10, local variables can use var when the type is obvious from the initializer (see Var Type Inference).

Declaration and initialization
int units = 3;
long worldPopulation = 8_000_000_000L; // L suffix required — int literal would overflow
double ratio = units / 2.0;             // 1.5 — one operand is double
var message = "inferred as String";     // Java 10+ local variable type inference

Conversions and casts

Widening conversions (intlongdouble) happen automatically. Narrowing conversions require an explicit cast and can silently lose data: (int) 300.99 is 300 (truncation, not rounding), and (byte) 300 is 44. When two different types meet in an expression, both are promoted to the "wider" one before the operation — and anything smaller than int is promoted to int first.

char is technically an unsigned 16-bit number holding a UTF-16 code unit — not necessarily a whole character. Supplementary characters like emoji need two chars (a surrogate pair). For real text processing, work with strings and code points (Strings Text), not raw chars.

Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 3.3–3.4 — Data Types; Variables and Constants
  • Learning Java (6th ed.)Ch. 4 — The Java Language (Types)
  • Effective Java (3rd ed.)Items 60, 61