Skip to content

Java Common Mistakes

This guide covers common Java programming mistakes and how to avoid them, with practical solutions and examples.

🚨 Most Common Java Errors

1. NullPointerException

The most frequent Java runtime error occurs when trying to access methods or fields of a null object.

Problem

String name = null;
int length = name.length(); // NullPointerException!

Solutions

// Solution 1: Null check
String name = null;
int length = 0;
if (name != null) {
    length = name.length();
}

// Solution 2: Use Optional (Java 8+)
Optional<String> nameOpt = Optional.ofNullable(name);
int length = nameOpt.map(String::length).orElse(0);

// Solution 3: Null-safe comparison
if ("John".equals(name)) {
    // Safe comparison
}

2. String Comparison Mistakes

Using == instead of .equals() for string content comparison.

Problem

String str1 = new String("hello");
String str2 = "hello";
if (str1 == str2) { // false - compares references!
    System.out.println("Same string");
}

Solutions

// Correct: Use .equals()
if (str1.equals(str2)) { // true - compares content
    System.out.println("Same string");
}

// Better: Null-safe comparison
if ("hello".equals(str2)) { // Safe even if str2 is null
    System.out.println("Same string");
}

3. Array Index Out of Bounds

Accessing array elements outside the valid index range.

Problem

int[] numbers = {1, 2, 3};
int value = numbers[3]; // ArrayIndexOutOfBoundsException!

Solutions

// Solution 1: Check bounds before access
int[] numbers = {1, 2, 3};
int index = 2;
if (index >= 0 && index < numbers.length) {
    int value = numbers[index];
}

// Solution 2: Use enhanced for-loop when possible
for (int number : numbers) {
    System.out.println(number); // No index needed
}

// Solution 3: Try-catch for error handling
try {
    int value = numbers[index];
} catch (ArrayIndexOutOfBoundsException e) {
    System.err.println("Invalid array index: " + index);
}

4. Resource Leaks

Not properly closing resources like files, database connections, or streams.

Problem

// Bad: Resource might not be closed if exception occurs
FileInputStream fis = new FileInputStream("file.txt");
// ... code that might throw exception
fis.close(); // Might not execute!

Solutions

// Good: try-with-resources (Java 7+)
try (FileInputStream fis = new FileInputStream("file.txt")) {
    // ... code that might throw exception
} // Resource automatically closed

// Alternative: Traditional try-finally
FileInputStream fis = null;
try {
    fis = new FileInputStream("file.txt");
    // ... code that might throw exception
} finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException e) {
            // Log error
        }
    }
}

5. Floating Point Precision Issues

Incorrect comparison of floating-point numbers due to precision limitations.

Problem

double result = 0.1 + 0.2;
if (result == 0.3) { // false due to precision!
    System.out.println("Equal");
}

Solutions

// Solution 1: Use epsilon comparison
private static final double EPSILON = 0.000001;
double result = 0.1 + 0.2;
if (Math.abs(result - 0.3) < EPSILON) {
    System.out.println("Equal within tolerance");
}

// Solution 2: Use BigDecimal for precise calculations
BigDecimal result = new BigDecimal("0.1").add(new BigDecimal("0.2"));
if (result.equals(new BigDecimal("0.3"))) {
    System.out.println("Exactly equal");
}

🔧 Logic Errors

6. Off-by-One Errors

Incorrect loop boundaries or array indexing.

Problem

// Process first 5 elements
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i <= 5; i++) { // Should be i < 5
    System.out.println(array[i]); // Processes 6 elements!
}

Solutions

// Correct: Use < instead of <=
for (int i = 0; i < 5; i++) {
    System.out.println(array[i]); // Processes exactly 5 elements
}

// Better: Use enhanced for-loop when possible
int[] firstFive = Arrays.copyOf(array, 5);
for (int value : firstFive) {
    System.out.println(value);
}

7. Infinite Loops

Loops that never terminate due to incorrect conditions.

Problem

int i = 0;
while (i < 10) {
    System.out.println(i);
    // Missing i++ - infinite loop!
}

Solutions

// Solution 1: Ensure loop variable changes
int i = 0;
while (i < 10) {
    System.out.println(i);
    i++; // Critical!
}

// Solution 2: Use for-loop when possible
for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

8. Integer Division

Unexpected results from integer division.

Problem

int result = 5 / 2; // result = 2, not 2.5!
double average = 5 / 2; // average = 2.0, not 2.5!

Solutions

// Solution 1: Cast to double before division
double result = 5.0 / 2; // result = 2.5
double average = (double) 5 / 2; // average = 2.5

// Solution 2: Use double literals
double result = 5.0 / 2.0; // result = 2.5

9. Type Casting Issues

Losing precision when casting between types.

Problem

double largeValue = 123456789.987;
int intValue = (int) largeValue; // intValue = 123456789 (lost decimal!)

Solutions

// Solution 1: Round before casting
double largeValue = 123456789.987;
int intValue = (int) Math.round(largeValue); // intValue = 123456790

// Solution 2: Check for overflow
if (largeValue > Integer.MAX_VALUE || largeValue < Integer.MIN_VALUE) {
    throw new ArithmeticException("Value out of integer range");
}
int intValue = (int) largeValue;

🛠️ Debugging Tips

Common Debugging Strategies

  1. Use IDE Debugger: Set breakpoints and step through code
  2. Print Statements: Add debug output to trace execution
  3. Unit Testing: Write tests to isolate problems
  4. Code Review: Have others review your code

Debugging Checklist

  • Check for null values before method calls
  • Verify array indices are within bounds
  • Ensure resources are properly closed
  • Use proper string comparison methods
  • Check loop conditions for termination
  • Verify type casting doesn't lose data

🔗 Common Programming Mistakes