Cannot find symbol java ошибка

Java Cannot find symbol error is a commonly occurring error in the Java compilation process. Find out its causes and ways to resolve it.

Symbols and Symbol Table

Before diving into the details of the “cannot find a symbol” error, here is a brief introduction to symbols and symbol tables in Java.  A symbol refers to an identifier in the compilation process in Java. All the identifiers used in the source code are collected into a symbol table in the lexical analysis stage. The symbol table is a very significant data structure created and maintained by the compilers to store all the identifiers and their information.

This information is entered into the symbol tables during lexical and syntax analysis which is then used in multiple phases of compilation.

From classes, variables, interfaces to methods, all of them require an identifier for declaration. During the code generation process, when these identifiers are encountered in the source code, the compiler checks for them in the symbol tables and the stored information is then used to verify the declarations, the scope of a variable, and verifying that the expression is semantically correct or not.

The compilation process usually does not go as smooth as you would think. Errors are inevitable in any development stage and one of the very commonly occurring errors during the compilation process is Java “cannot Find Symbol” Error. In this article, we will be discussing the reasons behind the occurrence of Java cannot find symbol errors and how you can resolve them.

As the name suggests, the Java cannot find symbol error occurs when a required symbol cannot be found in the symbol table. Although there can be various reasons behind this, it points to one fact the Java compiler was unable to find the symbol and its details associated with a given identifier.

As there are a variety of Java compilers available, many of them use slightly different terminologies, because of that, you can also find the “cannot find symbol” error termed as the “symbol not found” or “cannot resolve symbol” error. Besides the name, there is simply no difference between these errors.

Structure of Java Cannot Find Symbol Error

The compiler output a specific error message with the cannot find symbol error.

It contains the following two fields that indicate the missing symbol and its location:

  1. Symbol: The name and type of the identifier you are looking for.
  2. Location: The particular class in which that identifier has been referenced.

Causes of Java Cannot Find Symbol Error

We will be discussing the following most common causes of the cannot find symbol error during compilation,

  • misspelt identifiers
  • Undeclared variables
  • Out of scope references to variables and methods
  • The unintentional omission of import statements

Misspelt identifier names

This is the most common and most occurring reason behind the Java cannot find symbol error. Misspelling an existing variable, class, interface, package name or a method causes the “cannot find symbol error” as the compiler cannot recognize the symbol and identifies it as an undeclared variable. Java identifiers are also case-sensitive, so even a slight variation of an existing variable will result in this error.

See code example below:

1. public class MisspelledMethodNameExample {
2.    static int findLarger(int n1, int n2) {
3.      if (n1 > n2) return n1;
4.      if (n2 > n11) return n2;
5.      if (n2 == n11) return -1;
6.    }
7. 
8.    public static void main(String... args) {
9.       int value = findlarger(20, 4); // findlarger ≠ findLarger
10.      System.out.println(value);
11.   }
12. }
MisspelledMethodNameExample.java:9: error: cannot find symbol   
 int value = Fibonacci(20);
              ^
 symbol:   method findLarger(int, int)
  location: class MisspelledMethodNameExample

It can be easily resolved by correcting the spelling of the function in line 9.

Undeclared variables

When the Java compiler come across an identifier used in the code but it cannot be found in the symbol table, the “cannot find symbol” error is shown. The only reason behind the absence of a variable from the symbol table is that it is not declared in the code. Some new programming languages do not require explicit declaration of variables but it is mandatory in Java to always declare a variable before it is used or referenced in the source code.

The code snippet below demonstrates an undeclared variable in the code. In this case, the identifier sum on line 7, causes the Java “cannot find symbol error”.

See code example below:

1. public class UndeclaredVariableExample
2. {
3.     public static void main(String... args) {
4.        int num1 = 5;
5.        int num2 = 10;
6.        int num3 = 43;
7.        sum = (num1 + num2 + num3) // sum is not declared
8.        System.out.println(sum);
9.      }
10. }
UndeclaredVariableExample.java:7: error: cannot find symbol
    sum = (num1 + num2 + num3);
    ^
  symbol:   variable sum
  location: class UndeclaredVariableExample

UndeclaredVariableExample.java:8: error: cannot find symbol
    System.out.println(sum);
                       ^
  symbol:   variable sum
  location: class UndeclaredVariableExample
2 errors

Declaring this variable by specifying the appropriate data type can easily resolve the error.

See this corrected code below,

1. public class UndeclaredVariableExample
2. {
3.    public static void main(String args) {
4.      int num1 = 5;
5.      int num2 = 10;
6.      int num3 = 43;
7. 
8.      int sum = (num1 + num2 + num3);
9.      System.out.println(sum);
10.     }
11. }

Out of scope variable

When a Java code attempts to access a variable declared out of scope such as in a non-inherited scope the compiler will result in issuing the “cannot find symbol” error. This commonly happens when you attempt to access a variable declared inside a method or a loop, from outside of the method.

See this code example below where the “cannot find symbol” error has occurred when the counter variable which is declared inside a for loop is attempted to be accessed from out of the loop.

See code below:

1. public class OutOfScopeExample 
2. {
3.      public static void main(String args) {
4. 
5.             for (int counter = 0; counter < 100; counter++) 
6.             { … }
7. 
8. System.out.println(“Even numbers from 0 to 100”)
9.       if (counter mod 2 == 0) 
10.       {
11.            System.out.println(counter);
12.       }
13.    }
14. }
OutOfScopeVariableExample.java:9: error: cannot find symbol
    if (counter mod 2 == 0)
        ^
  symbol:   variable counter
  location: class OutOfScopeVariableExample

OutOfScopeVariableExample.java:12: error: cannot find symbol
      System.out.println(counter);
                         ^
 symbol:   variable counter
  location: class OutOfScopeVariableExample
2 errors

I can be easily resolved by just moving the if block inside the for loop (local scope).

See this code example,

1. public class OutOfScopeExample 
2. {
3.     public static void main(String... args) {
4. 
5.        for (int counter = 0; counter < 100; counter++) 
6.        { 
7.         System.out.println(“Even numbers from 0 to 100”)
8.         if (counter mod 2 == 0) 
9.        {
10.           System.out.println(counter);
11.        }
12.     }
13.   }
14. }

Missing import statement

Java allows you to use built-in classes or any imported libraries in your code to save your time by reusing the code but it requires importing them properly using the import statements at the start. Missing the import statement in your code will result in the cannot find symbol error.

java.util.Math class is utilized in the code given below but it is not declared with the “import” keyword, resulting in the “cannot find symbol error”.

See code below:

1. public class MissingImportExample {
2. 
3.     public static void main(String args) 
4.     {
5.         double sqrt19 = Math.sqrt(19);
6. System.out.println("sqrt19 = " + sqrt19);
7.    }
8. }
MissingImportExample.java:6: error: cannot find symbol
  double sqrt19 = Math.sqrt(19);
                  ^
  symbol:   class Math
  location: class MissingImportExample

Adding the missing import statement can easily solve the issue, see code below:

1. import java.util.Math;
2. 
3.    public class MissingImporExample {
4. 
5.     public static void main(String args) 
6.    {
7.       double sqrt19 = Math.sqrt(19);
8.  System.out.println("sqrt19 = " + sqrt19);
9.    }
10. }

Miscellaneous reasons

We have covered some of the main causes of the “cannot find symbol” Java error but occasionally it can also result due to some unexpected reasons. One such case is when attempting to create an object without the new keyword or an accidental semicolon at the wrong place that would terminate the statement at an unexpected point.

Also Read: Functional Interfaces In Java

Some other causes for the cannot find symbol error may include when you forget to recompile the code or you end up using the dependencies with an incompatible version of Java. Building a project with a very old JDK version can also be a reason as well as mistakenly redefining platform or library classes with the same identifier.

Conclusion

We have discussed that the “cannot find symbol Java” error is a Java compile-time error which is encountered whenever an identifier in the source code is not identified by the compiler. Similar to any other compilation error, it is very significant to understand the causes of this error, so that you can easily pinpoint the issue and address it properly.

