In Java, errors are problems that occur during the execution or compilation of a program. They can be broadly categorized into three main types:
- Compile-time Errors
These errors occur when you try to compile the program — before it runs.
They are usually syntax or semantic errors detected by the Java compiler (javac).
Examples:
- Missing semicolon (;)
- Using an undeclared variable
- Misspelling a keyword
- Type mismatch
Example Code:
public class Example {
public static void main(String[] args) {
int a = 5
System.out.println(a);
}
}
Error: Missing semicolon (;) → Compile-time error
- Runtime Errors
- These occur while the program is running, after successful compilation.
- They cause the program to crash or behave unexpectedly.
Examples:
- Dividing by zero → ArithmeticException
- Accessing invalid array index → ArrayIndexOutOfBoundsException
- Null object access → NullPointerException
- File not found → FileNotFoundException
Example Code:
public class Example {
public static void main(String[] args) {
int a = 10 / 0;
System.out.println(a);
}
}
Error: ArithmeticException: / by zero → Runtime error
- Logical Errors
- These occur when the program runs successfully but produces the wrong output.
- The compiler and runtime won’t catch them — they are human mistakes in logic.
Examples:
- Using the wrong formula
- Incorrect loop conditions
- Wrong variable used in calculation
Example Code:
public class Example {
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("Sum = " + (a - b)); // Logical mistake
}
}
Output: Sum = 5 → Incorrect result due to logic error
Top comments (0)