SteelReed

Search

Search posts, questions…

1. Java Core

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.

17 Nov 20268 min readJunior

–

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

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 octal

Other 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 be null.
  • Wrappers (Integer, Long) box primitives for collections. Java auto-boxes/unboxes; unboxing null throws 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/float for money; search the repo for double price, double amount.
  • BigDecimal comes from a string or BigDecimal.valueOf, never new BigDecimal(0.1); compare with compareTo.
  • Every (int) cast from long has a reason; otherwise use Math.toIntExact.
  • Java field types match column types (BIGINT ↔ long, NUMERIC ↔ BigDecimal).
  • No unboxing of an Integer that can be null (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.

JAVA
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
  1. new BigDecimal(double) copies the binary error exactly: new BigDecimal(0.1) is 0.1000000000000000055511151231257827021181583404541015625. Prices should enter as strings or BigDecimal from the start; if you must take a double, use BigDecimal.valueOf(p).
  2. BigDecimal.equals compares scale too: 2.0 isn't 2.00. Compare amounts with compareTo(...) == 0.
JAVA
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_VALUE and wrapped to negative. The column is BIGINT, so the bug is in Java: an int views field or the addition done in int.
  • 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, use Math.addExact so overflow throws; increment in the database (UPDATE post SET views = views + 1 WHERE id = ?) instead of read, add, write. Add a test for Integer.MAX_VALUE - 1 plus 2.

Summary

  • Three silent ways numbers go wrong: overflow, floating-point error, narrowing casts.
  • Counters, ids, totals: long; money: BigDecimal or long in minor units; codes: String.
  • Math.addExact and Math.toIntExact turn silent overflow into exceptions.
  • Primitives hold values; references can be null, and unboxing null throws an NPE.
  • Check types at boundaries: Java ↔ database column ↔ JSON for JavaScript.

Further reading: Operators and branching.

Practice interview questions on this topic

All Java Core questions →

Loading comments…