Once you can discover the reason behind the error, it can be easily resolved as demonstrated by various examples in this article.

Содержание

  1. How to Resolve The Cannot Find Symbol Error in Java
  2. Introduction to Symbol Tables
  3. Cannot Find Symbol Error
  4. What Causes the Cannot Find Symbol Error
  5. Cannot Find Symbol vs Symbol Not Found vs Cannot Resolve Symbol
  6. Cannot Find Symbol Error Examples
  7. Undeclared variable
  8. Ошибка компиляции “Не найти символ”
  9. 1. Обзор
  10. 2. Ошибки времени компиляции
  11. 3. Ошибка “не может найти символ”
  12. 3.1. Что может вызвать ошибку «не может найти символ»?
  13. 4. Опечатка
  14. 5. Сфера применения экземпляра
  15. 6. Неопределенные переменные
  16. 7. Переменный охват
  17. 8. Недействительное использование методов или полей
  18. 9. Импорт пакетов и классов
  19. 10. Неправильный импорт
  20. 11. Заключение
  21. The “Cannot find symbol” Compilation Error
  22. Symbols and Symbol Table
  23. Cannot Find Symbol Error
  24. Structure of Java Cannot Find Symbol Error
  25. Causes of Java Cannot Find Symbol Error
  26. Misspelt identifier names
  27. Undeclared variables
  28. Out of scope variable
  29. Missing import statement
  30. Miscellaneous reasons
  31. Conclusion

How to Resolve The Cannot Find Symbol Error in Java

Table of Contents

Introduction to Symbol Tables

Symbol tables are an important data structure created and maintained by compilers to store information associated with identifiers [1] in a given source code. This information is entered into the symbol tables during lexical and syntax analysis and is used in the later phases of compilation. As the declarations of classes, interfaces, variables, and methods are processed, their identifiers are bound to corresponding entries in the symbol tables. When uses of these identifiers are encountered in the source code, the compiler looks them up in the symbol tables and relies on this information for things such as verifying that a variable has been declared, determining the scope of a variable, and verifying that an expression is semantically correct with type checking. Symbol tables are also used for code generation and optimization [2].

A simplified representation of a symbol table entry (or simply, a symbol) in Java has the following format: . Given a global variable declaration like final double ratio; the corresponding symbol would then be .

Cannot Find Symbol Error

As its name implies, the cannot find symbol error refers to a symbol which cannot be found. While there are multiple ways and reasons this can occur, they all boil down to the fact that the Java compiler is unable to find the symbol associated with a given identifier.

The message produced by the compiler for the cannot find symbol error includes two additional fields:

  • “symbol”—the name and type of the referenced identifier; and
  • “location”—the specific class in which the identifier has been referenced.

What Causes the Cannot Find Symbol Error

The most common triggers for the cannot find symbol compile-time error include:

  • missing variable and method declarations;
  • out-of-scope references to variables and methods;
  • misspelled identifiers; and
  • omitted import statements.

Cannot Find Symbol vs Symbol Not Found vs Cannot Resolve Symbol

As different Java compilers use slightly different terminology, the cannot find symbol error can also be found under the terms symbol not found and cannot resolve symbol . Besides the naming, there is no difference between what these terms stand for.

Cannot Find Symbol Error Examples

Undeclared variable

When the Java compiler encounters a use of an identifier which it cannot find in the symbol table, it raises the cannot find symbol error. Consequently, the most common occurrence of this error is when there is a reference to an undeclared variable. Unlike some other languages that don’t require explicit declaration of variables [3], or may allow declaring a variable after it has been referenced (via hoisting [4]), Java requires declaring a variable before it can be used or referenced in any way.

Fig. 1(a) shows how an undeclared variable, in this case the identifier average on line 9, results in two instances of the cannot find symbol error, at the positions where they appear in the code. Declaring this variable by specifying its data type (or, alternatively, inferring its type with the var keyword in Java 10+) resolves the issue (Fig. 1(b)).

Источник

Ошибка компиляции “Не найти символ”

Просмотрите, что такое ошибки компиляции, а затем конкретно объясните, что такое ошибка «не может найти символ» и как она вызвана.

Автор: baeldung
Дата записи

1. Обзор

В этом учебнике мы рассмотрим, что такое ошибки компиляции, а затем конкретно объясним, что такое ошибка «не может найти символ» и как она вызвана.

2. Ошибки времени компиляции

Во время компиляции компилятор анализирует и проверяет код на многие вещи; типы ссылок, слепки типов и объявления методов, чтобы назвать несколько. Эта часть процесса компиляции важна, так как на этом этапе мы получим ошибку компиляции.

В основном существует три типа ошибок времени компиляции:

  • У нас могут быть синтаксисные . Одна из наиболее распространенных ошибок, которые может сделать любой программист, это забыть поставить заоколонку в конце заявления; некоторые другие забывают импорт, несоответствие скобки, или опуская заявление о возвращении
  • Далее, естьошибки проверки типов. Это процесс проверки безопасности типов в нашем коде. С помощью этой проверки мы убеждаемся, что у нас есть последовательные типы выражений. Например, если мы определяем переменную типа int , мы никогда не должны назначать двойной или Струнные значение для него
  • Между тем, существует вероятность того, что компилятор . Это очень редко, но это может произойти. В этом случае хорошо знать, что наш код не может быть проблемой, но что это скорее внешняя проблема

3. Ошибка “не может найти символ”

Ошибка “не может найти символ” возникает в основном, когда мы пытаемся использовать переменную, которая не определена или объявлена в нашей программе.

Когда наш код компилирует, компилятор должен проверить все идентификаторы, которые у нас есть. Ошибка “не может найти символ” означает, что мы ссылаясь на то, что компилятор не знает о .

3.1. Что может вызвать ошибку «не может найти символ»?

Действительно, есть только одна причина: Компилятор не смог найти определение переменной, на которую мы пытаемся ссылаться.

Но, Есть много причин, почему это происходит. Чтобы помочь нам понять, почему, давайте напомним себе, из чего состоит Java-код.

Наш исходный код Java состоит из:

  • Ключевые слова: правда, ложь, класс, в то время как
  • Буквально: цифры и текст
  • Операторы и другие не-альфа-токены: -,/,
  • Идентификаторы: основные , Читатель , Я , toString и так далее.
  • Комментарии и белое пространство

4. Опечатка

Наиболее распространенные вопросы связаны с орфографией. Если мы вспомним, что все идентификаторы Java чувствительны к случаям, мы можем видеть, что:

все это будет по-разному способы неправильно ссылаться на Стрингбилдер класс.

5. Сфера применения экземпляра

Эта ошибка также может быть вызвана при использовании чего-то, что было объявлено вне сферы действия класса.

Допустим, у нас есть Статья класс, который вызывает generateId метод:

Но, мы объявляем generateId метод в отдельном классе:

С помощью этой настройки компилятор даст ошибку “не может найти символ” для generateId на линии 7 Статья обрезок. Причина в том, что синтаксис строки 7 подразумевает, что generateId метод объявляется в Статья .

Как и во всех зрелых языках, существует несколько способов решения этой проблемы. Но, один из способов было бы построить ИдГенератор в Статья класса, а затем вызвать метод:

6. Неопределенные переменные

Иногда мы забываем объявить переменную. Как мы видим из фрагмента ниже, мы пытаемся манипулировать переменной мы не объявили, в данном случае, текстовые :

Мы решаем эту проблему, объявляя переменную текстовые типа Струнные :

7. Переменный охват

Когда переменная декларация выходит из сферы действия в момент, когда мы пытались использовать ее, это вызовет ошибку во время компиляции. Обычно это происходит, когда мы работаем с петлями.

Переменные внутри цикла недоступны за пределами цикла:

если заявление должно идти внутри для петли если нам нужно изучить символы больше:

8. Недействительное использование методов или полей

