elibraryportal Logo

Package in Java | Example

→ Package in java encapsulate a group of classes, interface and sub package.

Note:- Meaning of Subpackage:- Packages that are inside another package are the subpackages.

Package in Java

Types of packages in Java:-

  1. built-in package :- There are Many in built in package such as java, lang, awt, javax, swing, net, io, util, sql etc.
  2. user-defined package:- user-defined package which is created by the Programmer(User) is Known as User defined package..

    Syntax: of user-defined package

Advantage of Java Package

  • Easy to manage because class are categories.
  • Package provides access protection using access modifier.
  • removes naming collision.
  • Represent Scope.
  • Package helps in reusability of code.

1) Example


Package in Java Example

How to Compile and run java package Example

Compile: javac -d . A.java

Run:  java mypack1.A

. dot for current directory

-d Destination(where put class file)

Note:- (Javac One Space -d again One space dot one space classname.java)

How to access package from another package?

There are following way.

Access Package from Another way

2) without import(fully qualified name)

A) Example : import the packagename.*


import Package in Java Example

Compile:- javac -d . A.java

Compile: javac -d . Test.java

Run : java mypack2.Test

B) Example : import package.classname


import Package class  in Java Example

2) Example Without import


Without import Package class in Java Example

Sub Package

→ Package inside the Package is Called Sub package.


Subpackage Example in java