AppDividend
Latest Code Tutorials

Java Packages Tutorial With Example | Packages in Java

0

Java Packages Tutorial With Example | Packages in Java is today’s topic. A package in Java is used to group the related classes. Think of it as the folder in the file directory. To create a package is quite straightforward: include a package command as the first statement in a Java source file. The package statement defines a namespace in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name. While the default package is excellent for short, sample programs, it is inadequate for real applications. Object class in a superior class of all classes in Java.

Java Packages Tutorial

Creating a package is kind of straightforward in java: merely embody the package command and therefore the name of the package because of the initial statement in an exceeding java supply file. The package statement defines a reputation area during which categories square measure hold on. Any categories declared when the package statement could belong to its given package.

The general syntax of the package statement.

 

Java Packages Tutorial

Java uses file system directories to store packages. For example, a .class files for any classes you declare is being part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant, and the directory name must match the package name exactly. More than one file can include a same package statement. The package statement specifies to which package the classes defined in a file belong.

You can create a hierarchy of packages. To do so, separate each package name from the one above it by use of a period.

package pkg1[.pkg2[.pkg3]];

#Java sub-package

Package inside the package is known as a subpackage. The packages that come lower in the naming hierarchy are called “sub-package” of the corresponding package higher in the hierarchy, i.e., the package that we are putting into another package is called “sub-package”. 

See the following code example.

package package_name; 

public class ClassOne { 
	public void methodClassOne() { 
		System.out.println("Hello there its ClassOne"); 
	} 
}

package testing;
import package_name.ClassOne; 

public class Testing { 
	public static void main(String[] args){ 
		ClassTwo a = new ClassTwo(); 
		ClassOne b = new ClassOne(); 
		a.methodClassTwo(); 
		b.methodClassOne(); 
	} 
}

#Java package structure

 

Java package structure

#Advantage of java package

  1. Java package is employed to reason the categories and interfaces so that they will be maintained.
  2. Java package provides access protection.
  3. Java packages remove naming collision.
  4. It is additionally easier to find connected categories.
  5. Packages will offer reusability of code.

#Classification of packages in Java

Packages in Java can be divided into two categories,

  1. Built-in Packages (packages from Java API)
  2. User-defined Packages (create your packages)

Types of packages in Java

#Java Built-in Packages

Integrated packages are already defined packages in Java API like java.io.*, java.lang.* Etc. Java API is the library of prewritten classes that are free to use, included in the Java Development Environment. If we want to use the class or a package from a library, we need to use an import keyword.

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

See the following output.

 

Java Packages Tutorial With Example

Some of the commonly used java built-in packages are given below.

Package Name Description
java.lang

Contains language support class ( for the, e.g. class that defines primitive information sorts, mathematics operations, etc.). This package is automatically imported.

java.io Contains classes for supporting the input/output operations.
java.util

Contains utility classes which implement data the structures like Linked List, Hash Table, Dictionary, etc. and support for Date / Time operations.

java.applet Contains classes for creating Applets.
java.awt

Contains classes for implementing the components of a graphical user interface ( like buttons, menus, etc. ).

java.net

Contains classes for supporting the networking operations.

#User-defined packages

User outlined packages area unit those packages that area unit outlined by the user. 1st we tend to produce a directory calculate(name ought to be the same because of the name of the package). To make a category within a package, declare the package name within the 1st statement of the java program. To use a category or Associate in Nursing user outlined package from the library, we want to use the import keyword.

See the following code example.

//We are creating a package which can calculate the
//area of a Rectangle
 
package Rectangle; //declaring the package name
public class area
{
  public int rect(int a, int b)
  {
	return (a*b); 	//calculation area of rectangle
  }
  public static void main(String[] args)
  {
	area obj=new area(); //creating object for area class
	//obj.rect(10,5);
  }
}

See the following output.

Now let’s see how to use this package in another program.

import Rectangle.area;
class Demo
{
   public static void main(String args[])
   {
    area obj = new area();
    System.out.println("Area of rectangle is: ");
    System.out.println(obj.rect(10,5));
   }
}

See the following output.

 

User-defined packages in Java

#Finding Packages and CLASSPATH

A package or package hierarchy should replicate within the classification system of the Java development system. As an example a package declared as package java.awt.image; has to be held on in java\awt\image during a Windows surroundings.

How will the Java run-time system apprehend wherever to appear for packages that you create?

First, by default, the Java run-time system uses this operating directory as its place to begin. Thus, if your package is during a directory of this directory, it’ll be found.

Second, you’ll specify a directory path or ways by setting the CLASSPATH environment variable.

Third, you’ll use the -classpath choice with java and javac to specify the trail to your categories.

#Setting CLASSPATH

CLASSPATH can be set by any one of the following ways:

#CLASSPATH can be set permanently in an environment: 

In Windows, go to the control panel > System > Advanced > Environment Variables > choose the “System Variables” (for all users) or “User Variables” (only the currently login user) > choose “Edit” (if the CLASSPATH already exists) or “New” > Enter the “CLASSPATH” as a variable name > Enter the required directories and JAR files (separated by semicolons) as a value (e.g., “.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar”).

If we want to check the current setting of the CLASSPATH, type the following command in CMD:

> SET CLASSPATH

CLASSPATH can be set temporarily for that specific terminal shell session by using the following command:

> SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar

 Instead of using a CLASSPATH environment variable, you can also use the command-line option -classpath or -cp of the javac and java commands, for example,

 > java –classpath c:\javaproject\classes com.abc.project1.subproject2.MyClass3

#Points to remember

  1. Sometimes class name conflict may occur. Let us say we have two packages mypackage and tiny package and both the packages have a class with the same name. This will throw compilation error.
  2. If we create a class inside the package while importing another package, then a package declaration should be the first statement.
  3. A class can have only one package declaration, but it can have more than one package import statements.
  4. The wild card import like a package.* should be used carefully when working with sub-packages.
  5. If there is no package, the classes in the file go into an unnamed special package.

Finally, Java Packages Tutorial With Example | Packages in Java is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.