Error cannot find symbol ошибка

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,5372 gold badges11 silver badges30 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

8,0436 gold badges33 silver badges43 bronze badges

10

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,52114 silver badges24 bronze badges

3

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

7095 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.8k6 gold badges44 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,6635 gold badges34 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,9218 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,9912 gold badges16 silver badges33 bronze badges

1

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,1411 gold badge13 silver badges18 bronze badges

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,1092 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,8632 gold badges18 silver badges36 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,5926 gold badges39 silver badges52 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,5003 gold badges20 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

3981 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,2711 gold badge8 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

3942 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

Nimbrod'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

20.4k18 gold badges102 silver badges149 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

4871 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,4112 gold badges24 silver badges33 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,3402 gold badges18 silver badges36 bronze badges

In my case,

  1. close intelliJ.
  2. delete «.idea» (which are hidden folders by default) from project root.
  3. open IntelliJ
  4. open settings —> find annotation processors —> check «Enable annotation processing»
  5. Open Project structure from «File» menu. Set the appropriate JDK version.

answered Apr 2 at 0:37

coverboy's user avatar

coverboycoverboy

511 silver badge10 bronze badges

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: <symbol name (identifier), type, scope, [attributes]>. Given a global variable declaration like final double ratio; the corresponding symbol would then be <ratio, double, global, [final]>.

Install the Java SDK to identify and fix exceptions

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

(a)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class UndeclaredVariable {
    public static void main(String... args) {
        int x = 6;
        int y = 10;
        int z = 32;

        average = (x + y + z) / 3.0; // average is not declared
        System.out.println(average);
    }
}
UndeclaredVariable.java:9: error: cannot find symbol
    average = (x + y + z) / 3.0;
    ^
  symbol:   variable average
  location: class UndeclaredVariable

UndeclaredVariable.java:10: error: cannot find symbol
    System.out.println(average);
                       ^
  symbol:   variable average
  location: class UndeclaredVariable
2 errors

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

public class UndeclaredVariable {
    public static void main(String... args) {
        int x = 6;
        int y = 10;
        int z = 32;

        double average = (x + y + z) / 3.0;
        System.out.println(average);
    }
}
16.0
Figure 1: Cannot find symbol for undeclared variable (a) error and (b) resolution

Out of scope variable

When a Java program tries to access a variable declared in a different (non-inherited or non-overlapping) scope, the compiler triggers the cannot find symbol error. This is demonstrated by the attempt to access the variable counter on lines 17 and 18 in Fig. 2(a), which is accessible only within the for statement declared on line 11. Moving the counter variable outside the for loop fixes the issue, as shown on Fig. 2(b).

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package rollbar;

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

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

        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");
        }
    }
}
OutOfScopeVariable.java:17: error: cannot find symbol
    if (counter < strings.size()) {
        ^
  symbol:   variable counter
  location: class OutOfScopeVariable

OutOfScopeVariable.java:18: error: cannot find symbol
      System.out.println("The word " + searchFor + " was found at index " + counter);
                                                                            ^
  symbol:   variable counter
  location: class OutOfScopeVariable
2 errors

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package rollbar;

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

public class OutOfScopeVariable {
    public static void main(String... args) {
        final List<String> strings = Arrays.asList("Hello", "World");
        final String searchFor = "World";
        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");
        }
    }
}
The word ‘World’ was found at index 1
Figure 2: Cannot find symbol for out-of-scope variable reference (a) error and (b) resolution

Misspelled method name

Misspelling an existing method, or any valid identifier, causes a cannot find symbol error. Java identifiers are case-sensitive, so any variation of an existing variable, method, class, interface, or package name will result in this error, as demonstrated in Fig. 3.

(a)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class MisspelledMethodName {
    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 fib20 = Fibonacci(20); // Fibonacci ≠ fibonacci
        System.out.println(fib20);
    }
}
MisspelledMethodName.java:11: error: cannot find symbol
    int fib20 = Fibonacci(20);
                ^
  symbol:   method Fibonacci(int)
  location: class MisspelledMethodName

(b)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package rollbar;

public class MisspelledMethodName {
    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 fib20 = fibonacci(20);
        System.out.println(fib20);
    }
}
6765
Figure 3: Cannot find symbol for misspelled method name (a) error and (b) resolution

Missing import statement

