Common Mistakes Java Developers Make this is test

Even experienced developers make some common Java mistakes. Let’s look at a few, with examples and how to avoid them.

1. Not Closing Resources Properly  

Example:


BufferedReader br = new BufferedReader(new FileReader("file.txt")); 
String line = br.readLine(); 
// No br.close() – this causes resource leaks!
  

Use try-with-resources: 
Example:


try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { 
    String line = br.readLine(); 
}  
  

2. Overusing null or Forgetting Null Checks 

Example:


String name = getName(); //could return null 
System.out.println(name.toUpperCase()); // NullPointerException
  

Use Optional: 
Example:


Optional name = getNameOptional(); 
name.ifPresent(n -> System.out.println(n.toUpperCase())); 
  

3. Using Wrong Collections 

Example:


List list = new LinkedList<>(); 
// Doing frequent get(index) – slow with LinkedList 
  

4. Ignoring Thread-Safety 

Example:


public class Counter { 
    private int count = 0; 
 
    public void increment() { 
        count++; // Not thread-safe 
    } 
} 
  

Use AtomicInteger : 
Example:


private AtomicInteger count = new AtomicInteger(0); 
public void increment() { 
    count.incrementAndGet(); 
} 
  

Related Blog