What can cause a Cannot find symbol error in java?



Whenever you need to use external classes/interfaces (either user defined or, built-in) in the current program you need to import those classes in your current program using the import keyword.

But, while importing any class −

  • If the path of the class/interface you are importing is not available to JVM.

  • If the absolute class name you have mentioned at the import statement is not accurate (including packages and class name).

  • If you have imported the class/interface used.

You will get an exception saying “Cannot find symbol ……”

Example

In the following example we are trying to read a string value representing the name of the user from key-board (System.in). For this we are using 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

Since we are using a class named Scanner in our program and haven’t imported it in our program. On executing, this 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 class path for the JAR file holding the required class interface.

  • Import the required class from the package using the import keyword. While importing you need to specify the absolute name (including the packages and sub packages) of the required class.

Example

 Live Demo

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

Advertisements