×

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

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Count of Range Sum Problem in Java

In this article, we will discuss the basic approach or native approach used to count range sum problem in java. To solve this problem, we will check for numbers if they...

6 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

How to find characters with the maximum number of times in a string java

Problem statement In this problem, users want to find the maximum count of a character from the string and return the character along with its count. Your task is to create...

3 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Java Boolean logicalOr() Method

The logicalOr() method of Java Boolean class returns the result of implementing logical OR operation on the specified Boolean operands. Syntax: public static boolean logicalOr (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

How to use scanner in Java

Scanner class in Java is the part of java.util package. Java programming language has various ways to read input from the user, Scanner class is one of the classes to...

5 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Hourglass problem in Java

In this section, we will discuss the hourglass problem in Java.The aim is to find the largest sum of an hour glass given a 2D matrix. An hour glass is made...

2 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

How to Develop Programming Logic in Java?

Introduction In the world of software development, Java programming language is one of the most powerful programming languages that is used to create a wide range of applications. It includes desktop,...

18 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.