Ошибка package does not exist

Are they in the right subdirectories?

If you put /usr/share/stuff on the class path, files defined with package org.name should be in /usr/share/stuff/org/name.

EDIT: If you don’t already know this, you should probably read this doc about understanding classpath.

EDIT 2: Sorry, I hadn’t realised you were talking of Java source files in /usr/share/stuff. Not only they need to be in the appropriate sub-directory, but you need to compile them. The .java files don’t need to be on the classpath, but on the source path. (The generated .class files need to be on the classpath.)

You might get away with compiling them if they’re not under the right directory structure, but they should be, or it will generate warnings at least. The generated class files will be in the right subdirectories (wherever you’ve specified -d if you have).

You should use something like javac -sourcepath .:/usr/share/stuff test.java, assuming you’ve put the .java files that were under /usr/share/stuff under /usr/share/stuff/org/name (or whatever is appropriate according to their package names).

Usually, Java developers face the “package does not exist” error when they import a package into their class. If you are one of them, it’s worth reading this article.

If you’re a Java developer, you may have encountered the “package does not exist” error at some point. This error occurs when the Java compiler is unable to find the package that you’re trying to use in your code.

In this article, we’ll discuss what is a package in Java and how to import a package in your java program to utilize the built-in functionalities. Furthermore, we’ll also discuss the most common error that Java developers face which is Java package does not exist. So without further ado, let’s dive deep into the topic.

Table of Contents
  1. What is a Package in Java?
  2. How to Create And Use a Java Package in Java?
  3. What is the “Package Does Not Exist” Error in Java?
  4. Reasons and Solution for the Java “Package Does Not Exist” Error
    1. Case 1: Writing The Wrong Name of The Package
    2. Case 2: Install Packages Properly
    3. Case 3: IDE Problem
    4. Case 4: Setting Class Path
    5. Case 5: The Package Does Not Exist
    6. Additional Fixes

What is a Package in Java?

A package is a collection of related interfaces and classes. It helps us to organize different classes and interfaces in a folder structure. Each package in Java must have a unique name; it stores different classes in a separate namespace. We have two types of packages:

  1. Built-in Packages (Come with Java API)
  2. User-defined Packages (User created packages)

Packages improve the reusability of code and make it easy to locate. Packages are mainly used to avoid name conflicts between classes. Although classes with the same name are not allowed to appear in a package, they may appear in different packages.

How to Create And Use a Java Package in Java?

To create a package, we have to choose a unique name for the package and write a package statement on the top of the source file. After that, we can define all the classes, interfaces, enumerations, and annotations types we want in our package. 

The general syntax of creating a package is as follows:

package packagename;

How to fix Java Package Does Not Exist

Let’s create a user-defined package but first see its folder structure:

We have two classes in the package(mypackage) and the Main class that contain the main function.

Code of class1 

package mypackage;


public class class1 {

   public void welcome(){

       System.out.println("Welcome to my Class1");

   }
}

Code of class2

package mypackage;


public class class2 {

   public void welcome(){

       System.out.println("Welcome to my Class2");

   }

}

Code of Main class in which we import our package and create objects of its classes.

// import all class of mypackage

import mypackage.*;

public class Main {

   public static void main(String[] args) {

       // creating object of class1 of mypackage

       class1 c1= new class1();

       c1.welcome();



       // creating object of class1 of mypackage

       class2 c2= new class2();

       c2.welcome();



   }

}

Output

Welcome to my Class1

Welcome to my Class2

We can also import just one class of package just we have to write import mypackage.class1; in place of import mypackage.*;

What is the “Package Does Not Exist” Error in Java?

As we understand what a package is and how it stores in computer memory, Now we can easily understand what package does not exist error and when it occurs. We are getting this error because the compiler can not find the package we mention.

As in the above example, if we write mypackage1 instead of mypackage then we will get this error:

Java Package Does Not Exist

Reasons and Solution for the Java “Package Does Not Exist” Error

