Home
Java
package Example (import Keyword)
Updated Sep 24, 2023
Dot Net Perls
Package, import. A package contains Java code. It has classes, methods, and other forms of data. We import a package to use it in our program.
To begin, please create a new Java package. Call it something like testPackage and then place a public method in the class. The file declares itself as a package with the package keyword.
Code example. Here we see our testPackage package. It contains a class called Test and a printName method. These projects are in the same directory in Eclipse.
Detail In Eclipse we specify the default package. We can then import other packages with the import keyword into this.
Note We do not need to use the "import" keyword. We can specify a type like testPackage.Test but this is hard to type.
package testPackage;

public class Test {

    public void printName() {
        // This method is in the Test class in testPackage.
        System.out.println("Dot Net Perls");
    }
}
import testPackage.Test; public class Program { public static void main(String[] args) { // Create new instance of Test from testPackage. Test test = new Test(); // Call method. test.printName(); } }
Dot Net Perls
Star. With a star, we can import all types in a certain package. Consider the java.util.function package. We can import all its classes with a star directive.
Lambda
import java.util.function.*;
Package and import. We created a package and imported it into the default package. Importing a package simply makes it easier to access—we can use the "Test" class directly.
With the import keyword, we can use classes like ArrayList with simpler syntax. For ArrayList we import java.util.ArrayList. This makes programs easier to read.
ArrayList
Modularity is a key part of Java programming. Object-oriented programming is about decomposing programs into small parts that can be reused. Packages are meant to be used again and again.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 24, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen