×

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages.

package is a keyword in Java. The Java class's "name space" is declared. It must be the first Java statement line and must be placed at the top of the Java file.

The firm URL is typically utilized beginning in backward to guarantee that the package name will be distinctive between providers.

Uses for packages include:

  • avoiding name clashes Examples include college.staff.cse. Employee and college.staff.ee. Employee, two classes having the name Employee in two different packages.
  • Making classes, interfaces, enumerations, and annotations easier to search for, find, and use
  • Protected and default have access control at the package level, providing regulated access. A package in Java is a mechanism to group related classes, packages, and interfaces together.
  • Packages are an example of data encapsulation (or data-hiding).
  • Classes and interfaces are categorised in Java packages so they may be readily maintained.
  • The Java package offers access control.
  • The Java package eliminates naming conflicts.
  • The only thing left to do is group similar classes into packages.

The only thing left to do is group similar classes into packages. After that, we can use it in our software by writing a straightforward import class from pre-existing packages. A package is a container for a collection of related classes, some of which are maintained for internal use while others are made accessible and exposed.

Classes, interfaces, enumerations, and annotation types are the typical types that a package may contain. Classes (and interfaces) can be arranged into packages by a developer. These classes will all be connected in some way, whether it be through a shared use case or a set of operations. We can reuse pre-existing classes from the packages as often as necessary in our software

Working of Packages

Directory organization and package names are strongly connected. The three directories college, staff, and cse are present in both staff and college, for instance, if the package name is college.staff.cse. Additionally, the variable CLASSPATH makes the directory college accessible; specifically, the path to the parent directory of the college is listed in CLASSPATH. Making sure that classes are simple to find is the goal.

  • Package naming convention: Package names are arranged in the domain names' reverse order, for example, org. practice. The preferred convention, for instance, in a college is college.tech.cse, college.tech.ee, college.art. History, etc. Typically, packages are named in a hierarchical fashion, with periods separating each level of the hierarchy (., pronounced "period").For commonly used packages to have distinctive namespaces, naming conventions explain how to construct distinctive package names. This implements package to be unique easily and automatically installed and developed.
    For example, if a Canadian organization called MySoft created a package that deals with fractions, you could name the package ca.mysoft.fractions to distinguish it from another similar package created by another company.increase. If a German company called MySoft also created his Fraction package and called it de.mysoft.fractions, the classes in these two packages would be defined in unique and separate namespaces.
  • When a class is added to the package: By using the package name at the top of the programme and adding it to the package directory, we can add more classes to a created package. To declare a public class, a new java file must be generated; otherwise, we may just add the new class to an existing java file and recompile it.

The package keyword in Java is used to create packages.

In Java, a package is created with the package keyword.

package mypackage.  
public class Sim ex 1 {  
 public static void main (String as []) {
    System.out.println("initalizing the package");
   }  
}  

Compiling the java package:

If you are not using an IDE, you must use the following syntax:

Syntax:

javac -d directory javafilename  

Example for compiling package is:

javac -d. Simple.java 

The destination for the created class file is specified by the -d switch. Any directory name is acceptable, such as /home or d:/abc (for Windows) (for Linux). When you want to keep the package in the same directory, use (dot).

Java package programme execution:

Use a name that is completely qualified, like "mypackage."To Compile: javac -d. Simple.java

To Run:

java mypackage. Simple

Output:

initializing the package

The -d switch instructs the compiler to place the class file at the specified location.it represents destination. They represent the current folder.

Accessing Package from Another Package

The package can be accessed in three different ways from outside the package.

  1. import package. *;
  2. import package. Classname;
  3. fully qualified name.

Implementing Package Name:

  • Example of importing package from package name:
package pack 1;
public class ra {
  public void msg () {System.out.println("Package import");}  
}  
//save by ta.java  
package mypack11;
import pack1.*;  


