Monday, July 12, 2021

The Ultimate Guide to Package in Java? Examples

If you are learning Java then you might have come across a package concept and if you are wondering what is package and why should we use it then you have come to the right place. In this article, I will explain what is package in Java and other stuff around the package, including some best practices which using the package in Java. In the simplest form, a package is a way to organize related functionality or code in a single place in Java. If you look from a File System perspective then a package in Java just represent a directory where Java source file is stored in compilation and class files are stored after compilation. 

For example, if you create a class HelloWorld in a package called com.java67.welcome; then it will reside under directory com/java67/welcome in the source tree and you can view that in your IDE like Eclipse or Netbeans or even by navigating to the file system.

Once you compile your Java program either by using an IDE,  ANT build script or Maven compile plugin; it creates class files under the same package structure. For example, Maven will create target/classes/com/java67/welcome directory and place HelloWorld.class inside that.

It's mandatory that class files reside on the same package or directory as declared in their source file using package keyword, failure to do will result in java.lang.NoClassDefFoundError in Java.

In summary answer to the question of what is package in Java can be as simple as that package is a keyword in Java that is used to specify a directory structure for the particular class file, but at the same time, it is also used to control access. You can use a package to organize code in a meaningful directory for better navigation.

Now, that you know what is a package in Java, let's explore more about it by creating and using a package in the Java program.




1. How to create a package in Java

If you are using IDE like Eclipse for developing your Java program then you don't need to do anything.

Just click on the new-->package and Eclipse will ask you the name of the package, put the name of the package, and you are done.

Now if you want to create a Java class on that package, just select the package in the package explorer and create a new-->Java Class.

If you are not using any IDE then you manually need to create directories corresponding to your package in Java.

Eclipse IDE is also very smart with respect to packages. For example, if you copy code then you don't need to create packages for them. Just copy and select the project where you want to paste your code and paste it. 

You might be wondering what is default package here, well, it's nothing but when you don't put your classes on any package or directory they reside just under the project directory and that is referred to as the default package. If you are interested to learn more, I encourage you to check these free Eclipse courses from Udemy. 

The eclipse will create the necessary packages for you as shown below:

What is package in Java





2. How to use a package in Java

Using a package in Java is very simple. just use the package keyword along with the name of the package at the top of your Java source file to declare a package in Java. package declaration must be the first line in the Java source file even before the import statement.

Here is an example of how to use a package in Java

package blog.java67.welcome

public class Hello{
    public static void main(String args[]){
         System.out.println("An Example of using package in Java");
    }

}

In this example, we have a directory blog/java67/welcome, which is a package and Hello.java class is stored under it. When the Java compiler will compile this class, it will verify whether this particular class is stored as  /blog/java67/welcome/Hello.java, which is relative to the classpath.

Btw, if you are not familiar with the Classpath concept in Java, you can join these free Java Programming courses to learn Java fundamentals.

A Beginners Guide to Package in Java




3. Important packages in Java

All the Java classes are structured into a different package based upon their functionality for example java.lang package contains classes that are essential to Java programming language e.g. ThreadException, Error, Object, etc.

On the other hand package like java.util contains all utility classes e.g. Collection classes, Scanner, and other utility.  java.io package contains Java classes related to Input and Output functionality.

The java.util.concurrent also called sub package of java.util contains Concurrent utility classes like CountDownLatchCyclicBarrierSemaphore etc


Here is a nice diagram which shows some important package of Java API or JDK:


Package in Java What Why and Best Practices Example Tutorial


                                                                                                                                                                    The java.lang package is automatically imported by the compiler in Java. That's why if you a class from this package e.g. String, Integer, or System, you don't need to import them.

                                                                                                                                      

4. Why use the package in Java

A package provides Encapsulation in Java program. default access modifier for any variable or class is package-private i.e. they are only visible into the package, on which they are declared.

By using the package you Encapsulate the whole functionality which allows you to change the functionality, including new functionality, or just change the implementation without breaking the whole application.

Though the package is not the highest degree of Encapsulation in Java which is achieved using a private keyword, it still seconds the best option and must encapsulate whole functionality rather than just a class.



5. Things to know about Package in Java

Here are some of the key details to remember about the package in Java programming language :

1) java.lang package is automatically imported in every Java class.

2) You can import all classes and sub-packages from a package by using the wildcard * e.g. import com.abc.* will import all classes on package com.abc as well as classes on any subpackage.

3) package must be the first statement, even before import statement in Java source file.

You can further see Core Java Volume I and II by Cay S. Horstmann to learn more about the package and other fundamental concepts in Java.

Best Practices to Use Package in Java Program




6. Best Practices to Use Package in Java Program

Packages are also your main tool for organizing code. You should put a great deal of hard work while naming your package, deciding which class goes to which package etc. Also, try to follow Uncle Bob's (Robert C. Martin) package best practices for better architecture :

1) CCP (Common Closure Principle) - Advise putting classes together, which are likely to change together. Obviously, must be part of the same functionality.

2) CRP (Common Reuse Principle) - Advice putting classes based upon there re-usability aspect. It advises against a giant package with loads of classes, which can not be reused together. The idea is to keep the package small and cohesive.

Most important is naming the package properly, based upon functionality.

Oracle recommends following best practices and naming conventions for Java packages :


1) Programmers should use hierarchical structure to define packages and sub-packages, as used in JDK itself e.g. java.util, then java.util.concurrent, then java.util.concurrent.atomic or java.util.concurrent.lock etc.


2) Just like keeping the first letter as Capital case of a Java class, packages usually use all lowercase letters, you can see it through Java libraries e.g. java.langjava.utiljava.io they all use small letters.


3) One example of creating a package for a product in a company to define some features can be com.prod.features. If product or company has a hyphen in there name, replace them with an underscore.


4) packages and classes should not be dependent on each other in a cyclic manner because cyclic dependencies make it difficult to understand and modify a software system.



5) Prefer explicit import, identifying the particular classes imported over implicit import using a wildcard, by using * operator to include all classes from a package. Explicit import is better than implicit import as it cannot be misinterpreted.

The precedence of Java imports (explicit, package, wildcards) is not well known and often misused leading to hard-to-find and understand problems. Also, using explicit imports result in a precise list of all dependencies.

This makes it easier to comprehend how dependent a class is in other classes (the higher dependency, the more complex the class).

Consider the scenario where a programmer has defined a class Set in a package pkg. Consider now that someone else attempts to define a class UseSet in package pkg, which intends to use Java's own java.util.Set (and not p.Set). If the import is explicit, hence import java.util.Set, then the right version will be accessed.


However, if the import is implicit, hence import java.util.*, then p.Set will be accessed

package pkg ;

import java.util.HashSet; // ok
import java.util.Set; // ok
//import java.util.*; // this would not be ok

public class UseSet {
private Set set = new HashSet();

public void addElement(int i) {
   set.add(i);
}
...
}

Remember, just like class, you can not have two packages with the same name, but as you can have two classes with the same name in different packages, you can also have the same name of sub-packages inside two different packages.

6) Java 5 release also added a new feature on package concept, called static import which allows you to import static members of a class in Java. This is very useful and reduces a lot of code because then you can use the methods of an imported class as defined in same class i.e. without the class name.

Some of the popular examples of this are the static import of Assert class of JUnit testing library and Collectors class of Java 8 Stream library.

Since Collectors defined a lot of utility methods e.g. Collectors.toList() to convert Stream to List and Collectors.toMap() to convert Stream to Map, by static import you can just call them like toList() and toMap() which make your code more concise and readable.


That's all about what a Java programmer should know about a package in Java. We have gradually learned from basic like what is package in Java, Why should we use a package in Java and how to use a package in Java to some best practices while using a package in Java application.

A good knowledge of package feature is important to structure complex Java application and clever use of package-private encapsulation can lead to highly flexible and maintainable software.

One example of clever use of package is java.util.EnumSet class, which is abstract and both of its implementation JumboEnumSet and RegularEnumSet are package-private. Since the instance of EnumSet is created via factory methods and these classes are package-private, there is no way a client can use them directly, allowing you to ship a new implementation in the future without affecting any client.

A simple example of a package as shown in the above Java program is enough to make you going and explores how Java source files and class files organize into a package.


Other Articles You May Like to Explore
10 Things Java and Web Developer Should Learn
10 Testing Tools Java Developers Should Know
10 New Features of Java 10 Programmer Should Know
5 Frameworks Java Developers Should Learn
10 Books Every Java Programmer Should Read
10 Tools Java Developers uses in their day-to-day work
Data Structures and Algorithms: Deep Dive Using Java


Thanks for reading this article so far. If you like this Java Package tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.