Following are some of the main reasons this error occurs:

  1. Write the wrong name of the package
  2. Install packages properly
  3. IDE Problem
  4. Setting Class Path
  5. The package does not exist

Now we’ll discuss these reasons one by one and see what the solution to these reasons:

Case 1: Writing The Wrong Name of The Package

Most of the time, we face this problem when we write the wrong package name. Always double-check the package’s name so you don’t face this problem again. As in the above example, if we write mypackage in place of mypackage1, the error will be gone.

If you’re typing the package name manually, it’s easy to make a typo. Make sure you’re spelling the package name correctly, and double-check that you’re using the correct capitalization.

Case 2: Install Packages Properly

Sometimes we face this problem when our required package is not installed properly. If you are using IntelliJ IDE, then the settings for installing a package are:

  1. Click File menu
  2. Select the Project Structure option
  3. From the left pane, move to the Global libraries under the platform setting
  4. Click the + symbol 
  5. Select the required package from the hard disk you want to install

Java Package Does Not Exist in Java

That being said, this issue can potentially occur if the package is not imported. To use a package in your Java code, you need to import it using the import keyword. If you forget to import the package, or if you import the wrong package, you’ll get the “package does not exist” error. Ensure you’re importing the correct package, and double-check that you’re using the correct import statement.

Case 3: IDE Problem

If you are using IntelliJ or Eclipse IDE and you installed the package or created the package but still facing the problem, in this case, you have to rebuild the project. In Eclipse, if you have a Java package does not exist error then follow these steps:

  1. In the project folder, go to the src folder, cut all the files and folder from it to a temporary folder.
  2. Build the project
  3. Now copy all the files and folders from the temporary folder to the src folder.
  4. Run the build again

Now you don’t have the package does not exist error again. 

Case 4: Setting Class Path

We face this problem when the Class Path of our package is not set. To use a package in Java, it must be on the classpath. The classpath is a list of directories and JAR files that the Java compiler searches for class files. If the package you’re trying to use is not on the classpath, you’ll get the “package does not exist” error. To fix this, you need to add the package to the classpath.

To do so, follow these steps.

  1. Type Environment variables in the search box.
  2. Select Edit Environment variable option from the search.
  3. Select the Advanced tab.
  4. Click on the Environment Variables button.
  5. Click on the New button under System Variables.
  6. Add CLASSPATH as the variable name and the package’s path as a variable value.
  7. Select OK.

Fix Java Package Does Not Exist in Java

Case 5: The Package Does Not Exist

In rare cases, the “package does not exist” error might occur because the package you’re trying to use does not actually exist. This can happen if you’re trying to use a third-party library that has been removed or if you’re trying to use a package that has been deprecated.

Additional Fixes

