Skip to content
Tutorials Center
My learning

Topics

Lesson 165 of 201 ยท JVM and Advanced Topics

Best Practices and Common Mistakes

Avoid the Java mistakes that compile but break programs - == on objects, equals without hashCode, null leaks, mutable state, money in double, resource leaks and more.

The Java compiler catches typos and type errors, but many of the bugs that reach production compile without a single warning. Comparing strings with ==, putting objects without hashCode into a HashSet, returning null where a caller expects a list, storing money in a double: each one works in a quick test and fails later, often far from the line that caused it.

This lesson collects the habits that experienced Java developers follow so these bugs never happen, each with a runnable demonstration of what goes wrong and the fix. Most of the topics have their own lesson earlier in the course; here you get them in one place, as a checklist you can come back to before a code review or an interview.

Write code for the next reader

Code is read far more often than it's written, so clarity is the first best practice. Follow the standard Java naming conventions; every Java developer expects them:

Kind Convention Examples
Classes, interfaces, records, enums UpperCamelCase, nouns OrderService, Shippable, Money
Methods lowerCamelCase, verbs calculateTotal(), isEmpty(), toJson()
Variables and parameters lowerCamelCase, meaningful customerName, retryCount
Constants (static final) UPPER_SNAKE_CASE MAX_RETRIES, DEFAULT_TIMEOUT
Packages all lowercase, reversed domain com.example.billing
Type parameters one capital letter T, K, V, E

Beyond names:

  • Keep methods short and focused. A method that needs a comment for each block is several methods waiting to be extracted.
  • Prefer clear over clever. A plain for loop is better than a stream that needs a minute to decode, and vice versa.
  • Use var where the type is obvious from the right-hand side (var orders = new ArrayList<Order>()), and spell it out where it isn't (var).
  • Replace magic numbers with named constants or enums: if (status == 3) tells the reader nothing; if (status == Status.SHIPPED) does.
  • Program to interfaces. Declare List<Order> and Map<String, Customer>, not ArrayList and HashMap, so the implementation can change.
  • Comment why, not what. The code says what it does; a comment should explain a decision the code can't (Comments and Javadoc).

Compare values correctly

The single most common Java bug is comparing objects with ==. For objects, == asks "are these the same object?", not "do they have the same value?". It sometimes appears to work, because string literals are shared in the string pool and small Integer values are cached, which makes the bug even harder to spot:

Java Comparisons that compile but lie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rules:

  • Compare objects with equals, and use Objects.equals(a, b) when either side may be null. Use == only for primitives, enums and deliberate identity checks.
  • Never compare Integer, Long or other wrappers with ==. The cache covers only -128 to 127, so tests with small numbers pass and production data fails (Wrapper Classes).
  • Never compare floating-point results with ==; use a tolerance, or avoid double entirely for exact values.
  • Never use double for money. Use BigDecimal created from strings (new BigDecimal("0.10") or BigDecimal.valueOf(0.1)), or store whole cents in a long. Compare BigDecimal values with compareTo, because equals also compares the scale (0.30 vs 0.3) (BigInteger and BigDecimal).
  • Compare strings ignoring case with equalsIgnoreCase, and put the known non-null value first if the other might be null: "admin".equals(role).

equals and hashCode go together

Hash-based collections (HashMap, HashSet) first use hashCode to find a bucket, then equals to compare inside it. If you override equals but not hashCode, two equal objects usually land in different buckets, and the collection never finds the match:

Java equals without hashCode breaks HashSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rules (The Object Class):

  • Override both equals and hashCode, using the same fields, or neither. Objects.hash(field1, field2) builds a decent hashCode in one line.
  • For simple data carriers, use a record: it generates correct equals, hashCode and toString from its components.
  • Never change a field used by hashCode while the object is a key in a map or an element of a set; the collection will lose it (How HashMap Works Inside).
  • Always use @Override. A misspelled equals(Sku other) is an overload, not an override, and @Override turns that silent bug into a compile error.

Handle null deliberately

NullPointerException is the most common runtime exception in Java. You can't eliminate null, but you can stop it from spreading:

  • Return empty collections, never null. Callers can loop over List.of() safely; they will forget to check for null.
  • Return Optional<T> from methods that may have no result, such as findById. It forces the caller to decide what happens when the value is missing (Optional). Don't use Optional for fields or parameters.
  • Fail fast. Check arguments at the boundary with Objects.requireNonNull(value, "value") in constructors and public methods. An exception at construction time points at the real culprit; an NPE ten calls later doesn't.
Java Null handling: fail fast, return empty, use Optional

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line shows a helpful NullPointerException message (on by default since Java 15): the JVM names exactly which expression was null. Read it before reaching for the debugger (Debugging Java Programs).

Prefer immutability and don't leak mutable state

Objects that can't change are easier to reason about, safe to share between threads, and safe as map keys. Make fields private final by default, use records for data, and only add setters when there's a real need (Immutable Classes).

The classic leak is a getter that returns an internal mutable collection: any caller can then change your object behind its back. Collections have their own traps too:

