Java With Us
Home   |   Tutorial   |   Programs  

Java Tutorial

Introduction to Java
Hello World Program
Variables and Data types
More about data types
Displaying text using print and println
Displaying text using printf
Java Comments
Naming conventions for Identifiers
Mathematical operations in Java
Taking input from the user

Classes and Objects
Introduction to object oriented programming
The constituents of a Class
Creating objects and calling methods
Get and Set Methods
Default constructor provided by the compiler
Access Specfiers
Scope and lifetime of Variables
Call by value and Call by Reference

A few more topics
Class as a reference data type
Constants or literals
Final variables
Increment and decrement operators
Manipulating Strings
Overloading constructors and methods
Static methods and variables
The Java API
The Math class
this keyword
Wrapper classes

Control Structures
Control Statements
Repetition statements
Nested loops
Formulating algorithms
Branching Statements

Arrays introduction
Processing arrays using 1oops
Searching and sorting arrays
Array of objects
Multi dimensional arrays
Taking input as command line arguments
Using ellipsis to accept variable number of arguments

Inheritance introduction
Relation between a super class and sub class
Final classes and methods
The protected access specifier
Class Object

Abstract classes and methods

Exception handling
Exception handling introduction
Exception hierarchy
Nested try catch blocks
Throwing exceptions


We have come across packages many times. We have also used them in a few instances. We will now review all those concepts and also look into the unexplored items. We start with what a package is. A package in Java is used to group related classes together. For example, we can have a package named shapes which will contain various classes like Circle, Triangle and Square used to process various geometric shapes. Packages are also used to resolve namespace conflicts. Two classes cannot have the same name under normal circumstances. However, if they are declared in different packages, you can have more than a single class with the same name.

Packages are created when the program files are compiled. You can specify a class to be a part of a package by using the package keyword before any other code in your class, including class declaration and import declarations. You can however have comments before the package statement as they are ignored by the compiler. The following code declares the class Triangle to be a part of the package shapes. A package name by convention is written in all lowercase letters even if they consist of more than a single word.

package shapes;
class Triangle{
    // code

A package can in turn contain other packages. You specify this using a dot. For example, if you would like to include a class, say Cube in a package named threed which should be a part of the package shapes, then you do it in the following way.

package shapes.threed;

class Cube {

Understand that we include packages within packages only to represent the physical situation. The two packages shapes and shapes.threed are considered to be different packages when we deal with access protection and package imports. For instance, if the class Cube is declared as protected, then it would not accessible to the class Triangle since they both are situated in different packages. However, as already said packages are defined in this way to represent physical relations which are reflected in the way the compiled classes are organised. To understand this, define the following classes in different program files all in a single folder on your computer and compile them.

package shapes;
class Triangle{

package shapes;
class Rectangle{

package shapes.threed.sixfaces;
class Cube {

package shapes.threed;
class Sphere {

package shapes.threed.sixfaces;
class Cuboid {

package shapes.threed.fourfaces;
class Tetrahedron {

In all we have six classes. After compiling them, observe how the Class files generated are arranged in the folder. A new folder shapes has been created which contains Triangle.class, Rectangle.class and another folder named threed. The threed folder contains Sphere.class and two folders: sixfaces and fourfaces. The six faces folder contains two files : Cube.class and Cuboid.class. The folder fourfaces contains a single file Tetrahedron.class.

When a class is not specified to be a part of any package, it is then placed in the default package. In terms of a folder, the .class compiled file is placed in the same folder in which the .java file is present.

In order to use a class of a package other than the one to which the class we are working in belongs to, we need to import either that particular class or the entire package in which the class is located. Or, we can refer to the class by its fully qualified name. To import a package or a class, we use the import declaration placed after the package statement. To import a class or the entire package, we use the following syntaxes. To import more than one class, we specify each of these import declarations in different statements.

import <package name>.<class name>;
import <package name>.*;

The second statement above imports all the classes that are located in the specified package. Given below are a few import declarations for the above classes we have defined. Note that an import declaration similar to the second statement above does not import the classes contained within sub packages of the specified package. It only imports the classes of that package. For example, importing shapes imports only Triangle and Rectangle. It doesn't import the other classes, Cube, Cuboid and Tetrahedron. The package shapes and shapes.threed are considered to be different.

import shapes.Triangle; // imports Triangle 
import shapes.Rectangle; // imports Rectangle
import shapes.*; // imports both Triangle and Rectangle
import shapes.threed.*; // imports Sphere
import shapes.threed.sixfaces.*; //imports Cube and Cuboid
import shapes.threed.sixfaces.Cube; // imports Cube

Specifying only the package name without the class name or the asterisk (*) results in compilation error.

import shapes; // compilation error

Also, the * is not a general wild card character in this context. The asterisk is in daily life used as a substitute for a sequence of characters. For example T* may represent Tea, Tree and so on. However, here, the * is not a wildcard character and such a use isn't allowed. For example, the following statement generates a compilation error.

import shapes.T*; //compilation error

Once we import a class, we can use that class by referring to its simple name. See the example below:

import shapes.Triangle;
class Test {
    Triangle t; // referring to with its simple name

