Account acct2 = new SavingsAccount (name);
acct2.calculateBalance();
This is because although you have an object of SavingsAccount
you are using refrence variable of type Account
so you can access only those methods that are there in Account
class.
And you don’t have calculateBalance()
method in your Account
class.
That’s why you are not able to access it and compiler complains that it cannot find a method named calculateBalance
as it sees that reference type is Account
and there is no such method inside Account
class.
If you want to use that method then change reference type to SavingsAccount
:
SavingsAccount acct2 = new SavingsAccount (name);
Or you can explicitly cast it when accessing that method
((SavingsAccount) acct2).calculateBalance();
but be alert that it can throw ClassCastException
if acct2
object is actually not an object of SavingsAccount
UPDATE:
But
remember that at runtime, Java uses virtual method invocation to dynamically
select the actual version of the method that will run, based on the actual instance.
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
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
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
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]
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
(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!
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]
1. Overview
In this tutorial, we’ll review what compilation errors are. Then we’ll specifically explain the “cannot find symbol” error and how it’s caused.
2. Compile Time Errors
During compilation, the compiler analyses and verifies the code for numerous things, such as reference types, type casts, and method declarations, to name a few. This part of the compilation process is important, since during this phase we’ll get a compilation error.
Basically, there are three types of compile-time errors:
- We can have syntax errors. One of the most common mistakes any programmer can make is forgetting to put the semicolon at the end of the statement. Some other mistakes include forgetting imports, mismatching parentheses, or omitting the return statement.
- Next, there are type-checking errors. This is the process of verifying type safety in our code. With this check, we’re making sure that we have consistent types of expressions. For example, if we define a variable of type int, we should never assign a double or String value to it.
- Finally, there’s the possibility that the compiler crashes. This is very rare, but it can happen. In this case, it’s good to know that our code might not be the problem, and that it’s an external issue instead.
The “cannot find symbol” error comes up mainly when we try to use a variable that’s not defined or declared in our program.
When our code compiles, the compiler needs to verify all the identifiers we have. The error “cannot find symbol” means we’re referring to something that the compiler doesn’t know about.
3.1. What Can Cause the “cannot find symbol” Error?
There’s really only one cause; the compiler couldn’t find the definition of a variable we’re trying to reference.
But there are many reasons why this happens. To help us understand why, let’s remind ourselves what our Java source code consists of:
- Keywords: true, false, class, while
- Literals: numbers and text
- Operators and other non-alphanumeric tokens: -, /, +, =, {
- Identifiers: main, Reader, i, toString, etc.
- Comments and whitespace
4. Misspelling
The most common issues are all spelling-related. If we recall that all Java identifiers are case-sensitive, we can see that the following would all be different ways to incorrectly refer to the StringBuilder class:
- StringBiulder
- stringBuilder
- String_Builder
5. Instance Scope
This error can also be caused when using something that was declared outside of the scope of the class.
For example, let’s say we have an Article class that calls a generateId method:
public class Article {
private int length;
private long id;
public Article(int length) {
this.length = length;
this.id = generateId();
}
}
But we declare the generateId method in a separate class:
public class IdGenerator {
public long generateId() {
Random random = new Random();
return random.nextInt();
}
}
With this setup, the compiler will give a “cannot find symbol” error for generateId on line 7 of the Article snippet. This is because the syntax of line 7 implies that the generateId method is declared in Article.
Like in all mature languages, there’s more than one way to address this issue, but one way would be to construct IdGenerator in the Article class and then call the method:
public class Article {
private int length;
private long id;
public Article(int length) {
this.length = length;
this.id = new IdGenerator().generateId();
}
}
6. Undefined Variables
Sometimes we forget to declare the variable. As we can see from the snippet below, we’re trying to manipulate the variable we haven’t declared, which in this case is text:
public class Article {
private int length;
// ...
public void setText(String newText) {
this.text = newText; // text variable was never defined
}
}
We solve this problem by declaring the variable text of type String:
public class Article {
private int length;
private String text;
// ...
public void setText(String newText) {
this.text = newText;
}
}
7. Variable Scope
When a variable declaration is out of scope at the point we tried to use it, it’ll cause an error during compilation. This typically happens when we work with loops.
Variables inside the loop aren’t accessible outside the loop:
public boolean findLetterB(String text) {
for (int i=0; i < text.length(); i++) {
Character character = text.charAt(i);
if (String.valueOf(character).equals("b")) {
return true;
}
return false;
}
if (character == "a") { // <-- error!
...
}
}
The if statement should go inside the for loop if we need to examine characters more:
public boolean findLetterB(String text) {
for (int i = 0; i < text.length(); i++) {
Character character = text.charAt(i);
if (String.valueOf(character).equals("b")) {
return true;
} else if (String.valueOf(character).equals("a")) {
...
}
return false;
}
}
8. Invalid Use of Methods or Fields
The “cannot find symbol” error will also occur if we use a field as a method or vice versa:
public class Article {
private int length;
private long id;
private List<String> texts;
public Article(int length) {
this.length = length;
}
// getters and setters
}
If we try to refer to the Article’s texts field as if it were a method:
Article article = new Article(300);
List<String> texts = article.texts();
Then we’d see the error.
This is because the compiler is looking for a method called texts, and there isn’t one.
Actually, there’s a getter method we can use instead:
Article article = new Article(300);
List<String> texts = article.getTexts();
Mistakenly operating on an array rather than an array element is also an issue:
for (String text : texts) {
String firstLetter = texts.charAt(0); // it should be text.charAt(0)
}
And so is forgetting the new keyword:
String s = String(); // should be 'new String()'
9. Package and Class Imports
Another problem is forgetting to import the class or package, like using a List object without importing java.util.List:
// missing import statement:
// import java.util.List
public class Article {
private int length;
private long id;
private List<String> texts; <-- error!
public Article(int length) {
this.length = length;
}
}
This code won’t compile, since the program doesn’t know what List is.
10. Wrong Imports
Importing the wrong type, due to IDE completion or auto-correction is also a common issue.
Think of a scenario where we want to use dates in Java. A lot of times, we could import a wrong Date class, which doesn’t provide the same methods and functionalities as other date classes that we might need:
Date date = new Date();
int year, month, day;
To get the year, month, or day for java.util.Date, we also need to import the Calendar class and extract the information from there.
Simply invoking getDate() from java.util.Date won’t work:
...
date.getDay();
date.getMonth();
date.getYear();
Instead, we use the Calendar object:
...
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
However, if we’ve imported the LocalDate class, we won’t need additional code to provide us the information we need:
...
LocalDate localDate=date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
year = localDate.getYear();
month = localDate.getMonthValue();
day = localDate.getDayOfMonth();
11. Conclusion
Compilers work on a fixed set of rules that are language-specific. If a code doesn’t stick to these rules, the compiler can’t perform a conversion process, which results in a compilation error. When we face the “cannot find symbol” compilation error, the key is to identify the cause.
From the error message, we can find the line of code where the error occurs, and which element is wrong. Knowing the most common issues that cause this error will make solving it quick and easy.
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:
- Symbol: The name and type of the identifier you are looking for.
- 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
Tarun Luthra
Free
5
Enrolled: 51287
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:
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’.
tick-icon22
30+ free video courses by top instructors at Scaler
tick-icon22
2000+ challenges to solve, curated by industry experts
tick-icon22
5+ masterclasses, monthly by experts on real time problem solving
tick-icon22
Fortnightly contests on DSA
tick-icon22
35+ topics library of different tech stacks.
2 Lakh + users already signed in to explore Scaler Topics!