Using classes, either from the Java platform or any library, requires importing them correctly with the import statement. Failing to do so will result in the cannot find symbol error being raised by the Java compiler. The code snippet in Fig. 4(a) makes use of the java.util.List class without declaring the corresponding import, therefore the cannot find symbol error occurs. Adding the missing import statement (line 4 in Fig. 4(b)) solves the problem.

(a)

package rollbar;

import java.util.Arrays;

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

    public static void main(String... args) {
        System.out.println(CONSTANTS);
    }
}
MissingImportList.java:6: error: cannot find symbol
  private static final List<String> CONSTANTS = Arrays.asList("A", "B", "C");
                       ^
  symbol:   class List
  location: class MissingImportList

(b)

1
2
3
4
5
6
7
8
9
10
11
12
package rollbar;

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

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

    public static void main(String... args) {
        System.out.println(CONSTANTS);
    }
}
[A, B, C]
Figure 4: Cannot find symbol for missing import (a) error and (b) resolution

Less common examples

The root cause for the cannot find symbol Java error can occasionally be found in some unexpected or obscure places. Such is the case with accidental semicolons that terminate a statement ahead of time (Fig. 5), or when object creation is attempted without a proper constructor invocation which has to have the new keyword (Fig. 6).

(a)

package rollbar;

public class LoopScope {
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 + ", ");
        }
    }
}
LoopScope.java:7: error: cannot find symbol
      System.out.print(i == end ? i : i + ", ");
                       ^
  symbol:   variable i
  location: class LoopScope

LoopScope.java:7: error: cannot find symbol
      System.out.print(i == end ? i : i + ", ");
                                  ^
  symbol:   variable i
  location: class LoopScope

LoopScope.java:7: error: cannot find symbol
      System.out.print(i == end ? i : i + ", ");
                                      ^
  symbol:   variable i
  location: class LoopScope
3 errors

(b)

package rollbar;

public class LoopScope {
    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 + ", ");
        }
    }
}
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Figure 5: Cannot find symbol for prematurely terminated for loop (a) error and (b) resolution

(a)

package rollbar;

public class ObjectCreation {
    public static void main(String... args) {
        String s = String("Hello World!");
        System.out.println(s);
    }
}
ObjectCreation.java:5: error: cannot find symbol
    String s = String("Hello World!");
               ^
  symbol:   method String(String)
  location: class ObjectCreation

(b)

package rollbar;

public class ObjectCreation {
    public static void main(String... args) {
        String s = new String("Hello World!");
        System.out.println(s);
    }
}
Hello World!
Figure 6: Cannot find symbol constructor call (a) error and (b) resolution

Other causes for the cannot find symbol error may include:

  • using dependencies with old or incompatible versions;
  • forgetting to recompile a program;
  • building a project with an older JDK version;
  • redefining platform or library classes with the same name;
  • the use of homoglyphs in identifier construction that are difficult to tell apart;
  • etc.

Conclusion

The cannot find symbol error, also found under the names of symbol not found and cannot resolve symbol, is a Java compile-time error which emerges whenever there is an identifier in the source code which the compiler is unable to work out what it refers to. As with any other compilation error, it is crucial to understand what causes this error, pinpoint the issue and address it properly. In the majority of cases, referencing undeclared variables and methods, including by way of misspelling them or failing to import their corresponding package, is what triggers this error. Once discovered, resolution is pretty straightforward, as demonstrated in this article.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!

References

[1] Rollbar, 2021. Handling the <Identifier> Expected Error in Java. Rollbar Editorial Team. [Online]. Available: https://rollbar.com/blog/how-to-handle-the-identifier-expected-error-in-java/. [Accessed Nov. 22, 2021].

[2] ITL Education Solutions Limited, Principles of Compiler Design (Express Learning), 1st ed. New Delhi: Pearson Education (India), 2012.

[3] Tutorialspoint.com, 2021. Python — Variable Types. [Online]. Available: https://www.tutorialspoint.com/python/python_variable_types.htm. [Accessed: Nov. 23, 2021].

[4] JavaScript Tutorial, 2021. JavaScript Hoisting Explained By Examples. [Online]. Available: https://www.javascripttutorial.net/javascript-hoisting/. [Accessed: Nov. 23, 2021]

The Cannot Find Symbol Error in Java error occurs when the Java compiler cannot find a symbol that you are trying to reference in your code. In this article, we will explore how to resolve the “Cannot Find Symbol” error in Java.

