Basic Data Types
Variables
var works for local variables only — not fields, parameters or return types.
Tip
Make everything final that never changes. final var works too.
The eight primitives
| Type | Size | Use | Default |
|---|---|---|---|
byte |
8 bit | −128…127 | 0 |
short |
16 bit | −32,768…32,767 | 0 |
int |
32 bit | default integer type | 0 |
long |
64 bit | big integers, suffix L |
0L |
float |
32 bit | suffix f |
0.0f |
double |
64 bit | default decimal type | 0.0 |
char |
16 bit | one character, single quotes | '�' |
boolean |
– | true / false |
false |
Arithmetic
For money use BigDecimal, or count cents in a long:
Wrappers and autoboxing
Every primitive has an object twin: Integer, Long, Double, Boolean, Character.
Collections need those, and conversion is automatic.
Warning
Wrappers can be null. Integer x = null; int y = x; throws a NullPointerException.
Strings
Strings are immutable — every method returns a new one.
Building strings
| Format | Meaning |
|---|---|
%s |
any value as text |
%d |
integer, %05d → 00042 |
%.2f |
two decimals |
%n |
newline |
Comparing strings
The classic beginner bug
Use equals for objects, == only for primitives and enum constants.
Text blocks
Indentation is stripped relative to the closing """; no escaping of quotes needed.
StringBuilder
Input and output
The classic way still works: System.out.println(...), System.err.println(...).
★ Exercises
- Store your name, birth year and height in suitable types and print one sentence.
- Compute your age in days (365 per year is fine).
- Write three versions of
5 / 2that yield2.5. - Split
"ann,miller,berlin"and print each part capitalized on its own line. - Build a small HTML page with a text block and print it.
- Why is
0.1 + 0.2 == 0.3false? How would you compare instead?