Java for Beginners: Java - Packages
Tags: java, tutorial, beginners, programming
Published: 2022-03-07 18:25:35

A **package** can be defined as a group of similar types of classes, interface, enumeration and sub-package. Enumerations and annotation types are special kinds of classes and interfaces. Packages provide access protection and name space management in a java program. Therefore, a package provides a mechanism for organizing Java classes into namespaces similar to the modules in VB.
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc. Using package it becomes easier to locate the related classes.

**Package are categorized into two forms:**
**Built-in Package**:-Existing Java package for example java.lang and java.util
**User-defined-package**:- Java package created by user to categorize source files.
##Built-in Packages
These packages consist of a large number of classes which are a part of Java API. Some of the commonly used built-in packages are:

- **java.lang**: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.
- **java.io**: Contains classed for supporting input / output operations.
- **java.util**: Contains utility classes which implement data structures like Linked List, Dictionary and support ; for Date / Time operations.
- **java.applet**: Contains classes for creating Applets.
- **java.awt**: Contain classes for implementing the components for graphical user interfaces (like button , ;menus etc).
- **java.net**: Contain classes for supporting networking operations. And many others.
##User-defined packages
Programmers can define their own packages to bundle group of classes/interfaces etc. It is a good practice to group related classes implemented by you so that a programmers can easily determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classed.
To set up the programmer-defined packages for general reuse, not just use by the programs in the same folder, we have to perform the following tasks:
1. Include the statement
`package myutil;` as the first statement of the source file for the `Fraction class`.
2. The class declaration must include the visibility modifier public as `public class Fraction {}`
3. Create a folder named `myutil` , the same name as the package name. In Java, the package must have a one-to-one correspondence with the folder.
4. Place the modified Fraction class into the myutil folder and compile it.
5. Modify the `CLASSPATH environment variabl`e to include the folder that contains the myutil folder.

##Creating a package
To group classes into a package each class must have a package statement defined at the top of a java file. It lets the compiler know which package the class belongs to and must be the first line of code. The syntax for defining a package is:
`package <package name>` 
NB: A package name is a fully qualified variable name. e.g. package diploma_students. To create your own package, you need to understand that Java uses a file system directory to store them. Just like folders on your computer.

##Java Package Names and Directory Structure
Organizing classes in a program can take multiple levels so that each package can have as many sub-packages as needed. The Java Package name consists of words separated by periods. The first part of the name represents the organization which created the package. The remaining words of the Java Package name reflect the contents of the package. The Java Package name also reflects its directory structure. 
The period "." is used to distinguish the package and sub-package. The period is placed in-between the package names. E.g. package `university.college.department.course`
The first part of that package name "university" represents the organization that developed the package. The second part of the package name "college" stands for the contents of the package, in this case the department and lastly the course offered by a given department.

##The import Keyword
Import keyword is used to import built-in and user-defined packages into your java source file. Packages allow your class to refer to a class that is in another package by directly using its name. 
There are 3 different ways to refer to class that is present in different package.
1. Using fully qualified name (which is not a good practise). **Example**
```
class myDate extends java.util.Date{
    //body
}
```
2. Import the only class you need
**Example**
```
import java.util.Date;
class myDate extends Date{
    //body
}
```
3. Import all classes from a particular package
**Example**
```
import java.util.*;
class myDate extends Date{
    //body
}
```

**Importing a Class from an Existing Java Package using the import Keyword:**
If a class wants to use another class in the same package, the package name does not need to be used. Classes in the same package find each other without any special syntax.
If a class in one package uses details of another class in different package, the class to be used MUST be included in current class using the import statement. E.g.
`import javax.swing.JOptionPane;`
Note: The import statement is terminated with a semicolon.
###How to access Package from another package
There are three ways to access the package from outside the package.

- import package.*;
- import package.classname;
- fully qualified name.

###Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not sub-packages. The import keyword is used to make the classes and interface of another package accessible to the current package.
####Static import
`Static import` is a feature that extends the capabilities of `import` keyword. It is used to import static member of a class.We will know that static member are referred in association with its class name outside the class. Using static import, its possible to refer to the static member directly without its class name.

The 2 general form of static statement are:
1. The first form of static import statement, import only a single static member of a class.
**Syntax**: 
```
import static package.class-name.static-member-name
```
**Example**:
```
import static java.lang.Math.sqrt; 
//importing static method sqrt of Math class 
```
2. Second form of static import statement, imports all the static member of a class.
**Syntax**:
```
import static package.class-type-name.*;
```
**Example**:
```
import static java.lang.Math.*;
//importing all static method of Math class 
```
**Example without using static import**

```
public class Test {
    public static void main(String[] args) {
        System.out.println(Math.sqrt(144));
    }
}
```
Output: ` 12 `
**Example using static import**
```
import static java.lang.Math.*;
public class Test{
    public static void main(String[] args) {
        System.out.println(sqrt(144));
    }
}
```
###Handling name conflicts
The only time we need to pay attention to packages is when we have a name conflict . For example both, java.util and java.sql packages have a class named
Date. So if we import both packages in program as follows:
```
import java.util.*;
import java.sql.*;
```
//And then use Date class, then we will get a compile-time error :
`Date today ; //ERROR-- java.util.Date or java.sql.Date?`
The compiler will not be able to figure out which Date class do we want. This problem can be solved by using a specific import statement:

```
import java.util.Date;
import java.sql.*;
```
If we need both Date classes then, we need to use a full package name every time we declare a new object of that class.
For Example:
```
java.util.Date deadLine = new java.util.Date();
java.sql.Date today = new java.sql.Date();
```
###How to compile the Package (if not using IDE)
If you are not using any IDE, you need to follow the syntax given below:
`javac -d <directory or dot operator> <javafilename>`
For example
`javac -d . Simple.java`
The -d switch specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).
For more visit [Java Installation](https://dev.to/killallnano/java-for-beginners-installation-of-java-nhc).
**How to run the Package (if not using IDE)**
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
**To Compile:** `javac - d . Simple.java`
The `-d` is a switch that tells the compiler where to put the class file i.e. it represents destination. The `.` represents the current folder.

This marks the end of the Java for beginners.
You can learn more about Java through the urls below:
[https://beginnersbook.com/2013/03/packages-in-java/](https://beginnersbook.com/2013/03/packages-in-java/)
[https://www.geeksforgeeks.org/packages-in-java/](https://www.geeksforgeeks.org/packages-in-java/)
[https://www.javatpoint.com/package](https://www.javatpoint.com/package)