The Wayback Machine - https://web.archive.org/web/20240820165954/https://www.geeksforgeeks.org/how-to-create-a-package-in-java/
Open In App

How to Create a Package in Java?

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Package in Java is a mechanism to encapsulate a group of classes, sub-packages, and interfaces. All we need to do is put related classes into packages. After that, we can simply write an import class from existing packages and use it in our program. A package is a container of a group of related classes where some classes are accessible or exposed and others are kept for internal purposes. We can reuse existing classes from the packages as many times as we need them in our program. Package names and directory structure are closely related

Types of Packages in Java

There are two types of packages in java:

  1. User-defined Package (Create Your Own Package’s)
  2. Built-in packages are packages from the java application programming interface that are the packages from Java API for example such as swing, util, net, io, AWT, lang, javax, etc.

In this article, we will see How To Create A Package In Java. A package is a group of similar types of Classes, Interfaces, and sub-packages. We use Packages to avoid name conflicts. 

Syntax: To import a package

import package.name.*;

Example: Importing java.util package

Java
// Java Program to Import a package

// Importing java utility package
import java.util.*;

// Main Class
class GFG {

    // Main driver method
    public static void main(String[] args)
    {

        // Scanner to take input from the user object
        Scanner myObj = new Scanner(System.in);
        String userName;

        // Display message
        // Enter Your Name And Press Enter
        System.out.println("Enter Your Name:");

        // Reading the integer age entered using
        // nextInt() method
        userName = myObj.nextLine();

        // Print and display
        System.out.println("Your Name is : " + userName);
    }
}

Input

Enter Your Name:
geeksforgeeks

Output:

Your Name is : geeksforgeeks

Here In The Above Program, ‘java.util’ package is imported Scanner class is used to take input from the user. These are called as Inbuilt Packages. 

Creating a Package in Java

Now in order to create a package in java follow the certain steps as described below: 

  1. First We Should Choose A Name For The Package We Are Going To Create And Include. The package command In The first line in the java program source code.
  2. Further inclusion of classes, interfaces, annotation types, etc that is required in the package can be made in the package. For example, the below single statement creates a package name called “FirstPackage”.

Syntax: To declare the name of the package to be created. The package statement simply defines in which package the classes defined belong.

package FirstPackage ;

Implementation: To Create a Class Inside A Package 

  1. First Declare The Package Name As The First Statement Of Our Program.
  2. Then We Can Include A Class As A Part Of The Package.

Example 1: Creating a Class Inside a Package

Java
// Name of package to be created
package FirstPackage;

// Class in which the above created package belong to
class Welcome {
    // main driver method
    public static void main(String[] args)
    {
        // Print statement for the successful
        // compilation and execution of the program
        System.out.println(
            "This Is The First Program Geeks For Geeks..");
    }
}

So Inorder to generate the above-desired output first do use the commands as specified use the following specified commands

Procedure to Generate Output:

1. Compile the Welcome.java file: 

Command: javac Welcome.java 

2. This command creates a Welcome.class file. To place the class file in the appropriate package directory, use:

Command: javac -d . Welcome.java 

3. This command will create a new folder called FirstPackage. To run the class, use:

Command: java FirstPackage.Welcome 

Output: The Above Will Give The Final Output Of The Example Program.

Output

Example 2: Another Package Example 

Java
// Name of package to be created
package data;

// Class to which the above package belongs
public class Demo {

    // Member functions of the class- 'Demo'
    // Method 1 - To show()
    public void show()
    {

        // Print message
        System.out.println("Hi Everyone");
    }

    // Method 2 - To show()
    public void view()
    {
        // Print message
        System.out.println("Hello");
    }
}

Again, in order to generate the above-desired output first do use the commands as specified use the following specified commands

Procedure: 

1. Compile the Demo.java file:

Command: javac Demo.java 

2. This command will generate a Demo.class file: 

Command: javac -d . Demo.java 

3. This command will create a new folder called data containing the Demo.class file.

Note: In data Demo.java & Demo.class File should be present 

Example 3: Accessing Data from Another Program

Java
// Name of the package
import data.*;

// Class to which the package belongs
class ncj {

    // main driver method
    public static void main(String arg[])
    {

        // Creating an object of Demo class
        Demo d = new Demo();

        // Calling the functions show() and view()
        // using the object of Demo class
        d.show();
        d.view();
    }
}


Procedure to Generate the Output:

1. Compile the ncj.java file:

Command: javac ncj.java 

2. The above command compiles ncj.java and requires the Demo.class file to be present in the data package.

