×

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

Stack vs Heap in Java

In Java, whenever we declare an object or create a variable, whether it is an instance variable, local variable, or static variable, a certain memory is used to store the...

4 minutes read.

Static and Dynamic Binding in Java

Data Binding in Java The relation between a class and method or class and field is known as Data Binding. In Java, we can create a class for Student_info, but until we...

2 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Java Throw and Throws Keyword

Exceptions in Java enable us to construct high-quality programs where faults are checked at compile time rather than run time and where we may define unique exceptions that make code...

6 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Java For Keyword

For as a keyword in java: When we need to run a set of statements repeatedly in Java, we use loops. The Java for loop offers a clear way to express...

4 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Java Boolean getBoolean() Method

The getBoolean() method of Java Boolean class returns true if the specified system property is not null and is equal to the String ‘true’, else the result returned is false. Syntax public...

1 minute read.

Packages Program in java

Let us know what package is in the Java programming language, and later we will learn about types of packages and how to define a package. How to import Java...

4 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Java Generate UUID

What java Generate UUID? A 128-bit long value that is universally unique serves as the basis for the terms UUID (Universally Unique Identifier) and GUID (Globally Unique Identifier). Hexadecimal (octet) digits...

5 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

How to Install Java on MAC

There are many possible ways to install java on mac. This article is based on the installation of java on mac. The operating system platform is Mac OS X, macOS and...

3 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.