javac error: "package x does not exist" at "import x"

Your import statement tells the compiler that you need an artifact, in this case you're telling the compiler you need to use junit. But declaring you're using it and providing it to the JVM are different things. You need to make sure your junit jar file is on your classpath.

EDIT: By the way using an IDE will be a time saver for you. I realize eclipse can be intimidating, but I would recommend starting to use it. Unless you're more of a command line type of person, but even then if you're doing anything serious you should use an IDE IMO.


If you are using Java 9 or later with JUnit 5 or later, then it is possible that the JUnit package is defined in a module, and you may need to use --module-path to point to the directory which contains the module/Modular JAR.


You are getting this error because you're trying to import a package without telling your system where the package is located. Here are instructions on telling your system where the package is located:

Your javac target doesn't specify anything apart from the source and target directory - it doesn't add any classpath entries; you'll need to add an entry for the appropriate JUnit jar file. See the javac task documentation for more details. You may want to specify the path to JUnit as a classpath attribute, a nested element, or a reference to a path declared elsewhere.

  • javac task documentation

Source: problem running JUnit tests with Ant in Eclipse. Beginner question

prompt> javac -classpath .;$JUNIT_HOME\junit4.x.x.jar test.java

EDIT: JUNIT INSTALLATION (from here):

Windows

To install JUnit on Windows, follow these steps:

1. Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.

2. Add JUnit to the classpath (type the following into a command line shell): `set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%\junit.jar`

Unix (bash)

To install JUnit on Unix, follow these steps:

1. Unzip the junit.zip distribution file to a directory referred to as $JUNIT_HOME.

2. Add JUnit to the classpath (type the following into terminal):

`export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar`

You are getting this error because you are importing a package or using a jar file which it is unable to locate.

You should check your environment variables for classpath variable. Add the path of your jar file or your package to the classpath variable. Also, add your java file's class file path to the classpath variable if it shows the error "cannot load class, main file not found"

Hope this helps.!!