Command: java ncj 
// To Run This File

Output: Generated on the terminal after the above command Is executed 

Hi Everyone
Hello


Previous Article
Next Article

Similar Reads

Java Program to Create a Package to Access the Member of External Class and Same Package
As the name suggests a package in java that contains all the same kinds of classes, Abstract classes, interfaces, etc that have the same functionality. A Single package can contain many classes, Abstract classes e.g. java.util package etc. There are two types of packages: Built-in-package: These are the packages that are predefined in the java jar
2 min read
Java.lang.Package class in Java
Java 2 added a class called Package that encapsulates version data associated with a package. Package version information is becoming more important because of the proliferation of packages and because a java program may need to know what version of a package is available. This versioning information is retrieved and made available by the ClassLoad
8 min read
Java.util Package in Java
Java.util PackageIt contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array).Following are the Important Classes in Java.util package : AbstractCollection: This class provides a skelet
4 min read
Java.lang package in Java
Java.lang package in JavaProvides classes that are fundamental to the design of the Java programming language. The most important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time. Following are the Important Classes in Java.lang package : Boolean: The Boolean class wraps a val
3 min read
Java.io Package in Java
Java.io Package in JavaThis package provides for system input and output through data streams, serialization and the file system. Unless otherwise noted, passing a null argument to a constructor or method in any class or interface in this package will cause a NullPointerException to be thrown. Following are the important classes in Java.io package:
1 min read
HTTP API of java.net.http Package With Examples
HTTP Client and WebSocket APIs provide high-level client interfaces to HTTP (versions 1.1 and 2) and low-level client interfaces to WebSocket. The main types defined are namely as follows: HttpClientHttpRequestHttpResponse The protocol-specific requirements are defined in the Hypertext Transfer Protocol Version 2 (HTTP/2), the Hypertext Transfer Pr
14 min read
javax.xml.crypto Package in Java
Common classes having the XML cryptography for the Package javax.xml.crypto. now this crypto package includes similar classes that are used to accessing XML cryptographic on its operations, such as creating an XML signature or encrypted XML data. There are two types of javax.xml.crypto classes in this package that are KeySelector class, which allow
4 min read
Package getSpecificationVendor() method in Java with Examples
The getSpecificationVendor() method of java.lang.Package class is used to get the vendor of the specification of this package. The method returns the specification vendor of the package as a String.Syntax: public String getSpecificationVendor() Parameter: This method does not accept any parameter.Return Value: This method returns the specification
2 min read
Package getImplementationTitle() method in Java with Examples
The getImplementationTitle() method of java.lang.Package class is used to get the title of the implementation of this package. The method returns the implementation title of the package as a String.Syntax: public String getImplementationTitle() Parameter: This method does not accept any parameter.Return Value: This method returns the implementation
2 min read
Package getImplementationVersion() method in Java with Examples
The getImplementationVersion() method of java.lang.Package class is used to get the version of the implementation of this package. The method returns the implementation version of the package as a String.Syntax: public String getImplementationVersion() Parameter: This method does not accept any parameter.Return Value: This method returns the implem
2 min read
Package getSpecificationVersion() method in Java with Examples
The getSpecificationVersion() method of java.lang.Package class is used to get the version of the specification of this package. The method returns the specification version of the package as a String.Syntax: public String getSpecificationVersion() Parameter: This method does not accept any parameter.Return Value: This method returns the specificat
2 min read
Package getSpecificationTitle() method in Java with Examples
The getSpecificationTitle() method of java.lang.Package class is used to get the title of the specification of this package. The method returns the specification title of the package as a String.Syntax: public String getSpecificationTitle() Parameter: This method does not accept any parameter.Return Value: This method returns the specification titl
2 min read
Package getName() method in Java with Examples
The getName() method of java.lang.Package class is used to get the name of this package. The method returns the name of the package as a String.Syntax: public String getName() Parameter: This method does not accept any parameter.Return Value: This method returns the name of the package as a String.Below programs demonstrate the getName() method.Exa
2 min read
Package getImplementationVendor() method in Java with Examples
The getImplementationVendor() method of java.lang.Package class is used to get the vendor of the implementation of this package. The method returns the implementation vendor of the package as a String. Syntax: public String getImplementationVendor() Parameter: This method does not accept any parameter.Return Value: This method returns the implement
2 min read
Package isSealed(URL) method in Java with Examples
The isSealed(URL) method of java.lang.Package class is used to check if this package is sealed or not, with respect to the specified URL. The method returns the result as a boolean value.Syntax: public boolean isSealed(URL url) Parameter: This method does not accept any parameter.Return Value: This method returns the result as a boolean value.Below
2 min read
Package isCompatibleWith() method in Java with Examples
The isCompatibleWith() method of java.lang.Package class is used to check if this package's specification version is compatible with the specified version or not. The method returns the result as a boolean value.Syntax: public boolean isCompatibleWith(String desiredVersion) Parameter: This method accepts a parameter desiredVersion which is the vers
2 min read
Package toString() method in Java with Examples
The toString() method of java.lang.Package class is used to get the String representation of this package instance. The method returns the String representation as a String value. Syntax: public String toString() Parameter: This method does not accepts any parameter. Return Value: This method returns the String representation as a String value. Bel
1 min read
Package getPackages() method in Java with Examples
The getPackages() method of java.lang.Package class is used to get the Packages defined by the caller's class loader. The method returns the packages as an array of Package objects. Syntax: public boolean getPackages(String desiredVersion) Parameter: This method does not accept any parameter. Return Value: This method returns the packages as an arr
3 min read
Package isSealed() method in Java with Examples
The isSealed() method of java.lang.Package class is used to check if this package is sealed or not. The method returns the result as a boolean value.Syntax: public boolean isSealed() Parameter: This method does not accept any parameter.Return Value: This method returns the result as a boolean value.Below programs demonstrate the isSealed() method.E
2 min read
Package hashCode() method in Java with Examples
The hashCode() method of java.lang.Package class is used to get the hashCode value of this package instance. The method returns the hashCode value as an integer value.Syntax: public int hashCode() Parameter: This method does not accepts any parameter.Return Value: This method returns the hashCode value as an integer value.Below programs demonstrate
2 min read
Package getDeclaredAnnotationsByType() method in Java with Examples
The getDeclaredAnnotationsByType() method of java.lang.Package class is used to get the declared annotations of the specified declared annotation type present in this class. The method returns an array of declared annotations for the specified declared annotation type. Syntax: public A[] getDeclaredAnnotationsByType(Class<T> declared annotati
2 min read
Package getAnnotationsByType() method in Java with Examples
The getAnnotationsByType() method of java.lang.Package class is used to get the annotations of the specified annotation type present in this class. The method returns an array of annotations for the specified annotation type. Syntax: public A[] getAnnotationsByType(Class<T> annotationClass) Parameter: This method accepts a parameter annotatio
2 min read
Package getDeclaredAnnotation() method in Java with Examples
The getDeclaredAnnotation() method of java.lang.Package class is used to get the declared annotation of the specified declared annotation type, if such an declared annotation is present in this class. The method returns that class in the form of an object. Syntax: public T getDeclaredAnnotation(Class<T> declared annotationClass) Parameter: Th
2 min read
Package getDeclaredAnnotations() method in Java with Examples
The getDeclaredAnnotations() method of java.lang.Package class is used to get the declared annotations present in this class. The method returns an array of declared annotations present. Syntax: public DeclaredAnnotation[] getDeclaredAnnotations() Parameter: This method does not accepts any parameter. Return Value: This method returns an array of d
2 min read
Package getAnnotations() method in Java with Examples
The getAnnotations() method of java.lang.Package class is used to get the annotations present in this class. The method returns an array of annotations present. Syntax: public Annotation[] getAnnotations() Parameter: This method does not accepts any parameter. Return Value: This method returns an array of annotations present. Below programs demonst
2 min read
Package getAnnotation() method in Java with Examples
The getAnnotation() method of java.lang.Package class is used to get the annotation of the specified annotation type, if such an annotation is present in this Package. The method returns that Package in the form of an object. Syntax: public T getAnnotation(Class<T> annotationClass) Parameter: This method accepts a parameter annotationClass wh
2 min read
Package isAnnotationPresent() method in Java with Examples
The isAnnotationPresent() method of java.lang.Package class is used to check if an annotation of the specified annotation type is present in this class. The method returns a boolean value starting the same. Syntax: public boolean isAnnotationPresent(Class<T> annotationClass) Parameter: This method accepts a parameter annotationClass which is
2 min read
java.util.concurrent Package
Java Concurrency package covers concurrency, multithreading, and parallelism on the Java platform. Concurrency is the ability to run several or multi programs or applications in parallel. The backbone of Java concurrency is threads (a lightweight process, which has its own files and stacks and can access the shared data from other threads in the sa
9 min read
Protected vs Package Access Modifiers in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
4 min read
Public vs Protected vs Package vs Private Access Modifier in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access mo
7 min read
Practice Tags :
three90RightbarBannerImg