- Java Programming Basics
- Java Tutorial
- Java Overview
- Java Environment Setup
- Java Program Structure
- Java Basic Syntax
- Java First Program
- Java Constants
- Java Separators
- Java Keywords
- Java Data Types
- Java Data Types
- Java Integers
- Java Floating Point
- Java Characters
- Java Booleans
- Java Numbers
- Java Programming Variables
- Java Variables
- Java Variable Types
- Java Variable Scope
- Java Type Conversion
- Java Type Casting
- Java Auto Type Promotion
- Java Type Promotion Rules
- Java Programming Arrays
- Java Arrays
- Java One Dimensional Array
- Java Multidimensional Array
- Java Programming Operators
- Java Operators
- Java Arithmetic Operators
- Java Increment Decrement
- Java Bitwise Operators
- Java Left Shift
- Java Right Shift
- Java Relational Operators
- Java Boolean Logical Operators
- Java Ternary(?) Operator
- Java Operator Precedence
- Java Control Statements
- Java Decision Making
- Java if if-else if-else-if
- Java switch Statement
- Java Loops
- Java while Loop
- Java do-while Loop
- Java for Loop
- Java for-each Loop
- Java Nested Loops
- Java break Statement
- Java continue Statement
- Java Class Object Method
- Java Classes and Objects
- Java Class
- Java Object
- Java new Operator
- Java Methods
- Java Constructors
- Java this Keyword
- Java Stack
- Java Overloading Recursion
- Java Method Overloading
- Java Constructor Overloading
- Java Object as Parameter
- Java Call by Value Reference
- Java Returning Objects
- Java Recursion
- Java Modifier Types
- Java Encapsulate Poly String
- Java Encapsulation
- Java Polymorphism
- Java Nested Inner Class
- Java Strings
- Java Command Line Arguments
- Java Variable Length Arguments
- Java Inheritance Abstraction
- Java Inheritance
- Java super Superclass
- Java Multilevel Hierarchy
- Java Method Overriding
- Java Abstraction
- Java Packages Interfaces
- Java Packages
- Java Access Protection
- Java Import Statement
- Java Interfaces
- Java Programming Exceptions
- Java Exception Handling
- Java try catch
- Java throw throws
- Java finally Block
- Java Built In Exceptions
- Java Exception Subclasses
- Java Chained Exceptions
- Java Multithreading
- Java Multithreading
- Java Thread Model
- Java Main Thread
- Java Create Thread
- Java Thread Priorities
- Java Synchronization
- Java Inter Thread Communication
- Java Suspend Resume Stop Thread
- Java Get Thread State
- Java Enum Autobox Annotation
- Java Enumerations
- Java Type Wrappers
- Java Autoboxing
- Java Annotation
- Java Marker Annotations
- Java Single Member Annotation
- Java Built In Annotations
- Java Type Annotations
- Java Repeating Annotations
- Java Data File Handling
- Java Files I/O
- Java Streams
- Java Read Console Input
- Java Write Console Output
- Java PrintWriter Class
- Java Read Write Files
- Java Automatically Close File
- Java Programming Advance
- Java Date and Time
- Java Regular Expressions
- Java Collections Framework
- Java Generics
- Java Data Structures
- Java Network Programming
- Java Serialization
- Java Send Email
- Java Applet Basics
- Java Documentation
- Java Programming Examples
- Java Programming Examples
Java Package
Packages are containers for the classes.
Why Packages are Used ?
Packages are used to keep the class name space compartmentalized. For example, a package allows you to create a class named Demo, which you can store in your own package without concern that it will collide with some other class named Demo stored elsewhere.
How Packages are Stored ?
Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.
In the preceding chapters, the name of each example class was taken from the same name space. It means that a unique name had to be used for each class to avoid the name collisions.
After a while, without some way to handle the name space, you could run away of convenient, descriptive names for the individual classes. You also require some way to be assured that the name you choose for a class will be reasonably unique and not collide with the class names chosen by other programmers.
The package is both a naming and a visibility control mechanism. You can define classes within a package that are not accessible by the code outside that package. You can also define class members that are exposed only to the other members of the same package. This allows your classes to have intimate knowledge of each other, but not display that knowledge to the rest of the world.
Define a Package
To create a package, just include the package command as the first statement in a Java source file. Any classes declared within that file will belong to the determined package.
The package statement defines a name space in which classes are stored. If you exclude the package statement, the class names are put into the default package, which has no name. (This is why you have not had to worry about the packages before now). While the default package is fine for short, simple programs, it is inadequate for the real applications. Most of the time, you will define a package for your code.
Following is the general form of the package statement :
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a package, which is DemoPackage :
package DemoPackage;
How to Store Packages ?
To store packages, Java uses file system directories. For instance, the .class files for any classes that you declare to be part of the DemoPackage must be stored in a directory called DemoPackage. Remember that case is crucial, and the directory name must match the package name exactly.
More than one file can include the same package statement. And the package statement just specifies to which package the classes defined in a file belong. It doesn't exclude the other classes in other files from being part of that same package. Most of the real-world packages are spread across may files.
Create a Hierarchy of Packages
You can create a hierarchy of packages. To do so, separate each package name from the one above it by use of a period. The general form of a multilevelled package statement is shown below :
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system. Here is an example, a package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment. Always be sure to choose your package names carefully. You can't rename a package without re-naming the directory inside which, classes are stored.
Find Packages and CLASSPATH
As just explained, packages are mirrored by the directories. This produces a crucial question. The question is:
How does the Java run-time system know where to look for the packages that you create ?
The answer has the these three parts.
- By default, the Java run-time system uses the current working directory as its starting point. Therefore, if your package is in a subdirectory of the current directory, it will be found.
- You can specify a directory path/paths simply by setting the CLASSPATH environment variable.
- You can use the -classpath option with java and javac to determine the path to your classes.
For example, consider the following package specification:
package DemoPackage
In order for a program to find DemoPackage, then anyone of these three things must be true.
- either the program can be executed from a directory directly above DemoPackage
- or the CLASSPATH must be set to include the path to DemoPackage
- or the -classpath option must define the path to DemoPackage when the program is run via java
When the second two options are used, the classpath must not include DemoPackage, itself. It must specify the path to the DemoPackage. For instance, in a Windows environment, if the path to DemoPackage is
C:\JavaPrograms\Java\DemoPackage
then the class path to DemoPackage is
C:\JavaPrograms\Java
The easiest way to try the examples is to create the package directories below your current development directory, put the .class files into the proper directories, and then executed the programs from the development directory. This approach used in the coming example.
Java Package Example
Following is a simple package example program :
/* Java Program Example - Java Packages * This is a simple package example */ package DemoPackage; class Amount { String name; double bal; Amount(String nm, double bl) { name = nm; bal = bl; } void display() { System.out.println(name + " : $" + bal); } } class JavaProgram { public static void main(String args[]) { Amount present[] = new Amount[3]; present[0] = new Amount("Rajat Patel", 234.34); present[1] = new Amount("Ravi Patel", 268.13); present[2] = new Amount("Vikrant Patel", -23.44); for(int i=0; i<3; i++) { present[i].display(); } } }
Call this file JavaProgram.java and put it in a directory called DemoPackage.
Next, compile the file. First, make sure that the resulting .class file is also in the DemoPackage directory. Now, try executing the JavaProgram class, using the below command line:
java DemoPackage.JavaProgram
Remember, you will need to be in the directory above the DemoPackage whenever you executed this command.
As explained earlier, JavaProgram is now part of the package DemoPackage. This means that it cannot be executed by itself i.e., you cannot use this command line:
java JavaProgram
JavaProgram must be qualified with its package name.
« Previous Tutorial Next Tutorial »