Java basics: variables, data types and casting
Why numbers go wrong without any error: overflow, rounding, lossy casts and null on unboxing; how to pick a type for money, ids, counters and codes; the 8 primitive types, primitives vs references, wrappers; how to review AI-written code that touches numbers.
On this page
1. The problem
An int view counter worked for two years, then one morning the dashboard shows -2147483648. The same week, adding 0.1 ten times in double gives 0.9999999999999999, and a long id 5,000,000,123 cast to int becomes 705,032,827, someone else's id. Not one line throws.
2. Key idea
Numbers live in boxes with a fixed number of bits. Values that don't fit get transformed, and most languages do it silently.
| Effect | Java example | Also in |
|---|---|---|
| Overflow | Integer.MAX_VALUE + 1 is -2147483648 |
Go, C#; PostgreSQL raises an error instead |
| Floating-point error | 0.1 + 0.2 is 0.30000000000000004 |
JavaScript, Python |
| Narrowing cast | (int) 5_000_000_123L is 705032827 |
Go int32(x), C |
| Null instead of a number | int q = map.get("x") throws NPE |
nullable SQL columns |
2.1 Which type?
| Type | Use when | Don't use when |
|---|---|---|
int |
array indexes, quantity in one order | long-lived counters, money totals, ids in big tables |
long |
ids, millisecond timestamps, counters, money in minor units | you need variable fractions (interest rates) |
double |
measurements, statistics, coordinates | money, quantities that must match exactly |
BigDecimal |
money with fractions, interest, exchange rates | hot loops where long is enough |
Integer, Long |
collections, generics, nullable columns | locals, loop counters |
String |
postal codes, branch codes, phone numbers | values you do arithmetic on |
Check types on both sides of a boundary: a BIGINT column read into an int field overflows on load. JavaScript numbers are double, so ids above 2⁵³ − 1 sent as JSON get rounded in the frontend.
3. In Java
int views = Integer.MAX_VALUE;
views++; // -2147483648, no exception
Math.addExact(Integer.MAX_VALUE, 1); // throws ArithmeticException
long id = 5_000_000_123L;
int wrong = (int) id; // 705032827: keeps only the low 32 bits
int safe = Math.toIntExact(id); // throws ArithmeticException
double sum = 0;
for (int i = 0; i < 10; i++) sum += 0.1; // 0.9999999999999999
BigDecimal money = new BigDecimal("0.1").add(new BigDecimal("0.2")); // 0.3
Map<String, Integer> stock = new HashMap<>();
int q = stock.getOrDefault("x", 0); // stock.get("x") would throw NPE on unboxing
int code = 010; // 8: a leading zero means octalOther languages: Go wraps like Java and has math/big for large numbers; C# has checked { } blocks; Node.js has BigInt.
The 8 primitive types, primitives and references
| Type | Bits | Range | Default (field) |
|---|---|---|---|
byte |
8 | −128 … 127 | 0 |
short |
16 | −32,768 … 32,767 | 0 |
int |
32 | about ±2.1 billion | 0 |
long |
64 | about ±9.2 × 10¹⁸ | 0L |
float |
32 | ~7 significant digits | 0.0f |
double |
64 | ~15–16 significant digits | 0.0 |
char |
16 | '\u0000' … '' |
'\u0000' |
boolean |
true, false |
false |
- A primitive holds the value and is never
null. A reference (String,Integer, arrays, objects) holds an address and can benull. - Wrappers (
Integer,Long) box primitives for collections. Java auto-boxes/unboxes; unboxingnullthrows an NPE. - Locals must be assigned before use; only fields get default values.
- Widening (
int→long) is automatic and safe. Narrowing (long→int,double→int) needs(int)and drops fractions and high bits.
4. Working with AI
Hand to AI: generating boundary values for tests (0, -1, Integer.MAX_VALUE, 2⁵³, the string "08"), converting double to BigDecimal across a module.
Check yourself in AI-written code:
- No
double/floatfor money; search the repo fordouble price,double amount. -
BigDecimalcomes from a string orBigDecimal.valueOf, nevernew BigDecimal(0.1); compare withcompareTo. - Every
(int)cast fromlonghas a reason; otherwise useMath.toIntExact. - Java field types match column types (
BIGINT↔long,NUMERIC↔BigDecimal). - No unboxing of an
Integerthat can benull(map.get, nullable column, missing JSON field).
5. Exercises
Exercise 1: Review a payment check
The AI's PR says: "Switched to BigDecimal, so money is exact". A test with cart [0.1, 0.2] and paid = "0.30" fails. Find two bugs.
static boolean isPaidInFull(double[] prices, BigDecimal paid) {
BigDecimal total = BigDecimal.ZERO;
for (double p : prices) total = total.add(new BigDecimal(p));
return total.equals(paid);
}Solution 1
new BigDecimal(double)copies the binary error exactly:new BigDecimal(0.1)is0.1000000000000000055511151231257827021181583404541015625. Prices should enter as strings orBigDecimalfrom the start; if you must take adouble, useBigDecimal.valueOf(p).BigDecimal.equalscompares scale too:2.0isn't2.00. Compare amounts withcompareTo(...) == 0.
static boolean isPaidInFull(List<BigDecimal> prices, BigDecimal paid) {
BigDecimal total = prices.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
return total.compareTo(paid) == 0;
}Exercise 2: Read an incident
Dashboard at 09:12: total_views of a hot post jumps from 2147483100 to -2147483196. The database column is BIGINT. Diagnose it, say what to do in 15 minutes, fix the root cause.
Solution 2
- Diagnosis: it passed
Integer.MAX_VALUEand wrapped to negative. The column isBIGINT, so the bug is in Java: anint viewsfield or the addition done inint. - 15 minutes: hide negative values on the dashboard, stop writing negative values back to the database.
- Root fix: move the field and DTO to
long, useMath.addExactso overflow throws; increment in the database (UPDATE post SET views = views + 1 WHERE id = ?) instead of read, add, write. Add a test forInteger.MAX_VALUE - 1plus 2.
Summary
- Three silent ways numbers go wrong: overflow, floating-point error, narrowing casts.
- Counters, ids, totals:
long; money:BigDecimalorlongin minor units; codes:String. Math.addExactandMath.toIntExactturn silent overflow into exceptions.- Primitives hold values; references can be
null, and unboxingnullthrows an NPE. - Check types at boundaries: Java ↔ database column ↔ JSON for JavaScript.
Further reading: Operators and branching.
Practice interview questions on this topic
- What primitive types does Java have? What are the default values of variables and array elements?
- What is the difference between implicit and explicit casting? Why does s = s + 1 fail but s += 1 compile?
- What is the difference between stack and heap? When do StackOverflowError and OutOfMemoryError occur?
- What is LTS and which Java version should a new project use? How do OpenJDK, Oracle JDK, Temurin and Corretto differ?
- What are wrapper classes and autoboxing? Why is a == b false for Integer a = 128, b = 128?
- How does integer overflow work in Java, and does it throw an exception? How do you prevent it?
Comments
Community rules