Skip to main content

Primary tabs

Submitted by admin on 4 February 2023

A package in Java is a rule used to group your related classes, interfaces and sub-packages.

A Java package organizes Java classes into namespaces, providing a unique namespace .

packages provides a good structure of the project incase  huge amount of classes and files.

There are two types of package

  • Built-in Packages
  • User-defined Packages 

User-defined Packages 

package that is defined by the programmer. Classes and interfaces can be added to a package by including the package statement at the beginning of the source file, followed by the package name.

To create a package in Java, use the package keyword in package declaration.

package [PACKAGE_NAME];
class [CLASS_NAME]{
  public static void main(String[] args) {
    System.out.println("This is my first package!");
  }

 

Built-in Packages

 JDK is  best example of built-in packages.

To use Built-in Packages from the library, you need to use the import keyword

 Import the whole package with .* 

import package.name.*; 
Import the specific class from package

 

import package.name.Class; 

Example of most popular built-in package

java.sql

java.lang

java.util

java.net

java.io

java.awt

features:

  • Preventing naming conflicts.
  • Security
  • data encapsulation (or data-hiding)
  • Code reusability
Tags