10 Common Java Bugs and How to Avoid Them
This article lists ten typical Java programming mistakes—including array‑to‑ArrayList conversion errors, inefficient value checks, improper element removal in lists, misuse of Hashtable/HashMap, raw generic types, access‑level issues, and mutable versus immutable objects—explaining why they occur and providing correct code examples to prevent them.
As Java developers we often encounter quirky bugs such as NullPointerExceptions, ArrayIndexOutOfBounds, and unexpected behavior when modifying collections during iteration.
Error 1: Converting an Array to an ArrayList
Using Arrays.asList(arr) returns a fixed‑size list implementation that cannot be modified with add or remove. To obtain a mutable ArrayList, wrap the result in a new list:
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(arr));Error 2: Checking Whether an Array Contains a Value
Creating a HashSet from the array just to call contains adds unnecessary overhead. The simpler and more efficient approach is:
return Arrays.asList(arr).contains(targetValue);Alternatively, a manual loop can be used:
for (String s : arr) {
if (s.equals(targetValue))
return true;
}
return false;Error 3: Removing Elements from a List While Looping
Removing elements directly inside a standard for loop changes the list size and index, leading to unexpected results such as only half of the elements being removed.
The correct way is to use an Iterator and call iter.remove() after iter.next():
ArrayList<String> list = new ArrayList<String>(Arrays.asList("a", "b", "c", "d"));
Iterator<String> iter = list.iterator();
while (iter.hasNext()) {
String s = iter.next();
if (s.equals("a")) {
iter.remove();
}
}Using a foreach loop with list.remove(s) throws ConcurrentModificationException because the underlying structure changes while the iterator is active.
Error 4: Hashtable vs. HashMap
In Java, Hashtable is synchronized and generally unnecessary; HashMap should be preferred for unsynchronized use.
Error 5: Using Raw Types in Collections
Mixing raw types and wildcard generics bypasses compile‑time type checking and can cause ClassCastException. Always specify generic parameters, e.g., List<String> instead of List.
public static void add(List<String> list, Object o) {
list.add((String) o);
}Because of type erasure, both ArrayList<String> and ArrayList<Integer> become ArrayList at runtime, so the JVM cannot distinguish them.
Error 6: Improper Access Modifiers
Exposing class fields as public makes the internal state vulnerable; prefer encapsulation with private fields and accessor methods.
Error 7: Choosing Between ArrayList and LinkedList
ArrayListoffers fast random access but poor performance for massive insertions/deletions, while LinkedList excels at frequent insert/delete operations with less random access.
Error 8: Mutable vs. Immutable Objects
Immutable objects are safe and easy to share but may generate many temporary objects, increasing GC pressure. Use mutable objects like StringBuilder when building large strings to reduce overhead.
String result = "";
for (String s : arr) {
result = result + s;
}Error 9: Constructors and Superclass Initialization
If a superclass defines only a parameterized constructor, the compiler does not generate a default no‑arg constructor, causing subclass compilation errors. Adding an explicit no‑arg constructor to the superclass resolves the issue.
public Super() {
System.out.println("Super");
}Error 10: String Literals vs. New String Instances
String literals are interned and may refer to the same object ( a == b is true), whereas new String() always creates a distinct object ( c == d is false). This distinction affects memory usage and identity checks.
Conclusion
The ten pitfalls above are simple yet easy to overlook; understanding them helps write more robust Java code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
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.
