Packages in java

Ratings:
(4)
Views: 0
Banner-Img
Share this blog:

Packages in java

A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages. The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work. Syntax of the Package in Java:

package <Package Name>;

Types of package:

  • User defined package: The package we create is called user-defined package.
  • Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in packages.

How to use package

There are 2 ways in order to use the public classes stored in package.

  • Declare the fully-qualified class name. For example,
...
world.HelloWorld helloWorld = new world.HelloWorld();
world.moon.HelloMoon helloMoon = new world.moon.HelloMoon();
String holeName = helloMoon.getHoleName();
...

  • Use an "import" keyword:
import world.*;  // we can call any public classes inside the world package 
import world.moon.*;  // we can call any public classes inside the world.moon package
import java.util.*;  // import all public classes from java.util package
import java.util.Hashtable;  // import only Hashtable class (not all classes in java.util package)

Thus, the code that we use to call the HelloWorld and HelloMoon class should be

...
  HelloWorld helloWorld = new HelloWorld(); // don't have to explicitly specify world.HelloWorld anymore
  HelloMoon helloMoon = new HelloMoon(); // don't have to explicitly specify world.moon.HelloMoon anymore
...  

Note that we can call public classes stored in the package level we do the import only. We can't use any classes that belong to the subpackage of the package we import. For example, if we import package world, we can use only the HelloWorld class, but not the HelloMoon class.

How to create a package

At first create a folder like a name <cei> and store a program. Listing 1: Sample showing Example using package. This is the package program

armstrong.java
public class armstrong
{
	int x=407;
	int r,temp,a=0;
	public void test()
	{
	temp=x;
	while(x>0)
	{
		r=x%10;
		a=a+(r*r*r);
		x=x/10;
	}
	if(temp==a)
	{
		System.out.println("This is Armstrong no..");
	}
else
{
		System.out.println("This is not Armstrong no..");
}	
}	
}

After the creation of the program then compile this program with following syntax:

javac  armstrong.java

If compile this part with successfully then write down this program. Listing 2: Sample showing Example calling package

cal.java
import cei.*;
public class cal{
    public static void main(String args[]){
	   armstrong ob=new armstrong();
	   ob.test(); //this part is calling package method
    }
}

Then compile the code cal.java

javac  cal.java

After that we interpreting this program cal.java

java  cal

Then this call.java will be interpreted and run this program and show the output Output: This is Armstrong no. Packages in java Process to Compile package program and run.

Classpath Packages in Java

CLASSPATH is an environment variable (i.e., global variables of the operating system available to all the processes) needed for the Java compiler and runtime to locate the Java packages used in a Java program. (Why not call PACKAGEPATH?) This is similar to another environment variable PATH, which is used by the CMD shell to find the executable programs. CLASSPATH can be set in one of the following ways:

  • CLASSPATH can be set permanently in the environment: In Windows, choose control panel ⇒ System ⇒ Advanced ⇒ Environment Variables ⇒ choose "System Variables" (for all the users) or "User Variables" (only the currently login user) ⇒ choose "Edit" (if CLASSPATH already exists) or "New" ⇒ Enter "CLASSPATH" as the variable name ⇒ Enter the required directories and JAR files (separated by semicolons) as the value (e.g., ".;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar"). Take note that you need to include the current working directory (denoted by '.') in the CLASSPATH.

To check the current setting of the CLASSPATH, issue the following command:

SET CLASSPATH
  • CLASSPATH can be set temporarily for that particular CMD shell session by issuing the following command:
SET CLASSPATH=.;c:\javaproject\classes;d:\tomcat\lib\servlet-api.jar
  • Instead of using the 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

 

How to put two public classes in a package?

Two public classes in a package, have two source files containing one public class, but keep the package name same . For example.

//save as A.java  
package javatpoint;  
public class A{}  
//save as B.java   
package javatpoint;  
public class B{}  

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the package further. Let's take an example, Sun Microsystem has definded a package named java that contains many classes like System, String, Reader, Writer, Socket etc. These classes represent a particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java package into subpackages such as lang, net, io etc. and put the Input/Output related classes in io package, Server and ServerSocket classes in net packages and so on.

package com.javatpoint.core;  
class Simple{  
  public static void main(String args[]){  
   System.out.println("Hello subpackage");  
  }  
}

To Compile: javac -d . Simple.java To Run: java com.javatpoint.core.Simple

Output:Hello subpackage

Advantages of Packages in java

  • Package are generally used to organize the classes fitting to same category or given that similar functionality.
  • A package provides a primary namespace [Namespace is collection for set of identifier].
  • The class which is belonging in same package can access each other package-access member.
  • Classes are sharing the same name only if they are present in other package.
  • A package provides a means to group related classes.
  • To create a package we need two level each file in which the classes are defined with the name of the package.
  • We can easily decide that the classes and interfaces in a single package are related.
  • In generally, the names of our classes and interfaces should not conflict with the names in other packages because the package creates a new namespace.
  • You can permit the classes within the package to have unrestricted access to one another yet still restrict access for types outside the package.
  • In general, we can also declare the package name with our common name for easily remembers.

 

You liked the article?

Like: 0

Vote for difficulty

Current difficulty (Avg): Medium

EasyMediumHardDifficultExpert
IMPROVE ARTICLEReport Issue

About Author

Authorlogo
Name
TekSlate
Author Bio

TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.

Stay Updated
Get stories of change makers and innovators from the startup ecosystem in your inbox