    public Triangle meth() {  // referring to with its simple name

    public void action(Triangle t) {  // referring to with its simple name

We can also use a class without importing it. In that case, we need to refer to it using its fully qualified name which includes the package name, followed by a dot and the class name. For example, to create a Sphere object, we use the following statement:

shapes.threed.Sphere s = new shapes.threed.Sphere();

In a similar way, the following statements:

public void action(shapes.threed.Sphere  s) {  // referring to with its simple name

Such a use is highly inconvenient, hence it is always recommended to import the classes before using them. However, in certain circumstances, this might not be possible when name conflicts appear. Suppose, we have two packages p1 and p2 both containing the a class with the same name MyClass, then importing both the classes is allowed but that does not mean that we can refer to the either of the class with its simple name. For example, see the following statements. The identifier MyClass cannot be resolved to either of the two versions.

import p1.MyClass;
import p2.MyClass;

class Test {
    MyClass m ; // compilation error

In such a case, the only available solution is to refer to the class with its fully qualified name.

p1.MyClass m1; // correct
p2.MyClass m2; // correct

The current package in which the class is located and the java.lang package are imported automatically into all new classes. That was why we were able to use the String class which is a part of java.lang package without importing it. And also, we were able to use the class Student without importing it in the test classes since both of them belong to the same package- the default package.

We have said in the beginning that packages can be used to avoid name space collision i.e. more than a single class can have the same name if it is in the same package. First create a class named Cube and include it in package shapes.set1 using the package statement. Now try creating a class with the same name with the intention of including it in the package shapes.set2. You will not be allowed to do so as more than a single file in the same folder cannot have the same name on a computer. So here comes the natural question as to how name space collision can be resolved. The place where you store your .java files is immaterial. What ultimately matters is the place where your .class files will be stored. If you are keen on creating a new class with the name Cube, one solution available to you is to create the file in another folder on your computer, compile the two .java files to get the .class files and then arrange them in folders created by yourself. Create a folder named shapes. Within shapes, create two new folders set1 and set2. Place the two class files in their corresponding folders. Though this might sound unusual, this is the way it needs to be done. Or as an alternative, you may use an IDE like Net beans which allows you to create packages also. They too work in a similar way. What they actually create is nothing more than an empty folder similar to what we have done. The last in this topic is regarding the package access. We have already learnt about it. The package access is applied when we do not explicitly specify an access specifier. Such entities are accessible by all members with the package to which the class belongs.

Now that you know how to create packages, there should be a way by which you should be able to import them to a class located anywhere on your computer. For example, you can import the java.util package to any class file irrespective of the folder in which you are storing your program file. If you think that the same can be done here, check if it is true. You can import the shapes packages which you created only to those classes which are located in the same folder as that of the folder in which the shapes folders containing the compiled class files is located. This is because of the way in which Java locates packages. It only checks in two locations. One is the folder in which your file is located and the other is a folder found with the other jdk files. To learn how to make your package usable by others, check out this article.

Privacy Policy