×

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

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 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.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Radix Sort in Java

Radix Sort in Java Radix sort in Java uses the digits of the numbers given in the sorted array to sort the numbers. The radix sort uses the place value of...

5 minutes read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Second Smallest Number in an Array in Java

By sorting the arrays and returning the second element, we can use Java to discover the second-smallest number in the array. Input:  arr[] = {10, 11, 13, 15, 34, 51} Output: The...

6 minutes read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Grepcode Java util date

What is java.util.Date Class? The date and time in Java are provided through the java.util.Date class. If you imported java.util, it could be helpful. Use the Java.util.Date class to implement this class...

4 minutes read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.