Ошибка “не может найти символ” также произойдет, если мы используем поле в качестве метода или наоборот:

Теперь, если мы попытаемся сослаться на тексты поле, как если бы это был метод:

то мы увидим ошибку.

Это потому, что компилятор ищет метод под названием тексты , которого нет.

Вообще-то, есть getter метод, который мы можем использовать вместо этого:

Ошибка работы на массиве, а не элемент массива также является проблемой:

И так забывает новые ключевое слово, как в:

9. Импорт пакетов и классов

Другая проблема заключается в том, чтобы забыть импортировать класс или пакет. Например, с помощью Список объект без импорта java.util.List :

Этот код не будет компилироваться, так как программа не знает, что Список ош

10. Неправильный импорт

Импорт неправильного типа, из-за завершения IDE или автоматической коррекции также является общей проблемой.

Подумайте о ситуации, когда мы хотим использовать даты в Java. Много раз мы могли бы импортировать неправильный Дата класс, который не предоставляет методы и функции, как другие классы даты, которые нам могут понадобиться:

Чтобы получить год, месяц или день для java.util.Date , мы также должны импортировать Календарь класса и извлечь информацию оттуда.

Просто ссылаясь на getDate () из java.util.Date не будет работать:

Вместо этого мы используем Календарь объект:

Однако, если мы импортировали Местное класса, нам не нужен дополнительный код, который предоставляет нам информацию, в которой мы нуждаемся:

11. Заключение

Компиляторы работают над фиксированным набором правил, которые являются специфическими для языка. Если код не придерживается этих правил, компилятор не может выполнить процесс преобразования, что приводит к ошибке компиляции. Когда мы сталкиваемся с ошибкой компиляции “Не может найти символ”, ключ должен определить причину.

Из сообщения об ошибке мы можем найти строку кода, где происходит ошибка, а какой элемент неправильный. Зная наиболее распространенные проблемы, вызывающие эту ошибку, сделает ее решение очень легко и быстро.

Источник

The “Cannot find symbol” Compilation Error

Table of Contents

Symbols and Symbol Table

Before diving into the details of the “cannot find a symbol” error, here is a brief introduction to symbols and symbol tables in Java. A symbol refers to an identifier in the compilation process in Java. All the identifiers used in the source code are collected into a symbol table in the lexical analysis stage. The symbol table is a very significant data structure created and maintained by the compilers to store all the identifiers and their information.

This information is entered into the symbol tables during lexical and syntax analysis which is then used in multiple phases of compilation.

From classes, variables, interfaces to methods, all of them require an identifier for declaration. During the code generation process, when these identifiers are encountered in the source code, the compiler checks for them in the symbol tables and the stored information is then used to verify the declarations, the scope of a variable, and verifying that the expression is semantically correct or not.

The compilation process usually does not go as smooth as you would think. Errors are inevitable in any development stage and one of the very commonly occurring errors during the compilation process is Java “cannot Find Symbol” Error. In this article, we will be discussing the reasons behind the occurrence of Java cannot find symbol errors and how you can resolve them.

Cannot Find Symbol Error

As the name suggests, the Java cannot find symbol error occurs when a required symbol cannot be found in the symbol table. Although there can be various reasons behind this, it points to one fact the Java compiler was unable to find the symbol and its details associated with a given identifier.

As there are a variety of Java compilers available, many of them use slightly different terminologies, because of that, you can also find the “cannot find symbol” error termed as the “symbol not found” or “cannot resolve symbol” error. Besides the name, there is simply no difference between these errors.

Structure of Java Cannot Find Symbol Error

The compiler output a specific error message with the cannot find symbol error.

It contains the following two fields that indicate the missing symbol and its location:

  1. Symbol: The name and type of the identifier you are looking for.
  2. Location: The particular class in which that identifier has been referenced.

Causes of Java Cannot Find Symbol Error

We will be discussing the following most common causes of the cannot find symbol error during compilation,

  • misspelt identifiers
  • Undeclared variables
  • Out of scope references to variables and methods
  • The unintentional omission of import statements

Misspelt identifier names

This is the most common and most occurring reason behind the Java cannot find symbol error. Misspelling an existing variable, class, interface, package name or a method causes the “cannot find symbol error” as the compiler cannot recognize the symbol and identifies it as an undeclared variable. Java identifiers are also case-sensitive, so even a slight variation of an existing variable will result in this error.

See code example below:

It can be easily resolved by correcting the spelling of the function in line 9.

Undeclared variables

When the Java compiler come across an identifier used in the code but it cannot be found in the symbol table, the “cannot find symbol” error is shown. The only reason behind the absence of a variable from the symbol table is that it is not declared in the code. Some new programming languages do not require explicit declaration of variables but it is mandatory in Java to always declare a variable before it is used or referenced in the source code.

The code snippet below demonstrates an undeclared variable in the code. In this case, the identifier sum on line 7, causes the Java “cannot find symbol error”.

See code example below:

Declaring this variable by specifying the appropriate data type can easily resolve the error.

See this corrected code below,

Out of scope variable

When a Java code attempts to access a variable declared out of scope such as in a non-inherited scope the compiler will result in issuing the “cannot find symbol” error. This commonly happens when you attempt to access a variable declared inside a method or a loop, from outside of the method.

See this code example below where the “cannot find symbol” error has occurred when the counter variable which is declared inside a for loop is attempted to be accessed from out of the loop.

See code below:

I can be easily resolved by just moving the if block inside the for loop (local scope).

See this code example,

Missing import statement

Java allows you to use built-in classes or any imported libraries in your code to save your time by reusing the code but it requires importing them properly using the import statements at the start. Missing the import statement in your code will result in the cannot find symbol error.

java.util.Math class is utilized in the code given below but it is not declared with the “import” keyword, resulting in the “cannot find symbol error”.

See code below:

Adding the missing import statement can easily solve the issue, see code below:

Miscellaneous reasons

We have covered some of the main causes of the “cannot find symbol” Java error but occasionally it can also result due to some unexpected reasons. One such case is when attempting to create an object without the new keyword or an accidental semicolon at the wrong place that would terminate the statement at an unexpected point.

Also Read: Functional Interfaces In Java

Some other causes for the cannot find symbol error may include when you forget to recompile the code or you end up using the dependencies with an incompatible version of Java. Building a project with a very old JDK version can also be a reason as well as mistakenly redefining platform or library classes with the same identifier.

Conclusion

We have discussed that the “cannot find symbol Java” error is a Java compile-time error which is encountered whenever an identifier in the source code is not identified by the compiler. Similar to any other compilation error, it is very significant to understand the causes of this error, so that you can easily pinpoint the issue and address it properly.

Once you can discover the reason behind the error, it can be easily resolved as demonstrated by various examples in this article.

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.

Источник

I make this call to a static singleton instance from the class GameManager.java.

HUD.getInstance().update(timeDelta);

HUD.java contains the HUD class as well as two other related classes, HUDTextElement and HUDElement. All the classes are in the same root path ../src/org/mypackage.

However, when compiling this project in IntelliJ I get cannot find Symbol HUD on the line I make the HUD.getInstance() call.

This exact same code compiles just fine in Eclipse, any idea what the problem is?

2240's user avatar

2240

1,5272 gold badges10 silver badges28 bronze badges

asked Aug 26, 2012 at 16:50

joe's user avatar

2

Select Build->Rebuild Project will solve it

answered Dec 10, 2016 at 5:34

tiboo's user avatar

tibootiboo

7,7496 gold badges31 silver badges42 bronze badges

9

I had the same problem and fixed it by clicking File>Invalidate caches/ restart

answered May 10, 2016 at 10:03

ganninu93's user avatar

ganninu93ganninu93

1,48114 silver badges24 bronze badges

4

I had the same problem, and turns out I had never completely compiled the fresh project. So right-clicking and selecting Compile» (shift-cmd-F9 on mac) fixed it. It seems the compile on save does not ‘see’ non-compiled files.

