Common Java Errors

Understand, identify, and fix common Java errors

Compile-Time Errors

1. "Cannot find symbol"

Cause: Variable, method, or class not declared or misspelled.

// Error
System.out.println(myVariable);  // myVariable not declared

// Fix
int myVariable = 10;
System.out.println(myVariable);

2. "Class, interface, or enum expected"

Cause: Code written outside of any class definition.

// Error
System.out.println("Hello");  // Outside class

// Fix
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello");
    }
}

3. "Incompatible types"

Cause: Assigning value of wrong type without proper casting.

// Error
int num = "123";  // String to int

// Fix
int num = Integer.parseInt("123");
// or
String str = "123";

4. "Missing return statement"

Cause: Method with non-void return type doesn't return a value in all paths.

// Error
public int getValue(boolean flag) {
    if (flag) {
        return 10;
    }
    // Missing return for else case
}

// Fix
public int getValue(boolean flag) {
    if (flag) {
        return 10;
    }
    return 0;  // Default return
}

5. "Unreported exception; must be caught or declared"

Cause: Checked exception not handled.

// Error
FileReader fr = new FileReader("file.txt");  // IOException not handled

// Fix 1: try-catch
try {
    FileReader fr = new FileReader("file.txt");
} catch (IOException e) {
    e.printStackTrace();
}

// Fix 2: throws declaration
public void readFile() throws IOException {
    FileReader fr = new FileReader("file.txt");
}

6. "Variable might not have been initialized"

Cause: Local variable used before initialization.

// Error
int x;
System.out.println(x);  // x not initialized

// Fix
int x = 0;
System.out.println(x);

Runtime Errors (Exceptions)

1. NullPointerException

Cause: Calling method or accessing field on null reference.

// Error
String str = null;
int len = str.length();  // NullPointerException

// Fix: Null check
if (str != null) {
    int len = str.length();
}

// Fix: Optional (Java 8+)
Optional.ofNullable(str)
    .ifPresent(s -> System.out.println(s.length()));

2. ArrayIndexOutOfBoundsException

Cause: Accessing array with invalid index.

// Error
int[] arr = {1, 2, 3};
System.out.println(arr[3]);  // Index 3 doesn't exist (0-2)

// Fix: Check bounds
int index = 3;
if (index >= 0 && index < arr.length) {
    System.out.println(arr[index]);
}

3. ClassCastException

Cause: Invalid type casting.

// Error
Object obj = "Hello";
Integer num = (Integer) obj;  // String cannot be cast to Integer

// Fix: Check type first
if (obj instanceof Integer) {
    Integer num = (Integer) obj;
}

4. NumberFormatException

Cause: Parsing non-numeric string to number.

// Error
int num = Integer.parseInt("abc");  // "abc" is not a number

// Fix: Validate or catch
try {
    int num = Integer.parseInt(input);
} catch (NumberFormatException e) {
    System.out.println("Invalid number format");
}

5. ArithmeticException

Cause: Division by zero (integer).

// Error
int result = 10 / 0;  // ArithmeticException

// Fix: Check divisor
int divisor = 0;
if (divisor != 0) {
    int result = 10 / divisor;
} else {
    System.out.println("Cannot divide by zero");
}

6. ConcurrentModificationException

Cause: Modifying collection while iterating with for-each.

// Error
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));
for (String s : list) {
    list.remove(s);  // ConcurrentModificationException
}

// Fix: Use Iterator
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    it.remove();  // Safe removal
}

// Fix: removeIf (Java 8+)
list.removeIf(s -> s.equals("B"));

7. StackOverflowError

Cause: Infinite recursion or too deep recursion.

// Error
public void infiniteRecursion() {
    infiniteRecursion();  // No base case
}

// Fix: Add base case
public int factorial(int n) {
    if (n <= 1) return 1;  // Base case
    return n * factorial(n - 1);
}

8. OutOfMemoryError

Cause: JVM runs out of heap space.

// Error - creating too many objects
List<byte[]> list = new ArrayList<>();
while (true) {
    list.add(new byte[1000000]);  // OutOfMemoryError
}

// Fix: Limit data, increase heap (-Xmx), use streaming

Logical Errors

1. Off-by-one Error

Cause: Loop iterates one too many or too few times.

// Error
for (int i = 0; i <= arr.length; i++) {  // Should be < not <=
    System.out.println(arr[i]);
}

// Fix
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i]);
}

2. == vs .equals() for Strings

Cause: Using == to compare string content.

// Error
String s1 = new String("hello");
String s2 = new String("hello");
if (s1 == s2) { ... }  // false - compares references

// Fix
if (s1.equals(s2)) { ... }  // true - compares content

3. Floating Point Comparison

Cause: Direct equality comparison of floating point numbers.

// Error
double a = 0.1 + 0.2;
if (a == 0.3) { ... }  // May be false due to precision

// Fix: Use epsilon comparison
double epsilon = 0.0001;
if (Math.abs(a - 0.3) < epsilon) { ... }

4. Integer Overflow

Cause: Arithmetic exceeds int range.

// Error
int big = Integer.MAX_VALUE;
int result = big + 1;  // Overflows to negative

// Fix: Use long
long big = Integer.MAX_VALUE;
long result = big + 1;  // Works correctly

5. Forgetting break in switch

Cause: Fall-through to next case.

// Error
switch (day) {
    case 1: System.out.println("Monday");
    case 2: System.out.println("Tuesday");  // Also prints for day=1
}

// Fix
switch (day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
}