What is the difference between a compile-time error and a runtime error in Java, and what does the compiler actually catch for you?
A compile-time error is one the compiler refuses to produce bytecode for. A runtime error is one that compiles cleanly and only misbehaves once the code executes. The dividing line is not about severity — it is about whether the compiler can prove the problem at translation time.
javac catches a lot: type mismatches, missing returns on a value-returning method, unassigned local variables, unreachable statements, misspelled method names, arguments that do not match any overload, and the use of a variable before its definite assignment point. It also catches a small class of runtime-looking errors statically, such as division by a literal zero, which it rejects outright.
public class Main {
public static void main(String[] args) {
int x = 10;
int y = zero();
System.out.println("this compiles fine, but blows up at run time:");
try {
System.out.println(x / y);
} catch (ArithmeticException e) {
System.out.println("caught: " + e.getClass().getSimpleName()
+ " - " + e.getMessage());
}
String s = null;
try {
System.out.println(s.length());
} catch (NullPointerException e) {
System.out.println("caught: " + e.getClass().getSimpleName());
}
}
static int zero() {
return 0;
}
}Note why the divisor is produced by a method rather than written as a literal: a literal zero is a compile-time constant, so javac would reject the program before it ever ran, which would not illustrate the point. Once the zero comes from anywhere the compiler cannot see, the division is accepted and the ArithmeticException surfaces at run time. The same is true of the null dereference: the compiler has no idea that s is null because the assignment is two lines above, so it happily compiles a call to length on it.
The practical takeaway for interviews: compilation guarantees type correctness, not correctness of values. Null dereferences, division by zero, array index errors, failed casts and every checked exception live entirely in the runtime category, and defensive coding plus tests are the only protection.