DEV Community

PRIYA K
PRIYA K

Posted on

Packages in Java

read gfg,tutorialpoint,w3schools

A package in Java is a mechanism to group related classes, interfaces, and sub-packages into a single unit.
Packages help organize large applications, avoid naming conflicts, provide access protection, and make code modular and maintainable.

Avoiding name conflicts (two classes with the same name can exist in different packages)
Providing access control using public, protected, and default access
Reusability: packaged code can be imported and used anywhere
Encouraging modular programming
Enter fullscreen mode Exit fullscreen mode

It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.

Think of it as a folder in a file directory.

Packages are used in Java in order to prevent naming conflicts, control access, make searching/locating and usage of classes, interfaces, enumerations, and annotations easier, etc.

A package is simply a container that groups related types (Java classes, interfaces, enumerations, and annotations). providing access protection and namespace management.

For example, in core Java, the ResultSet interface belongs to the java.sql package. The package contains all the related types that are needed for the SQL query and database connection.

If you want to use the ResultSet interface in your code, just import the java.sql package (Importing packages will be discussed later in the article).

packages are just containers for Java classes, interfaces and so on. These packages help you to reserve the class namespace and create a maintainable code.

For example, you can find two Date classes in Java. However, the rule of thumb in Java programming is that only one unique class name is allowed in a Java project.

How did they manage to include two classes with the same name Date in JDK?

This was possible because these two Date classes belong to two different packages:
java.util.Date - this is a normal Date class that can be used anywhere.
java.sql.Date - this is a SQL Date used for the SQL query and such.

Types of Java Package
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)

Some of the existing packages in Java are −
java.lang − bundles the fundamental classes
java.io − classes for input , output functions are bundled in this package

1. Built-in Packages
Built-in Packages comprise a large number of classes that are part of the Java API.
The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.

The library contains components for managing input, database programming, and much much more.

The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.

Built-in packages are existing java packages that come along with the JDK. For example, java.lang, java.util, java.io, etc. For example:

import java.util.ArrayList;
class ArrayListUtilization {
    public static void main(String[] args) {
        ArrayList<Integer> myList = new ArrayList<>(3);
        myList.add(3);
        myList.add(2);
        myList.add(1);
        System.out.println(myList);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
myList = [3, 2, 1]

The ArrayList class belongs to java.util package. To use it, we have to import the package first using the import statement.

import java.util.ArrayList;
Enter fullscreen mode Exit fullscreen mode

To use a class or a package from the library, you need to use the import keyword:

Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package

Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:
Example

import java.util.Scanner;
Enter fullscreen mode Exit fullscreen mode

java.util is a package, while Scanner is a class of the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. we will use the nextLine() method, which is used to read a complete line:

Example

Using the Scanner class to get user input:

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    System.out.println("Enter username");
    String userName = myObj.nextLine();
    System.out.println("Username is: " + userName);
  }
}
Enter fullscreen mode Exit fullscreen mode

Import a Package
There are many packages to choose from. we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (). The following example will import ALL the classes in the java.util package:
**Example
*

import java.util.*;
Enter fullscreen mode Exit fullscreen mode

2. User-defined Packages

To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer:
Example

└── root
  └── mypack
    └── MyPackageClass.java
Enter fullscreen mode Exit fullscreen mode

To create a package, use the package keyword:

MyPackageClass.java

package mypack;
class MyPackageClass {
  public static void main(String[] args) {
    System.out.println("This is my package!");
  }
}
Enter fullscreen mode Exit fullscreen mode

Save the file as MyPackageClass.java, and compile it:

C:\Users\Your Name>javac MyPackageClass.java
Enter fullscreen mode Exit fullscreen mode

Then compile the package:

C:\Users\Your Name>javac -d . MyPackageClass.java
Enter fullscreen mode Exit fullscreen mode

This forces the compiler to create the "mypack" package.

The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign ".", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class names.

When we compiled the package in the example above, a new folder was created, called "mypack".

To run the MyPackageClass.java file, write the following:
C:\Users\Your Name>java mypack.MyPackageClass

The output will be:
This is my package!

Some of the commonly used built-in packages are:

java.lang: Contains language support classes(e.g, classes that define primitive data types, math operations). This package is automatically imported.
java.io: Contains classes for supporting input/output operations.
java.util: Contains utility classes that implement data structures such as Linked Lists and Dictionaries, as well as support for date and time operations.
java.applet: Contains classes for creating Applets.
java.awt: Contains classes for implementing the components for graphical user interfaces (like buttons, menus, etc)

Example: Using java.util.Random (Built-in Package)

import java.util.Random;   // built-in package
public class GFG{ 
    public static void main(String[] args) {   
        // using Random class
        Random rand = new Random();   
        // generates a number between 0–99
        int number = rand.nextInt(100);  
        System.out.println("Random number: " + number);
    }
}

Enter fullscreen mode Exit fullscreen mode

Output
Random number: 59

User-defined Packages are the packages that are defined by the user.

You can define your own packages to bundle groups of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes.

Java also allows you to create packages as per your need. These packages are called user-defined packages.
How to define a Java package?

To define a package in Java, you use the keyword package.

package packageName;
Enter fullscreen mode Exit fullscreen mode

Java uses file system directories to store packages. Let's create a Java file inside another directory.

For example:

└── com
└── test
└── Test.java

Now, edit Test.java file, and at the beginning of the file, write the package statement as:

package com.test;

Here, any class that is declared within the test directory belongs to the com.test package.

Here's the code:

package com.test;

class Test {
public static void main(String[] args){
System.out.println("Hello World!");
}
}

Output:
Hello World!

Here, the Test class now belongs to the com.test package.

Creating a Java Package

While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package.

Compiling with Java Package

To compile the Java programs with package statements, you have to use -d option as shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder.

Example:

package com.myapp;
public class Helper {
    public static void show() {
        System.out.println("Hello from Helper!");
    }
}
Enter fullscreen mode Exit fullscreen mode

To use it in another class:

import com.myapp.Helper;
public class Test {
    public static void main(String[] args) {
        Helper.show();
    }
}
Enter fullscreen mode Exit fullscreen mode

Accessing Classes Inside a Package

In Java, we can import classes from a package using either of the following methods:

1. Import a Single Class

import java.util.Vector; 
Enter fullscreen mode Exit fullscreen mode

This imports only the Vector class from the java.util package.

2. Import all classes from a package:

import java.util.*; 
Enter fullscreen mode Exit fullscreen mode

This imports all classes and interfaces from the java.util package but does not include sub-packages.

Example: Import the Vector class

