SteelReed

Search

Search posts, questions…

1. Java Core

Object-oriented programming: wrapper classes, BigInteger/BigDecimal and String

Why money drifts by one đồng without an error and why comparing two ids with == only works up to 127; how to choose between double, long, BigDecimal, wrappers and String/StringBuilder; how to review AI-written money code.

17 Nov 20269 min readMid

–

1. The problem

An invoice has three lines of 333,333 VND each, with 10% VAT. The cart screen rounds VAT per line and sums: 99,999 VND. The accounting report computes VAT on the total: 100,000 VND. Reconciliation flags a mismatch every day, with no exception anywhere.

2. Key idea

Machines store numbers in finite representations; every change of representation or rounding is a place where money can silently disappear. Not just Java: JavaScript's Number, Go's float64 and Python's float are all binary IEEE 754.

Source of error Symptom Root cause
Binary numbers 0.1 + 0.2 != 0.3 0.1 has no exact binary representation
Rounding 1 VND off between two screens rounding in two places with two rules
Even splits 100,000 VND split 3 ways gives 99,999 the remainder is dropped
Comparison 2.0 and 2.00 are two keys; Long 128 isn't 128 scale is compared; object addresses are compared

2.1 Which type?

Type Use when Don't use when
long in the smallest unit one currency, only addition and subtraction, speed matters exchange rates, many-decimal interest
BigDecimal money with multiplication, division, rates, tax scientific computing that needs speed
double measurements, statistics, ML scores money, quantities that must match exactly
BigInteger integers beyond long (~9.2 × 10¹⁸) ordinary ids, counters
Wrappers (Integer, Long) generics, values that may be absent hot loops; == comparisons

2.2 Three rules that keep money right

  • Round in one place, agreed with accounting (per line or on the total), in a single function.
  • When splitting evenly, the remainder must go somewhere: the parts always sum to the total.
  • Database columns match the Java type: NUMERIC(19, 4) for BigDecimal, BIGINT for long.

3. In Java

JAVA
BigDecimal price = new BigDecimal("19.99");          // from a String, never a double
new BigDecimal(0.1);                                 // 0.1000000000000000055511151231257827...
BigDecimal vat = price.multiply(new BigDecimal("0.10"))
        .setScale(0, RoundingMode.HALF_UP);          // round in exactly one place
BigDecimal share = total.divide(BigDecimal.valueOf(3),
        0, RoundingMode.DOWN);                       // divide always with a scale + RoundingMode
new BigDecimal("2.0").equals(new BigDecimal("2.00"));     // false: different scale
new BigDecimal("2.0").compareTo(new BigDecimal("2.00"));  // 0
 
Long a = 128L, b = 128L;
a == b;                                              // false; Objects.equals(a, b) -> true
 
String csv = String.join(",", ids);                  // instead of += in a loop

HALF_EVEN (banker's rounding) reduces accumulated bias when aggregating many numbers; choose it with accounting. Other languages: C# decimal; Python decimal.Decimal; Go uses int64 in the smallest unit or shopspring/decimal.

Inside wrappers and String
  • Autoboxing: Integer c = a + b unboxes, adds, then calls Integer.valueOf(...). Integer.valueOf guarantees caching for -128..127; outside that range you get new objects.
  • Unboxing null: int x = map.get("k") with a missing key throws NullPointerException. Common with maps, nullable JPA columns and JSON missing fields.
  • String is immutable for the string pool (identical literals share an object), security, and a cached hash. "hi" == "hi" is true (same pool entry), new String("hi") == "hi" is false.
  • Compact strings (Java 9): Latin-1 strings use 1 byte per character. A single + expression is optimized by the compiler; only loops need a StringBuilder.

4. Working with AI

Give the AI: boundary tests (100,000 split by 3, 7, 0; negatives; null), a property test "parts sum to the total", migrating double code to BigDecimal.

Check in AI-written code:

  • No new BigDecimal(double).
  • Every divide has a scale and a RoundingMode.
  • Rounding lives in exactly one function; setScale isn't scattered across services.
  • Even splits handle the remainder; a sum(parts) == total test exists.
  • No == between two Integers or Longs.

5. Exercises

Exercise 1: A bill-splitting function

The AI says "accurate to the last VND because it uses BigDecimal and HALF_UP":

JAVA
BigDecimal[] split(BigDecimal total, int n) {
    BigDecimal share = total.divide(BigDecimal.valueOf(n), 0, RoundingMode.HALF_UP);
    BigDecimal[] parts = new BigDecimal[n];
    Arrays.fill(parts, share);
    return parts;
}

Find the bug, name a test that proves it, fix it.

Solution to Exercise 1

Each part is rounded independently, so the parts don't sum to the total: 100,000 split 3 ways gives [33333, 33333, 33333] = 99,999 (1 VND lost); 200,000 gives [66667, 66667, 66667] = 200,001 (1 VND overcharged).

Test: for total from 1 to 1,000,000 and n from 1 to 10, sum(split(total, n)).compareTo(total) == 0.

Fix: round down, then add 1 VND to the first remainder parts (remainder = total - share × n). Who gets the extra VND is a business decision: ask, don't let the AI pick.

Exercise 2: 403s for user ids from 128

Some users get 403 opening their own orders. Logs: userId=128 owner=128 allowed=false, userId=97 owner=97 allowed=true. Code: if (order.getUserId() == currentUser.getId()), both returning Long. Diagnose, the 15-minute action, the root fix.

Solution to Exercise 2
  • Diagnosis: == compares object addresses. Long.valueOf caches -128..127, so ids ≤ 127 happen to share an object; from 128 on they're two objects.
  • 15 minutes: hotfix with Objects.equals(a, b), deploy, watch allowed=false drop to 0.
  • Root fix: enable a static analysis rule (SpotBugs RC_REF_COMPARISON) in CI; test data uses ids above 127.

Summary

  • Money uses BigDecimal or a long in the smallest unit, never double.
  • BigDecimal from String, divide with a scale and RoundingMode, compare with compareTo.
  • Round in one place; even splits lose nothing.
  • Compare wrappers with equals; watch out for unboxing null.
  • Concatenate in loops with StringBuilder.

Read more: Flight booking: bookings, ledger and history.

Practice interview questions on this topic

All Java Core questions →All OOP & Design questions →

Loading comments…
Next on the roadmapEnums in Java: a closed set of values so the compiler catches bugs for you