There are several tools and techniques you can use to diagnose and fix the “package does not exist” error in Java. Here are some suggestions:

  1. Check the classpath: Make sure that the package you’re trying to use is on the classpath. You can check the classpath by running the java command with the -cp or -classpath option. For example: java -cp .:lib/* MyClass
  2. Use the javac command: The javac command is the Java compiler. You can use it to compile your Java code and see any errors that occur. For example: javac MyClass.java
  3. Use a build tool: If you’re using a build tool like Maven or Gradle, you can use it to build and run your Java code. The build tool will handle the classpath and dependencies for you, and it will also show you any errors that occur.
  4. Use an IDE: An Integrated Development Environment (IDE) is a software tool that helps you write, debug, and run Java code. Most IDEs have features that can help you fix the “package does not exist” error, such as code completion, automatic imports, and error highlighting.

By using these tools and techniques, you can more easily diagnose and fix the “package does not exist” error in Java. Whether you’re using the command line, a build tool, or an IDE, you should be able to find and fix the problem quickly and get your Java code running smoothly.

  1. Clean and rebuild: If you’re using a build tool like Maven or Gradle, try running the clean task to remove any compiled files, and then run the build task to rebuild the project. This can sometimes fix the “package does not exist” error if it’s caused by a build issue.
  2. Check for missing dependencies: If you’re using a third-party library or package, ensure it’s properly installed and included in your project. If you’re using a build tool like Maven or Gradle, check the dependencies section of your build file to ensure the package is listed.
  3. Check for outdated dependencies: If you’re using a third-party library or package, ensure it’s up to date. Outdated dependencies can sometimes cause the “package does not exist” error if the package has been changed or removed.
  4. Check for conflicting dependencies: If you have multiple dependencies that use the same package, there may be a conflict. Try excluding the package from one of the dependencies to see if that fixes the problem.
  5. Check for missing or outdated JAR files: If you’re using external JAR files (Java Archive files) in your project, ensure they’re properly installed and included in your classpath. Outdated or missing JAR files can sometimes cause the “package does not exist” error.
  6. Check for mismatched Java versions: Ensure you’re using the correct version of Java for your project. If you’re using a newer version of Java than what your project is compatible with, you may get the “package does not exist” error.
  7. Check for syntax errors: Make sure you don’t have any syntax errors in your code that could be causing the “package does not exist” error. Pay attention to the error messages you’re getting, and look for clues as to what might be causing the problem.

Conclusion

By understanding the causes of the “package does not exist” error, you can more easily troubleshoot and fix the problem. Make sure the package is on the classpath, check the spelling and capitalization of the package name, import the package correctly, and verify that the package actually exists. With these tips, you should be able to fix the “package does not exist” error and get your Java code running smoothly.

Finally, at the end of this article, we conclude this topic with this statement that the Java package does not exist is commonly caused if you type the wrong name of the package or do not set the classpath. Still, we sometimes face this problem due to IDE; we must rebuild our project or install the package properly.

By following these suggestions, you should be able to fix the “package does not exist” error in Java. If you’re still having trouble, you might want to check online forums or ask for help from other Java developers. With a little bit of effort, you should be able to find a solution and get your Java code running smoothly.

Let’s have a quick review of the topics discussed in this article.

  1. What is a package?
  2. How can we create and use a package?
  3. What is the package does not exist error in Java?
  4. Reasons and solutions for the Java package do not exist.

If you are satisfied with the information given in this article, don’t forget to share it with your coding mates, also comment below 👇 which solution has worked in your case.

Happy coding!🥳

  1. Demonstration of Package Does Not Exist in Java
  2. Resolve Package Does Not Exist Error in Java

Resolve the Package Does Not Exist Error in Java

Today, we will reproduce the package does not exist error in Java to understand the error and its reasons. Further, we will also learn about its solution with the help of code examples.

Demonstration of Package Does Not Exist in Java

Example Code (Students.java file):

package name;

public class Students implements Comparable<Students>{
    private String studentFirstName;
    private String studentLastName;

    public Students(String studentFirstName, String studentLastName){
        this.studentFirstName = studentFirstName;
        this.studentLastName = studentLastName;
    }

    public String getStudentFirstName() {
        return studentFirstName;
    }

    public void setStudentFirstName(String studentFirstName) {
        this.studentFirstName = studentFirstName;
    }

    public String getStudentLastName() {
        return studentLastName;
    }

    public void setStudentLastName(String studentLastName) {
        this.studentLastName = studentLastName;
    }

    /**
     *
     * @param other
     * @return
     */
    @Override
    public int compareTo(Students other) {

        int compareResults = this.studentLastName
                             .compareTo(other.studentLastName);

        if(compareResults == 0){
            if(this.studentFirstName.chars().count() ==
               other.studentFirstName.chars().count()) {
                compareResults = 0;
                return compareResults;
            }
            else if(this.studentFirstName.chars().count() >
                    other.studentFirstName.chars().count()){
               compareResults = 1;
               return compareResults;
            }
            else{
                compareResults =  -1;
                return compareResults;
            }
        }
        else{
            return compareResults;
        }
    }
}

Example Code (StudentMain.java file):

import names.Students;

public class StudentMain {

