×

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

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

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.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Thread Synchronization in Java

In Java, the smallest processing component is a thread, which is a small subprocess. It follows a different course of action. Threads are autonomous. If an exception occurs in one thread,...

6 minutes read.

Java Date add Days

In order to operate with the time and the Date in Java, we used the abstract Calendar class. It has several helpful interfaces that enable us to convert dates between...

4 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Java Boolean logicalXor() Method

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

2 minutes read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

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

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Can Abstract Classes have Static Methods in Java

Abstract Class An abstract class in Java is one that explicitly uses the keyword "abstract" in its declaration. There are options for both non-abstract and abstract techniques (method with the body)....

4 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.