Creating packages in java and import package

Java Package

A package is simply a container that groups related types (Java classes, interfaces, enumerations, and annotations). For example, in core Java, the ResultSet interface belongs to the java.sql package. The package contains all the related types that are needed for the SQL query and database connection.

If you want to use the ResultSet interface in your code, just import the java.sql package (Importing packages will be discussed later in the article).

As mentioned earlier, packages are just containers for Java classes, interfaces and so on. These packages help you to reserve the class namespace and create a maintainable code.

For example, you can find two Date classes in Java. However, the rule of thumb in Java programming is that only one unique class name is allowed in a Java project.

How did they manage to include two classes with the same name Date in JDK?

This was possible because these two Date classes belong to two different packages:

  • java.util.Date — this is a normal Date class that can be used anywhere.
  • java.sql.Date — this is a SQL Date used for the SQL query and such.
Читайте также:  Error cannot find module typescript

Based on whether the package is defined by the user or not, packages are divided into two categories:

Built-in Package

Built-in packages are existing java packages that come along with the JDK. For example, java.lang , java.util , java.io , etc. For example:

import java.util.ArrayList; class ArrayListUtilization < public static void main(String[] args) < ArrayListmyList = new ArrayList<>(3); myList.add(3); myList.add(2); myList.add(1); System.out.println(myList); > > 

The ArrayList class belongs to java.util package . To use it, we have to import the package first using the import statement.

User-defined Package

Java also allows you to create packages as per your need. These packages are called user-defined packages.

How to define a Java package?

To define a package in Java, you use the keyword package .

Java uses file system directories to store packages. Let’s create a Java file inside another directory.

Now, edit Test.java file, and at the beginning of the file, write the package statement as:

Here, any class that is declared within the test directory belongs to the com.test package.

package com.test; class Test < public static void main(String[] args)< System.out.println("Hello World!"); >>

Here, the Test class now belongs to the com.test package.

Package Naming convention

The package name must be unique (like a domain name). Hence, there’s a convention to create a package as a domain name, but in reverse order. For example, com.company.name

Here, each level of the package is a directory in your file system. Like this:

And, there is no limitation on how many subdirectories (package hierarchy) you can create.

How to create a package in Intellij IDEA?

In IntelliJ IDEA, here’s how you can create a package:

  1. Right-click on the source folder.
  2. Go to new and then package. New package in Intellij IDEA
  3. A pop-up box will appear where you can enter the package name. Package Naming convention in Java

Once the package is created, a similar folder structure will be created on your file system as well. Now, you can create classes, interfaces, and so on inside the package.

Package directory

How to import packages in Java?

Java has an import statement that allows you to import an entire package (as in earlier examples), or use only certain classes and interfaces defined in the package.

The general form of import statement is:

import package.name.ClassName; // To import a certain class only import package.name.* // To import the whole package
import java.util.Date; // imports only Date class import java.io.*; // imports everything inside java.io package

The import statement is optional in Java.

If you want to use class/interface from a certain package, you can also use its fully qualified name, which includes its full package hierarchy.

Here is an example to import a package using the import statement.

import java.util.Date; class MyClass implements Date < // body >

The same task can be done using the fully qualified name as follows:

class MyClass implements java.util.Date < //body >

Example: Package and importing package

Suppose, you have defined a package com.programiz that contains a class Helper .

package com.programiz; public class Helper < public static String getFormattedDollar (double value)< return String.format("$%.2f", value); >>

Now, you can import Helper class from com.programiz package to your implementation class. Once you import it, the class can be referred directly by its name. Here’s how:

import com.programiz.Helper; class UseHelper < public static void main(String[] args) < double value = 99.5; String formattedValue = Helper.getFormattedDollar(value); System.out.println("formattedValue Importing packages in Java" height="177" src="https://cdn.programiz.com/sites/tutorial2program/files/import-package-java_0.jpg" title="Java import package" width="400">
Java import package

In Java, the import statement is written directly after the package statement (if it exists) and before the class definition.

For example,

package package.name; import package.ClassName; // only import a Class class MyClass < // body >

Table of Contents

Источник

Packages in Java: How to Create/Import Package

PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It helps organize your classes into a folder structure and make it easy to locate and use them. More importantly, it helps improve code reusability.

Each package in Java has its unique name and organizes its classes and interfaces into a separate namespace, or name group.

Although interfaces and classes with the same name cannot appear in the same package, they can appear in different packages. This is possible by assigning a separate namespace to each Java package.

The following video takes you through the steps of creating a package.

Click here if the video is not accessible

Let’s study package with an example. We define a class and object and later compile this it in our package p1. After compilation, we execute the code as a java package.

How to Create a package?

Creating a package is a simple task as follows

  • Choose the name of the package
  • Include the package command as the first line of code in your Java Source File.
  • The Source file contains the classes, interfaces, etc you want to include in the package
  • Compile to create the Java packages

Step 1) Consider the following package program in Java:

package p1; class c1() < public void m1()< System.out.println("m1 of c1"); >public static void main(string args[]) < c1 obj = new c1(); obj.m1(); >>

How to Create a package

  1. To put a class into a package, at the first line of code define package p1
  2. Create a class c1
  3. Defining a method m1 which prints a line.
  4. Defining the main method
  5. Creating an object of class c1
  6. Calling method m1

Step 2) In next step, save this file as demo.java

How to Create a package

How to Create a package

Step 3) In this step, we compile the file.

How to Create a package

The compilation is completed. A class file c1 is created. However, no package is created? Next step has the solution

How to Create a package

This command forces the compiler to create a package.

The “.” operator represents the current working directory.

How to Create a package

Step 5) When you execute the code, it creates a package p1. When you open the java package p1 inside you will see the c1.class file.

How to Create a package

Step 6) Compile the same file using the following code

Here “..” indicates the parent directory. In our case file will be saved in parent directory which is C Drive

How to Create a package

File saved in parent directory when above code is executed.

How to Create a package

Step 7) Now let’s say you want to create a sub package p2 within our existing java package p1. Then we will modify our code as

How to Create a package

Step 8) Compile the file

How to Create a package

As seen in below screenshot, it creates a sub-package p2 having class c1 inside the package.

How to Create a package

Step 9) To execute the code mention the fully qualified name of the class i.e. the package name followed by the sub-package name followed by the class name –

How to Create a package

This is how the package is executed and gives the output as “m1 of c1” from the code file.

How to Create a package

How to Import Package

To create an object of a class (bundled in a package), in your code, you have to use its fully qualified name.

java.awt.event.actionListner object = new java.awt.event.actionListner();

But, it could become tedious to type the long dot-separated package path name for every class you want to use. Instead, it is recommended you use the import statement.

Once imported, you can use the class without mentioning its fully qualified name.

import java.awt.event.*; // * signifies all classes in this package are imported import javax.swing.JFrame // here only the JFrame class is imported //Usage JFrame f = new JFrame; // without fully qualified name.

Step 1) Copy the code into an editor.

package p3; import p1.*; //imports classes only in package p1 and NOT in the sub-package p2 class c3 < public void m3()< System.out.println("Method m3 of Class c3"); >public static void main(String args[]) < c1 obj1 = new c1(); obj1.m1(); >>

Step 2) Save the file as Demo2.java. Compile the file using the command javac –d . Demo2.java

Step 3)Execute the code using the command java p3.c3

Packages – points to note:

  • To avoid naming conflicts packages are given names of the domain name of the company in reverse Ex: com.guru99. com.microsoft, com.infosys etc.
  • When a package name is not specified, a class is in the default package (the current working directory) and the package itself is given no name. Hence you were able to execute assignments earlier.
  • While creating a package, care should be taken that the statement for creating package must be written before any other import statements
// not allowed import package p1.*; package p3; //correct syntax package p3; import package p1.*;

the java.lang package is imported by default for any class that you create in Java.

The Java API is very extensive, contains classes which can perform almost all your programming tasks right from Data Structure Manipulation to Networking. More often than not, you will be using API files in your code. You can see the API documentation here.

Источник

Java Packages

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into two categories:

  • Built-in Packages (packages from the Java API)
  • User-defined Packages (create your own packages)

Built-in Packages

The Java API is a library of prewritten classes, that are free to use, included in the Java Development Environment.

The library contains components for managing input, database programming, and much much more. The complete list can be found at Oracles website: https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes. Meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.

To use a class or a package from the library, you need to use the import keyword:

Syntax

import package.name.Class; // Import a single class import package.name.*; // Import the whole package 

Import a Class

If you find a class you want to use, for example, the Scanner class, which is used to get user input, write the following code:

Example

In the example above, java.util is a package, while Scanner is a class of the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read a complete line:

Example

Using the Scanner class to get user input:

import java.util.Scanner; class MyClass < public static void main(String[] args) < Scanner myObj = new Scanner(System.in); System.out.println("Enter username"); String userName = myObj.nextLine(); System.out.println("Username is: " + userName); >> 

Import a Package

There are many packages to choose from. In the previous example, we used the Scanner class from the java.util package. This package also contains date and time facilities, random-number generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign ( * ). The following example will import ALL the classes in the java.util package:

Example

User-defined Packages

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:

Example

└── root └── mypack └── MyPackageClass.java

To create a package, use the package keyword:

MyPackageClass.java

package mypack; class MyPackageClass < public static void main(String[] args) < System.out.println("This is my package!"); >> 

Save the file as MyPackageClass.java, and compile it:

This forces the compiler to create the "mypack" package.

The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign " . ", like in the example above.

Note: The package name should be written in lower case to avoid conflict with class names.

When we compiled the package in the example above, a new folder was created, called "mypack".

To run the MyPackageClass.java file, write the following:

Источник

Оцените статью