Javac Cannot Find Symbol Error in Java

Sheeraz Gul Jul 25, 2022
Javac Cannot Find Symbol Error in Java

This tutorial demonstrates how to solve Java’s javac cannot find symbol error.

the Javac Cannot Find Symbol in Java

The Javac is a tool that reads a class and interfaces written in Java and compiles them into the bytecode. The javac is a command used with Java files in CLI.

The javac cannot find symbol error occurs when we are trying to run a Java file which contains the use of a variable which is defined or declared in our programs. The javac cannot find symbol error means that we are referring to something for which the compiler has no idea.

The javac cannot find symbol error occurs when we have problems with the following things in our programs.

  1. Literals, including numbers and text.
  2. The keywords like true, false, class, while.
  3. The operators and other non-alphanumeric tokens like -, /, +, =, {.
  4. The identifiers like Reader, main, toString, etc.
  5. The white spaces and comments.

Let’s create an example that will throw the javac cannot find symbol.

public class Example {
    public static void main(String... args) {
        int a = 10;
        int b = 20;
        int c = 30;

        sum = a + b + c; // sum is not declared
        System.out.println(sum);
    }
}

The code above has a variable sum, which is not declared before, so it will throw the cannot find symbol error. Get the path of the Java file in CMD and compile the file with javac.

Use the following command.

javac Example.java

The code above will throw the following error.

C:\>javac Example.java
Example.java:7: error: cannot find symbol
        sum = a + b + c; // sum is not declared
        ^
  symbol:   variable sum
  location: class Example
Example.java:8: error: cannot find symbol
        System.out.println(sum);
                           ^
  symbol:   variable sum
  location: class Example
2 errors

To fix the problem, ensure all variables are declared before using them. See the solution:

public class Example {
    public static void main(String... args) {
        int a = 10;
        int b = 20;
        int c = 30;
        int sum; // declare sum
        sum = a + b + c;
        System.out.println(sum);
    }
}

Run the program with the same command, and the program will successfully compile.

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java Javac

Related Article - Java Error