top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Packages in Java

Introduction

Organizing code effectively is a key aspect of the programming journey. That's where Packages in Java come into play. Picture them as big folders in your computer holding related files, making them easier to find, manage, and protect. Similarly, Java Packages group together related classes, interfaces, and sub-packages. This makes the code much more manageable and prevents naming conflicts. Also, it promotes code reusability, a key principle of efficient software development.

What Are Java Packages?

Packages in Java are like neatly arranged containers for your code. They hold and organize related classes and interfaces in Java, making navigating through the complexities of your code easier. It helps in maintaining your codebase.

Characteristics of Java Packages

Packages in Java are characterized by their ability to prevent naming conflicts and control access to classes and interfaces. They provide a layered structure for your applications, which promotes code modularity and reusability. Effective use of the packages helps to design a well-structured, efficient software system.

Important characteristics of Java packages are:

1. Code Organization

Java packages are used for code organization. They bundle related classes and interfaces into packages.

2. Namespace Management

Each package in Java creates a new namespace, which helps avoid name conflicts. Two classes in different packages can share the same name without conflict because the package name forms part of the class's full name.

3. Access Control

By using access modifiers like public, private, protected, and default, you can control the visibility and accessibility of your classes, interfaces, and their members.

4. Code Reusability

Since related classes and interfaces are organized into packages, they can be reused easily across different parts of an application or even across dissimilar applications. 

5. Ease of Distribution

Packages help in bundling related classes and interfaces together into a single distributable unit (like a JAR file), which is useful while dispensing your application.

6. Built-In and User-Defined 

Java comes with many built-in packages like java.util, java.io, java.math, etc., which provide a vast array of ready-to-use classes and interfaces. However, you can also define your own packages to suit the requirements of your application.

7. Hierarchical Structure

Packages in Java are hierarchical, meaning one can contain other packages, forming a directory-like structure. This structure is reflected in their naming convention.

How to Declare and Define a Java Package?

Declaring a package is simple. The package ‘keyword’ is used for creating a new package in Java. It should be the first line of code in your Java file. Here's the general syntax:

package packageName;

Defining a package involves creating the Java classes within that. Here's an example:

Package myPackage ;

public class MyC1ass {

// Your code goes here

}

Here, ‘myPackage’ is the package name, and ‘MyClass’ is a Java class that belongs to ‘myPackage’.

Naming Convention for Java Packages

Java has some widely accepted rules for naming packages to ensure consistency and avoid conflicts:

1. Lowercase letters

Package names should be in lowercase to avoid conflict with class names and interfaces.

2. Unique names

To avoid conflicts, use unique package names. A common practice is to use the reverse of your domain name, as these are distinctive.

3. No keywords

Java keywords should not be used as package names.

For example, if your website is ‘www.mywebsite.com’, a good package name could be ‘com.mywebsite.mypackage’.

How Packages Work in Java?

Packages in Java help with the following:

1. Prevent naming conflicts

Packages allow classes to be grouped together. This means you can use the same class name in different packages without causing a naming conflict.

2. Improve readability and organization

By grouping related classes together in packages, your code becomes easier to navigate and understand.

3. Control access

Packages can control access to classes and class members. Java has a number of access modifiers (public, protected, no modifier, and private) that determine the visibility of classes and class members. For instance, class members marked as 'public' are accessible from any other class, while those marked as 'private' can only be approached from within the same class.

Let's consider an example. Assume you're building a library management system. You can have a package for each major feature like this:

package com.library.users;

public class User {
    // User-related code
}
package com.library.books;
public class Book {
    // Book-related code
}

This code has two packages: ‘com.library.users’ and ‘com.library.books’. The ‘User’ class is in the ‘users’ package, while the ‘Book’ class is in the ‘books’ package.

To use a class from another package, you need to import it. For example, if you want to use the ‘Book’ class in the ‘User’ class, you'd do it like this:

package com.library.users;

import com.library.books.Book;

public class User {
    Book myBook;
    // Rest of the User code
}

Types of Packages in Java

There are two main types of packages in Java:

1. Built-in Packages: Also known as standard packages, these are part of the Java Development Kit (JDK). They come pre-installed with Java and provide a wide range of classes and methods for developers. Examples: java.lang, java.util, java.io, etc.

Here's an illustration of using a class (ArrayList) from the built-in java.util package:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Hello");
        list.add("World");
        System.out.println(list);
    }
}

Output:


2. User-Defined Packages: These are packages created by developers to organize their application's code. You can define yours using the ‘package’ keyword.

For instance, you could create a package com.myapp.shapes and define a Circle class in it:

package com.myapp.shapes;

public class Circle {
    // Circle related code
}

To use this Circle class in another package, you would import it like this:

import com.myapp.shapes.Circle;

public class Main {

    public static void main(String[] args) {

        Circle myCircle = new Circle();

        // Rest of the code

    }

}

Organizing Code with Java Packages

Both built-in and user-defined Java packages are fundamental to keeping your codebase organized and manageable. 

Consider the following steps for effective structuring:

1. Categorize Your Code

Identify the distinct functionalities in your application. Each major one could be a separate package.

2. Create Packages

Declare your packages using the package keyword followed by your chosen package name. The package declaration should be the first line of your Java file.

3. Add Classes and Interfaces to Packages

Place related classes and interfaces in the corresponding packages.

For example, if you're building a student management system, you can organize your code like this:

\
package com.myapp.students;
public class Student {
    // Student-related code
}
package com.myapp.courses;
public class Course {
    // Course-related code
}

Here, com.myapp.students and com.myapp.courses are user-defined packages in Java, holding Student and Course classes, respectively.

Real-World Examples Of Using Java Packages In Various Scenarios

Let's highlight the practical usage of packages in Java with example programs.

Example 1: An E-Commerce Application

In an e-commerce application, you can have different modules such as user management, product management, and order management. Each of these can be represented as a package:

// User Management
package com.ecommerce.user;
public class User {
    // User-related code
}
// Product Management
package com.ecommerce.product;
public class Product {
    // Product-related code
}
// Order Management
package com.ecommerce.order;
public class Order {
    // Order-related code
}

2. Example 2: A Banking System

You may have different modules in a banking system, such as account management, loan management, and customer service. Each of these could be a separate package:

// Account Management

package com.bank.account;

public class Account {
    // Account-related code
}
// Loan Management
package com.bank.loan;
public class Loan {
    // Loan-related code
}
// Customer Service
package com.bank.service;
public class CustomerService {
    // CustomerService-related code
}
Example 3: A Library Management System

In a library management system, you may have book management, user management, and loan management modules. Each of these could be a separate package:

// Book Management

package com.library.book;
public class Book {
    // Book-related code
}
// User Management
package com.library.user;
public class User {
    // User-related code
}
// Loan Management
package com.library.loan;
public class Loan {
    // Loan-related code
}

Creating and Managing Java Packages

Creating packages in Java is a simple yet essential process for managing your codebase effectively. 

Here's a step-by-step guide to developing and managing your Java packages:

Step 1: Define Your Package

To create a package in Java, use the ‘package’ keyword. This declaration should be the first line in your Java file. Here's an example:

packåge com.myapp.shapes;

This line of code creates a package named shapes under the directory com/myapp.

Step 2: Create Classes or Interfaces in Your Package

Next, you need to define classes or interfaces within your package. A class is added to a package like this:

package com.myapp.shapes;

public class Circle {

    // Circle-related code

}

In this example, a class named Circle is created within the com.myapp.shapes package.

Step 3: Compile Your Java Files

Compile your Java files using javac in your terminal. The command is like this:

javac Circle.java

This will create the ‘Circle.class’ file in the com/myapp/shapes directory.

Step 4: Using Classes from Your Package

To use the classes from your package, you have to import them into the Java file where they're needed:

import com.myapp.shapes.Circle;

public class Main {

    public static void main(String[] args) {

        Circle myCircle = new Circle();

        // Rest of the code

    }

}

Step 5: Package Management

