TL;DR: A null
Booleanin anif,Objects.equals(Long, int), ahashCodethat changes,assertused as a null check, and a bareOptional.get(). All five compile without a warning, and all five will bite you eventually. There’s a checklist at the end.
While learning Java more deeply, I kept running into the same five bugs in examples, tutorials, and my own practice code. Each one taught me something about how Java actually works under the hood, so I wrote them down.
None of them are hard bugs. You won’t need a debugger and a pot of coffee to understand them. That’s what makes them sneaky: they look so normal that your eyes slide right over them. The code compiles, the happy-path test passes, and then one day a null or a big number turns up and things break.
So here they are, using a tiny made-up bookstore (books, orders, a cart) as the example, with snippets you can paste into a file and run yourself. I ran every example on JDK 25, and the outputs are copied straight from the terminal.
1. A Boolean that’s secretly null
Here’s an order with an optional gift-wrap flag:
class Order {
Boolean giftWrap; // capital B: it can be null
}
if (order.giftWrap) {
addGiftWrap(order);
}
Looks fine, right? Until someone places an order without sending giftWrap at all:
NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()"
because "<local1>.giftWrap" is null
What’s going on
if needs a primitive boolean, but giftWrap is a Boolean object. Java helps by quietly calling giftWrap.booleanValue() for you. That’s called auto-unboxing. When the object is null, there’s nothing to call the method on, so you get an NPE.
Where do these nulls come from? Mostly from the edges of your app:
- JSON. If the client leaves a field out, Jackson leaves a
Booleanfield asnull. - Database columns that allow
NULL. - Optional request parameters.
The sneakier version: ternaries
This one took me a while to understand:
Integer count = inStock ? stock.get(isbn) : 0; // NPE if get() returns null
There’s no int variable anywhere, so why would anything unbox? Because of the 0. When one side of a ternary is a primitive int, Java makes the whole expression an int. It unboxes stock.get(isbn) first, then boxes the result back into Integer. If the map has no entry, null gets unboxed in the middle and crashes:
NullPointerException: Cannot invoke "java.lang.Integer.intValue()"
because the return value of "java.util.Map.get(Object)" is null
How to fix it
Decide what null means and write it down in the code:
// "null means no"
if (Boolean.TRUE.equals(order.giftWrap)) { ... }
// keep both sides boxed, so nothing unboxes
Integer count = inStock ? stock.get(isbn) : Integer.valueOf(0);
// or avoid null entirely
int count = stock.getOrDefault(isbn, 0);
And if “no value” isn’t a meaningful state for a field, just use a primitive boolean. Jackson sets a missing primitive field to false, and the problem is gone.
馃挕 Those friendly NPE messages (“because … is null”) are helpful NullPointerExceptions, on by default since JDK 15. If you’re on an older JDK, you’ll only get a line number, which makes this bug much harder to spot.
2. Objects.equals(Long, int) is always false
This one reads perfectly and never works:
static final int FLAGSHIP_STORE_ID = 7;
if (Objects.equals(order.getStoreId(), FLAGSHIP_STORE_ID)) { // storeId is a Long
applyFreeShipping(order);
}
Say you want to give orders from one store free shipping. This code never applies it. No error, no exception, just no free shipping.
Objects.equals(7L, 7) -> false
Objects.equals(7L, 7L) -> true
storeId == 7 -> true (unboxes, so it NPEs if storeId is null)
What’s going on
FLAGSHIP_STORE_ID is an int, so Java boxes it into an Integer. Then Long.equals(Integer) runs, and the first thing it checks is “is the other object a Long?” It isn’t, so the answer is false, even though both hold the number 7.
The same thing happens anywhere Java compares objects. Collections are the worst, because they also fail silently:
Map<Long, String> titles = Map.of(7L, "Dune");
int id = 7;
titles.get(id) -> null // looked up an Integer key
titles.get((long) id) -> Dune
Set<Long> featured = Set.of(7L);
featured.contains(7) -> false
Map.get takes an Object, so the compiler happily accepts an int and boxes it to Integer, which never matches a Long key.
Bonus trap: == on Long
When the types match, it’s tempting to use == instead. Don’t:
Long 127 == Long 127 -> true
Long 128 == Long 128 -> false
== on objects compares references (are they the same object?), not values. It only seems to work for small numbers, because Java caches boxed values from -128 to 127 and hands back the same object each time. So your tests with small IDs pass, and it breaks once real data passes 127. That’s a nasty one to debug.
How to fix it
- Keep types consistent. If the ID is a
Long, make the constant7Lorlong. - Compare values, not references:
Objects.equalswith matching types, or primitives after a null check. - Let tools catch it. IntelliJ warns about "’equals()’ between objects of inconvertible types", SpotBugs has
EC_UNRELATED_TYPES, and Error Prone hasEqualsIncompatibleType. Turning one of these on catches this whole family of bugs for free.
3. Changing a field that hashCode depends on
Here’s a Book where two books count as equal if they have the same title:
class Book {
String isbn;
String title;
@Override public boolean equals(Object o) {
return o instanceof Book b && Objects.equals(title, b.title);
}
@Override public int hashCode() { return Objects.hash(title); }
}
Set<Book> shelf = new HashSet<>();
Book book = new Book("978-0", "Draft Title");
shelf.add(book);
book.title = "Final Title"; // the author renamed the book
The book is definitely still in the set. The set just can’t find it anymore:
shelf.contains(book) -> false
shelf.remove(book) -> false
shelf.size() -> 1
What’s going on
Think of a HashSet as a wall of numbered boxes. When you add an object, the set calls hashCode(), uses that number to pick a box, and drops the object in. Later, contains calls hashCode() again and looks in that box.
Change the title and the hash code changes, so the set looks in a different box, finds nothing, and says “not here”. The book is still sitting in its original box. You can’t reach it or remove it, and it stays there forever. A HashMap key behaves the same way.
Where this sneaks in
- Lombok’s
@DatageneratesequalsandhashCodefrom all fields, including the ones you change later. It’s very convenient and very easy to trip over. - JPA entities with a generated ID. If
hashCodeusesid, it’snullwhen you create the object and gets a value when you save it. Put the entity in aSetbefore saving and you get the same problem:
id assigned after adding to the set: contains -> false
How to fix it
- Base equality on something that never changes, like a business key (
isbn), or make the class immutable. - Java records are great for this:
record Book(String isbn, String title) {}gives you correctequalsandhashCodeover final fields, for free. - Be careful whenever you change an existing
equals/hashCode. It silently changes how everySetandMapholding that type behaves.
4. Using assert as a null check
void applyDiscount(Book book) {
assert book != null : "book must not be null";
book.price = book.price * 0.9;
}
This looks like a safety check. In production, it’s a comment.
java Demo -> NullPointerException: Cannot read field "price" because "<parameter1>" is null
java -ea Demo -> AssertionError: book must not be null
What’s going on
Java assertions are switched off by default. They only run when the JVM starts with -ea (“enable assertions”), and almost nobody runs production with that flag.
Here’s the twist that makes it really sneaky: Maven Surefire and Gradle both enable assertions when running tests. So in your tests the assert works, throws the nice AssertionError, and a test like “rejects null books” passes. In production, the same line does nothing at all. Your tests are literally testing different code than what runs live.
How to fix it
Use a check that always runs:
void applyDiscount(Book book) {
Objects.requireNonNull(book, "book must not be null");
book.price = book.price * 0.9;
}
assert is still fine for things that should be impossible, internal sanity checks while you develop. Just never use it to validate input coming into a method.
5. Calling Optional.get() without checking
Book book = bookRepository.findById(id).get();
When there’s no book with that ID:
NoSuchElementException: No value present
What’s going on
Optional exists to make you think about the empty case, and .get() skips that thinking entirely. In a web app, the exception usually turns into a generic HTTP 500 with a message that helps nobody. But a missing book isn’t a server error. It’s a perfectly normal situation and should probably be a 404.
How to fix it
Say what “not found” means:
Book book = bookRepository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id)); // map this to a 404
Or pick a fallback that makes sense:
String title = bookRepository.findById(id)
.map(Book::getTitle)
.orElse("Unknown book");
If you’re truly sure the value exists, orElseThrow() with no arguments (Java 10+) does the same as get() but makes your intent obvious to whoever reads it next. That’s usually you, six months later.
The checklist
Whenever I read Java code now, I scan for:
- A
Boolean/Integer/Longused in anif, in maths, or in a ternary next to a primitive -
equalsbetween different boxed types, includingMap.getandSet.containswith the wrong key type -
==between boxed numbers -
equals/hashCodebuilt on fields that can change (watch out for@Dataand generated IDs) -
assertguarding method inputs - A bare
Optional.get()
The nice thing about this list is that you don’t need to understand the whole system to use it. These bugs are visible in a single line, so they’re cheap to catch early and annoying to catch late.
If you’ve got a favourite sneaky Java bug that isn’t on this list, I’d love to hear about it.