Language Fundamentals
Primitive Types & Variables
- 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
doublecannot 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)
| Type | Size | Range / values | Literal examples |
|---|---|---|---|
int | 4 bytes | −2,147,483,648 … 2,147,483,647 | 42, 1_000_000, 0xFF, 0b1010 |
long | 8 bytes | ±9.2 × 10¹⁸ | 42L, 9_000_000_000L |
short | 2 bytes | −32,768 … 32,767 | (short) 12 |
byte | 1 byte | −128 … 127 | (byte) 0x1F |
double | 8 bytes | ~15–16 significant digits | 3.14, 2.5e3, 1e-9 |
float | 4 bytes | ~6–7 significant digits | 3.14F |
char | 2 bytes | UTF-16 code unit | 'A', '\u2122' |
boolean | — | true / false | true |
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).
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 inferenceConversions and casts
Widening conversions (int → long → double) 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.