Testingservlet java 5 error cannot find symbol public class testingservlet extends httpservlet

Ошибка компиляции “Не найти символ” Просмотрите, что такое ошибки компиляции, а затем конкретно объясните, что такое ошибка «не может найти символ» и как она вызвана. Автор: baeldung Дата записи 1. Обзор В этом учебнике мы рассмотрим, что такое ошибки компиляции, а затем конкретно объясним, что такое ошибка «не может найти символ» и как она […]

Содержание

  1. Ошибка компиляции “Не найти символ”
  2. 1. Обзор
  3. 2. Ошибки времени компиляции
  4. 3. Ошибка “не может найти символ”
  5. 3.1. Что может вызвать ошибку «не может найти символ»?
  6. 4. Опечатка
  7. 5. Сфера применения экземпляра
  8. 6. Неопределенные переменные
  9. 7. Переменный охват
  10. 8. Недействительное использование методов или полей
  11. 9. Импорт пакетов и классов
  12. 10. Неправильный импорт
  13. 11. Заключение
  14. Servlet Compilation error
  15. Comments
  16. JAR сервлета 5.0 выдает ошибку компиляции в javax.servlet.*, Но Servlet 4.0 JAR нет
  17. 3 ответа

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

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

Автор: 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. Заключение

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

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

Источник

Servlet Compilation error

Hi all,
I am trying to compile a simple Servlet program. with following path and classpath details.
I have stored .java(servlet program) file in «C:Ashu» folder.

I have installed jre 1.5 in C:Program FilesJavajre1.5.0_12

I have installed SDK(Java EE 5 SDK) in C:Sun.

I have jdk1.5 in C:jdk1.5

when i try to compile the TestingServlet.java program, I am getting following error: Please help me to set the classpath

1) You´ve defined three servlet implementations in the environment variable %CLASSPATH%. Please stick to one. Which appserver are you using? Use its servlet implementation.

2) Whenever you´ve spaces in the path, you need to surround the path by double quotes. Something like: or to use its «short hand» notation:3) You wrote TOMCAT_HOME in the path. But it´s an invalid path. Use valid paths. I think you copypasted it from some tutorial without actually reading the text or thinking logically. With TOMCAT_HOME is generally meant the actual file system path to the root directory of Tomcat installation.

4) An important thing to know about the environment variable %CLASSPATH% is that it is completely ignored whenever you used the -cp or -classpath parameter in javac.exe and java.exe.

With the above information you must be able to solve this problem. Good luck.

Thank you BalusC.

I have installed JDK in C:jdk1.5
The JRE is installed in C:Program FilesJavajre1.5.0_12
Inside C:jdk1.5 folder there is also a jre folder.

What is the difference between C:Program FilesJavajre1.5.0_12 and C:jdk1.5jre ??

Which one i need to add in «path» as well as «classpath»?

what i need to include in TOMCAT_HOME as classpath?

I am totally confussed. I have not copied from any webiste. Since two days i have stuck with servlet compilation ..
Please help me.

Thank you BalusC.

As you said, i have included contents for classpath in » «. Following what i gave in user variables:
all the path to jar files are seperated by semicolan.

classpath=»C:Program FilesApache Software FoundationTomcat 5.5commonlibservlet-api.jar;TOMCAT_HOME/LIB/servlet.jar;C:SunSDKlibj2ee.jar»

Where am i going wrong?
Which file’s directory sturcture i need to give for TOMCAT_HOME? as you said it is invalid.

I have also tried going to my app directory under web-apps and execut the javac -cp command: But still, not able to solve the problem.

please help
Regards

anu-radha wrote:
As you said, i have included contents for classpath in » «. Following what i gave in user variables:
all the path to jar files are seperated by semicolan.

classpath=»C:Program FilesApache Software FoundationTomcat 5.5commonlibservlet-api.jar;TOMCAT_HOME/LIB/servlet.jar;C:SunSDKlibj2ee.jar»

I have stored .java(servlet program) file in «C:Ashu» folder.

I have installed jre 1.5 in C:Program FilesJavajre1.5.0_12

I have installed SDK(Java EE 5 SDK) in C:Sun.

I have jdk1.5 in C:jdk1.5

