×

Package Program in Java

Package Program in Java

The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages. Package programs in Java are the best examples of data hiding (or data encapsulation). There are two types of packages in Java namely pre-defined/ Build-in packages and user-defined packages.

Pre-defined/ Built-in Packages in Java

Built-in packages are those packages that are comes with JDK. We have to include it in our code and use it. Some of the pre-defined packages are:

  • java.util: We use this package whenever we want to use data structures like Dictionary, LinkedList and assistance for Time and Date operation.

  • java.io: It is used to perform input-output operations.
  • java.net: For networking, we use java.net package.

  • java.lang: This is the package that is imported automatically. This package contains the classes that define math operations, primitive data types like int, float etc. System class is defined in this package.

Sub-Packages in Java

Sub-packages are those packages that reside inside a package. We have to import a sub-package explicitly as the automatic import feature does not come with a sub-package.

Let us observe the following code for a better understanding of the above concepts.

Filename: PackageExample.java

// Importing all classes of util package
import java.util.*;
public class PackageExample
{             
public static void main(String argvs[])
{
               Vector v = new Vector(); // Creating an object of class Vector.
               LinkedList ll = new LinkedList(); // Creating an object of class LinkedList.
               System.out.println("We are learning about Java-package.");  
}
}

Output:

We are learning about Java-package.

Explanation: As we have imported all classes of the java.util package, therefore, we have created objects of Vector and LinkedList class. However, the util package is not only confined to these two classes. It contains a lot of other classes, too, which we have imported and not used in our code. That is why this type of import is generally avoided. We must import only those classes which we are going to use in our code. Thus, the first line of code can be replaced by the following:

import.java.util.Vector;
import.java.util.LinkedList;

Here, we are only loading Vector and LinkedList class, which a good practice. Please note that the util is a package that resides inside the java package. Hence, we can say the util is a sub-package. Since java.lang package is already imported. Therefore, the statement System.out.println(); always works.

We can also re-write the above program to generate the same output.

Filename: PackageExample1.java

public class PackageExample1
{             
public static void main(String argvs[])
{
               // Providing package details along-with class name
               java.util.Vector v = new java.util.Vector(); // Creating an object of class Vector.
               java.util.LinkedList ll = new java.util.LinkedList(); // Creating an object of class
               // LinkedList.
               System.out.println("We are learning about Java-package.");  
}
}

Output:

We are learning about Java-package.

Explanation: Since we have not used the import statements. Therefore, we have to provide every package detail along-with the class name.

The Static Import

Static import is the unique feature applicable for Java 5 (or above). This type of import allows the methods and fields present in a class as public static to be used in the Java code. The following example demonstrates the same.

Filename: PackageExample2.java

// static keyword is important in static import
import static java.lang.System.*;
public class PackageExample2
{             
public static void main(String argvs[])
{
               // No need for the System class here.
               out.println("We are learning about static import.");
}
}

Output:

We are learning about static import.

Explanation: Since out is a static and public member of the System class, and we have already done a static import on the System class. Therefore, we can omit the word System in the code.

User-Defined Package in Java

The packages that are defined by the user are known as user-defined packages. The first step is to create a directory of any name of one’s choice. In our case, we will use the name firstPackage. Inside the firstPackage directory, we create a .java file called BasicPrograms.java.

Package Program in Java

Filename: BasicPrograms.java

// The package name must match the name of the directory.

package firstPackage;
public class BasicPrograms
{             
               // A method for printing names passed in its argument.
               public void printNames(String str)
               {       
                               System.out.print(str);       
               }
}

Outside the firstPackage directory, we create another .java file, namely PackageExample3.java.

Package Program in Java

Filename: PackageExample3.java

// Importing class BasicPrograms by using package firstPackage.
import firstPackage.BasicPrograms;
public class PackageExample3
{
               public static void main(String[] args)
                {
                               // Creating object of BasicPrograms class
                               BasicPrograms obj = new BasicPrograms();
                               // Calling method printNames()
                               obj.printNames("Tutorial And Example");
               }
}

Now, compile the PackageExample3.java file using javac PackageExample3.java and execute it using java PackageExample3. We will get the following output.

Output:

Tutorial And Example

Explanation: The visibility of the class BasicPrograms will be maximized as we are using public access specifier. The same goes for the method printNames(). Therefore, we can easily create an object of BasicPrograms and invoke the method printNames(). But for that to work, we must import BasicNames class, which is achieved with the help of the firstPackage.


Related Topics

How to Change the Day in the Date using Java?

To operate with the date and time in Java, we need the Calendar abstract class. It provides a number of helpful interfaces that enable us to convert dates between a...

4 minutes read.

Java Class Name

How to write a class name? The following considerations should be made while writing class names. The name of the current class shouldn't be based on a preset or existing class. Java keywords...

3 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Segment Tree in Java

Binary trees can address a variety of issues; however, the Segment Tree is more efficient in terms of time complexity. The segment tree in Java is represented using an array. Native...

4 minutes read.

How to check if date is valid in Java?

In this article, you will acknowledge about how to verify if a date is valid or not. For this you will learn the approach, you will be able to write...

3 minutes read.

Java Variable Declaration

In this article, you will be acknowledged about java variable declaration. You will be able to learn and interpret about declaring a variable in Java. Variable in Java Variables are necessary for...

6 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

What’s New in Java 15

Sealed classes are the new concept that was introduced by Java 15. Sealed classes are a preview feature. Most of the features which are released in java 15 are in...

3 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Binary Strings Without Consecutive Ones in Java

N, an integer, is provided. Our objective is to determine the overall number of strings with length N that do not include successive 1s. Example: Input: 3 Output: 6 Explanation The binary forms of length...

6 minutes read.

How to find the length of an Array in Java

Arrays: An array is a sort of container object that stores constant quantities of values of a single type in one memory area. A finite number of items must all be...

3 minutes read.

Access Modifier in Java

The access modifiers in java are used to change the accessibility and scope of a method, constructor, class, and fields. If you are aware of C++ language, when we declare any member...

2 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

JDBC Program in Java

JDBC Program in Java JDBC is an API that defines how a client may access a database. It is a part of Java Standard Edition (Java SE). JDBC stands for Java...

4 minutes read.