Variables and Types
Java has two fundamentally different kinds of types: primitives, and objects. Mixing them up is one of the most common early confusions.
Primitives
int xp = 0;
double ratio = 0.5;
boolean loggedIn = true;
char grade = 'A';
xp += 10;
Primitives store their value directly, are fixed-size, and are not objects, they have no methods, can't be null, and are always passed by value.
Objects
Everything else, starting with String, is an object, a reference to data living on the heap:
String name = "Ada";
Integer boxedXp = 10; // the "boxed" object version of int
name = null; // objects CAN be null, primitives cannot
String looks like a primitive in everyday use (you can write "hello" directly), but it's really an object under the hood, with methods like .length() and .toUpperCase().
Type inference with var
Modern Java lets the compiler infer a local variable's type from its initializer:
var count = 5; // inferred as int
var name = "Ada"; // inferred as String
var is purely a compile-time convenience, Java is still 100% statically typed underneath, count is genuinely an int forever, the compiler just saved you from typing it twice.
| Primitive | Object | |
|---|---|---|
| Examples | int, double, boolean, char | String, Integer, any class |
| Can be null | No | Yes |
| Has methods | No | Yes |
| Stored | Directly, on the stack | Reference to the heap |