Managing your packages involves organizing your classes into logical units, reusing code across different classes, and ensuring there are no naming conflicts. 

Using Static Import

Java's static import is a feature that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined. This can lead to more readable and less verbose code.

Normally, to access static members, you need to prefix it with the class name like this:

double result = Math.sqrt(25); // Using sqrt method from Math class

But with static import, you can import the ‘sqrt’ method once and use it directly in your code:

import static java.lang.Math.sqrt;

public class Main {

    public static void main(String[] args) {

        double result = sqrt(25); // Directly using sqrt without prefixing Math

        System.out.println(result);

    }

}

In the code above, ‘sqrt’ method from ‘java.lang.Math’ is statically imported, and you can use it directly without prefixing it with ‘Math’.

However, caution is required when using static imports as it may reduce readability if overused because it's not clear which class the method or field is coming from. They are generally employed for frequently used static methods, like those from ‘java.lang.Math’.

This mechanism of importing packages in Java makes your code more readable and reduces verbosity.

Importing Packages In Java With Example Program

Consider we have two packages, ‘com.myapp.shapes’ and ‘com.myapp.main’. In the ‘shapes’, we have a ‘Circle’ class:

// File: com/myapp/shapes/Circle.java

package com.myapp.shapes;

public class Circle {

    private double radius;

    public Circle(double radius) {

        this.radius = radius;

    }

    public double getArea() {

        return Math.PI * radius * radius;

    }

}

Now, if we want to use this ‘Circle’ class in our ‘Main’ class, which is in a different package (com.myapp.main), we need to import it:

// File: com/myapp/main/Main.java

package com.myapp.main;

import com.myapp.shapes.Circle; // Importing the Circle class from shapes package

public class Main {

    public static void main(String[] args) {

        Circle myCircle = new Circle(5.0);

        System.out.println("The area of the circle is: " + myCircle.getArea());

    }

}

In this example, ‘com.myapp.shapes.Circle’ is imported into the ‘Main’ class. This allows us to create instances of the ‘Circle’ class in ‘Main’. The ‘import’ statement allows the JVM to locate and use the ‘Circle’ class in the ‘Main’ class. 

The output of the above code is:

This value is the result of the formula π*r² (pi times the radius squared), which calculates the area of a circle. For a circle with a radius of 5.0, the area is approximately 78.54 (when rounded to the nearest hundredth).

How to Access A Package?

Accessing packages in Java is a simple process. You need to use the ‘import’ keyword followed by the package name (and class or interface) you want to access. Here's a step-by-step guide:

1. Import the Required Package

In your Java file, use the ‘import’ keyword to import the required package. For example, to import the ‘Scanner’ class from the ‘java.util’ package, you would write:

import java.util.Scanner;

If you want to import all classes within a package, you can use the ‘*’ wildcard:

import java.util.*;

Note

Importing packages in Java does not affect the performance of your program. It's simply a directive for the compiler to locate the classes and interfaces you want to use.

  1. Use the Imported Class or Interface

Once you've imported a package, you can use the classes or interfaces from that in your code. For example, after importing the ‘Scanner’ class, you can create an instance of it like this:

Scanner scanner = new Scanner(System.in);

Conclusion

Understanding packages in Java is fundamental to becoming a proficient Java programmer. They help in organizing your code into logical groupings and provide access control mechanisms. They also promote the reusability of code and help prevent naming conflicts. Whether you're working with built-in packages, creating your own, or importing classes and interfaces from packages, these concepts form the backbone of code structure in Java.

FAQs

1. What does the 'default package' mean in Java? 

The default package in Java is a package that has no name. When a class or interface is not associated with any package, it belongs to this. 

2. When is the ’default package’ used?

Although the ‘default package’ is convenient for small programs and  testing purposes, using it for more significant, professional applications is generally discouraged.

3. How does the access control work in Java packages?

Access control in Java packages is managed through access modifiers (public, private, protected, and default (no modifier)). The 'public' modifier allows a class or class member to be accessible from any other class, while the 'private' restricts access to the same class only.

Leave a Reply

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