What is 'Cannot find symbol' Java Error
A 'Cannot find symbol' in Java is a compilation error that occurs when a compiler cannot find what an identifier refers to, for example, an undeclared variable in your code. In simple words, this error occurs when your source code refers to an identifier (id) that the compiler is unable to understand because that identifier is not defined in your code.
At the time of compilation of any Java program, the compiler creates a list of all the identifiers used in the program and then tries to understand what each of those identifiers means or refers. A 'Cannot find symbol' implies that your code is referring to something which compiler cannot understand.
Cause of this error
The compiler while compiling the java programs looks in the code to check where all the identifiers are defined, if in case the compiler cannot find the definition of any identifier it will return an error 'Cannot find symbol.'
Some common causes of this error are:
- Use of incorrect identifier spelling for example StringBffer instead of StringBuffer
- Java identifiers are case-sensitive; therefore, the use of wrong case can cause this error.
- Use of inappropriate underscore, letters, numbers, underscore, dollar sign, etc; i.e., stringstechies and string_stechies are different
- In case if any variable is not declared or variables declared is outside of the scope, which user is referencing too.
- If in case, the identifier refers to a method that has not been declared.
- Or the identifier is trying to inherit a method or field which is not defined in the parent classes.
- If you forget to import the class
Example
/Java program for Compiler Error: cannot find symbol
//Error
//Main class of the program
public class Main{
//Main method of the program
public static void main (String[] args) {
//First Number
int fNumber = 45;
//Second Number
int sNumber = 33;
//Variable to hold the multiplication of the program
result = fNumber * sNumber;
//Printing the output
System.out.println(result);
}
}
Output
Main.java:10: error: cannot find symbol
result = fNumber * sNumber;
^
symbol: variable result
location: class Main
Main.java:12: error: cannot find symbol
System.out.println(result);
^
symbol: variable result
location: class Main
2 errors
In the above code, we are getting error: 'cannot find symbol' because we have not defined the variable 'result' anywhere in our code.
Correct Program
//Java program to resolve Compiler Error: cannot find symbol
//resolve Error
//Main class of the program
public class Main{
//Main method of the program
public static void main (String[] args) {
//First Number
int fNumber = 45;
//Second Number
int sNumber = 33;
//Variable to hold the multiplication of the program
int result = fNumber * sNumber;
//Printing the output
System.out.println(result);
}
}
Output:
1485