Common Java Pitfalls and Their Solutions
The article outlines frequent Java pitfalls—including BigDecimal precision loss, immutable lists from Arrays.asList, double division by zero returning Infinity, null values in switch statements, stream filters mutating original objects, and autoboxing nulls causing NullPointerExceptions—and provides clear explanations and practical fixes to enhance code reliability.
This article shares several common Java pitfalls encountered in daily development and provides explanations and fixes.
BigDecimal precision loss : Using new BigDecimal(0.1d) yields a long binary representation. The safe way is BigDecimal.valueOf(0.1d) , which converts the double to a string first.
Arrays.asList immutability : Arrays.asList(1, 2) returns a fixed‑size list; calling add() throws UnsupportedOperationException . Use a mutable list such as new ArrayList<>(Arrays.asList(...)) or Guava's Lists.newArrayList() .
Division by zero with double : 6.6d/0 prints Infinity instead of throwing an exception, following IEEE‑754. Only integer division throws ArithmeticException .
Switch on null : A switch statement with a null expression causes a NullPointerException because it invokes hashCode() and equals() on the null value.
Stream filter modifies original objects : Filtering a list returns references to the original objects; mutating them changes the source list as well.
Autoboxing null : Returning a null Integer from a method expecting int triggers NullPointerException . Prefer returning wrapper types or checking for null.
Understanding these underlying mechanisms helps improve code quality and stability.
DaTaobao Tech
Official account of DaTaobao Technology
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.