Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Package Program in Java

Last Updated on June 9, 2023 by Mayank Dham

A package in Java is a collection of related classes and interfaces. Packages are used to organize code and to prevent name conflicts. To create a package, you use the package keyword followed by the name of the package.

What is a java package?

A set of classes, sub-packages, and interfaces with a similar purpose can be said to be contained within a Java package. There are two different kinds of packages available in Java: built-in packages and user-defined packages. The built-in packages we have include util, java, io, net, sql, java, and so on. We will learn about these pre-built packages in this post, as well as how to make a user-defined package.

What are the advantages of a java package?

  • Java packages are used to proved access protection
  • Java packages are used to eliminate naming collision
  • Java packages are used to classify the classes and the interfaces into categories

Let’s see how the hierarchy of the java build-in package looks like

In the above image, we can see that there is one main package java that contains sub-packages like io, lang, net, util, etc. And these sub-packages contain various classes. For example, the io sub-package contains FileReader.class, Writer.class, and many more. The lang sub-package contains Thread.class, System.class, and many more. The net sub-package contains Socket.class, URL.class, and many more. The util sub-package contains Scanner.class, Random.class, and many more.

Simple package program in java:

Let’s see how to write a simple package program in java using built-in packages of java.

import java.util.Scanner;
class PrepBytes {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int num=sc.nextInt();
        System.out.println("The Number is "+num);
    }
}

Output: The Number is 10

In the above program, we have imported the Scanner class of sub-package util which belongs to package java. We have used this Scanner class to take input from the user. In the output, we can see that number entered by the user is printed.

Now, let’s see how we can write our user-defined package program in java.

package mypackage;
class PrepBytes {
    public static void main(String[] args) {
        System.out.println("This is user-defind package");
    }
}

In the above program, we have given the package name mypackage using the keyword package. We can use this package in another program of java using the import package name. You can compile the above program using the below steps if you are not using IDE.

Syntax: javac java_file_name

For example: javac PrepBytes.java

You can use the above steps to compile your program using the command prompt. After compiling, we can use the above package in other java programs. Following the below steps, you can run the above java program.

Syntax: java package_name.class_name

For example: java mypackage.PrepBytes

Output: This is user-defined package

Using the above syntax, we can run a java program.

Ways to access a package from another package:

There are mainly three ways to access a package from another package.

  • Using import package_name.*
  • Using import package_name.class_name;
  • Using the fully qualified name

1) Using import package_name.*;

When we want to import all the classes and the interfaces to our java program from the package we can use this method. * means the java compiler will import all the classes and the interfaces into the current program. The import keyword will make all the classes and interfaces accessible to the current package. Let’s understand this method by writing a package program in java.

import java.util.*;
class HelloWorld {
    public static void main(String[] args) {
        Date d=new Date();
        System.out.println(d);
        Random r=new Random();
        int num=r.nextInt(100);
        System.out.println(num);
    }
}

In the above program, we have imported all the classes of sub-package util. In the program, we used the Date class of the package java.util and we also used the Random class from the same package. In the output, we can see that we don’t get any error even if we didn’t import the Date and Random classes separately it’s because we imported all the classes and interfaces of the package using the * sign.

2) Using import package_name.class_name

We will use this method when we want to import a particular class or interface from the package. This method is very useful when we don’t want to import all the classes and interfaces and we want to use a specific class or interface. The import keyword will all the specified classes and interfaces accessible to the current package. Let’s understand this method by writing a package program in java.

import java.util.Date;
class HelloWorld {
    public static void main(String[] args) {
        Date d=new Date();
        System.out.println(d);
    }
}

In the above program, we have imported a class Date using the method of importing a specific class. In the output, we can see that we can use the Date class in the program and we do not get any errors. Now, let’s try to use the Random class without importing it.

