1. Overview

In this tutorial, we’ll review what compilation errors are. Then we’ll specifically explain the “cannot find symbol” error and how it’s caused.

2. Compile Time Errors

During compilation, the compiler analyses and verifies the code for numerous things, such as reference types, type casts, and method declarations, to name a few. This part of the compilation process is important, since during this phase we’ll get a compilation error.

Basically, there are three types of compile-time errors:

  • We can have syntax errors. One of the most common mistakes any programmer can make is forgetting to put the semicolon at the end of the statement. Some other mistakes include forgetting imports, mismatching parentheses, or omitting the return statement.
  • Next, there are type-checking errors. This is the process of verifying type safety in our code. With this check, we’re making sure that we have consistent types of expressions. For example, if we define a variable of type int, we should never assign a double or String value to it.
  • Finally, there’s the possibility that the compiler crashes. This is very rare, but it can happen. In this case, it’s good to know that our code might not be the problem, and that it’s an external issue instead.

3. The “cannot find symbol” Error

The “cannot find symbol” error comes up mainly when we try to use a variable that’s not defined or declared in our program.

When our code compiles, the compiler needs to verify all the identifiers we have. The error cannot find symbol” means we’re referring to something that the compiler doesn’t know about.

3.1. What Can Cause the “cannot find symbol” Error?

There’s really only one cause; the compiler couldn’t find the definition of a variable we’re trying to reference.

But there are many reasons why this happens. To help us understand why, let’s remind ourselves what our Java source code consists of:

  • Keywords: true, false, class, while
  • Literals: numbers and text
  • Operators and other non-alphanumeric tokens: -, /, +, =, {
  • Identifiers: main, Reader, i, toString, etc.
  • Comments and whitespace

4. Misspelling

The most common issues are all spelling-related. If we recall that all Java identifiers are case-sensitive, we can see that the following would all be different ways to incorrectly refer to the StringBuilder class:

  • StringBiulder
  • stringBuilder
  • String_Builder

5. Instance Scope

This error can also be caused when using something that was declared outside of the scope of the class.

For example, let’s say we have an Article class that calls a generateId method:

public class Article {
    private int length;
    private long id;

    public Article(int length) {
        this.length = length;
        this.id = generateId();
    }
}

But we declare the generateId method in a separate class:

public class IdGenerator {
    public long generateId() {
        Random random = new Random();
        return random.nextInt();
    }
}

With this setup, the compiler will give a “cannot find symbol” error for generateId on line 7 of the Article snippet. This is because the syntax of line 7 implies that the generateId method is declared in Article.

Like in all mature languages, there’s more than one way to address this issue, but one way would be to construct IdGenerator in the Article class and then call the method:

public class Article {
    private int length;
    private long id;

    public Article(int length) {
        this.length = length;
        this.id = new IdGenerator().generateId();
    }
}

6. Undefined Variables

Sometimes we forget to declare the variable. As we can see from the snippet below, we’re trying to manipulate the variable we haven’t declared, which in this case is text:

public class Article {
    private int length;

    // ...

    public void setText(String newText) {
        this.text = newText; // text variable was never defined
    }
}

We solve this problem by declaring the variable text of type String:

public class Article {
    private int length;
    private String text;
    // ...

    public void setText(String newText) {
        this.text = newText;
    }
}

7. Variable Scope

When a variable declaration is out of scope at the point we tried to use it, it’ll cause an error during compilation. This typically happens when we work with loops.

Variables inside the loop aren’t accessible outside the loop:

public boolean findLetterB(String text) {
    for (int i=0; i < text.length(); i++) {
        Character character = text.charAt(i);
        if (String.valueOf(character).equals("b")) {
            return true;
        }
        return false;
    }

    if (character == "a") {  // <-- error!
        ...
    }
}

The if statement should go inside the for loop if we need to examine characters more:

public boolean findLetterB(String text) {
    for (int i = 0; i < text.length(); i++) {
        Character character = text.charAt(i);
        if (String.valueOf(character).equals("b")) {
            return true;
        } else if (String.valueOf(character).equals("a")) {
            ...
        }
        return false;
    }
}

8. Invalid Use of Methods or Fields

The “cannot find symbol” error will also occur if we use a field as a method or vice versa:

public class Article {
    private int length;
    private long id;
    private List<String> texts;

    public Article(int length) {
        this.length = length;
    }
    // getters and setters
}

If we try to refer to the Article’s texts field as if it were a method:

Article article = new Article(300);
List<String> texts = article.texts();

Then we’d see the error.

This is because the compiler is looking for a method called texts, and there isn’t one.

Actually, there’s a getter method we can use instead:

Article article = new Article(300);
List<String> texts = article.getTexts();

Mistakenly operating on an array rather than an array element is also an issue:

for (String text : texts) {
    String firstLetter = texts.charAt(0); // it should be text.charAt(0)
}

And so is forgetting the new keyword:

String s = String(); // should be 'new String()'

9. Package and Class Imports

Another problem is forgetting to import the class or package, like using a List object without importing java.util.List:

// missing import statement: 
// import java.util.List

public class Article {
    private int length;
    private long id;
    private List<String> texts;  <-- error!
    public Article(int length) {
        this.length = length;
    }
}

This code won’t compile, since the program doesn’t know what List is.

10. Wrong Imports

Importing the wrong type, due to IDE completion or auto-correction is also a common issue.

Think of a scenario where we want to use dates in Java. A lot of times, we could import a wrong Date class, which doesn’t provide the same methods and functionalities as other date classes that we might need:

Date date = new Date();
int year, month, day;

To get the year, month, or day for java.util.Date, we also need to import the Calendar class and extract the information from there.

Simply invoking getDate() from java.util.Date won’t work:

...
date.getDay();
date.getMonth();
date.getYear();

Instead, we use the Calendar object:

...
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);

However, if we’ve imported the LocalDate class, we won’t need additional code to provide us the information we need:

...
LocalDate localDate=date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
month = localDate.getMonthValue();
day = localDate.getDayOfMonth();

11. Conclusion

Compilers work on a fixed set of rules that are language-specific. If a code doesn’t stick to these rules, the compiler can’t perform a conversion process, which results in a compilation error. When we face the “cannot find symbol” compilation error, the key is to identify the cause.

From the error message, we can find the line of code where the error occurs, and which element is wrong. Knowing the most common issues that cause this error will make solving it quick and easy.