The following example demonstrates How to Import a Package in Java.

Step 1: Create a Package

First, let’s create a simple package and a class inside it. Create a directory structure as follows.

mypackage
    └── MyPackageClass.java

MyPackageClass.java (inside the mypackage directory):

package mypackage;

public class MyPackageClass {
    public void displayMessage() {
        System.out.println("This is a message from MyPackageClass.");
    }
}

Step 2: Create a Java Program That Imports the Package

Now, let’s create a Java program that imports the mypackage package and uses the MyPackageClass from that package:

ImportDemo.java (outside the mypackage directory):

import mypackage.MyPackageClass; // Importing the MyPackageClass from mypackage

public class ImportDemo {
    public static void main(String[] args) {
        // Create an object of MyPackageClass
        MyPackageClass myObject = new MyPackageClass();

        // Use a method from MyPackageClass
        myObject.displayMessage();
    }
}

Step 3: Compile and Run

Compile both MyPackageClass.java and ImportDemo.java. Make sure that both files are in separate directories, and the directory containing mypackage is in your classpath.

javac mypackage/MyPackageClass.java
javac ImportDemo.java

Then, run the ImportDemo class:

java ImportDemo

The program will import the mypackage package and use the MyPackageClass to display a message. This demonstrates how to import and use classes from a package in Java.



Further Reading

Spring Framework Practice Problems and Their Solutions

From Google to the World: The Story of Go Programming Language

Why Go? Understanding the Advantages of this Emerging Language

Creating and Executing Simple Programs in Go

20+ Interview Questions on Go Programming Language

Java Practice Exercise

programmingempire

Princites