☕📦 Java PRIMITIVES vs WRAPPERS: when should you use Integer instead of int?
☕📦 Java PRIMITIVES vs WRAPPERS: when should you use Integer instead of int?
int by default. Integer when your domain or API needs an object.
🔸 TLDR
Java primitives are usually simpler, faster, and safer from null.
But wrappers become necessary when you need:
▪️ null to represent “no value”
▪️ Generic types
▪️ Collections
▪️ APIs expecting objects
▪️ A distinction between “unset” and a legitimate primitive value

🔸 USE PRIMITIVES BY DEFAULT ⚡
For calculations, counters, flags, loops, and values that must always exist:
int age = 42; double price = 19.99; boolean active = true;
Why?
▪️ No null
▪️ No boxing/unboxing
▪️ Usually less memory overhead
▪️ Clearer semantics when a value is mandatory
If 0, false, or another primitive value makes sense as a real domain value, primitives are often the natural choice.
🔸 USE WRAPPERS WHEN NULL HAS MEANING 📭
Imagine a form where the age has not been provided yet:
Integer age = null;With:
int age = 0;you cannot distinguish:
“the user entered 0”
from:
“the user did not provide a value.”
This distinction is especially useful in DTOs, persistence models, PATCH requests, and nullable database columns.
🔸 GENERICS REQUIRE OBJECTS 📦
You cannot write:
List<int>
You need:
List<Integer> numbers; Map<String, Boolean> flags; Optional<Double> value;
Java generics work with reference types, not primitives.
When specialized alternatives exist, however, consider them:
OptionalInt IntStream
instead of unnecessarily boxing large numbers of values.
🔸 BE CAREFUL WITH AUTOBOXING ⚠️
Java makes conversion convenient:
Integer count = 10;
int result = count + 1;But this can hide problems:
Integer count = null; int result = count + 1;
💥 NullPointerException
Unboxing a null wrapper is one of those bugs that looks harmless until runtime.
🔸 NEVER RELY ON WRAPPER IDENTITY 🔍
Avoid:
Integer a = 200; Integer b = 200; a == b
Wrappers are objects.
When comparing values, prefer:
a.equals(b)
or, if null is possible:
Objects.equals(a, b)
🔸 TAKEAWAYS
▪️ Prefer int, long, boolean, etc. when the value is mandatory.
▪️ Use wrappers when null carries domain meaning.
▪️ Wrappers are required for collections and generics.
▪️ Watch for hidden boxing/unboxing in performance-sensitive code.
▪️ Never forget that unboxing null throws an NPE.
▪️ Model the meaning first; choose the Java type second.
Primitive or wrapper is not just a syntax choice.
Sometimes it is part of your domain model. ☕
#Java #JavaDeveloper #Programming #SoftwareEngineering #CleanCode #JVM #JavaTips #BackendDevelopment #OCPJava
Go further with Java certification:
Java👇
Spring👇
SpringBook👇
JavaFullstackBook👇