Why Long Over Primitive Long in Java IDs

Last week a junior dev asked me this in a code review: "Why do you always use Long instead of long for IDs?" 10 minutes earlier — I'd probably have said: "Habit. It's just better." But that's a garbage answer. So I actually stopped and thought about it. Here's what I came up with 👇 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ❌ long id; (primitive) → Default value: 0 → Cannot be null → Database NULL? Boom. NullPointerException   at unboxing time. → "Is this ID missing or is it genuinely zero?"  You can't tell. ✅ Long id; (wrapper)   → Default value: null → Can distinguish "not set" from "zero" → Works seamlessly with Spring Data JPA,  Jackson, Optional, database NULLs → The 10-byte object overhead is irrelevant  in 99.9% of real apps ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ The same logic applies to: → Integer over int (for nullable fields) → Boolean over boolean (for "not answered" states) → BigDecimal over double (for money — ALWAYS) The "use primitives for performance" advice  made sense in 2005. In 2026, with Spring Boot apps running on  containers with 2GB RAM? Clarity > micro-optimization. Every. Single. Time. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Which Java "obvious habit" did YOU realize was  actually wrong after 1-2 years of real work? Drop it below 👇 #Java #SpringBoot #CleanCode #BackendDeveloper  #SoftwareEngineering

  • text

To view or add a comment, sign in

Explore content categories