    public static void main(String[] args) {
        Students student1 = new Students ("Ali", "Ashfaq");
        Students student2 = new Students ("Ali", "Ashfaq");
        System.out.println("Comparison 1: " + student1.compareTo(student2));

        Students student3 = new Students ("Ali", "Ashfaq");
        Students student4 = new Students ("Zoya", "Ashfaq");
        System.out.println("Comparison 2: " + student3.compareTo(student4));

        Students student5 = new Students ("Mehr-un-nissa", "Ashfaq");
        Students student6 = new Students ("Hina", "Ashfaq");
        System.out.println("Comparison 3: " + student5.compareTo(student6));
    }
}

We have a directory Desktop/java/stuff/com/name where all our .java files are located except those containing the main() method. For the above code example, we have Students.java in the Desktop/java/stuff/com/name directory, while StudentMain.java with the main() method is in the Desktop/java/stuff/com directory.

It is also important to note that we have set Desktop/java/stuff to our CLASSPATH.

Let’s understand the code to figure out the error and its causes.

The above code compares the last names of the Students and stores the result in the compareResults variable. This result is further used to compare their first names. How?

If the last name matches, the result would be true means 0. So, it jumps to the if condition and assesses if the number of characters in their first names matches.

The result of comparing first names is based on the following conditions:

  1. If this.count is equal to the other.count, the result will be 0.
  2. If this.count is greater than the other.count, the result will be 1.
  3. If this.count is less than the other.count, the result will be -1.

But, when we try to compile the program, it gives us the following error.

C:UsersMEHVISH ASHIQDesktopjavastuffcom>javac StudentMain.java
StudentMain.java:1: error: package names do not exist
import names.Students;

What does it mean, and why are we facing this problem? This error means the package we are trying to import does not exist.

There can be different reasons for that, and all of them are listed below:

  1. We have imported the incorrect package, or we may have some typos while importing the package.

  2. Recheck if all of the files are in the correct sub-directories.

  3. If we have set our CLASSPATH to Desktop/java/stuff, then the files defined with package name; must reside in the Desktop/java/stuff/com/name directory. You may check this to learn how to set CLASSPATH.

  4. Make sure all the Java source files are in the correct sub-directory. We must also ensure that the Java source files are compiled in the Desktop/java/stuff/com/name directory.

    Why? The .class files must be on the CLASSPATH. Remember, the .java files are not required to be on the CLASSPATH but SOURCEPATH, while .class files are generated when we compile the file using the javac command.

  5. We also get this error if we don’t use the built-in package properly. See the following code:

Example Code:

public class Test{
    public static void main(String[] args){
        /*
        Solution: This line must be as follows:
        System.out.println("Hi!");
        */
        system.out.println("Hi!");
    }
}

Error Description:

Test.java:3: error: package system does not exist
                system.out.println("Hi!");
                      ^
1 error

Resolve Package Does Not Exist Error in Java

Example Code (Students.java file):

package name;

public class Students implements Comparable<Students>{
    private String studentFirstName;
    private String studentLastName;

    public Students(String studentFirstName, String studentLastName){
        this.studentFirstName = studentFirstName;
        this.studentLastName = studentLastName;
    }

    public String getStudentFirstName() {
        return studentFirstName;
    }

    public void setStudentFirstName(String studentFirstName) {
        this.studentFirstName = studentFirstName;
    }

    public String getStudentLastName() {
        return studentLastName;
    }

    public void setStudentLastName(String studentLastName) {
        this.studentLastName = studentLastName;
    }

    /**
     *
     * @param other
     * @return
     */
    @Override
    public int compareTo(Students other) {

        int compareResults = this.studentLastName
                             .compareTo(other.studentLastName);

        if(compareResults == 0){
            if(this.studentFirstName.chars().count() ==
               other.studentFirstName.chars().count()) {
                compareResults = 0;
                return compareResults;
            }
            else if(this.studentFirstName.chars().count() >
                    other.studentFirstName.chars().count()){
               compareResults = 1;
               return compareResults;
            }
            else{
                compareResults =  -1;
                return compareResults;
            }
        }
        else{
            return compareResults;
        }
    }
}