Marking the src folder as source did not help in my case.

answered Mar 6, 2013 at 9:13

Sjoerd K's user avatar

Sjoerd KSjoerd K

6995 silver badges2 bronze badges

0

This is likely to be your ../src folder is not marked as a «source» folder in Intellij IDEA, so it doesn’t know to look there to find your class. You can right click the folder in the project explorer and choose «mark as source folder» to fix this.

answered Aug 26, 2012 at 16:54

Paul Sanwald's user avatar

Paul SanwaldPaul Sanwald

10.7k6 gold badges43 silver badges59 bronze badges

5

I was getting the same «cannot find symbol» error when I did Build -> Make Project. I fixed this by deleting my Maven /target folder, right clicking my project module and doing Maven -> Reimport, and doing Build -> Rebuild Project. This was on IntelliJ Idea 13.1.5.

It turns out the Maven -> Reimport was key, since the problem resurfaced a few times before I finally did that.

answered Oct 13, 2014 at 18:43

Christian Wilkie's user avatar

Christian WilkieChristian Wilkie

3,5935 gold badges33 silver badges48 bronze badges

1

For me — I tried these steps(Invalidate Cache & Restart, Maven Reimport)) but they didn’t work. So I deleted the .idea, .settings, and .project folder and tried — it worked.

answered Oct 25, 2019 at 22:38

R11G's user avatar

R11GR11G

1,8618 gold badges26 silver badges37 bronze badges

3

I faced the same problem, and there are a lot of solutions given in the answer, trying all these solutions took me quite some time, so here I would like to propose a methodical approach if you get this error.

Check for the following things, create/update if something is missing

  1. src folder is marked as the source folder
  2. .imls files are present
  3. Annotation processing is enabled
  4. If you recently used @UtilityClass then it can also be the reason, Bug Link

If everything is fine, you can try following solutions in given order

  1. Recompile the file/module

  2. If that didn’t fix the issue, try refreshing maven dependency and building the project using Maven -> Reimport and Build -> Rebuild Project

  3. Try mvn clean install -DskipTests

  4. Try invalidating the IntelliJ cache and restarting the IDE, using File > Invalidate caches/ restart

  5. Delete the .idea folder and reimport the project

Credit and Thanks to everyone who answered this question, you can refer to their answers for more description regarding each point.

answered Jun 18, 2020 at 11:10

Deepak Patankar's user avatar

Deepak PatankarDeepak Patankar

2,8412 gold badges16 silver badges31 bronze badges

1

Thanks for the help so far, turns out the fix was to compile HUD.java first (right click on the file-> Compile HUD.java). After compiling the java file the rest of the project could be compiled without any problems.

I don’t really know why this fixed it, or why IntelliJ wouldn’t do this automatically, but root error seems it has to do with IntelliJ not correctly handling having multiple classes in a single .java file.

answered Aug 26, 2012 at 18:09

joe's user avatar

joejoe

2,0492 gold badges15 silver badges13 bronze badges

2

This happened to me when I deleted a folder and then copy-pasted it back to the project.

Right-click project folder -> Rebuild worked for me.

answered Aug 9, 2019 at 8:25

Tomas Lukac's user avatar

Tomas LukacTomas Lukac

1,7532 gold badges17 silver badges35 bronze badges

I solved this problem doing right click on Java Folder and Rebuild

IntelliJ screenshot

answered Nov 22, 2021 at 12:01

Federico Traiman's user avatar

Federico TraimanFederico Traiman

1,1011 gold badge13 silver badges18 bronze badges

I had to right-click the project, and select «Reimport» under the «Run Maven» submenu.

answered Sep 19, 2018 at 19:58

bitsmcgee77's user avatar

bitsmcgee77bitsmcgee77

3813 silver badges10 bronze badges

I use maven in my project. For some reason IntelliJ was giving me these kind of wierd errors. I ran mvn clean and tried a resync and these errors disappeared.

answered Apr 25, 2013 at 19:58

Moiz Raja's user avatar

Moiz RajaMoiz Raja

5,5226 gold badges39 silver badges51 bronze badges

1

recompiling the main Application.java class did it for me, right click on class > Recompile

answered Jan 20, 2019 at 6:28

Taranjit Kang's user avatar

Taranjit KangTaranjit Kang

2,4723 gold badges19 silver badges40 bronze badges

If you are using Lombok, make sure you have enabled annotation processing.

answered Feb 3, 2020 at 15:46

Muzammil's user avatar

MuzammilMuzammil

3881 gold badge3 silver badges18 bronze badges

For me was a problem with Lombok, because it requires Annotation Processing to be enabled. You can find this checkbox on Settings > Build > Compiler > Annotation Processors

answered Feb 27, 2020 at 9:09

RaulDanielPopa's user avatar

RaulDanielPopaRaulDanielPopa

1,1311 gold badge7 silver badges2 bronze badges

1

I know this is an old question, but as per my recent experience, this happens because the build resources are either deleted or Idea cannot recognize them as the source.

Wherever the error appears, provide sources for the folder/directory and this error must be resolved.

Sometimes even when we assign sources for the whole folder, individual classes might still be unavailable. For novice users simple solution is to import a fresh copy and build the application again to be good to go.

It is advisable to do a clean install after this.

answered Jul 14, 2014 at 15:41

Matt's user avatar

MattMatt

1713 silver badges13 bronze badges

I know this thread is old but, another solution was to run

$ mvn clean install -Dmaven.test.skip=true

And on IntelliJ do CMD + Shift + A (mac os) -> type «Reimport all Maven projects».

If that doesn’t work, try forcing maven dependencies to be re-downloaded

$ mvn clean -U install -Dmaven.test.skip=true

answered Jul 19, 2019 at 13:23

edmar's user avatar

edmaredmar

361 silver badge5 bronze badges

1

For me, the error was coming from @RequiredArgsConstructor(onConstructor = @__(@Inject)), and the message was cannot find symbol __. The error message right above this was «java: You aren’t using a compiler supported by lombok, so lombok will not work and has been disabled».

Adding argument below in VM options worked as suggested here worked for me.

-Djps.track.ap.dependencies=false

answered May 20, 2021 at 1:31

learnerer's user avatar

learnererlearnerer

3442 silver badges16 bronze badges

For my case, the issue was with using Lombok’s experimental feature @UtilityClass in my java project in Intellij Idea, to annotate a class methods as «static». When I explicitly made each method of the class as «static» instead of using the annotation, all the compilation issues disappeared.

answered Oct 2, 2018 at 20:20

Ram's user avatar

RamRam

1911 gold badge2 silver badges12 bronze badges

Since this is the first hit on Google searching for «intelliJ cannot find symbol» error, I’m gonna throw in my solution as well.

The problem for me was that my project originated from Eclipse, and some files contained dependency on classes that were generated in src/generated-sources by specifications in pom.xml. For some reason, this was not properly executed when I first opened the project and rebuilding/re-importing did not help, so the files were never generated.

The solution was to right-click on the module, and select Maven -> Generate Sources and Update Folders That solved the issue and I could compile.

answered May 30, 2016 at 9:10

Araklaj's user avatar

Make sure the source file of the java class you are trying to refer to has a .java extension. It was .aj in my case (I must have hit «Create aspect» instead of «Create class» when creating it). IntelliJ shows the same icon for this file as for «normal» class, but compiler does not see it when building.

Changing .aj to .java fixed it in my case.

answered Jun 14, 2016 at 21:23

fracz's user avatar

fraczfracz

20k17 gold badges104 silver badges148 bronze badges

Sometimes the class you want is in the test source directory. Happened to me, anyway…

answered Feb 7, 2017 at 1:15

Sam Barnum's user avatar

Sam BarnumSam Barnum

10.5k3 gold badges54 silver badges60 bronze badges

I was having the same problem except that I was importing the classes for which dependencies were not resolving somehow. I refreshed maven projects, Rebuild Project. It still did not resolve.
Looks like IntelliJ was caching something incorrectly.
I restarted IntelliJ and that resolved the dependencies. I guess it cleared the cache somehow.

answered Aug 20, 2018 at 13:52

MoneeK's user avatar

I’m seeing a lot of answers proposing a build or a re-build but just in case this don’t fix your problem just notice that IDEA can detect a method but it will not compile in case you have a new before as it will be expecting the instance.

enter image description here

answered Feb 13, 2020 at 14:19

Carlos López Marí's user avatar

In my case, I had a problem with finding a class from another module. In pom.xml, I just had this dependency with <scope>compile</scope> specified. Removing this line helped.

answered Mar 24, 2020 at 14:52

nikiforovpizza's user avatar

nikiforovpizzanikiforovpizza

4891 gold badge7 silver badges13 bronze badges

1

This works for me, say class A depends on class B(and class c, d etc) but the error throws on class A which does not have any errors. So I try to compile class A alone first ->it shows error on the package of class B. So tried to compile whole package of class B. Now it throws which is the exact error class(on my case class B had error). Usually Intellj shows the exact error class with line number when compile/build. On some occasions it throws error in wrong place/class. Have a try.

answered Jan 23, 2021 at 13:43

Raja aar's user avatar

Once when Maven Reimport, Rebuild Project, Invalidate caches didn’t help I deleted subfolders artifacts and libraries from .idea folder, not whole one, so I saved custom project settings.

…and when nothing written here helps check idea.log file as posted here

answered Mar 4, 2021 at 18:04

Sergei Ryzhov's user avatar

I tried everything and nothing worked for me. So, after wasting a couple of hours, I decided to upgrade the IntelliJ idea version, and finally, it worked!

answered Aug 5, 2021 at 10:20

AConsumer's user avatar

AConsumerAConsumer

2,3312 gold badges21 silver badges32 bronze badges

Delete all the contents inside ~/.m2 . Start intellij-idea.
(Using IntelliJ IDEA 2021.3 (Community Edition))

answered Mar 15, 2022 at 16:49

dr0i's user avatar

dr0idr0i

2,3001 gold badge18 silver badges35 bronze badges

I know this is old, but for anyone else, make sure that the class that’s missing is in the same package as the class where you get the error/where your calling it from.

answered Nov 2, 2015 at 0:28

Pasha Shestakov's user avatar

1

When a user refers to a variable that hasn’t been declared in the application, the “can’t find symbol” error occurs. To put it another way, the compiler isn’t aware of the variable’s declaration. For example:

class HelloCodeunderscored {
    public static void main( String args[] ) {
      int x = 15;
      int y =1 4;
      // result is not declared. It will show an error.
      result = x * y;
    }
}

What are possible solutions to this problem?

If you ever encounter this issue, you should review the code for the following scenarios:

  • Make sure you’ve declared the variable, for example, int i = 15;. If int has not been written, the error may show.
  • Also, see if the defined variable is outside the code, for example, if it is not a member of the HelloCodeunderscored class.
  • Make sure you’re using the right case. If you declare a variable as var but access it as Var, it is an example of such a scenario.
  • Numbers, dollar signs, and hyphens are not allowed in identifier values; check for them.

Errors in Compilation Time

The compiler examines and checks the code for various things during compilation, including reference types, type casts, and method declarations, to mention a few. This stage of the compilation process is crucial since it is here that we will encounter a compilation mistake.

Compile-time mistakes can be divided into three categories:

Syntax errors

One of the most common programming errors is failing to use a semicolon at the end of a statement; other typical errors include forgetting imports, mismatching parentheses, and omitting the return statement.

Type-checking errors

This is a method of ensuring that our code is type-safe. With this check, we provide that the kinds of expressions are consistent. If we define a variable of type int, we should never assign a value of type double or String to it.

Compiler will crash

Meanwhile, there’s a chance the compiler will crash. It is exceptionally uncommon, but it does happen. In this scenario, it’s good to know that the issue isn’t with our code but with something else.

Compilers follow a set of rules that are specific to each language. If a code doesn’t follow these requirements, the compiler won’t be able to convert it, resulting in a compilation error. The key to resolving the “Cannot find symbol” compilation problem is to figure out what’s causing it.

We may deduce the line of code where the problem occurred and which element is incorrect from the error message. Knowing the most common causes of this mistake will make it easier and faster to resolve.

Symbol Tables: An Overview

Compilers construct and maintain symbol tables, which are significant data structures for storing information related to identifiers in source code. This information is placed into symbol tables during lexical and syntactic analysis and subsequently used in the compilation process.

The identifiers of classes, interfaces, variables, and methods are bound to correspond entries in the symbol tables when the declarations are processed. When these identifiers appear in source code, the compiler looks them up in the symbol tables. It uses that information to confirm that a variable has been declared, establish the variable’s scope, and do type checking to ensure that an expression is semantically correct.

Symbol tables are also employed in the creation and optimization of code. The following is a simplified representation of a symbol table entry (or simply a symbol) in Java:

<symbol name (identifier), type, scope, [attributes]>

The comparable notation for a global variable declaration, such as final double ratio, would be <ratio, double, global, [final]>.

Error: Cannot Find Symbol

As the name implies, the cannot locate symbol error refers to a symbol that you cannot find. While there are a variety of causes for this, they all boil down to the Java compiler being unable to locate the symbol associated with a given identifier.

Two more fields are included in the compiler’s message for the cannot locate symbol error:

“symbol” refers to the name and type of the referenced identifier. On the other hand, “location” refers to the class where the identifier is used.

What causes the symbol cannot be found error?

The following are the most typical causes of the cannot locate symbol compile-time error:

  • Variable and method declarations missing,
  • References to variables and methods being out of scope
  • misspelled identifiers, and
  • omitted import statements.

Symbol Not Found vs. Cannot Find Symbol vs. Cannot Resolve Symbol

The cannot find symbol issue can also be encountered under the words symbol not found and cannot resolve symbol, as different Java compilers use somewhat different wording. Apart from the names, there is no difference between the meanings of these phrases.

Examples of “Cannot Find Symbol Error.”

Some of these “Cannot find symbol error” are as follows:

Handling an undeclared variable

The cannot find symbol error is raised when the Java compiler encounters an identifier it can’t find in the symbol table. As a result, the most common cause of this error is when a reference to an undeclared variable is made. Unlike some other languages, which don’t require explicit variable declarations or may enable declaring a variable after it’s been referenced (through hoisting ), Java requires that a variable be declared before being used or referenced in any form.

Figure (a) shows how an undeclared variable, in this case, the identifier average on line 9, causes two instances of the cannot find symbol error at the code’s locations. Figure (b) resolves the issue by declaring this variable with its data type (or inferring its kind with the var keyword in Java 10+).

Figure (a)

package codeunderscored;

public class CodeUndeclaredVariable {
    public static void main(String... args) {
        int x = 16;
        int y = 20;
        int z = 42;

        averageResults = (x + y + z) / 3.0; // averageResults is not declared
        System.out.println(averageResults);
    }
}

Figure (b)

package codeunderscored;

public class UndeclaredVariable {
    public static void main(String... args) {
        int x = 16;
        int y = 20;
        int z = 42;

        double averageResults = (x + y + z) / 3.0;
        System.out.println(averageResults);
    }
}

Dealing with an Out of scope variable

The compiler throws the cannot find symbol error when a Java application tries to access a variable declared in a separate (non-inherited or non-overlapping) scope. The effort to try and have access to the variable counter on lines 17 and 18 in Figure (a), which is only available within the statement declared on line 11, demonstrates this. Figure (b) indicates that moving the counter variable outside the for loop resolves the problem.

Figure (a)

package codeunderscored;

import java.util.Arrays;
import java.util.List;

public class CodeOutOfScopeVariable {
    public static void main(String... args) {
        final List<String> strings = Arrays.asList("Hello", "Codeunderscored");
        final String searchFor = "Codeunderscored";

        for (int counter = 0; counter < strings.size(); counter++) {
            if (strings.get(counter).equals(searchFor)) {
                break;
            }
        }

        if (counter < strings.size()) {
            System.out.println("The word " + searchFor + " was found at index " +    counter);
        } else {
            System.out.println("The word " + searchFor + " wasn't found");
        }
    }
}

Figure (b)

package codeunderscored;

import java.util.Arrays;
import java.util.List;

public class CodeOutOfScopeVariable {
    public static void main(String... args) {
        final List<String> strings = Arrays.asList("Hello", "Codeunderscored");
        final String searchFor = "Codeunderscored";
        int counter;

        for (counter = 0; counter < strings.size(); counter++) {
            if (strings.get(counter).equals(searchFor)) {
                break;
            }
        }

        if (counter < strings.size()) {
            System.out.println("The word " + searchFor + " was found at index " + counter);
        } else {
            System.out.println("The word " + searchFor + " wasn't found");
        }
    }
}

Figures (a) & (b): Error and resolution for not being able to discover a symbol for an out-of-scope variable.

Method name misspelled

A cannot locate symbol error is caused by misspelling an existing method or any valid identifier. Because Java identifiers are case-sensitive, any change of an existing variable, method, class, interface, or package name, as shown in Figure (b), will result in this error.

Figure (a)

package codeunderscored;

public class CodeMisspelledMethodName {

    static int fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String... args) {
        int fibResult = Fibonacci(20); // Fibonacci ≠ fibonacci
        System.out.println(fibResult);
    }
}

Figure (b)

package codeunderscored;

public class CodeMisspelledMethodName {
    static int fibonacci(int n) {
        if (n == 0) return 0;
        if (n == 1) return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String... args) {
        int fibResult = fibonacci(20);
        System.out.println(fibResult);
    }
}

Error Figure (a) and resolution Figure (b): Cannot find the symbol for a misspelled method name

An import statement is missing

Using classes, whether from the Java platform or a library, necessitates appropriately importing them using the import statement. If you don’t, the Java compiler will complain about a symbol that can’t be found. The java.util package is used in the code sample in Figure (a). The cannot locate symbol issue arises because the list class was created without specifying the necessary import. The problem is solved by adding the missing import statement line 4 in Figure (b).

Figure (a)

package codeunderscored;

import java.util.Arrays;

public class CodeMissingImportList {
    private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");

    public static void main(String... args) {
        System.out.println(CONSTANTS);
    }
}

Figure (b)

package codeunderscored;

import java.util.Arrays;
import java.util.List;

public class CodeMissingImportList {
    private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");

    public static void main(String... args) {
        System.out.println(CONSTANTS);
    }
}

Figure (a) Error and resolution (b): Cannot find the symbol for missing import

Examples that aren’t as common

The fundamental cause of the Java error cannot locate the symbol is sometimes found in unexpected or hidden areas. It is the case when a sentence is prematurely terminated by an unintentional semicolon Figure (a) or when object creation is attempted without a correct constructor invocation, which must include the new keyword Figure 6.

Figure (a)

package codeunderscored;

public class CodeLoopScope {

public static void main(String... args) {
        int start = 1, end = 10;
        for (int i = start; i <= end; i++); {
            System.out.print(i == end ? i : i + ", ");
        }
    }
}

Figure (b)

package codeunderscored;

public class CodeLoopScope {
    public static void main(String... args) {
        int start = 1, end = 10;
        for (int i = start; i <= end; i++) {
            System.out.print(i == end ? i : i + ", ");
        }
    }
}

Unable to locate a symbol for a prematurely stopped loop Figure (a) error and Figure (b) resolution

Figure (a)

package codeunderscored;

public class CodeObjectCreation {
    public static void main(String... args) {
        String s = String("Hello Codeunderscored!");
        System.out.println(s);
    }
}

Figure (b)

package codeunderscored;

public class CodeObjectCreation {
    public static void main(String... args) {
        String s = new String("Hello Codeunderscored!");
        System.out.println(s);
    }
}

Figure (a) Error and Figure (b) Resolution for Cannot Find Symbol Constructor Call

Other reasons for the problem “can’t find symbol” include:

Here are a few instances where the “Cannot detect symbol” appears unexplainable until you investigate further.

Inability to find symbol ‘var’:

You’re presumably trying to compile source code with an older compiler or an older—source level that employs local variable type inference (i.e., a var declaration). In Java 10, the var was introduced. Check your JDK version, build files, and IDE settings (if this happens in an IDE).

You’re not compiling or recompiling anything

New Java programmers occasionally don’t grasp how the Java toolchain works or haven’t set up a repeatable “build process,” such as utilizing an IDE, Ant, Maven, Gradle, etc. In this case, the programmer may end up chasing his tail, looking for an imaginary fault that is caused by improper recompilation of the code, and so on.

Another example is when you compile and run a class with (Java 9+) java SomeClass.java. You’re likely to get “Cannot resolve symbol” errors referring to the 2nd class if the class depends on another class that you haven’t compiled (or recompiled). The other source file(s) are not compiled automatically. In addition, the new “compile and execute” mode of the java command isn’t suited for launching programs with multiple source code files.

Incorrect dependencies

If you use an IDE or a build tool that manages the build path and project dependencies, you may have made a mistake with the dependencies; for example, you may have left out a dependency or chosen the incorrect version. Check the project’s build file if you’re using a build tool (Ant, Maven, Gradle, etc.). Further, examine the project’s build path setup if you’re using an IDE.

An issue with a previous build

It’s possible that a previous build failed, so a JAR file was created with missing classes. You would usually note such failure if you were using a build tool. If you acquire JAR files from someone else, you’ll have to rely on them constructing correctly and catching mistakes.

Use tar -tvf when you need to list the suspected JAR files contents if you suspect this.

Problems with Android

When programming for Android and seeing “Cannot discover symbol” issues linked to R, keep in mind that the context.xml file defines the R symbols. Check that your context.xml file is valid and in the right location and that the R class file for it has been generated and compiled. Because Java symbols are case sensitive, the corresponding XML ids are as well.

Other symbol problems on Android are most frequently caused by the factors mentioned above, such as missing or inaccurate dependencies, wrong package names, methods or fields that don’t exist in a specific API version, spelling/typing issues, and so on.

Problems with the IDE

People have reported occasions when their IDE becomes confused, and the compiler in the IDE cannot detect a class that already exists… or vice versa. If the IDE is set up with the incorrect JDK version, it can happen.

If the IDE’s caches become out of sync with the file system, it can happen.

There are IDE-specific solutions to this. The latter could be a problem in the IDE. For example, there is a typical case of how Eclipse incorrectly handled a Maven “test” tree. That particular bug, it appears, was fixed a long time ago.

Homoglyphs

It’s possible to have identifiers that appear the same but aren’t because they contain homoglyphs if you use UTF-8 encoding for your source files. You can circumvent this by limiting the source file encoding to ASCII or Latin-1 and utilizing Java uxxxx escapes for additional characters.

Hidden System classes

We’ve seen situations when the compiler complains that substring is an unknown symbol, such as this.

String s = ...
String s1 = s.substring(1);

It turns out that the programmer had written their version of String, which lacked substring operations. It has been done with System, Scanner, and other classes in the past.

Overall, don’t use the same names as common library classes when defining your classes! You can also use fully qualified names to remedy the situation. In the preceding example, the programmer may have written:

java.lang.String s = ...

java.lang.String s1 = s.substring(1);

What should I do about these errors?

  • In general, you should start by determining what triggered the compilation mistake.
  • Examine the line in the file that the compilation error notice refers to.
  • Determine which symbol the error message is referring to.
  • Figure out why the compiler says it can’t find the symbol; check the section above!
  • Then you consider what your code is trying to communicate.
  • Subsequently, try to figure out what changes you need to make to your source code to get it to do what you want.