The “Cannot Find Symbol” error occurs when you are trying to reference a symbol that has not been defined or imported properly. Symbols can include variables, methods, and classes or in easy language when you try to reference an undeclared variable in your code. The error typically occurs when you have made a typo, used the wrong case in the symbol name, or when you are trying to reference a symbol that is out of scope. You may also encounter this error when you are using multiple files, and the compiler cannot find a class or package that you are trying to reference.

Common mistakes that lead to “Cannot Find Symbol” error in Java and resolving them, you can follow these steps:

  • Typos
  • Undeclared Variable
  • Scope of Current block
  • Import Statement

Typos

Make sure that the symbol you are trying to reference is spelled correctly and matches the case used in the definition.

Example 1:

Java

public class Main {

    static int Large(int a, int b)

    {

        if (a > b) {

            return a;

        }

        else if (b > a) {

            return b;

        }

        else {

            return -1;

        }

    }

    public static void main(String... args)

    {

        int value = large(20, 4);

        System.out.println(value);

    }

}

Output:

./Main.java:17: error: cannot find symbol
        int value = large(20, 4);
                    ^
  symbol:   method large(int,int)
  location: class Main

Explanation of the above program

We get this error as the function we initialized is Large(int a,int b) whereas we are calling large(a,b) so to resolve this typo mistake we just change large to Large.

Example 2:

Java

public class Main {

    static int Large(int a, int b)

    {

        if (a > b) {

            return a;

        }

        else if (b > a) {

            return b;

        }

        else {

            return -1;

        }

    }

    public static void main(String... args)

    {

        int value = Large(20, 4);

        System.out.println(value);

    }

}

Undeclared Variable

We can also get errors by undeclared Variables.

Example 1:

Java

public class Main {

    public static void main(String[] args)

    {

        int n1 = 500;

        int n2 = 400;

        sum = n1 + n2;

        System.out.println(sum);

    }

}

Output: 

./Main.java:6: error: cannot find symbol
        sum = n1 + n2;
        ^
  symbol:   variable sum
  location: class Main
./Main.java:7: error: cannot find symbol
        System.out.println(sum);
                           ^
  symbol:   variable sum
  location: class Main

Explanation of the program