Java Mutable state leaks and collection traps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The rules:

  • Return copies (List.copyOf) or unmodifiable views from getters, and copy mutable arguments in constructors (defensive copies, see Encapsulation).
  • List.of, Set.of and Map.of create truly immutable collections and reject null elements; Arrays.asList is a fixed-size view over an array (Immutable Collections).
  • Never add to or remove from a collection while looping over it with for-each. Use removeIf, an explicit Iterator.remove(), or build a new list (Iterators).
  • Avoid mutable static fields: they're global state shared by every thread and every test.

Watch the numbers

Integer arithmetic silently wraps around on overflow: Integer.MAX_VALUE + 1 is a large negative number, with no exception (Working with Numbers). It bites in code that looks harmless:

Java
int millis = 30 * 24 * 60 * 60 * 1000;          // milliseconds in 30 days: overflows to -1702967296
long safe = 30L * 24 * 60 * 60 * 1000;           // 2592000000: the L makes it long arithmetic
int checked = Math.multiplyExact(30, 86_400_000); // throws ArithmeticException instead of lying
int middle = low + (high - low) / 2;             // not (low + high) / 2, which can overflow

Also remember that / on two integers truncates (7 / 2 is 3), and that % keeps the sign of the left operand (-7 % 3 is -1); use Math.floorMod for "always positive" remainders.

Close resources and handle exceptions properly

Files, sockets, database connections and streams hold operating-system resources that the garbage collector doesn't release in time. Open them in a try-with-resources statement, which closes them even when an exception is thrown:

Java
// Wrong: if readLine throws, the reader is never closed
BufferedReader reader = Files.newBufferedReader(path);
String header = reader.readLine();
reader.close();

// Right: closed automatically, in reverse order of opening
try (BufferedReader in = Files.newBufferedReader(path)) {
    String firstLine = in.readLine();
}

For exceptions, the essentials from Exception Handling Best Practices:

  • Never swallow exceptions. An empty catch (Exception e) {} turns a clear failure into a mystery. At the very least, log it with its stack trace (Logging).
  • Catch specific exceptions you can actually handle; let the rest propagate to a place that can.
  • Keep the cause when translating: throw new OrderException("Import failed for " + file, e).
  • Don't use exceptions for normal control flow, and don't return null or -1 to signal errors that callers must not ignore.

A professional's checklist

Before you open a pull request, run through these:

  1. Do names tell the reader what things are and do?
  2. Are objects compared with equals (or compareTo for BigDecimal), never ==?
  3. Does every class that overrides equals also override hashCode, or is it a record?
  4. Can any method return null where an empty collection or Optional would be clearer?
  5. Are fields private final where possible, and are mutable collections copied in and out?
  6. Is money in BigDecimal or long cents, and can any int arithmetic overflow?
  7. Is every resource opened in try-with-resources, and is every exception handled or propagated, never swallowed?
  8. Are there tests for the new behavior and its edge cases (Unit Testing with JUnit)?
  9. Did you fix every compiler warning? Static analysis tools such as SpotBugs and Error Prone find many of the bugs in this lesson automatically (Code Quality and Static Analysis).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? Integer a = 1000, b = 1000; System.out.println(a == b);

    == compares references for wrapper objects. Only values from -128 to 127 are cached and shared, so two boxed 1000s are different objects. Use a.equals(b).
  2. 2. A class overrides equals but not hashCode. You add an object to a HashSet and then call contains with an equal object. What happens most likely?

    HashSet looks in the bucket given by hashCode first. With Object's identity hashCode, equal objects almost always land in different buckets, so equals is never even called.
  3. 3. What does new BigDecimal("2.50").equals(new BigDecimal("2.5")) return?

    BigDecimal.equals considers 2.50 (scale 2) and 2.5 (scale 1) different. Use compareTo(...) == 0 to compare numeric values.
  4. 4. A method findOrders(customerId) has no orders to report. What should it return?

    Returning an empty collection lets callers loop and count without special cases. Optional is for a single value that may be missing, and exceptions are for real errors.
  5. 5. Why is for (String s : list) { if (s.isBlank()) list.remove(s); } a bug?

    The for-each loop's hidden iterator detects the structural change on its next step. Use list.removeIf(String::isBlank) instead.

Summary

  • Write for the reader: standard naming conventions, short focused methods, named constants, interfaces as declared types, comments that explain why.
  • Compare objects with equals/Objects.equals, never == (wrappers and strings included); never compare doubles with ==; use BigDecimal from strings (and compareTo) or long cents for money.
  • Override equals and hashCode together, use @Override, and prefer records for data classes.
  • Stop null from spreading: empty collections, Optional return values, Objects.requireNonNull at the boundaries.
  • Prefer immutable objects, copy mutable collections in and out, and never modify a collection inside its own for-each loop.
  • Watch for silent integer overflow; use long literals or Math.*Exact.
  • Close resources with try-with-resources, and never swallow exceptions.

Next: Java Versions and History, a tour of how Java evolved from 1.0 to Java 25 and which features each release added.