It’s worth noting that not every “correction” is accurate. Consider the following:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Assume the compiler says for j, “Cannot find symbol.” There are several ways we could “correct” this:

  • We suppose we could edit the inner for to for (int j = 1; j< 10; j++) – which would be correct.
  • Alternatively, we could put a declaration for j before the inner or outer for loops, which would probably be correct.
  • In the inner for loop, we could also change j to i, and that would be incorrect! and so forth. To discover the proper remedy, you must first understand what your code is attempting to accomplish.

Example: how erroneous variable scoping can result in a “Cannot find symbol” error

List<String> stringsVar = ...

for (int i = 0; i < stringsVar.size(); i++) {
    if (stringsVar.get(i).equalsIgnoreCase("fnord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

For i in the if statement, this will result in a “Cannot find symbol” problem. Even though we earlier declared i, it only applies to the for statement and its body. The if statement’s reference to i cannot see that declaration of I because it is not within the project’s scope. A suitable correction would be to place the if statement within the loop or declare I before the loop begins.)

Example: an apparently strange “Cannot find symbol” issue caused by a typo

for (int i = 0; i < 100; i++); {
    System.out.println("i is " + i);
}

It will result in a compilation error in the println call, indicating that i is missing. But (as you point out), we did declare it!

The issue is the semicolon (;) that appears before the {. In that instance, a semicolon is an empty statement according to the Java language syntax. The for loop’s body is therefore made up of the empty statement. So here’s what that code actually means:

for (int i = 0; i < 100; i++);

// The previous and following are separate statements!!

{
    System.out.println("i is " + i);
}

The preceding declaration of i in the for statement is out of scope in the block. That is because the {…} block is not the body of the for loop.

Example: A “Cannot find symbol” error produced by a typo

int tmp = ...
  
int res = tmp(a + b);

The tmp in the tmp(…) phrase is incorrect, despite the earlier declaration. The compiler will look for a tmp method, but it will not locate one. The previously specified tmp is in the variables namespace, not the methods namespace. In one of the examples we saw, the programmer had forgotten to include an operator. This is what he wanted to write:

If you’re compiling from the command line, there’s another reason why the compiler might not discover a symbol. It’s possible that you just neglected to build or recompile another class.

For instance, suppose you have two classes, Secondary and Primary, and Secondary utilizes Primary. If you’ve never compiled Primary before and run javac Secondary.java, the compiler will likely fail because it can’t find the symbol Primary.

Compile Secondary and Primary together, for example, with javac Secondary.java Primary.java or javac *.java. Better still, utilize a Java build tool such as Ant, Maven, Gradle, etc.

Conclusion

The cannot find symbol error, also known as a symbol not found and cannot resolve symbol, is a Java compile-time error that occurs when the compiler cannot figure out what an identifier in the source code refers to. As with every other compilation fault, it’s critical to figure out what’s causing it, isolate the problem, and fix it effectively.

This error is mainly caused by referring to undeclared variables and methods, such as by misspelling them or failing to import their associated package. As seen in this article, once a problem has been identified, resolving it is relatively simple.

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:

  • You have the correct version of the library. Possibly, you are using an old version of the library where MyClass is not present. This is often the case when using SNAPSHOT versions in maven since different developers might have different SNAPSHOTs so one might have issue building while another might not.
  • You are using the correct import statement (refer to the docs or the source code of the library to check if you are using the correct package.

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’.

In this article, we’ll see the reason behind the error can not find symbol or can not resolve symbol in Java So you can solve it by removing that cause. So let’s start.

A java program consists of keywords, literals, operators, comments, whitespaces, and identifiers. This error is related to identifiers (an identifier is a name that user assign to an element of a program such as a type, function, variable, namespace, or class). Because when you compile your code, the compiler needs to know about each of the identifiers that we have used, and when we put an identifier that refers to something, and the compiler doesn’t understand that so it throws the error “can not find symbol”.

Reason 1: Using an Undeclared Variable

Example:

public class Demo

{

    public static void main(String[] s)

    {

        int n1 = 10;

        int n2 = 20;

        sum = n1+n2;

        System.out.println(«Sum = «+ sum);

    }

}

Output:

Demo.java:8: error: cannot find symbol

        sum = n1+n2;

        ^

  symbol:   variable sum

  location: class Demo

In the above program, we are using the sum variable to store the sum of n1 and n2 variables and our program is throwing the error “cannot find symbol” and it is pointing to the sum variable. So we can easily solve it by declaring the sum variable before using it.

So make sure your code won’t be having this mistake.

Reason 2: Spelling Mistakes or Using Wrong Cases

Example:

public class Demo

{

    public static void main(String[] s)

    {

        int n1 = 10;

        int n2 = 20;

        int sum;

        sum = n1+n2;

        System.out.println(«Sum= «+ Sum);

    }

}

Output:

 Demo.java:10: error: cannot find symbol

             System.out.println(“Sum= “+ Sum);

                                    ^

              symbol:   variable Sum

              location: class Demo

Again this is one of the most common reasons for this error. Java is a case sensitive language which means Sum is different from the sum. So we have to use the exact name in the same case format as we have declared it to prevent this error.

Reason 3: Variable is Out of Scope

Example:

public class Demo

{

    public static void main(String[] s)

    {

        for(int i = 0; i<=10; i++)

        {

            System.out.println(«i =» + i);

        }

        System.out.println(«loop breaked at — « + i);

    }

}

Output:

Demo.java:11: error: cannot find symbol

        System.out.println(“loop breaked at – ” + i);

                                                  ^

  symbol:   variable i

  location: class Demo

1 error

So here we can see that even we have declared the variable i and still it is showing “cannot symbol error” because we have declared it inside for loop and trying to use it outside of for loop. It’s called out of scope. To prevent this make sure that your variable is defined in the same scope where you’re using it. Like in the above program to use i outside of the for loop i have declared i inside the main function.

Reason 4: Forgot to Import Class

Example:

public class Demo

{

    public static void main(String[] s)

    {

        ArrayList a = new ArrayList();  

    }

}

Output:

 error: cannot find symbol

        ArrayList a = new ArrayList();

        ^

  symbol:   class ArrayList

  location: class Demo

Here, we are using the correct spelling of ArrayList to use it. But still, it says  “cannot find symbol”. Again compiler couldn’t find the meaning of the ArrayList because ArrayList exists in a package “java.util”, so to use it we have to import ArrayList from this package. It is again a common mistake we usually do by using a class or method without importing it in our program. If you’re using an editor like visual studio code or eclipse you can fix it by hovering on the ArrayList and it will show the package to import. But if you’re using a simple text editor then you have to manually write a line at the top of your java file.

import java.util.ArrayList;

So make sure for the next time, you’ve imported all the classes that you’re using in your program.

Reason 5: Using a Method that is Undefined for the Class
Example:

import java.util.ArrayList;

public class Demo

{

    public static void main(String[] s)

    {

       String string = «the crazy programmer»;

       System.out.println(s.size());

    }

}

Output:

Demo.java:8: error: cannot find symbol

       System.out.println(s.size());

                           ^

  symbol:   method size()

  location: variable s of type String[]

1 error

Here is another example that cause the same error. Here i am trying to get the size or length of the string using size() method which is not a String class’s method. It is used to get the size of an array, not the string that’s why it is showing this error. So make sure that the methods we’re using are defined for the class or not. In the above case the right we can use length property instead of size() method to get the size of a string.

So these were some reasons when we face cannot find symbol error. I hope this article has helped you to solve this. If you have any queries or suggestions related to this article please comment below.

Query:

Please explain the following about “Cannot find symbol”, “Cannot resolve symbol” or “Symbol not found” errors (in Java).

“Cannot find symbol”, “Cannot resolve symbol” and “Symbol not found” all mean the same thing. Different Java compilers use different phraseology.

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

  • Keywords: like classwhile, and so on.
  • Literals: like truefalse42'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +={, and so on.
  • Identifiers: like ReaderitoStringprocessEquibalancedElephants, and so on.
  • Comments and whitespace.

A “Cannot find symbol” error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A “Cannot find symbol” error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn’t understand.

What can cause a “Cannot find symbol” error?

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn’t find the definition. This could be caused by a number of things. The common ones are as follows:

  • For identifiers in general:
    • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
    • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
    • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake …)
    • Perhaps you are trying to use something that was declared “somewhere else”; i.e. in a different context to where you have implicitly told the compiler to look. (A different class? A different scope? A different package? A different code-base?)
  • For identifiers that should refer to variables:
    • Perhaps you forgot to declare the variable.
    • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • For identifiers that should be method or field names:
    • Perhaps you are trying to refer to an inherited method or field that wasn’t declared in the parent / ancestor classes or interfaces.
    • Perhaps you are trying to refer to a method or field that does not exist (i.e. has not been declared) in the type you are using; e.g. "rope".push()2.
    • Perhaps you are trying to use a method as a field, or vice versa; e.g. "rope".length or someArray.length().
    • Perhaps you are mistakenly operating on an array rather than array element; e.g. String strings[] = ... if (strings.charAt(3)) { ... } // maybe that should be 'strings[0].charAt(3)'
  • For identifiers that should be class names:
    • Perhaps you forgot to import the class.
    • Perhaps you used “star” imports, but the class isn’t defined in any of the packages that you imported.
    • Perhaps you forgot a new as in: String s = String(); // should be 'new String()'
  • For cases where type or instance doesn’t appear to have the member (e.g. method or field) you were expecting it to have:
    • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
    • Perhaps you are shadowing a static or instance variable.
    • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction may have suggested java.awt.List rather than java.util.List.
    • Perhaps you are using (compiling against) the wrong version of an API.
    • Perhaps you forgot to cast your object to an appropriate subclass.
    • Perhaps you have declared your variable’s type to be a supertype of the one with the member you are looking for.

The problem is often a combination of the above. For example, maybe you “star” imported java.io.* and then tried to use the Files class … which is in java.nio not java.io. Or maybe you meant to write File … which is a class in java.io.


Here is an example of how incorrect variable scoping can lead to a “Cannot find symbol” error:

List<String> strings = ...

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a “Cannot find symbol” error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)


Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable “Cannot find symbol” error:

for (int i = 0; i < 100; i++); {
    System.out.println("i is " + i);
}

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon ( ; ) before the {. The Java language syntax defines a semicolon in that context to be an empty statement. The empty statement then becomes the body of the for loop. So that code actually means this:

for (int i = 0; i < 100; i++); 

// The previous and following are separate statements!!

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, and therefore the previous declaration of i in the for statement is out of scope in the block.


Here is another example of “Cannot find symbol” error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won’t find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can’t find the symbol Bar. The simple answer is to compile Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

There are some other more obscure causes too … which I will deal with below.

How do I fix these errors ?

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every “correction” is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says “Cannot find symbol” for j. There are many ways I could “fix” that:

  • I could change the inner for to for (int j = 1; j < 10; j++) – probably correct.
  • I could add a declaration for j before the inner for loop, or the outer for loop – possibly correct.
  • I could change j to i in the inner for loop – probably wrong!
  • and so on.

The point is that you need to understand what your code is trying to do in order to find the right fix.

Obscure causes

Here are a couple of cases where the “Cannot find symbol” is seemingly inexplicable … until you look closer.

  1. Incorrect dependencies: If you are using an IDE or a build tool that manages the build path and project dependencies, you may have made a mistake with the dependencies; e.g. left out a dependency, or selected the wrong version. If you are using a build tool (Ant, Maven, Gradle, etc), check the project’s build file. If you are using an IDE, check the project’s build path configuration.
  2. Cannot find symbol ‘var’: You are probably trying to compile source code that uses local variable type inference (i.e. a var declaration) with an older compiler or older --source level. The var was introduced in Java 10. Check your JDK version and your build files, and (if this occurs in an IDE), the IDE settings.
  3. You are not recompiling: It sometimes happens that new Java programmers don’t understand how the Java tool chain works, or haven’t implemented a repeatable “build process”; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like …
  4. An earlier build problem: It is possible that an earlier build failed in a way that gave a JAR file with missing classes. Such a failure would typically be noticed if you were using a build tool. However if you are getting JAR files from someone else, you are dependent on them building properly, and noticing errors. If you suspect this, use tar -tvf to list the contents of the suspect JAR file.
  5. IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists … or the reverse situation.
    • This could happen if the IDE has been configured with the wrong JDK version.
    • This could happen if the IDE’s caches get out of sync with the file system. There are IDE specific ways to fix that.
    • This could be an IDE bug. For instance @Joel Costigliola described a scenario where Eclipse did not handle a Maven “test” tree correctly: see this answer. (Apparently that particular bug was been fixed a long time ago.)
  6. Android issues: When you are programming for Android, and you have “Cannot find symbol” errors related to R, be aware that the R symbols are defined by the context.xml file. Check that your context.xml file is correct and in the correct place, and that the corresponding R class file has been generated / compiled. Note that the Java symbols are case sensitive, so the corresponding XML ids are be case sensitive too.Other symbol errors on Android are likely to be due to previously mention reasons; e.g. missing or incorrect dependencies, incorrect package names, method or fields that don’t exist in a particular API version, spelling / typing errors, and so on.
  7. Hiding system classes: I’ve seen cases where the compiler complains that substring is an unknown symbol in something like the followingString s = ... String s1 = s.substring(1); It turned out that the programmer had created their own version of String and that his version of the class didn’t define a substring methods. I’ve seen people do this with SystemScanner and other classes.Lesson: Don’t define your own classes with the same names as common library classes!The problem can also be solved by using the fully qualified names. For example, in the example above, the programmer could have written:java.lang.String s = ... java.lang.String s1 = s.substring(1);
  8. Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java uxxxx escapes for other characters.

What does a “Cannot find symbol” error mean? Answer #2:

One more example of ‘Variable is out of scope’

As I’ve seen that kind of questions a few times already, maybe one more example to what’s illegal even if it might feel okay.

Consider this code:

if(somethingIsTrue()) {
  String message = "Everything is fine";
} else {
  String message = "We have an error";
}
System.out.println(message);

That’s invalid code. Because neither of the variables named message is visible outside of their respective scope – which would be the surrounding brackets {} in this case.

You might say: “But a variable named message is defined either way – so message is defined after the if“.

But you’d be wrong.

Java has no free() or delete operators, so it has to rely on tracking variable scope to find out when variables are no longer used (together with references to these variables of cause).

It’s especially bad if you thought you did something good. I’ve seen this kind of error after “optimizing” code like this:

if(somethingIsTrue()) {
  String message = "Everything is fine";
  System.out.println(message);
} else {
  String message = "We have an error";
  System.out.println(message);
}

“Oh, there’s duplicated code, let’s pull that common line out” -> and there it it.

The most common way to deal with this kind of scope-trouble would be to pre-assign the else-values to the variable names in the outside scope and then reassign in if:

String message = "We have an error";
if(somethingIsTrue()) {
  message = "Everything is fine";
} 
System.out.println(message);

What does a “Cannot find symbol” error mean? Answer #3:

You’ll also get this error if you forget a new:

String s = String();

versus

String s = new String();

because the call without the new keyword will try and look for a (local) method called String without arguments – and that method signature is likely not defined.

And one of the simplest solution that might work for you in 99% of the cases is:

Using IntelliJ

Select Build->Rebuild Project will solve it.

Hope this post helped you in understanding what does a “Cannot find symbol” error means.

Follow Programming Articles for more!

Понравилась статья? Поделить с друзьями:
  • Cannot find os partition s for disk 0 как исправить windows
  • Cannot find file gamedata config system ltx как исправить lost alpha
  • Cannot find file gamedata config system ltx как исправить anomaly
  • Cannot find engineer mode app mediatek chipset is mandatory and stock rom как исправить
  • Cannot find appropriate setup exe file matlab ошибка