Java Errors
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java Errors

Harine

Java Errors

Errors are a natural part of programming—even for experienced Java developers. Understanding how to identify and fix errors is essential for writing reliable, bug-free applications. In Java, errors generally fall into three main categories: compile-time errors, runtime errors, and logical errors

Compile-Time Errors in Java

Compile-time errors occur when the Java compiler detects syntax or type problems before the

program runs.

1. Missing Semicolon

Java requires a semicolon at the end of most statements.

public class MissingSemicolonExample {

  public static void main(String[] args) {

    int value = 10

    System.out.println("Value = " + value);

  }

}

Compiler error

';' expected

Fix

int value = 10;

2. Using an Undeclared Variable

Variables must be declared before use.


public class UndeclaredVariableExample {

  public static void main(String[] args) {

    total = 50;

    System.out.println(total);

  }

}

Compiler error

cannot find symbol

symbol: variable total

Fix

int total = 50;

3. Type Mismatch

Assigning an incompatible value to a variable causes a compile-time error.


public class TypeMismatchExample {

  public static void main(String[] args) {

    double price = "19.99";

    System.out.println(price);

  }

}

Compiler error

incompatible types: String cannot be converted to double

Fix

double price = 19.99;

Runtime Errors in Java

Runtime errors occur after successful compilation, while the program is running. These typically

throw exceptions.

1. Division by Zero

public class DivisionByZeroExample {

  public static void main(String[] args) {

    int items = 25;

    int groups = 0;

    int perGroup = items / groups;

    System.out.println(perGroup);

  }

}

Runtime error

java.lang.ArithmeticException: / by zero

2. Array Index Out of Bounds

Accessing an invalid array index causes an exception.

public class ArrayBoundsExample {

  public static void main(String[] args) {

    String[] cities = {"Delhi", "Chennai", "Mumbai"};

    System.out.println(cities[5]);

  }

}

Runtime error

java.lang.ArrayIndexOutOfBoundsException

Logical Errors in Java

Logical errors are the most difficult to detect because the program runs successfully but

produces incorrect results.

public class LogicalErrorExample {

  public static void main(String[] args) {

    int length = 8;

    int width = 4;

    int area = length + width; // mistake

    System.out.println("Rectangle area = " + area);

  }

}

Output

Rectangle area = 12

Expected

Rectangle area = 32

Issue: Area should be calculated using multiplication, not addition.

Fix

int area = length * width;

Tags
Our website uses cookies to enhance your experience. Learn More
Accept !