Java Fundamentals and Data Types
Domain 1 tests whether you can read a short snippet and decide whether it compiles and what it prints: primitive widths, literal syntax, promotion and casting, var, arrays, and String equality.
Primitives and literal rules
- Eight primitives:
byte(8 bits),short(16),int(32),long(64),float(32),double(64),char(16, unsigned),boolean. - Integer literals are
intunless suffixedL; floating-point literals aredoubleunless suffixedf. Prefixes:0xhex,0bbinary, leading0octal. - Underscores may only separate digits:
1_000_000compiles;_100,100_,1_.0and1.0_fdo not.
Promotion and casting
- Binary numeric promotion widens to
double, elsefloat, elselong, elseint.byte,shortandcharalways promote tointin arithmetic. - Widening is implicit; narrowing needs a cast. Compound assignment (
+=) and++/--apply an implicit cast, which is whyb += 3compiles whenb = b + 3does not.
var, arrays, String
varis legal only for local variables with an initializer; not for fields, parameters, ornull.- Arrays are covariant:
Object[] o = new String[1];compiles, but storing anIntegerthrowsArrayStoreExceptionat runtime.lengthis a field, not a method. Stringis immutable and pooled;==compares references, so useequalsfor content.
Worked example
byte b = 5;
b = b + 3; // compile error: int cannot be assigned to byte
b += 3; // compiles; implicit cast to byte
long n = 1_000 * 1_000_000_000L; // int * long -> long
The first assignment fails because b + 3 is an int. The compound form hides the cast, so no error.
Traps
switchacceptsint-compatible types,Stringand enums, neverlong,floatorboolean.char c = 'a' + 1;is legal (constant expression in range);char c = 'a' + 1L;is not.varis resolved at compile time, sovar x = 1; x = "s";fails.