import java.util.Date;
class HelloWorld {
    public static void main(String[] args) {
        Date d=new Date();
        System.out.println(d);
        Random r=new Random();
        int num=r.nextInt(100);
        System.out.println(num);
    }
}

In the output, we can see that the above program throws an error because we have not imported the Random class.

3) Using the fully qualified name

In this method, we will specify the full name of the class with its sub-package name and package name. To make the class accessible to the program we can give a fully qualified name. Let’s understand this method by writing a package program in java.

class HelloWorld {
    public static void main(String[] args) {
        java.util.Date d=new java.util.Date();
        System.out.println(d);
    }
}

In the above program, we did not import any classes or interfaces using the above two methods. In this method, we give fully qualified names to access the classes or interfaces rather than importing them on the top. One disadvantage of this method is that every time we want to use the classes or interfaces we need to give a fully qualified name every time.

The flow of the package in java:

In the above image, we can see a flow of the java package. First, java packages are imported and after that, we can import classes and interfaces belonging to that package.

What is a sub-package in java?

If one package is inside the other package then that package is called a sub-package. The main purpose of this sub-package is to divide the classes and interfaces into categories.

For example, in java language, there is one main package java that contains many sub-packages like io, lang, net, util, etc. These all sub-packages contain the classes and interfaces with the same categories.

For example, the io sub-package contains classes like Reader and Writer which are used for input and output, and the net sub-package contains classes like Socket and URL which are used for networking. The util class contains classes like Scanner and Random which are used to create an applet.

Let’s see an example of how to write a sub-package program in java.

package com.prepbytes.core;
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Welcome to sub-package program in java");
    }
}
Output: Welcome to the sub-package program in java

In the above program, we have defined the package name at the top of the program. We have given package name like com.prepbytes.core. For this program, our main package is com which contains sub-package prepbytes. Inside the sub-package, we have created the class HelloWorld. Now, if we see the structure of the package then first, we have to call main package com after that we have to call sub-package prepbytes and after that, we can use the class HelloWorld in another program. This is a standard technic for creating user-defined packages because it is more readable and easy to use. We will see the above structure in every industry-level coding standard.

Conclusion
Packages are a powerful tool for organizing code and preventing name conflicts. They can also be used to control access to classes and interfaces. By using packages, you can make your code more readable, maintainable, and secure.

Here are some of the benefits of using packages in Java:

Organization: Packages can be used to organize code into logical units. This makes it easier to find and understand the code.
Prevention of name conflicts: Packages can be used to prevent name conflicts. This is because each package has a unique name.
Control of access: Packages can be used to control access to classes and interfaces. This can be useful for security purposes.

Frequently Asked Questions

Q1. What is the purpose of using packages in Java?
Packages in Java serve multiple purposes. They help organise and structure your code, prevent naming conflicts between classes, and provide access control through access modifiers. Packages also support modularity and code reusability.

Q2. How do I create a package in Java?
To create a package in Java, you include the package statement at the top of your source file, followed by the package name. For example, package com. example; would create a package named "com. example".

Q3. How do I import classes from a package in Java?
You can import specific classes from a package using the import statement followed by the fully qualified class name. For example, import com.example.MyClass; would import the class "MyClass" from the package "com. example". Alternatively, you can use the wildcard to import all classes from a package, like import com.example..

Q4. What is the default package in Java?
In Java, if you don’t specify a package for your classes, they belong to the default package. However, it’s considered good practice to organize your classes into explicitly named packages to avoid conflicts and improve code maintainability.

Q5. How are packages related to directory structure in Java?
A: The package hierarchy in Java corresponds to the directory structure on the file system. Each level of the package name represents a directory. For example, the "com.example" package would correspond to the directory structure "com/example" on your file system.

Q6. Can I have nested packages in Java?
Yes, you can have nested packages in Java. For example, you can have a package "com.example.utilities" nested within the "com. example" package. The directory structure would reflect this nesting, such as "com/example/utilities" on the file system.

Leave a Reply

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