Java Packages

Java Packages with Examples

In this article, I am going to discuss Java Packages with Examples. Please read our previous article where we discussed Strings in Java. At the end of this article, you will understand the following pointers in Java which are related to Java Packages.

  1. What are Packages in Java?
  2. Types of Packages in Java
  3. User-Defined Packages in Java
  4. How to Compile Java Package?
  5. How to execute the Java Package Program?
  6. How to access package from another package in Java?
  7. Difference Between Implicit Import and Explicit Import
  8. Difference Between #include and import statement
  9. Subpackage in Java
  10. Adding a class to a Package
  11. Advantages of Packages in Java
What are Packages in Java?

The package is a collection of classes and interfaces in the form of .class files. It helps organize your classes into a folder structure and make it easy to locate and use them. More importantly, it helps improve re-usability. Each package in Java has its unique name and organizes its classes and interfaces into a separate namespace, or name group. Although interfaces and classes with the same name cannot appear in the same package, they can appear in different packages.

Packages are used for:
  1. Preventing naming conflicts.
  2. Making searching and usage of classes, interfaces, enumerations, and annotations easier.
  3. Offers access protection such as protected classes, default classes, and private classes.
  4. Packages can be considered as data encapsulation (or data-hiding).
  5. With packages, you can organize your project better and easily locate related classes.
Types of Packages in Java

We have the following two types of packages in Java:

  1. In-Built Packages
  2. User-defined Packages

Types of Packages in Java

In-Built Packages

In-Built Packages are the packages that are given by Sun Microsystems or some other companies as a part of Java. We have the following three types of in-built packages:

  1. Core Packages: Core Packages are predefined packages given by Sun MicroSystems which begin with “java”.
  2. Extended Packages: Extended packages are also predefined packages given by Sun Microsystems which begin with “javax”.
  3. Third-Party Packages: Third-Party Packages are also predefined packages which are given by some other companies as a part of Java Software. Example: oracle.jdbc, com.mysql, etc.
Some In-Built Packages in Java are:
java.lang :

This package is the collection of classes and interfaces using which we can perform basic operations like parsing, to store strings, etc. This package is by default available for every java program. Example: Object, String, Integer, etc.

java.io :

This package is the collection of classes and interfaces using which we can perform basic input and output operations. Example: BufferedReader, Printstream, FileReader, etc.

java.util :

This package is the collection of classes and interfaces using which we can display date, store the group of objects(Collection API). Example: Date, Collection, ArrayList, etc.

java.text :

This package is the collection of classes and interfaces using which we can perform operations like formatting the date, number, etc. Example: NumberFormat, DateFormat, etc.

java.net :

This package is the collection of classes and interfaces using which we can develop network-related applications. Example: Socket, ServerSocket, etc.

java.sql :

This package is the collection of classes and interfaces using which we can perform JDBC related operations like connecting to DB, creating the tables, inserting records, etc. Example: Connection, Driver, DriverManager, etc.

java.awt :

This package is the collection of classes and interfaces using which we can develop GUI based applications. Example: Frame, Label, Button, etc.

javax.swing :

This package is the collection of classes and interfaces using which we can develop a better GUI based Applications. Example: JFrame, JLabel, JButton, etc.

java.applet :

This package is the collection of classes and interfaces using which we can develop applications that run in the browser. Example : Applet, AppletContext, etc.

User-Defined Packages in Java

In Java, we can also create user-defined packages according to our requirements. To create the user-defined packages we have to use a java keyword called “package”. User-defined packages contain only user-defined classes or interfaces in the form of .class files.

Syntax:

User-Defined Packages in Java

Rules:

  1. While writing the package name we can specify packages in any number of levels but specifying one level is mandatory.
  2. The package statement must be written as the first executable statement in the program.
  3. We can write at most one package statement in the program
Sample Program to demo on Packages
package Demo;
public class PackageDemo {
 public static void main(String args[]) {
  System.out.println("Have a Nice Day...!!!");
 }
}
How to Compile Java Package?

If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename 
Example:
javac –d . PackageDemo.java
Or
javac –d E: PackageDemo.java
Or
javac –d D:\practice PackageDemo.java

Here,
-d: This option is used to create the package based on the name specified in the program using the package statements and locate the generated class into the package. E: or D: – Specify the location where to locate the created package.

