Types, variables, and values
Java is statically typed: the compiler checks what values a variable may hold and which operations are valid.
Primitive and reference types
The eight primitives are byte, short,
int, long, float,
double, char, and boolean. A
reference variable holds a reference to an object or null.
Primitives are values and cannot be null.
int attempts = 3;
BigDecimal amount = new BigDecimal("19.95");
String customer = "Amina";Use BigDecimal for exact decimal money rules. Construct
it from a string or another exact representation;
new BigDecimal(0.1) captures the binary floating-point
approximation.
Declaration, initialization, and scope
Fields receive default values. Local variables must be definitely assigned before use. Keep scope as narrow as possible. A variable that exists only inside one loop is easier to reason about than shared mutable state.
var asks the compiler to infer a local variable's static
type from its initializer. It is not dynamic typing and cannot be used
without an initializer. Use it when the type remains obvious.
Conversions
Widening primitive conversions such as int to
long are generally safe. Narrowing conversions require a
cast and can lose information. Numeric promotion means arithmetic on
byte or short normally produces
int.
Autoboxing converts between primitives and wrappers such as
int and Integer. Unboxing a null
wrapper throws NullPointerException. Wrapper identity with
== is not a value comparison.
Strings
String is immutable. Concatenation in a loop can create
many intermediate objects; use StringBuilder for repeated
assembly. Compare string values with equals, not
==.
Feynman check
A primitive variable is a labeled box containing a value. A reference variable is a labeled card pointing to an object. Two cards can point to the same object.