×

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide a very efficient mechanism for alignment of various files. The files which are related to each other can be stored in the same package, and whenever there is a need to access the related files, we just have to go through one package. A unique namespace is provided by the package. A package can contain the following types of file in java:
  • Class
  • Interface
  • Enumerated types
  • Annotations

Advantages of packages

  • Two classes in two different packages can have the same name so, name collision issue is not a problem.
  • Classes related to each other are stored in the same package so, accessing them is easy.
  • Access protection is provided by packages so, no need to worry about the security concerns. The files that are crucial can be hidden successfully.
  • Programmer can make their own packages as per their convenience. It is programmer friendly.
  • Code reusability is provided.

Types of packages in Java

Built-in packages: They are the ones which are predefined by the java compiler. They can be imported to use by the user. User-defined packages: They are the ones which are made by the programmer to group related classes, enumerations, annotations and interfaces as required by him.

Built-in packages in java.

There are some built-in packages in java that can be used as it is by the programmer. They are listed below. Let us take a look at each one of these packages:
  1. java.lang: This package contains language support classes. They are by default imported in the java programs.
  2. java.util: This package contains language utility classes such as vectors, lists, hash tables, etc.
  3. java.awt: This package contains a set of classes for implementing the graphic user interface.
  4. java.applet: This package contains a set of classes for using applets in java program.
  5. java.net: This package contains a set of network classes.
  6. java.io: This package contains classes for input and output support.

User-defined packages

Having seen the predefined packages, now it's time to see how the packages can be created, imported and used by the users. Creating Packages
  • Select a suitable name for the package.
  • Declare the name of the package with the 'package' keyword in the first line of a program. E.g. package firstpack.
  • Define a public class inside that package.
  • Create a subdirectory in the main directory to store the class. Save it as classname.java.
  • Compile the file.
E.g.
package packagename;
public class classname;
{
.................
}
Importing Packages After the creation of packages, it can be imported using the 'import' keyword. Packages can be imported in two ways.
  • By explicitly declaring the class name to be imported: E.g. import firstpackage.secondpackge.classname;
  • By importing all the classes in a package. E.g. import packagename.*;
The drawback of using the shortcut approach is that it is difficult to determine from which class a particular member came. While using the shortcut approach, all the classes get imported. If the programmer wishes to hide some of the class then it is advised to use access modifier other then public for that class. Using Packages After having seen how packages are created and imported, let us have a look at how they are used. In the program given below, we will see all the steps mentioned.
package pkg1; //creating package
public class Calculator
{
int x;
int y;
public int add(int a,int b)
{
x=a;
y=b;
return x+y;
}
public int sub(int c,int d)
{
x=c;
y=d;
return x-y;
}
public int mul(int e,int f)
{
x=e;
y=f;
return x*y;
}
public int div(int g,int h)
{
x=g;
y=h;
return x/y;
}
}
pack1 is the user-defined package, and 'Calculator' is the name of the class. The program is saved with the name Calculator.java. Once defined, let's see how the package is used.
import pkg1.Calculator; //importing package
class Operate
{
public static void main(String args[])
{
Calculator obj1 = new Calculator();
obj1.add(5,6);
Calculator obj2 = new Calculator();
obj2.sub(8,6);
Calculator obj3 = new Calculator();
obj3.mul(5,6);
}
}

Program to import two packages simultaneously.

package pkg1;
public class Calculator
{
int v=45;
public void show()
{
System.out.println("Hy!! value of v is"+v);
}
}
Now, we will make another class which will import both the packages.
import pkg1.Calculator;
import pkg2.ClassA;
class Test
{
public static void main(String args[])
{
Calculator obj1 = new Calculator();
obj1.add(5,6);
ClassB obj2 = new ClassB();
obj1.show();
}
}
This class uses both the packages simultaneously. We can import as many packages as we desire.

How to add a new class to an existing package?

There is an example given below to add a new class to an existing package.
package p1;
public class One
{
..............
}
This is the package in which we wish to add a new class, and it can be done as:
  • Define the class and use a public modifier.
  • Place the package statement at the top of the program.
  • Compile the class as done earlier.
  • The class is now added to the package.
package p1
public class Two
{
................
}

Related Topics

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

SHA Decrypt in Java

In this section, we will be acknowledged about the decryption of SHA in Java. Java SHA The SHA cryptographic hash algorithm in cryptography outputs the hash value as an approximately 40-digit-long hexadecimal...

4 minutes read.

The Diamond Operator in Java 7

The Diamond operator is a comparatively recent Java operator originally developed in JDK 7 to enhance type identification and eliminate boilerplate Java code. The Diamond operator is characterized by a...

2 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called...

3 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

How to find length of integer in Java

We can find the length of the integer in many ways. The length of an integer is defined as the count of the number of digits for the given integer. These...

5 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Vector in Java

Java Vector Class The Vector class is a legacy class that implements a growable array of objects. The components that it contains can be accessed using an integer index. The size of...

26 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Banking Application in Java

JDBC (Java Database Connectivity), which provides an API to connect to, execute, and fetch data from any databases, can be used to handle transactions in Java. There are several factors...

7 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.