Home  >  Article  >  Java  >  What causes "Cannot find symbol" error in Java?

What causes "Cannot find symbol" error in Java?

王林
王林forward
2023-08-19 12:37:264722browse

在Java中,什么原因会导致"Cannot find symbol"错误?

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

Example

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);
   }
}

Compile time error

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

Solution

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

Example

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);
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete