Chapter 3b - Errors
Syntax error: Syntax errors are mistakes that a developer/user can do while writing the code. Examples of syntax errors are missing commas, quotes or spelling errors.
Example Syntax Errorβ
System.out.print(" I Love Java ");// This line is correct
system.out.print(" I Love Java ");//Syntax Error as 's' of "system" is in lowercase.
Logical Error: A logical error is a bug in a program that causes it to produce wrong or unintended result. However, the program compiles and runs without showing an error on the console.
Example Logical Errorβ
class Main {
public static void main(String args[]){
int a = 20;
int b = 0;
int result=a/b;// it is logical error as program will compile and throw
} // error at runtime i.e. java.lang.ArithmeticException: / by zero
}
Mini quiz β spot the error typeβ
Syntax vs logical errors
1 / 3System.out.println("Hi") (missing the closing semicolon) is an example of a
Pick an answer to see if you are right.
Chapter summaryβ
Key takeaways
- A syntax error breaks Java's grammar rules (missing semicolons, wrong capitalization, mismatched braces) β the compiler catches these before your program ever runs.
- A logical error compiles and runs fine, but produces the wrong answer β these are the hardest to catch because Java gives you no error message.
- Some logical mistakes (like dividing by zero) surface as a runtime exception, which at least tells you where things went wrong, even though the compiler could not catch it in advance.
- Reading the exact wording of a compiler error (and the line number it points to) is the fastest way to fix a syntax error.
Exercisesβ
Activity: Fix the syntax error
The starter code below is missing a semicolon. Fix it so it compiles and prints Ready.