import java.util.Vector;
public class Geeks {
    public Geeks() {
        // java.util.Vector is imported, We are able to access it directly in our code.
        Vector v = new Vector();
        java.util.ArrayList l = new java.util.ArrayList();
        l.add(3);
        l.add(5);
        l.add(7);
        System.out.println(l);
    }
    public static void main(String[] args) {
        new Geeks();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
[3, 5, 7]

Directory Structure of a Java Package
Two major results occur when a class is placed in a package −
The name of the package becomes a part of the name of the class.
The name of the package must match the directory structure where the corresponding bytecode resides.

Here is simple way of managing your files in Java −

Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java.

For example −

// File Name : Car.java
package vehicle;

public class Car {
// Class implementation.

}

Now, put the source file in a directory whose name reflects the name of the package to which the class belongs −

....\vehicle\Car.java

Now, the qualified class name and pathname would be as follows −

Class name → vehicle.Car
Path name → vehicle\Car.java (in windows)

In general, a company uses its reversed Internet domain name for its package names.

Example − A company's Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory.

Example − The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this −

....\com\apple\computers\Dell.java

At the time of compilation, the compiler creates a different output file for each class, interface and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class.

For example −

// File Name: Dell.java
package com.apple.computers;

public class Dell {
}

class Ups {
}

Now, compile this file as follows using -d option −

$javac -d . Dell.java

The files will be compiled as follows −

.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class

You can import all the classes or interfaces defined in \com\apple\computers\ as follows −

import com.apple.computers.*;

Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as −

\sources\com\apple\computers\Dell.java

\classes\com\apple\computers\Dell.class

By doing this, it is possible to give access to the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.

The full path to the classes directory, \classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path.

Say \classes is the class path, and the package name is com.apple.computers, then the compiler and JVM will look for .class files in \classes\com\apple\computers.

A class path may include several paths. Multiple paths should be separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in the class path.
Set CLASSPATH System Variable

To display the current CLASSPATH variable, use the following commands in Windows and UNIX (Bourne shell) −

In Windows → C:> set CLASSPATH
In UNIX → % echo $CLASSPATH

To delete the current contents of the CLASSPATH variable, use −

In Windows → C:> set CLASSPATH =
In UNIX → % unset CLASSPATH; export CLASSPATH

To set the CLASSPATH variable −

In Windows → set CLASSPATH = C:\users\jack\java\classes
In UNIX → % CLASSPATH = /home/jack/java/classes; export CLASSPATH

Package Naming convention

The package name must be unique (like a domain name). Hence, there's a convention to create a package as a domain name, but in reverse order. For example, com.company.name

Here, each level of the package is a directory in your file system. Like this:

└── com
└── company
└── name

And, there is no limitation on how many subdirectories (package hierarchy) you can create.
How to create a package in Intellij IDEA?

In IntelliJ IDEA, here's how you can create a package:

Right-click on the source folder.
Go to new and then package.
New package in Intellij IDEA

A pop-up box will appear where you can enter the package name.
Package Naming convention in Java
Enter fullscreen mode Exit fullscreen mode

Once the package is created, a similar folder structure will be created on your file system as well. Now, you can create classes, interfaces, and so on inside the package.
Package directory

How to import packages in Java?

Java has an import statement that allows you to import an entire package (as in earlier examples), or use only certain classes and interfaces defined in the package.

The general form of import statement is:

import package.name.ClassName; // To import a certain class only
import package.name.* // To import the whole package

For example,

import java.util.Date; // imports only Date class
import java.io.*; // imports everything inside java.io package

The import statement is optional in Java.

If you want to use class/interface from a certain package, you can also use its fully qualified name, which includes its full package hierarchy.

Here is an example to import a package using the import statement.

import java.util.Date;

class MyClass implements Date {
// body
}

The same task can be done using the fully qualified name as follows:

class MyClass implements java.util.Date {
//body
}

Example: Package and importing package

Suppose, you have defined a package com.programiz that contains a class Helper.

package com.programiz;

public class Helper {
public static String getFormattedDollar (double value){
return String.format("$%.2f", value);
}
}

Now, you can import Helper class from com.programiz package to your implementation class. Once you import it, the class can be referred directly by its name. Here's how:

import com.programiz.Helper;

class UseHelper {
public static void main(String[] args) {

    double value = 99.5;
    String formattedValue = Helper.getFormattedDollar(value);
    System.out.println("formattedValue = " + formattedValue);
}
Enter fullscreen mode Exit fullscreen mode

}

Output:

formattedValue = $99.50

Here,

the Helper class is defined in com.programiz package.
the Helper class is imported to a different file. The file contains UseHelper class.
The getFormattedDollar() method of the Helper class is called from inside the UseHelper class.
Enter fullscreen mode Exit fullscreen mode

Importing packages in Java
Java import package

In Java, the import statement is written directly after the package statement (if it exists) and before the class definition.

For example,

package package.name;
import package.ClassName; // only import a Class

class MyClass {
// body
}

Top comments (0)