In the above example, the “Cannot find symbol” error occurs as we have not declared the sum. The corrected code is given below (will occur because “sum” is not declared. In order to solve the error, we need to define “int sum = n1+n2” before using the variable sum.

Example 2:

Java

public class Main {

    public static void main(String[] args)

    {

        int n1 = 500;

        int n2 = 400;

        int sum = n1 + n2;

        System.out.println(sum);

    }

}

Check the scope

Make sure that the symbol you are trying to reference is within the scope of the current code block.

Example 1:

Java

public class Main {

    public static void main(String[] args)

    {

        int x = 5;

        if (x > 0) {

            int y = 10;

        }

        System.out.println(y);

    }

}

Output:

./Main.java:8: error: cannot find symbol
                System.out.println(y);
                                   ^
  symbol:   variable y
  location: class Main

Explanation of the above program

In this program, we define an integer variable x and initialize it to 5. We then have an if statement that checks if x is greater than 0. If it is, we define another integer variable y, and initialize it to 10. However, y is only within the scope of the if block, and cannot be accessed outside of it. 

Example 2:

Java

public class Main {

    public static void main(String[] args) {

        int x = 5;

        int y = 0;

        if (x > 0) {

            y = 10;

        }

        System.out.println(y);

    }

}

Check the import statements

Make sure that any classes or packages that you are trying to reference are imported properly.

Example 1:

Java

import java.util.Rand;

public class Main {

    public static void main(String[] args)

    {

        Rand rand = new Rand();

        int x = rand.nextInt(10);

        System.out.println("Random number: " + x);

    }

}

Output:

./Main.java:1: error: cannot find symbol
import java.util.Rand;
                ^
  symbol:   class Rand
  location: package java.util
./Main.java:6: error: cannot find symbol
        Rand rand = new Rand();
        ^
  symbol:   class Rand
  location: class Main
./Main.java:6: error: cannot find symbol
        Rand rand = new Rand();
                        ^
  symbol:   class Rand
  location: class Main

Example 2:

Java

import java.util.Random;

public class Main {

    public static void main(String[] args) {

        Random rand = new Random();

        int x = rand.nextInt(10);

        System.out.println("Random number: " + x);

    }

}

Last Updated :
14 May, 2023

Like Article

Save Article

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.

What is the Cannot Find Symbol Java Error?

Learn via video course

Java Course - Mastering the Fundamentals

Java Course — Mastering the Fundamentals

Tarun Luthra

Free

5

icon_usercirclecheck-01

Enrolled: 54029

Start Learning

The Cannot Find Symbol in Java is a compilation error that occurs when we try to refer to something that is not present in the Java Symbol Table. A very common example of this error is using a variable that is not declared in the program.

Java compilers create and maintain Symbol tables. The symbol table stores the information of the identifiers i.e. classes, interfaces, variables, and methods in the given source of code. When we use these identifiers in our code, the compiler looks up to the symbol table for information. If the identifier is not declared or is not present in the given scope the compiler throws ‘Cannot Find Symbol’.

What Causes the Java Cannot Find Symbol Error?

There are multiple ways and reasons this error can occur, they all boil down to the fact that the online Java compiler couldn’t find the identifier in the Symbol table. Some of the very commonly made mistakes are listed below:

  • Java is case sensitive, thus hello and Hello are two different variables.
  • If identifiers are misspelled say the variable’s name is name and we are trying to access nmae can cause an error.
  • Sometimes variables are declared in a particular iterating loop or method and if we try to call them from outside causes an error as it is out of the scope of the variable.
  • Using variables without their declaration is also the common cause of the Java ‘Cannot find Symbol’ error.
  • Sometimes we use methods from classes of a different package. To do so we are required to import the package of the class. Missing import statements can cause the error too.
  • Use of underscore, dollar sign, numbers, letter even a character before or after different from the initial declaration can cause ‘Cannot Find Symbol’.

Examples of Java Cannot Find Symbol error

Let us now see these common errors in the form of code:

Example 1

Let us take a very simple example of a function that takes user input of a number and returns if the number is even or odd.


Output:


In the example above, the Scanner class is not imported and thus it is throwing a Cannot Find Symbol error. The compiler is not able to find Scanner in the program. Once we import the package, it is able to identify the Scanner class.

Example 2

Another example is wrong spelling and undeclared variables. Let us take a simple example where we multiply a variable a few times in a loop.


Output:


In the example above we can see 3 errors, all of them being ‘cannot find symbol’. The first one is because N is not declared in the program, and the two are because we declared finalResult but we are calling final_Result. Thus, a single underscore can also cause an error.

Example 3

Lastly, out-of-scope variables also cause a ‘Cannot find Symbol’ error, below example demonstrates it.


Output:


In the example above, the sum variable is declared inside the for loop and its scope is only inside for loop. As we are trying to access it outside the for loop, it is causing the error.

Structure of Java Cannot Find Symbol

Look at the output generated by the compiler for the 3rd example:

output-generated-bycompiler

As we can see in the output, the compiler tells the line number of the error as well as points to the variable where the error occurred and the type of the error which is cannot find symbol in this case.
The compiler also produces the cannot find symbol including these two additional fields:

  • The very first one is the symbol it is unable to find, i.e. the name and type of the referenced identifier.
  • The other field is the location of the place where the symbol is used. The class and line number are returned where the identifier has been referenced.

Cannot Find Symbol vs Symbol Not Found vs Cannot Resolve Symbol

Different compilers may use slightly different terminologies. The ‘Cannot Find Symbol’, ‘Symbol Not Found’, and ‘Cannot Resolve Symbol’ are all same errors only. Besides the naming, these convey the same meaning to the user and the compiler.

Learn more about Java errors

Conclusion

  • The ‘Cannot Find Symbol’ error in Java is a compilation error caused when the compiler cannot find a reference to an identifier.
  • Silly mistakes like case sensitivity, use of underscore, use of undeclared variables, use of out-of-scope variables, etc. can cause this error.
  • It is also identified by ‘Symbol Not Found’ and ‘Cannot Resolve Symbol’.

  • Error c2061 синтаксическая ошибка идентификатор tchar
  • Error 2003 mysql ошибка
  • Error 1962 lenovo как исправить ошибку
  • Error 1935 ошибка при установке сборки microsoft visual c windows 10 x64
  • Error 1935 ошибка при установке сборки microsoft vc80 crt