I am assuming you are keeping your .java files in G:AshuServlets and just map your apache-tomcat directory, replacing G:apache-tomcat-6.0 . which is basically Tomcat6 version base folder, in my system.

Declare 4 environment variables as follows :
[1] CLASSPATH =
.;G:apache-tomcat-6.0.18libservlet-api.jar;G:apache-tomcat-6.0.18libjsp-api.jar;G:apache-tomcat-6.0.18libel-api.jar;
G:AshuServlets

[the last one ie, G:AshuServlets after last semicolon]

[2] JAVA_HOME = G:Program FilesJavajdk1.6.0_01

[3] JRE_HOME = G:Program FilesJavajre1.6.0_01

[4] TOM_LIB = G:apache-tomcat-6.0.18lib

Now coming to the command you will execute from your working folder :

[1]G:AshuServlets> javac -cp %tom_lib%servlet-api.jar;G:AshuServlets TestingServlet.java

The above [1] is keeping in mind, if your TestingServlet might use any utility java class existing in G:AshuServlets folder.
Otherwise just compile with :

[2] G:AshuServlets>javac -cp %tom_lib%servlet-api.jar TestingServlet.java

Now copy the TestingServlet.class file and put it under :
G:apache-tomcat-6.0.18webappsROOTWEB-INFclasses — you need to create a «classes» folder, if there’s not, as shown.
Open the browser and type :http://localhost:8080/servlet/TestingServlet — ofcourse, if you not changed your port(8080).

See how it goes — mine works fine.

Thank you BalusC and Atanu,

I have considered all your suggessions and made following entries in the Environment variables:

In User Variable:

/* classpath contains all the .jar files and my working folder */
Classpath = “C:Program FilesApache Software FoundationTomcat 5.5commonlibservlet-api.jar”;“C:Program FilesApache Software FoundationTomcat 5.5commonlibjsp-api.jar”;C:Ashu

In System Variables:

CATALINA_HOME = «C:Program FilesApache Software FoundationTomcat 5.5»

CLASSPATH = “C:Program FilesApache Software FoundationTomcat 5.5commonlibservlet-api.jar”;“C:Program FilesApache Software FoundationTomcat 5.5commonlibjsp-api.jar”;“C:SunSDKlibj2ee.jar»;C:Ashu

JRE_HOME= C:Program FilesJavajre1.5.0_12

/*PATH contains path to all the bin folders in java, EE 5 SKD, jre and Tomcat*/

PATH = %SystemRoot%system32;%SystemRoot%;%SystemRoot%System32Wbem;%JAVA_HOME%bin;”C:SunSDKbin”;”C:Program FilesJavajre1.5.0_12bin”;”C:Program FilesApache Software FoundationTomcat 5.5bin”

TOM_LIB = C:Program FilesApache Software FoundationTomcat 5.5commonlib

I have few doubts:
1. what is the difference between user variables and system variables in Environment variable. Where to define classpath and other path declarations?
2. Is it case sensitive? (Environment varialbe)
3. IS it ok, if I define classpath and path both in uservariables and system variables.
4. there are some variations in system variable classpath and user variable classpath. Is that ok? Or should it match exactly ??
5. is that necessary to start a classpath declaration with .; ? example .;c:program files.
6. Do I need to leave space between two semi-collans? Example “cjdk1.4”; “cprogram files. ”

Источник

JAR сервлета 5.0 выдает ошибку компиляции в javax.servlet.*, Но Servlet 4.0 JAR нет

Я пытаюсь скомпилировать и развернуть простое веб-приложение из командной строки.

servlet-api.jar из Apache Tomcat не компилирует мой java-файл, но javax.servlet-api-4.0.1 из центрального репозитория maven успешно его компилирует. Тем не менее, я получаю сообщение об ошибке, когда развертываю приложение и пытаюсь использовать его в браузере.

  • javac 11.0.8
  • Apache Tomcat 10.0 (servlet-api.jar 5.0)

Когда я пытаюсь скомпилировать его с помощью servlet-api.jar, я получаю:

Однако javax.servlet-api-4.0.1 успешно компилирует файл. Примечание. Я уже протестировал и исключил команду командной строки как возможную причину проблемы.

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

Я попытался поместить javax.servlet-api-4.0.1 в каталог Tomcat/lib, но затем получил:

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

