21
NovWhat is Package in Java - Types, Uses & Work
Package in Java
Package in Java in simple words is a collection of similar classes, subclasses, ennumerations, annotations, and interfaces. In Java, every class is a part of some or the other package. You need to import the package for using any specific class.
In this Java tutorial, we'll have a detailed discussion regarding all the aspects of packages in Java. After going through this, you'll have a concept clarity of types of packages, their pros and cons, applications, etc. Let's begin.
Join our Java Full Stack Developer Training to gain the coding expertise needed for top development roles.
Read More: Top 50 Java Interview Questions and Answers |
Why is a Package Important in Java?
There are some common uses of packages in Java:
- Encapsulation: Packages hide implementation details and display only the necessary functionalities.
- Code Reusability: You can create reusable components and use them anywhere in the application by importing them.
- Modularity and Organization: Maintenance and search are easy as packages consist of all related classes and interfaces.
- Namespace Management: Packages create unique namespaces for different classes and interfaces thus avoiding naming conflicts when classes with the same name appear in two or more packages. It helps reduce ambiguity in code.
- Access Control: Java provides different access levels (private, protected, public, and package-private) to restrict access to classes and their members. protected and default members have package-level access control.
Read More: What is Java? A Beginner Guide to Java |
How Do Packages Work?
There is a resemblance between packages and directories. They have a similar structure. Let us understand this with an example. Let's suppose we have a package whose name is office.employee.rollcall, then there are three directories, office, employee, and rollcall such that rollcall is present in employee and employee is present inside office. Here, the office is the package name, the employee is the subpackage name and rollcall is the class name. You can access the directory using the CLASSPATH variable.
- Package naming conventions: The packages in Java are named in the reverse order of the domain name. e.g. scholarhat.com becomes com.scholarhat.
- Adding a class to a Package: For this, you need to add the package name at the beginning of the program and save it in the corresponding directory. To define a public class, we need a new Java file. Otherwise, we can add the new class to an existing .java file and recompile it.
- Subpackages: These are packages defined inside another package. You cannot import them explicitly; they have no default access controls. They are like separate entities or package.
Become a certified Java Full-Stack Developer with ScholarHat’s intensive course. | |
Training Name | Price |
Full-Stack Java Developer Certification (Proven Steps to ₹3 - ₹9 LPA* Jobs) | Book a FREE Live Demo! |
Accessing Classes inside a Package
// Importing the Random class from the java.util package
import java.util.Random;
// Importing all classes from the java.util package
import java.util.*;
// Importing all classes and interfaces from a specific package
import mypackage.*;
// Importing only a specific class from a package
import mypackage.MyClass;
// Using fully qualified names to avoid naming conflicts
import java.util.HashMap;
import mypackage.HashMap;
Example
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack stack = new Stack<>();
// Push elements onto the stack
stack.push(100);
stack.push(200);
stack.push(300);
// Print the top element of the stack
System.out.println("Top element:"+stack.peek());
// Pop elements from the stack
int poppedElement=stack.pop();
System.out.println("Popped element:"+poppedElement);
// Check if the stack is empty
System.out.println("Is the stack empty? "+stack.isEmpty());
// Get the size of the stack
System.out.println("Stack size:"+stack.size());
System.out.println("Stack elements:");
for (Integer element:stack)
{
System.out.println(element);
}
}
}
Output
Top element:300
Popped element:300
Is the stack empty? false
Stack size:2
Stack elements:
100
200
Read More: Top 50 Java Full Stack Developer Interview Questions and Answers |
Types of Packages in Java
1. Built-in packages
The classes in these packages are part of the Java API. These packages get installed when you install Java on your computer. The JAVA API is the library of pre-defined classes available in the Java Development Environment. Following are some of the built-in packages in Java
- Java.lang: package of fundamental classes
- Java.io: package of input and output function classes
- Java.awt: package of abstract window toolkit classes
- Java.swing: package of windows application GUI toolkit classes
- Java.net: package of network infrastructure classes
- Java.util: package of collection framework classes
- Java.applet: package of creating applet classes
- Java.sql: package of related data processing classes
The built-in packages are further classified into extension packages. These extension packages start with javax. For example:
- Javax.swing
- Javax.servlet
- Javax.sql
The only default package without an explicit import statement is the java.lang package.
public class Main {
public static void main(String[] args) {
// Using String (java.lang.String)
String message = "Hello, World!";
System.out.println(message);
// Using Math (java.lang.Math)
int max = Math.max(10, 20);
System.out.println("Max: " + max);
// Using System (java.lang.System)
long currentTime = System.currentTimeMillis();
System.out.println("Current Time: " + currentTime);
}
}
Output
Hello, World!
Max: 20
Current Time: 1716034810123
In the above code, we implicitly import java.lang.* to have access to some of the fundamental classes provided by Java, such as Math, String, and System.
2. User-defined packages
As the name suggests, these packages are created by the developers to define the classes and interfaces as per the application requirements.
Syntax to create user-defined packages
package packageName;
The package keyword is used to define the package name. Declare the package before any import statements in the Java class. In your created package, ensure that all the classes should be public so that one can access them outside the package.
Read More: |
package package_first;
public class FirstClass {
public void printFunctionFirst()
{
System.out.println("Hello this is our first package");
}
}
package package_second;
public class SecondClass {
public void printFunctionSecond()
{
System.out.println("Hello this is our second package");
}
}
import package_first.FirstClass;
import package_second.SecondClass;
public class Testing {
public static void main(String[] args)
{
FirstClass a = new FirstClass();
SecondClass b = new SecondClass();
a.printFunctionFirst();
b.printFunctionSecond();
}
}
Output
Hello this is our first package
Hello this is our second package
Using Static Import
This feature is included in the Java Version 5 and above. Using static import, one can use the static fields and methods defined in a class as public static without specifying the class in which the field is defined.
import static java.lang.System.*;
class StaticImportExample {
public static void main(String args[])
{
// out without System prefix
out.println("Welcome to ScholarHat");
}
}
Output
Welcome to ScholarHat
Subpackage in java
A subpackage is a package inside another package. It improvises the package structure. You can use it to create related classes, group them, and make them a part of the bigger package. Let's take an example and understand.
Suppose, there's a package called Vehicles. Now you want to create some classes related to a specific type of vehicle, let's say bikes. In this case, you can create a subpackage named Bikes inside the major package, Vehicles. This organizes your package structure like files in the directory.
In the above image, one can look, at how the package structure is organized. The more the complexity of the application grows, the more organized must be the package structure.
Example of Subpackage
- Create a utility class in the com.example.util subpackage.
package com.example.util; public class Utility { public static void printMessage(String message) { System.out.println(message); } }
- Create the main class in the com.example.main package and use the Utility class from the com.example.util subpackage.
package com.example.main; import com.example.util.Utility; public class Main { public static void main(String[] args) { String message = "Hello from subpackage example!"; Utility.printMessage(message); } }
To compile and run this code,
- Navigate to the src directory
cd src
- Compile the Java files
javac com/example/util/Utility.java com/example/main/Main.java
- Run the Main class
java com.example.main.Main
Read More: |
Summary
We saw the importance of packages in Java. The two types of Java packages provide users with a lot of functionalities to develop their applications. The classes inside the packages make Java such an application-oriented programming language. It's widely used in all kinds of industries due to these features. For a practical understanding, consider our Java Full Stack Developer Course Online.
FAQs
- Built-in packages
- User-defined packages
- Use lowercase letters only.
- Separate words with periods (.).
- Traditionally, they follow a reverse domain name structure (e.g., com.example.mypackage).