Example Code (StudentMain.java file):

import name.Students;

public class StudentMain {

    public static void main(String[] args) {
        Students student1 = new Students ("Ali", "Ashfaq");
        Students student2 = new Students ("Ali", "Ashfaq");
        System.out.println("Comparison 1: " + student1.compareTo(student2));

        Students student3 = new Students ("Ali", "Ashfaq");
        Students student4 = new Students ("Zoya", "Ashfaq");
        System.out.println("Comparison 2: " + student3.compareTo(student4));

        Students student5 = new Students ("Mehr-un-nissa", "Ashfaq");
        Students student6 = new Students ("Hina", "Ashfaq");
        System.out.println("Comparison 3: " + student5.compareTo(student6));
    }
}

We got the package does not exist error because of importing the wrong package in the StudentMain.java file. We were importing as import names.Students;, while it must be import name.Students;.

You may see all the commands below, including how we set the CLASSPATH.

Output:

C:UsersMEHVISH ASHIQ>cd Desktop/java/stuff
C:UsersMEHVISH ASHIQDesktopjavastuff>set classpath=.;
C:UsersMEHVISH ASHIQDesktopjavastuff>cd com/name
C:UsersMEHVISH ASHIQDesktopjavastuffcomname>javac Students.java
C:UsersMEHVISH ASHIQDesktopjavastuffcomname>cd..
C:UsersMEHVISH ASHIQDesktopjavastuffcom>javac StudentMain.java
C:UsersMEHVISH ASHIQDesktopjavastuffcom>java StudentMain
Comparison 1: 0
Comparison 2: -1
Comparison 3: 1

I’m afraid I’m able to reproduce. Here’s a diff I applied to enunciate-sample:

diff --git a/pom.xml b/pom.xml
index 332623b..ca961e8 100644
--- a/pom.xml
+++ b/pom.xml
@@ -36,6 +36,7 @@
         <version>${enunciate.version}</version>
         <executions>
           <execution>
+            <phase>process-classes</phase>
             <goals>
               <goal>assemble</goal>
             </goals>
@@ -52,6 +53,13 @@
 
   <dependencies>
     <dependency>
+      <groupId>org.immutables</groupId>
+      <artifactId>value</artifactId>
+      <version>2.5.6</version>
+      <scope>provided</scope>
+    </dependency>
+
+    <dependency>
       <groupId>com.webcohesion.enunciate</groupId>
       <artifactId>enunciate-core-annotations</artifactId>
       <version>${enunciate.version}</version>
diff --git a/src/main/java/com/ifyouwannabecool/api/PersonaService.java b/src/main/java/com/ifyouwannabecool/api/PersonaService.java
index a1b238d..9b4f121 100644
--- a/src/main/java/com/ifyouwannabecool/api/PersonaService.java
+++ b/src/main/java/com/ifyouwannabecool/api/PersonaService.java
@@ -15,6 +15,7 @@ import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
 
 import com.ifyouwannabecool.domain.persona.Persona;
+import com.ifyouwannabecool.domain.persona.Thing;
 
 /**
  * The persona services is used to perform actions on the data associated with a persona.
@@ -33,6 +34,10 @@ public interface PersonaService
     @GET
     Persona readPersona(@PathParam("id") String personaId);
 
+    @Path("/thing")
+    @GET
+    Thing getThing();
+
     @Path("/{id}.json")
     @GET
     @Produces("application/json")
diff --git a/src/main/java/com/ifyouwannabecool/domain/persona/Thing.java b/src/main/java/com/ifyouwannabecool/domain/persona/Thing.java
index 3aede1b..2256278 100644
--- a/src/main/java/com/ifyouwannabecool/domain/persona/Thing.java
+++ b/src/main/java/com/ifyouwannabecool/domain/persona/Thing.java
@@ -1,7 +1,14 @@
 package com.ifyouwannabecool.domain.persona;
 
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import org.immutables.value.Value;
+
 /**
  *
  */
