1. Overview
In this tutorial, we'll review what compilation errors are, and then specifically explain what the “cannot find symbol” error is and how it's caused.
2. Compile Time Errors
During compilation, the compiler analyses and verifies the code for numerous things; 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 others are forgetting imports, mismatching parentheses, or omitting the return statement
- Next, there are type-checking errors. This is a 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
- Meanwhile, there is a 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 a problem, but that it's rather an external issue
3. The “cannot find symbol” Error
The “cannot find symbol” error comes up mainly when we try to use a variable that is not defined or declared in our program.
When our code compiles, the compiler needs to verify all identifiers we have. The errror “cannot find symbol” means we're referring to something that the compiler doesn't know about.
3.1. What Can Cause “cannot find symbol” Error?
Really, there's 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 Java code consists of.
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:
- StringBiulder
- stringBuilder
- String_Builder
would all be different ways to incorrectly refer to the StringBuilder class.
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. The reason is that 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, in this case, 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 of 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 }
Now, 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.
That's because the compiler is looking for a method called texts, which there isn't one.
Actually, there's a getter method that 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 as in:
String s = String(); // should be 'new String()'
9. Package and Class Imports
Another problem is forgetting to import the class or package. For example, 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 would not 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 the situation when we want to use dates in Java. A lot of times we could import a wrong Date class, which doesn't provide 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 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 have imported the LocalDate class, we wouldn't need additional code that provides 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 which are language-specific. If a code doesn't stick to these rules, the compiler cannot 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 causing this error, will make solving it very easy and fast.