class ta {
  public static void main (String s []) {
ra bj = new ra ();
bj.msg ();
  }  
}  

Output:

Package Import

Using packagename. Classname:

Only the declared classes of this package will be accessible if you import package. classname.

Example of importing package from package classname

package pack2;
public class PA {  
  public void message () {
System.out.println("Package.classname");}  
}  
//save by BA.java  
package mypack2;
import pack1.PA;


class BA {  
  public static void main (Strings []) {
PA bj = new PA ();
bj. messsage ();
  }  
}  

Output:

Package.Classname

Using fully qualified name:

Only the stated classes of this package will be accessible if you use the fully qualified name. No longer is it necessary to import. However, whenever you visit a class or interface, you must always use the fully qualified name.

It is typically used when two packages contain the same class name, for example, when the Date class is present in both the Java.util and Java.sql packages.

A fully qualified package by import example:

package pack3;
public class PA {  
  public void message () {
System.out.println("fully qualified package ");}  
}  
//save by BA.java  
package mypack2;
import pack 1.PA;


class BA {  
  public static void main (Strings []) {  
PA bj = new PA (); //using fully qualified name  
   bj. messsage ();
  }  
}  

Output:

Fully qualified package

When you import a package, all its classes and interfaces—except for those from its subpackages—are imported. As a result, you also need to import the subpackage.

Note: 1. Subpackages won't be imported when a package is imported.

  • The program's sequence must be package, import, then class.

Subpackage in Java

Classes like Reader and Writer are used for input and output, Socket and ServerSocket are used for networking, and so on and placed classes related to input/output in the io package, servers and server sockets in the net packages, and so on.

Sub packagre example:

package com. raju.core;  
class sim Ex {  
  public static void main (String s []) {
   System.out.println("importing subpackage");
  }  
}  

To Compile: javac -d . Simple.java

To Run: java com. raju. core. Simple

Output:

importing subpackage

Sending the class file to another directory or drive:

Example:

package mypack1;
public class Sim Ex{  
 public static void main (String s []) {  
    System.out.println("Package directory");
   }  
}  

By telling Java where to seek for class files, the -classpath switch can be used to run this application from the e:source directory.

The classpath instructs Java where to search for the files defining these classes in the filesystem. Classpath variables are variables and methods that are accessible and readily available. By default, JVM always access the classpath classes while executing a programme. JVM always search into the deep of classpath to analise for a class or resource.

Putting two public classes in a package:

Two Java source files should each contain one public class if you want to include two public classes in a package, but the package name should remain the same. For instance:

package javaKeywords;

public class AP {} 

//save as BP.java 

package javaKeywords;

public class BP {} 

Loading the class files or jar files:

The class files can be loaded in two different ways: temporarily and permanently.

Temporary

By modifying the command prompt's classpath with the -classpath switch

Permanent

By putting the classpath in the environment variables generating the class file jar file and placing it in the jre/lib/ext folder are both ways to install class files.


Related Topics

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Constructor Chaining and Constructor Overloading in Java

Constructor Chaining Constructor chaining and constructor overloading are two confusing terms. Let's first understand constructor chaining.Constructor chaining is the process of calling one constructor from another constructor using the same object....

2 minutes read.

Java Math signum() Method

The signum() method of Java Math class returns the signum function of the value. Syntax: public static double signum(double d)public static float signum (float d) Parameters: The parameter ‘d’ represents the floating-point value whose...

2 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

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.

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.

How to Convert long to int in Java

How to Convert long to int in Java When we assign a larger type value to a variable of smaller type, then we need to perform explicit casting for the conversion....

2 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Automorphic Number Program in Java

We will learn about automorphic numbers through examples in this article, and we'll also make Java programmes that can determine whether a specific number was automorphic or not. What is an...

3 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 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 Write File

In this post, we'll examine various Java programming methods for writing into files. Since this class is character-oriented due to how it is used in file handling in Java, it...

4 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.