+@Value.Immutable
+@JsonDeserialize(as = ImmutableThing.class)
 public interface Thing {
+
+  String getName();
 }
diff --git a/src/main/java/com/ifyouwannabecool/impl/PersonaServiceImpl.java b/src/main/java/com/ifyouwannabecool/impl/PersonaServiceImpl.java
index 72b8b7a..933edca 100644
--- a/src/main/java/com/ifyouwannabecool/impl/PersonaServiceImpl.java
+++ b/src/main/java/com/ifyouwannabecool/impl/PersonaServiceImpl.java
@@ -12,6 +12,7 @@ import javax.ws.rs.Path;
 import com.ifyouwannabecool.api.PermissionDeniedException;
 import com.ifyouwannabecool.api.PersonaService;
 import com.ifyouwannabecool.domain.persona.Persona;
+import com.ifyouwannabecool.domain.persona.Thing;
 
 /**
  * @author Ryan Heaton
@@ -28,6 +29,11 @@ public class PersonaServiceImpl implements PersonaService
         return persona;
     }
 
+    @Override
+    public Thing getThing() {
+        return null;
+    }
+
     public Persona readPersonaJson()
     {
         final Persona persona = new Persona();

I had no problem with setting the scope to provided; Enunciate picked up that artifact just fine.

I did have to change my Maven phase to process-classes in order to pick up the generated immutables classes, which are generated in the compile phase, which happens after the default Enunciate phase (process-sources).

Anyway, if you can send me an alternate diff that exposes the problem, I’d be happy to re-open and look into it further.


803 views
31/07/202231/07/2022

Casue of error, error, Error: java: package org.junit.jupiter.api does not exist, intellij, Java, java: package org.junit.jupiter.api does not exist, jupiter, mavel, org.junit.jupiter.api, package org.junit.jupiter.api does not exist, Solution of error

This java: package org.junit.jupiter.api does not exist error happens when a particular package is not added to your coding environment while you are setting it. One of the major solutions to fix this is by simply making some changes in your environment. Apart from this, there are many other ways of solving the same. 

The code for the following error is: 

import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;

public class SimpleEditMeTest {
private EditMe editMe;
@Before
public void setUp() throws Exception {
    editMe = new EditMe();
}
@Test
public void test() {
    assertNotNull(editMe.getFoo());
}
}

The error message comes out to be: 

java: package org.junit does not exist

Solution for Error: java: package org.junit.jupiter.api does not exist

The solutions for the same are:

For the users who are using maven, there are a few points that they must keep in mind. 

  • Adding JUnit as a dependency in your pom.xml. 
  • Intellij must accept your module as a maven module. If not then add your module as a maven module by right-clicking on it. 
  • The explicit version must have a dependency declaration in your pom file. 
  • You must have dependency management. It is a requirement by maven to resolve the correct version of your project 
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.myorg</groupId>
            <artifactId>myproject-parent</artifactId>
            <version>${myproject.version}</version>
            <scope>import</scope>
            <type>pom</type>
        </dependency>
    </dependencies>
</dependencyManagement>

Another solution can be adding Jar Dependencies manually in your Open Module Settings. You can find these in the installation Intellij Library directory. 

One more solution is by simply adding the JUnit library or by changing the JUnit dependency of your project. 

For those who are using Jupiter. This problem needs features for the solution:

  • Jupiter-junit-api
  • Jupiter Engine

One more solution in the row is to manually add the jar dependencies junit-4.12.jar and hamcrest-core-1.3.jar from the IntelliJ installation lib directory to my project’s Open Module Settings in order to fix it.

Also Read: Switch In Java

Понравилась статья? Поделить с друзьями:
  • Ошибка php failed to open stream
  • Ошибка p704 на автономке планар
  • Ошибка php eval d code on line
  • Ошибка p5353 на ваз 2114
  • Ошибка photoshop not a png file