How to use a package in Java

A Java package is a container of a group of related classes, interfaces, and sub-packages like in your device one folder containing multiple different subfolders and every subfolder containing their subfolders. Simply package is considered to be the main stem of a tree and from which other branches arrises. A package contains various methods which can be either pre-defined or user-defined.

The package is of two types:

  1. Built-in/pre-defined package
  2. User-defined package

Built-in/pre-defined packages are those packages which are already been defined and User defined packages are those packages that are defined by the user or made by the user.

Examples of some pre-defined/built-in packages of Java: java.lang, java.util, java.io, java.math, java.sql, java.awt etc.

A package is used to satisfy the DRY(DO not Repeat Yourself) property. Simply it means write once and use it as many times as you want. Helps in code re-usability, maintenance, data encapsulation, etc.

Steps to follow: How to use pre-defined/built-in packages

Use the import keyword by using the following syntax:

import java.<pre-defined package-name>.<* or class-name or interface-name>;

import java.util.*;      //In this case we can use all the classes, interface, sub-packages and their predefined methods. * symbolise all
import java.util.Scanner;    //In this case we are using a particular class that is Scanner class of java.util package.

Steps to follow: How to use user-defined packages

  • To use a user-defined package in a program, firstly we have to create a user-defined package by using the package keyword. Use the following syntax:
  • package <package-name>;
  • Include classes, interfaces, etc to your user-defined package using the following syntax:
package CodeSpeedy;    //let CodeSpeedy be the user-defined package name we want to use

class CodeSpeedyAns
{
        public static void main(String arg[])
        {
                //write the required functions
        }
}
//write as many classes and interfaces with their required methods
  • Now use your user-defined package in your other programs easily by using the import keyword and following the same syntax used for built-in/pre-defined methods.

          import java.<user-defined package-name>.<* or class-name or interface-name>;

import CodeSpeedy.CodeSpeedyAns;       //assuming our user-defined package name is CodeSpeedy and its main method class is CodeSpeedyAns

 

Leave a Reply

Your email address will not be published.