Common syntax errors in Java and tips on how to fix them

In this post, you will find some of the most common syntax errors in Java and tips on how to fix them. Most of these errors are common to all programming languages.

Here, you will only find the errors and possible ways on how to fix them. For you to have a better understanding of what syntax errors are and how to approach them, you can read this article.

Table of Contents

Common syntax error: Cannot resolve symbol X

This syntax error shows that the compiler cannot find the definition of the symbol X.

If you are trying to use a variable, make sure it is defined (and initialized) before you use it.

Another situation that you can find this error is when you forget to write the quotes to specify a string. So, if you are trying to use a string in the place the error is showing, make sure it is between quotes (“sample string”).

Java syntax error example
Java syntax error example

Another common case when you can get the error “Cannot resolve symbol X” is if you are trying to use a type that the compiler cannot find. See the example below.

common syntax error: cannot resolve symbol X

Every time that the compiler tells you that it cannot resolve a symbol that you are trying to use as a type (to declare a variable or a parameter) you have two choices:

  • Tell the compiler where to find the class, usually using an import statement, like this one: import java.io.File;
  • Create the type, usually through a class definition.

Common syntax error: ‘X’ expected

Two examples of this common syntax error are:

  • ‘;’ expected
  • ‘)’ expected

What this error means is that the compiler was expecting X (in the examples above ‘;’ or ‘,’), but you wrote (or just missed to write ) something different.

common syntax error: ';' expected

Incompatible types syntax error

This syntax error is very common in beginners. In compiled programming languages like Java, you can only assign values to compatible variables.

Compatible means that they have the same type or, they have types that can be automatically converted by the compiler.

In the example below you can see that in Java, you cannot assign a double to an integer variable. Some programming languages might do the conversion automatically, but if you see the error below, the fix is simple. Just change the type of the variable ‘a’, or assign an integer value instead of a double one (5.5).

common syntax error: incompatible types

If you are stuck with a syntax error and don’t how to fix it, leave a comment below and I’ll add it to this list so more beginners can benefit from it. Especially while writing the first programs.

H@ppy coding!