Whenever you need to use external classes/interfaces (whether user-defined or built-in) in the current program, you need to import these classes into the current program using the import keyword .
But, while importing any class:
If the path of the class/interface you imported is not available to JVM.
If the absolute class name you mentioned in the import statement is not accurate (including package and class name).
If you have imported the used class/interface.
You will receive an exception saying "Cannot find symbol..."
In the following example, we are trying to read a string value representing the user's name from the keyboard (System.in). For this purpose, we use the scanner class of the Java.Util package.
public class ReadingdData { public static void main(String args[]) { System.out.println("Enter your name: "); Scanner sc = new Scanner(System.in); String name = sc.next(); System.out.println("Hello "+name); } }
Because we used a class named Scanner in the program but did not import it in the program. On execution, the program generates the following compile-time error:
ReadingdData.java:6: error: cannot find symbol Scanner sc = new Scanner(System.in); ^ symbol: class Scanner location: class ReadingdData ReadingdData.java:6: error: cannot find symbol Scanner sc = new Scanner(System.in); ^ symbol: class Scanner location: class ReadingdData 2 errors
You need to set the classpath for the JAR file that contains the required class interface.
Import the required classes from the package using the import keyword. When importing, you need to specify the absolute name of the required class (including packages and subpackages).
Online demonstration
import java.util.Scanner; public class ReadingdData { public static void main(String args[]) { System.out.println("Enter your name: "); Scanner sc = new Scanner(System.in); String name = sc.next(); System.out.println("Hello "+name); } }
Enter your name: krishna Hello krishna
The above is the detailed content of What causes 'Cannot find symbol' error in Java?. For more information, please follow other related articles on the PHP Chinese website!