Java types and variables
Primitives versus objects, autoboxing traps, and the equality rules that decide whether two values are 'the same'.
Eight primitives
| Type | Size | Range / notes |
|---|---|---|
byte | 8-bit | −128…127 |
short | 16-bit | −32,768…32,767 |
int | 32-bit | Default integer type |
long | 64-bit | Needs the L suffix: 10L |
float | 32-bit | Needs the f suffix: 1.5f |
double | 64-bit | Default floating type |
char | 16-bit | A single UTF-16 code unit |
boolean | — | true / false |
int count = 10;
long big = 10_000_000_000L; // underscores aid readability
double rate = 0.075;
char grade = 'A'; // single quotes, char only
boolean active = true;Objects and autoboxing
Every primitive has a wrapper class (Integer, Double, Boolean…) so it can live in collections. The compiler converts between them automatically, which hides a few traps.
Integer boxed = 1000; // autoboxed
int unboxed = boxed; // auto-unboxed
Integer a = 1000, b = 1000;
System.out.println(a == b); // false: different objects
System.out.println(a.equals(b)); // true: same value
Integer c = 100, d = 100;
System.out.println(c == d); // true: small values are cached (-128..127)⚠️
Unboxing a
null wrapper throws NullPointerException. Prefer Integer.valueOf(x).equals(y) or Objects.equals(a, b) over == for wrappers.Strings and equality
String s1 = "hello";
String s2 = new String("hello");
System.out.println(s1 == s2); // false: reference comparison
System.out.println(s1.equals(s2)); // true: value comparison
// string pool: literals are interned and share storage
String joined = "a" + "b" + 1; // "ab1"
String better = "%s has %d items".formatted("Cart", 3);💡
Strings are immutable. Every
+ in a loop creates a new object — use StringBuilder for repeated concatenation.FAQ
When do I use int vs Integer?
int for local maths and fields where null is meaningless; Integer in collections and where a missing value must be representable.Why is 0.1 + 0.2 not 0.3?
Binary floating point cannot represent those decimals exactly. For money use
BigDecimal with a scale and rounding mode.Related
Java: getting started Java collections
Last refreshed 2026-09-17.