Java SE 11 Developer study materials
Java SE 11 Developer study resources

Java SE 11 Developer: Working with Java Data Types

Java SE 11 Developer · Work through your exam, one topic at a time.

All guide sections

Working with Java Data Types

The exam tests whether you can pick the right type, predict promotion and boxing behaviour, and know exactly what var may and may not do.

Primitives, promotion and literals

Java has eight primitives: byte, short, char (16-bit unsigned), int, long, float, double, boolean. Binary numeric promotion applies to most operators: if either operand is double the result is double, then float, then long, otherwise int. That is why byte b = 1; b = b + 1; fails to compile while b += 1 succeeds - compound assignment inserts an implicit cast. Integer literals are int unless suffixed with L; underscores may separate digits but cannot start or end a literal, sit next to a decimal point, or precede the L/F/D suffix. char c = 'A' + 1; is legal because it is a constant expression, but char c = someInt; needs a cast.

Wrappers and autoboxing

Autoboxing calls valueOf, which caches Boolean, Byte, Short, Long and Integer in -128..127 and Character in 0..127. So two boxed 127s are == but two boxed 1000s are not. Unboxing a null reference throws NullPointerException, including inside == comparisons between a wrapper and a primitive.

Strings and var

String is immutable, so s.concat("b") must be assigned. Java 11 adds isBlank, strip, repeat, lines and stripLeading/Trailing. StringBuilder is mutable but not thread-safe. var works only for local variables with an initializer that gives an unambiguous type; it cannot be null, cannot be used for fields, parameters or return types, and var in lambda parameters requires all parameters to use it.

Worked example

Integer a = 127, b = 127; prints true, while Integer c = 128, d = 128; prints false for c == d, yet c.equals(d) is true. Reasoning: both are boxed through the cache, whose upper bound is 127.

Traps

Using byte or float where int or double promotion surprises you; comparing boxed values with ==; relying on new Integer(...) (deprecated); assuming var is dynamic typing - it is not, the type is fixed at compile time.