Любая помощь приветствуется!

3 ответа

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

В jakarta.servlet.Servlet является частью Servlet API версии 5.0, которая, в свою очередь, является частью Jakarta EE версии 9. Ваш сервлет фактически расширяется от javax.servlet.Servlet который, в свою очередь, является частью более старой версии JEE, которая фактически не поддерживается вашей целевой средой выполнения (Tomcat 10.x).

У вас есть 2 варианта:

Заменить javax.servlet.* импортирует в ваш код jakarta.servlet.* ед.

Затем вы можете просто скомпилировать библиотеки из целевой среды выполнения на основе Servlet 5.0.

Или понизьте версию контейнера сервлетов с Servlet API версии 5.0 до предыдущей версии, по крайней мере, той, которая все еще имеет javax.servlet.* имя пакета. Tomcat 9.x — последний из них, в котором все еще используется старый пакет.

Техническая причина в том, что при переходе от Java/Jakarta EE 8 к Jakarta EE 9 все javax.* пакеты были переименованы в jakarta.* пакеты. Так что с Jakarta EE 9 обратной совместимости больше нет.

Источник


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Hi guys i am a bit new to java ee. here is the problem the below command is throwing can not find symbol error

I am using this command from windows cmd :

book HF servlets and jsp page 31

here is the code for Ch1Servlet.java

Bartender

Posts: 7488


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

What is the actual command you’re using? Surely, «your path» is not correct…? And it were, you’d need to enclose the path in double quotes because of the space character.

Also, is javac in your PATH?

Agena Agenam

Greenhorn

Posts: 3


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

i have used the full path of javac and servlet-api.jar and rest of the directory structure i followed as it was in the book.


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Can you post the actual full error text?

Agena Agenam

Greenhorn

Posts: 3


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Tim Moores

Bartender

Posts: 7488


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Please post the exact command you used.

Marshal

Posts: 77299


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Why do you want to delete a post? We only delete posts if they have something wrong with them.


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

You do not use javac to run servlets. Servlets are not Java Applications.

Servlets are components of Web Applications, which are collections of Servlets, JSPs and supporting resources bundled together in a single deployable unit known as a WAR (for Web Application Archive).

A WAR is not an executable program. It’s more like a Windows DLL — a collection of services that can be called. In the case of a Web Application, the caller is a Web Application Server.

So to run a servlet you need to create a WAR and deploy it to a Web Application Server. There are many such servers available, although Tomcat is probably the most popular one for basic applications as it’s easy to install, simple to use, and doesn’t require a long time to start up and shut down.

I’m going to be a «small government» candidate. I’ll be the government. Just me. No one else.

Tim Moores

Bartender

Posts: 7488


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

You do not use javac to run servlets.

The question is about compilation, not running. So using javac is appropriate. Seems to be a classpath problem, but we don’t know without seeing the actual command being used.

Tim Holloway

Saloon Keeper

Posts: 26557

Android
Eclipse IDE
Tomcat Server
Redhat
Java
Linux


posted 2 years ago

  • Mark post as helpful


  • send pies

    Number of slices to send:

    Optional ‘thank-you’ note:



  • Quote
  • Report post to moderator

Sorry. I’m exceptionally blind in the mornings. Not used to seeing Java webapps being built one file at a time.

I’m suspecting that the most likely problem is that Agena copied the compile command straight out of the book and that’s a problem for two reasons:

1.

/your path/tomcat/common/lib/servlet-api.jar

— the space between «your» and «path» will throw off the command parser.

2. Almost certainly, Agena has not installed Tomcat in a directory that’s literally named «/your path/tomcat». That part needs to be replaced with the actual Tomcat home directory.

Wait, there’s a third problem.

TOMCAT_HOME/common/lib

has not been a valid library path since Tomcat 4. This example is ancient.

The

tomcat-api.jar

now resides in the TOMCAT_HOME/lib directory.

I’m going to be a «small government» candidate. I’ll be the government. Just me. No one else.

wood burning stoves

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.

Понравилась статья? Поделить с друзьями:
  • Teso error 210 что делать
  • The android sdk location is inside studio install location как исправить
  • Testing pass stopped due to a critical error in the east
  • Teso error 200
  • The amazing spider man ошибка buddha