Oracle Java Foundations study materials
Oracle Java Foundations study resources

Oracle Java Foundations: Working with Java Data Types

Oracle Java Foundations · Work through your exam, one topic at a time.

All guide sections

Working with Java Data Types

The eight primitives

byte (8 bits, -128..127), short (16), int (32), long (64), float (32), double (64), char (16-bit unsigned, 0..65535), and boolean. Each primitive has a wrapper: Byte, Short, Integer, Long, Float, Double, Character, Boolean.

Literals and defaults

Whole-number literals are int unless suffixed L; decimal literals are double unless suffixed f/F. Allowed forms include 0b1010, 0xFF, octal 010, and underscores between digits (1_000_000), but never at the start or end. Field and array-element defaults are 0, 0.0, '\u0000', false, and null; local variables have no default and must be assigned before use.

Conversions

Widening (byte→short→int→long→float→double, plus char→int) is automatic. Narrowing needs an explicit cast and may lose information; casting a floating value to an integer truncates toward zero. Binary numeric promotion makes both operands at least int, so byte b = 10; b = b + 5; fails to compile while b += 5; compiles because compound assignment inserts an implicit cast.

Autoboxing traps

Boxing caches values -128..127, so Integer a = 127, b = 127; gives a == b true, but 1000 gives false - always use equals for wrapper values. Unboxing a null wrapper throws NullPointerException. Mixing Integer and int in == unboxes and compares values.

Worked example

int i = (int) 3.99; stores 3. char c = 'A'; int n = c; stores 65. long L = 5; is fine (widening), but int x = 5L; needs a cast.