How to execute the Java Package Program?

You need to use a fully qualified name to run the class.
To Compile javac -d . PackageDemo.java
To Run: java mypack.PackageDemo
Output: Have a Nice Day…!!!

Note: In Java, for every java program following two packages are available by default:

  1. java.lang
  2. Current working directory
How to access package from another package in Java?

We can use all the classes and interfaces are available in the above two packages but if we want to use classes and interfaces that are available in the other packages we must import into our program by using any one of the following two ways:

  1. Using Fully Qualified Name
  2. Using import Statement
Using Fully Qualified Name

Fully Qualified Name means writing the class name using the package name directly. Using this concept we can import only one class at a time. This concept will increase the code size and decrease the readability of the program and this concept is not recommended to use. The Syntax is shown in the below image.

How to access package from another package in Java?

Using the import statement

Using import statement we can import either only one class or many classes from the package. We have the following two types of import statements:

  1. Implicit import
  2. Explicit import
Implicit import :

By using implicit import we can import many classes from the package.

Syntax :
import package.*;
import package1.package2.*;

Example :
import java.io.*;
class ReadingData{
       public static void main(String args[]) throws IOException{
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       }
}

Here, the compiler will decide what class to be loaded in the program hence it is called implicit import.

Explicit import :

By using explicit import we can import only one class from the package.

Syntax :
import package.ClassName;
import package1.package2.ClassName;

Example :
import java.io.BufferedReader;
import java.io.InputstreamReader;
import java.io.IOException;
class ReadingData{
          Public static void main(String args[]) throws IOException{
                 BufferedReader br = new BufferedReader(new InputstreamReader(System.in));
        }
}

Here, the programmer is specifying explicitly what classes to be loaded hence it is called as an explicit import.

Note: It is always recommended to use explicit import in the industry because it always improves the readability of the program.

Rules for writing import statement:
  1. Import statements must be written after the package statement and before the class declaration.
  2. We can write any number of import statements.
Difference Between Implicit Import and Explicit Import

Using implicit import or explicit import both are the same but explicit import will take a little bit more compilation time compared to implicit import but at run time there is no difference.

Difference Between #include and import statement

#include statement is used in C, C++ languages to import the library functions into the program. This #include statement will import the library functions into the program directly so that the length of the program will be increased and compilation time is increased as well. #include will load all library functions whether we use or not. This kind of loading is called static loading.

import statement is used in java to import the classes from the packages. It will load classes into a method area not into the program so that no code size will be increased and no compilation time is increased. This import statement will load only the classes that we use in the application, this kind of loading is called as dynamic loading or load on demand.

Note: When we import the main package then we can use only the classes available in the particular main package, but if we want to use the classes available in the subpackage again we have to write one more important statement for subpackage.

Example-1 :
import java.*; //Invalid
class Demo{
        ArrayList al = new ArrayList();
}

Example-2 :
import java.util.*; //Valid
class Demo{
       ArrayList al = new ArrayList();
}

Subpackage in Java

Packages that are inside another package are the sub-packages. It should be created to categorize the package further. These are not imported by default, they have to imported explicitly. Also, members of a subpackage have no access privileges, i.e., they are considered as a different package for protected and default access specifiers.

Example: import java.util.*; Here, util is a subpackage created inside java package.

Adding a class to a Package

We can add more classes to a created package by using the package name at the top of the program and saving it in the package directory. We need a new java file to define a public class, otherwise, we can add the new class to an existing .java file and recompile it. It is simple to add a class to an existing package.

Adding a class to a Package

If we want to add another class B to this package. Define the class and make it public. Place the package statements

Adding a class to a Package in Java

Store B.java file in p1 directory. Compile B.java file. This will create B.class file and place it in the directory p1.

Advantages of Packages in Java
  1. The package is used to categorize the classes and interfaces so that they can be easily maintained.
  2. Application development time is less because reuse the code
  3. Application memory space is less (main memory)
  4. Application execution time is less
  5. Application performance is enhanced (improve)
  6. Redundancy (repetition) of code is minimized
  7. The package provides access protection
  8. Package removes naming collision

In the next article, I am going to discuss JVM Architecture in detail. Here, in this article, I try to explain Java Packages with Examples. I hope you enjoy this Java Packages with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this Java Packages with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *