Packages in Java – Know their Importance in Java !!

Before we get into the depths of the topic Packages in Java, let us look at a real-life example at first.

Imagine you are shopping at a mall. You need a new shaving kit as your old one has worn out completely. So you decide you have to buy a few things, such as a shaver, a trimmer, shaving foam, and antiseptic liquid. Now, instead of buying each item individually, you come across a person who is selling all of the kits inside a package. They are calling it “money saver pack” because they are selling all the items at a lower price than each individual item combined.

You understand that you would be saving both money and time if you buy the pack instead of buying the individual items. What you did was invoke a package rather than individual classes. This is the function of packages in Java.

Keeping you updated with latest technology trends, Join DataFlair on Telegram

Packages in Java

Since the beginning of these articles we have been writing import java.io.* or import java.util.*;. These are packages in Java that have classes each of which has a specific function. Hence packages in Java encapsulate similar classes and functions. It can also have interfaces and sub-packages!

Creating Packages in Java

Creating packages in Java is very simple. Just include the package command and the name of the package after it. Remember that this should be the first line of your program. For example, if I want my class to be in a package called “javatutorials” then my program would look like:

package javatutorials;
public class DeclarePackage {
  public static void main(String[] args) {
    System.out.println("This class is inside the javatutorials package.");
  }
}

Output

This class is inside the javatutorials package.

Compiling  Java Package Program

If you are using an IDE, directly executing the program will do. However, if you are not using an IDE, then you should follow the following steps.

In order to compile the program, use the javac command to compile the program as usual. But there is a little twist to it. The syntax changes to:

javac -d <directory> <filename.java>

The -d marker allows you to set the directory inside which the java file is present. It also specifies the directory whether the class file will be present after compilation of the program.

For example, if my java file was inside C:/javatutorials, and my filename was Javapackages.java, then my command to compile this particular class would be:

javac -d C:/javatutorials JavaPackages.java

However you can directly navigate to the target folder using CMD or whatever Command Line Input you are using, and then execute the java file like we did before.

javac -d . JavaPackages.java;

The dot represents the current folder.

Executing Package in Java

Executing package programs is as easy as compiling them. The fully qualified name of a class is <package>.<classname>. This is one way of executing package programs. For example, if I have to execute the class file created when I compiled my JavaPackages program I would have to write: java javatutorials.javapackages

This would immediately execute the class file.

Advantages of Using Java Packages

  1. Implementing Data Encapsulation in Java is easy with the help of packages.
  2. Packages help prevent naming conflicts.
  3. It orders the classes according to their functions. Hence it is easy to search for classes.
  4. You can control the accessibility of the classes by using access specifiers and packages together. A detailed table of access controls in packages is present at the end of the article.

While programming you have to put the related classes inside a particular package. That way we can invoke the classes as we want while programming. You can also use the CLASSPATH variable in Java to access the directory “dataflair”.

Naming Convention In Java Packages

If you observe carefully, you will see a resemblance between packages and directory paths. For example, if a package looks like “dataflair.courses.java”, then it is understood that the java class is present within the courses folder which is, in turn, present inside the dataflair folder.

You have to name packages following their directory positions. You also have to follow a reverse order for domain names while declaring packages.

How Packages Work In Java

Packages in Java store the classes and interfaces inside them. How to store them? The next topic will illustrate that for you. You can also use your java programs to import classes from other packages.

When you compile a program it is saved to the respective package if you explicitly mention the package name in the program. Otherwise, it gets saved to a different package that holds all the default classes inside it. (i.e, classes with no explicit mention of a package). We will see a detailed explanation about how packages work in Java in the following subtopics.

How to Add Class to a Package in Java?

If you follow our articles carefully, you would notice that before the start of every program we write something on the lines of “package com.dataflair….”? This is the syntax for adding a particular class to a package:

package <directory name1>.<directoryname2>…<finaldirectoryname>;

For example, if you want to save my class in the encapsulation folder you would write the following line before my program
“package com.dataflair.encapsulation”

Subpackages in Java

Subpackages, as the name suggests, are packages inside other packages. You need to explicitly import them into a program if you need to use classes inside the subpackages. You can limit the access privileges of subpackages by using private variables and methods. For more information about this, refer to the access specifier article.

A very common example of using subpackages in java is as follows:
import java.util.*;

util is a subpackage of the package java.

Java program to illustrate the use of subpackages in java:

package com.dataflair.packagetutorial;

public class SubPackages {
  public static void main(String[] args) {
    System.out.println("This program is inside a subpackage of the dataflair package");
  }

}

Output

This program is inside a subpackage of the dataflair package.

How do I Access Class Inside a Package in Java?

Accessing classes inside a subpackage is as simple as it can be. You simply have to specify the name of the class after the import package command. For example, if you have to use the Scanner class of the util package you simply import that by saying

import java.util.Scanner;

Note that you can only access the classes and interfaces within the package. The import command does not import the classes within subpackages. If you want to import them you have to do so explicitly.

For example import java.*; will not import the subpackage util. You have to explicitly mention it.

So, there are two ways of accessing classes:

  • One of them is the usage of the star operator(import java.io.*) which imports all the classes and interfaces from the package.
  • The other one being explicitly mentioning the particular class. (import java.util.Scanner;)
  • Using a fully qualified name i.e, <packagename>.<classname>

Java program to illustrate the use of * operator to import classes:

package com.dataflair.packagetutorials;
import java.io. * ;
public class StarImport {
  public static void main(String[] args) throws IOException {
    System.out.println(“The star operator imports all the classes and interfaces from the java.io package”);
  }
}

Output

The star operator imports all the classes and interfaces from the java.io package

Java program to illustrate the use of the class name after the package name:

package com.dataflair.packagetutorial; //subpackage 
import java.util.Scanner;
import java.io. * ;
public class PackageDotClass {
  public static void main(String[] args) throws IOException {
    System.out.println("This class is in a subpackage");
    Scanner sc = new Scanner(System. in );
    System.out.println("We could use the Scanner class because we imported it");
  }
}

Output

This class is in a subpackage
We could use the Scanner class because we imported it.

Java program to illustrate the use of fully qualified names:

package com.dataflair.packagetutorial;
public class FullQualifiedPackage {
  public static void main(String[] args) {
    //We will use the fully qualified name of the scanner class
    java.util.Scanner sc = new java.util.Scanner(System. in );
    System.out.println("This is an example of the usage of a fully qualified name");
  }
}

Output

This is an example of the usage of a fully qualified name.

Creating Java Package and Importing other Java Packages

You can save a class in a package and import other packages in the same program! Let us see an example to understand all the concepts till now.

Java program to understand the concept of packages in java:

package com.dataflair.packagetutorial;

import java.io. * ; //Imports all classes
import java.util.Scanner; //imports only the Scanner class. 
public class Packages {
  public static void main(String args[]) throws IOException {
    System.out.println("This class is an example of packages in Java");
  }
}

Output

This class is an example of packages in Java

This program creates a packages class and stores the class inside the package “packagetutorial”. It also imports all of the classes from java.io and a specific java.util.Scanner class.

Types of Packages in Java

Types of Packages in Java (df)

Just like datatypes, packages are also of two types:

  1. in-built
  2. User-Defined

In-Built Packages in Java

Let us look at in-built packages in java:

1. java.lang – This package consists of classes that help in performing input out operations in the program. It also contains language support for data types and math operations. Whenever you create a class, this package is automatically imported.
2. java.io – This package contains classes that specialize in input and output operations only. One popular thing class you might have seen in programs is the InputStreamReader class and the BufferedReader class.
3. java.util – This class contains basic utilities that can be useful while implementing LinkedLists, Trees, HashMaps, and so on. It also has a Scanner class for input-output operations to the program. It also contains support for date and time.
4. java.applet – This package contains necessary classes for creating applets.
5. java.awt – This package specializes in providing support for designing GUI elements in Java.
6. java.net – This package contains classes which help in performing network operations.

User-Defined Packages in Java

As the name suggests, user-defined packages in Java are essentially packages, which the programmer-defined explicitly. Basically all our programs throughout these articles are inside explicitly defined packages. Whenever you need to add a class within a package, just specify the package name along with the “package” keyword at the beginning of the program.

Program to illustrate user-defined packages in Java:

packages com.dataflair.packagetutorial;
public class UserDefinedPackages {
  public static void main(String[] args) throws IOException {
    System.out.println(“This class is inside the packagetutorial package which is a user - defined package.”);
  }
}

Output

This class is inside the packagetutorial package which is a user-defined package.

Using Static Import in Java

Static import is a function that is present in Java versions 5 and above. Using static import you do not need to specify the entire class name of static functions. You can simply access the static member of the class without using the fully qualified name. Confusing? Don’t worry we have an example set up for your benefit.

Java program to illustrate the concept of static import in java:

package com.dataflair.packagetutorial;

import static java.lang.System. * ;
public class StaticImport {
  public static void main(String[] args) {
    //System.out.println(“this is normal printing?”);
    out.println("This is printed by the help of static import in Java");
  }
}

Output

This is printed by the help of static import in Java

Important Points to Note while using Packages in Java

  1. If you do not specify a package name for a class then there is a default package which stores that class.
  2. We can access classes of different packages by using the simple syntax <package_name.<Class_name>
  3. The classes and interfaces are part of the same class. However, there can be multiple files which specify the package name.
  4. The directory name must always match with the package name.
  5. Every class you define in Java is a part of a package.

Dividing Classes into Packages in Java

There are no hard and fast rules for dividing the classes into packages, but there are certain conventional ways to do so.

1. Divide by layer

This essentially means that classes that work on the same layer should be in the same package. For example, all the programs which manage the backend of the software should be inside a package called “backend”

2. Divide by functionality of the application

This means that the classes which serve the same functionalities are inside the same package. This is how we group our programs in the articles you read. Notice that each package starts with “com.dataflair” and ends with a package name which directly corresponds to what topic we would be learning about. For example, in this article, the package name is “com.dataflair.packagetutorials”. All the programs related to packages in java are inside this folder.

As your application grows it is easier to group your classes by functionality rather than by layer. This is because the number of layers remains the same throughout and the number of classes inside the packages increase. On the other hand, the number of classes inside packages is limited if you divide your classes on the basis of functionality.

Access Protection in Packages in Java

You can limit the access of classes, methods, and variables throughout packages by using access specifiers. We came to know about them in the article about access specifiers in Java. In the table, ‘Yes’ means that the data is accessible and ‘No’ means the data can not be accessible.

Public Private  Protected Default
Inside the same class Yes Yes Yes Yes
Inside the same package and in a subclass Yes No Yes Yes
Inside the same package but not in a subclass.  Yes No Yes Yes
Inside different packages but in a subclass Yes No Yes No
Inside different packages and not in a subclass.  Yes No No No

Summary

We learned a lot about packages in Java, where we should use them, their advantages. We also learned about static imports, accessibilities, and many more. Packages are an essential part of the clean and fluid development of software.

4 Responses

  1. priya says:

    A package is a grouping of related types providing access protection and name space management. Many thanks for sharing this blog.

    • Asif khan says:

      Packages is the collection of classes sub packages and interfaces..

      • Data Flair says:

        Hi Asif,
        We glad you provide such a brief information to other readers. We hope you explore other Java tutorials, we refer you to participate on this Java Quiz
        Regards,
        Data-Flair

    • Data Flair says:

      Hi Priya,
      Thanks for sharing information with us on. It will help other readers to understand the definition of Packages in Java.
      Visit Data-Flair to learn java Programming Language.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.