What is packages and how to use packages in java?

Packages and Import:~

Package = directory. Java classes can be grouped together in packages. A package name is the same as the directory (folder) name which contains the .java files. You declare packages when you define your Java program, and you name the packages you want to use from other libraries in an import statement.

java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form:

  • built-in package
  • user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Package declaration:

The first statement, other than comments, in a Java source file, must be the package declaration.

Following the optional package declaration, you can have import statements, which allow you to specify classes from other packages that can be referenced without qualifying them with their package.

Default package. Although, all Java classes are in a directory, it's possible to omit the package declaration. For small programs it's common to omit it, in which case Java creates what it calls a default package. Sun recommends that you do not use default packages.

Package declaration syntax:

The statement order is as follows. Comments can go anywhere.

  1. Package statement (optional).
  2. Imports (optional).
  3. Class or interface definitions.

Simple example of java package:-

The package keyword is used to create a package in java.

//save as Simple.java

package mypack;

public class Simple{

public static void main(String args[]){

System.out.println("Welcome to package");

}

}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example

javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.

Leave a Reply