How to fix 'cannot find symbol' in Java

Problem:

You want to compile some Java source code (e.g. using Maven), but you get an error message like

[ERROR] /home/user/myproject/src/main/java/com/mydomain/myproject/Main.java:[123,40] cannot find symbol
[ERROR] symbol: class MyClass

Solution:

Java does not know where to find MyClass.

First, check if you have imported MyClass correctly.

If MyClass can be found in your library, you most likely are missing an import statement at the top of the file where the error occurs.

If, on the other hand, MyClass is imported from an external library, check if:

If you don’t know in which library you can find a certain symbol in, see our post [To be done].

What exactly are ‘symbols’?

The concept and term of a symbol is used in many different programming languages. Basically it means ‘a name that refers to something declared somewhere else in more detail’.

Therefore, if you encounter error messages like ‘cannot find symbol’, the compiler is trying to tell you: “I don’t know what that name refers to”.

Example:

When you declare a class in Java, e.g.

class MyClass {
    /* Your code goes here ! */
}

you can later refer to that class by its name, MyClass, e.g. in

MyClass class = new MyClass();

In that line of code, MyClass is used symbolically to refer to the full class declaration (class MyClass { /* ... */}) which we listed before.

Hence, MyClass is used as a symbol to refer to your previous (full) declaration of MyClass.

If the name MyClass, however, has no associated full declaration, the compiler will tell you ‘cannot find symbol’.