Parsing: (07) Syntax vs. Semantic Errors

The formal definition of the difference

In Java, there is a rule final variables cannot be changed after initial assignment. For example:

Bad CodeCompile error
(not a syntax error though)
public class Bad {
    private final int foo=3;
    public void makeFooFive() {
	foo=5;
    }
}
$ javac Bad.java
Bad.java:4: error: cannot assign a value to final variable foo
	foo=5;
	^
1 error
$ 

Even though this error is reported by the compiler, strictly speaking, it isn’t a syntax error. Leaving off the return type of a method, leaving out a semicolon, or parentheses/braces that aren’t properly balanced are all syntax errors—but things that require subtle analysis of the relationships between remote parts of the code generally are not, stricty speaking, syntax errors.

This distinction between what is and is not, strictly speaking, a syntax error may be hard to fully understand without exploring more about grammars, productions, and ASTs.

So if you aren’t prepared to divide into those topics yet, it may sufficient for the time being to understand that there is a difference between the two.

Formal explanation of the difference

The formal difference between a syntax and semantic error is specified in terms of the context-free grammar and the AST.

It has to do with when and how the error is detected.