There are folders or directories in our computers for the classification and accessibility of various files. In Java, there is a similar system called packages. Packages are mainly used to organize classes and interfaces.
Java packages are a way to organize java code by grouping related java classes, interfaces, and other packages together. It allows java developers to categorize their java code and group it in a single location. In this way, Java Packages help us write code that is easier to manage and prevents naming conflicts.
Post On: | Java Package API |
Post Type: | Java Tutorials |
Published On: | www.softwaretestingo.com |
Applicable For: | Freshers & Experience |
Get Updates: | Software Testingo Telegram Group |
If this sounds like something interesting to learn, then keep reading for more information because, in this post, we are going to discuss:
- Java Packages Definition
- What is a package in java?
- Java Package Creation
- Types of packages in Java
- How to access a package from another package?
- Java Package Naming Convention
- Subpackage in Java
- Static Import in Java
- Java package class
- Advantages of Java Package
- Java Package Manager
Java Packages Definition
A Java package is a set of related classes, interfaces, and sub-packages that share common characteristics such as the same data types or perform similar operations on the data.
Classes in the same package can access each other’s package-private and protected members. This allows classes to share information and functionality while still maintaining a high level of security.
What is a package in java?
Java packages are introduced in the java language to organize java classes, interfaces, and sub-packages logically and allow java developers to group them into a hierarchy of related concepts or tasks. In simple words, java packages simplify java code and java developers’ tasks of organizing java classes.
Java Package Creation
Java Package creation is an easy task in Java. If you want to create a package, you need to add the package command as the first statement in the Java source file. And the Java file may contain classes, enumerations, interfaces, and annotation types that you want to include in the package.
With some examples, let’s understand how we can create packages in Java, compile Java programs inside the packages and execute them.
For Creating Java packages, we need to write the statement below:
package myPackage;
Here Package is the keyword, and myPackage is the package’s name.
Types of packages in Java
In Java, we have two types of packages and which are:
- User-defined package
- Java API packages or built-in packages
User-Defined Package
As the name suggests, the packages created by the user are called user-defined packages. We are creating a directory whose name should be the same as the package name for creating a package. Then inside the directory, we can create classes.
User-Defined Packages Example:
In the below example, we will create a package called “PackageExamples.” And inside that, we will create a class. But it would help if you kept in mind that the package statement should be written as the first statement Of your program, and the class is part of your package.
Note: A class can have only one package declaration. To understand this, you can follow the below program.
package myPackage; public class SumOfTwoNumber { public int add(int a, int b) { return a+b; } public static void main(String args[]) { SumOfTwoNumber obj = new SumOfTwoNumber(); System.out.println(obj.add(10, 20)); } }
Java API packages or built-in packages
To make Java users friendly, Java already provides many classes in Grouping. This is based on their functionality. There are a lot of predefined classes and interfaces in Java that you can use for your programs. Some of the most popular built-in packages are java.lang, java.io, java.util, and java.applet.
For Example:
- java.lang: It contains classes for primitive types, strings, math functions, threads, and exceptions.
- java.util: It includes classes such as vectors, hash tables, dates, Calendars, etc.
- java.io: It has stream classes for Input/Output.
- java.awt: Classes for implementing Graphical User Interface – windows, buttons, menus, etc.
- java.net: Classes for networking
- java. Applet: Classes for creating and implementing applets
How to access a package from another package?
We can use the class of a package into another package by using three different ways.
- Import package.class name;
- Import package.*;
- Fully Qualified Name.
Using import package.class name;
Note: The import keyword is used to import the classes or interfaces of other packages into current packages and make them accessible.
package com.SoftwareTestingo.PackageExamples; import myPackage.Add; public class Use_UDPForAdd { public static void main(String[] args) { Add obj = new Add(); System.out.println(obj.add(100, 200)); } }
In the above program, We want to implement the Add method of Add class of myPackage java packages. So for that, we have to use the import statement.
import myPackage.Add;
But if a package has more classes and you want to consume them in your program, we can import all the classes by using a single statement. To import all the classes of that package, we have to use * with the import statement.
import myPackage.*;
Using import package name.*;
When we want to import all the classes of a specific package at that time, we can use the package name.*. Then it will import all the classes and interfaces of that package, but it will not import any classes or interfaces of the sub-packages.
Example of package that imports the package name.*
package com.SoftwareTestingo.PackageExamples; import myPackage.*; public class Use_UDPForMulti { public static void main(String[] args) { // Accessing Add method of Add Class Add obj = new Add(); System.out.println("Sum Of Two Numbers: "+obj.add(100, 200)); // Accessing Multiplication method of Multi Class Multi obj1=new Multi(); System.out.println("Multiplication Of Two Numbers: "+obj1.multiplication(20, 30)); } }
We have to use the import statement with *in the above program. So it imports all the classes of myPackage, and that’s why we can access the methods of Add & Multi classes inside the PackageExamples package.
Using Fully Qualified Name
Suppose you don’t want to use the import statement in your java program, but you want to use other package classes. Then, in that case, we can use the fully qualified name. Then only the mentioned class of another package will be accessible.
It is generally used when two packages have the same class name, e.g., java.util and java.sql packages contain the Date class.
Here’s an example to understand the concept. I declared a package earlier in the blog called myPackage. I’m going to use that same package here as an example.
package com.SoftwareTestingo.PackageExamples; public class Use_FullyqualifiedName { public static void main(String[] args) { // using fully qualified name myPackage.Add obj=new myPackage.Add(); System.out.println("Sum Of Two numbers: "+ obj.add(11, 22)); } }
Note: The sequence of the program must be package name then import statement after both the class begins.
Java Package Naming Convention
There is a possibility that multiple packages can have the same name. So to avoid this, we are following some naming conventions:
- We define our package names in all lower case
- package names are period-delimited
- Names are also determined by the company or organization that creates them
To find the package name for a particular organization, we usually start by reversing the company’s URL. After that, the company’s naming convention may include the names of divisions and projects.
For example,
com.softwaretestingo;
We can then further define sub-packages of this, like:
com.softwaretestingo.packageexamples;
Subpackage in Java
If a package is present inside another package, the inner package is called a subpackage. It is created to categorize packages further. For example, if we make a tutorial package inside the Softwaretestingo package, then the tutorial package will be called a subpackage.
package softwaretestingo.tutorials;
Here softwaretestingo is a package, whereas tutorials is a subpackage. The standard for defining the package is domain.company.package. For Example, com.SoftwareTestingo.PackageExamples.
Static Import in Java
This Static Import in Java feature was first introduced in the Java 5 and above version. The static import allows the method & variables of a class to be directly used inside other classes without mentioning the name of the class in which these public static fields or methods are defined.
Note: But if you overuse this static import in your program, then it’s your program will be unreadable and unmaintainable.
package com.SoftwareTestingo.PackageExamples; import static java.lang.System.*; public class StaticImportExample { public static void main(String[] args) { // We don't need to use 'System.out' // Bcoz we have added imported the package by using static. out.print("SoftwareTestingo: This Is Example of Static Import"); } }
Java package class
The Java package class provides methods which helps to get the information about the specification and implementation of a package. In the Java package class we have different methods like getName(), getImplementationTitle(), getImplementationVendor(), getImplementationVersion() etc.
package com.SoftwareTestingo.PackageExamples; public class PackageInfo { public static void main(String[] args) { Package p=Package.getPackage("java.lang"); System.out.println("package name: "+p.getName()); System.out.println("Specification Title: "+p.getSpecificationTitle()); System.out.println("Specification Vendor: "+p.getSpecificationVendor()); System.out.println("Specification Version: "+p.getSpecificationVersion()); System.out.println("Implementaion Title: "+p.getImplementationTitle()); System.out.println("Implementation Vendor: "+p.getImplementationVendor()); System.out.println("Implementation Version: "+p.getImplementationVersion()); System.out.println("Is sealed: "+p.isSealed()); } }
Output:
package name: java.lang Specification Title: Java Platform API Specification Specification Vendor: Oracle Corporation Specification Version: 1.8 Implementaion Title: Java Runtime Environment Implementation Vendor: Oracle Corporation Implementation Version: 1.8.0_152 Is sealed: false
Advantages of Java Package
Most of the times people are asking what the benefit of using Package is, So we thought to club all the advantages of using Java in a single place.
- Java packages enable better modularity and code reuse.
- Java packages are used to organize classes with the same general functionalities, such as GUI or validation, etc., but they don’t need to be in any particular order.
- Java package is a way of grouping related classes into one modular unit, which can be used for better code organization.
- Java packages enable better modularity and code reuse with the help of java imports, which make it possible to use different java packages in a single java file without needing to import them directly.
- Java package provides an easy mechanism for organizing Java classes that have been logically grouped together on the basis of their similar functionalities. But don’t need to be located at the same level as they would if they were children or siblings of some common parent class from which all inherited functionality came.
- Java packages are also helpful when working on more than one project because you can group your related projects by placing them under specific folders within your IDE.
Java Package Manager
A package manager keeps track of what software is installed on your computer and allows you to easily install new software, upgrade the software to more recent versions, or remove previously installed software.
For Different languages, we have different package managers available for python; we have pypi.org. For ruby, we have rubygems.org. And for Csharp, we have nuget.org. But when we think about Java Package Manager, there is no such specific Java Manager.
Final Words:
Coming to the end of our tutorial, we learned about the importance of packages for better management and access to code & also discussed the two types of Java Packages.
We also covered how to access packages in other packages in Java with the help of syntax and coding examples. This will surely be helpful for your further study of the Java language.
Thanks for reading our article on Packages in Java. If you have any questions, please let us know by commenting below.
Leave a Reply