Unit 3
Unit 3
Aim of Packages is to create containers for classes that are used to keep the class name space
compartmentalized.
Packages are stored in a hierarchical manner and are explicitly imported into new class
definitions.
Objectives
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Introduction to Packages
One of the main features of the Object Oriented Programming language is the ability to reuse the
code that is already created. One way for achieving this is by extending the classes and
implementing the interfaces. Java provides a mechanism to partition the classes into smaller
chunks. This mechanism is called Package. The Package is container of classes and interfaces.
The class is the container of the data and code. The package also addresses the problem of name
space collision that occurs when we use same name for multiple classes. Java provides
convenient way to keep the same name for classes as long as their subdirectories are different.
.
1. Predefined packages –Java API provides large number of classes grouped into different
Packages according to the functionality. Most of the time we use the package available with
JavaAPI.
Java
In the above figure java is root package in it has many sub packages like lang,io ect.
Java System Packages and their Classes
While creating a package, you should choose a name for the package
and include a package statement along with that name at the top of
every source file that contains the classes, interfaces, enumerations,
and annotation types that you want to include in the package.
Syntax:
Package packagename;
Example;
package mypack;
package packagename.subpackagename.subpcakage….;
Example
package mypack.B;
The package statement should be the first line in the source file.
There can be only one package statement in each source file, and it
applies to all types in the file.
i.e
package mypack;
class Demo()
code;
}
If a package statement is not used then the class, interfaces,
enumerations, and annotation types will be placed in the current
default package.
To compile the Java programs with package statements, you have to use -d
option as shown below.
Syntax:
In the above statement –d specifies the java compiler to create a separate sub directory and place
the . class file there. The dot (.) after - d indicates that the package should be created in .the
current directory
Naming a package
Packages can be named using the Java Standard naming rules.
Packages begin with "lowercase" letters.
It is easy for the user to distinguish it from the class names.
All the class Name by convention begin with "upper case" letters.
Example:
double d= java.lang.Math.sqrt(3);
Here, "java.lang" is the package, and "Math" is the class name, and "sqrt()" is the method name.
Package members
The types that comprise a package are known as the package members.
To use a public package member from outside its package, you must do one of the following:
we can use a package member's simple name if the code we are writing is in the same package as that
member or if that member has been imported.
However, if we are trying to use a member from a different package and that package has not been imported,
you must use the member's fully qualified name, which includes the package name. Here is the fully qualified
name for the Demo class declared in the mypack package
mypack.Demo
You could use this qualified name to create an instance of mypack.Demo
Qualified names are all right for infrequent use. When a name is used repetitively, however, typing the name
repeatedly becomes tedious and the code becomes difficult to read. As an alternative, you can import the
member or its package and then use its simple name.
To import a specific member into the current file, put an import statement at the beginning of the file before any
type definitions but after the package statement, if there is one. Here's how you would import the Demo class
from the mypack package created in the previous section.
Import mypack.Demo;
This approach works well if you use just a few members from the mypack package. But if you use many
types from a package, you should import the entire package.
To import all the types contained in a particular package, use the import statement with the
asterisk (*) wildcard character.
import mypack.*;
Now you can refer to any class or interface in the mypack package by its simple name.
// creating a package
package mypack; //mypack is used defined package name
public class Mul
{
//i nstance variables
private double a,b;
public Mul(double x , double y)
{
}
a=x;
b=y;
//method to find mul of two numbers
public void mul()
{
System.out.println(“multiplication of two numbers is :“+a*b);
}
}
Now .Mul class has been created in package mypack and it can be imported in other classes
//importing user defined package mypack
import mypack.Mul ;
class Muldemo
{
public static void main(String args[ ])
{
//create Mul class object
Mul obj = new Mul(2.0,3.0);
//call the mul() method
obj . mul();
}
}
c:\> javac Muldemo.java
c:/>java Muldemo
multiplication of two numbers is :“6.0
Public
Protected
Default
Private
When we do not mention any access modifier, it is called default access modifier. The scope of
this modifier is limited to the package only. This means that if we have a class with the default
access modifier in a package, only those classes that are in this package can access this class. No
other class outside this package can access this class. Similarly, if we have a default method or
data member in a class, it would not be visible in the class of another package. Lets see an
example to understand this
package abcpackage;
package xyzpackage;
* modifier.
*/
import abcpackage.*;
*/
obj.addTwoNumbers(10, 21);
Output:
The method addTwoNumbers(int, int) from the type Addition is not visible
at xyzpackage.Test.main(Test.java:12)
If a class has private constructor then you cannot create the object of that class from outside of
the class.
Let’ o understand this example, you must have the knowledge of packages in java.
In this example we have two classes, Test class is trying to access the default method of Addition
class, since class Test belongs to a different package, this program would throw compilation
error, because the scope of default modifier is limited to the same package in which it is
declared.
Addition.java
class ABC{
return a*a;
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:
Protected data member and method are only accessible by the classes of the same package and
the subclasses present in any package. You can also say that the protected access modifier is
similar to default access modifier with one exception that it has visibility in sub classes.
Classes cannot be declared protected. This access modifier is generally used in a parent child
relationship.
In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test class
extends class Addition and the protected modifier allows the access of protected members in
subclasses (in any packages).
Addition.java
package abcpackage;
return a+b;
Test.java
package xyzpackage;
import abcpackage.*;
System.out.println(obj.addTwoNumbers(11, 22));
Output:
33
Note:
Subclass in another package cannot access protected access member of super class
Example:
package package1;
package package2;
import package1.Class1;
The members, methods and classes that are declared public can be accessed from anywhere. This
modifier doesn’t put any restriction on the access.
Let’s take the same example that we have seen above but this time the method
addTwoNumbers() has public modifier and class Test is able to access this method without even
extending the Addition class. This is because public modifier has visibility everywhere
Addition.java
package abcpackage;
return a+b;
Test.java
package xyzpackage;
import abcpackage.*;
class Test{
Output:
101
return a-b;
Test.java
package xyzpackage;
import abcpackage.Sub;
class Test{
Output:
99
Benefits of packages:
1. The classes in the packages can be easily reused.
2. In the packages, classes are unique compared with other classes in the other packages.
3. Packages provide a way to hide classes thus prevent classes from accessing by other programs.
4. Packages also provide way to separate "design" from "coding".
This section explains how to use the PATH and CLASSPATH environment variables on Microsoft
Windows, Solaris, and Linux. Consult the installation instructions included with your installation
of the Java Development Kit (JDK) software bundle for current information.
After installing the software, the Java folder has been created in particular path we have selected
in that we have JDK directory will have the structure shown below.
JDK version
You can run Java applications just fine without setting the PATH environment variable. Or, you
can optionally set it as a convenience.
Set the PATH environment variable if you want to be able to conveniently run the executables
(javac.exe, java.exe, javadoc.exe, and so on) from any directory without having to type the
full path of the command. If you do not set the PATH variable, you need to specify the full path to
the executable every time you run it, such as:
C:\Java\jdk1.7.0\bin\javac MyClass.java
The PATH environment variable is a series of directories separated by semicolons ( ;). Microsoft
Windows looks for programs in the PATH directories in order, from left to right. You should have
only one bin directory for the JDK in the path at a time (those following the first are ignored), so
if one is already present, you can update that particular entry.
C:\Java\jdk1.7.0\bin;C:\Windows\System32\;C:\Windows\;C:\Windows\System32\Wbem
It is useful to set the PATH environment variable permanently so it will persist after rebooting. To
make a permanent change to the PATH variable, use the System icon in the Control Panel. The
precise procedure varies depending on the version of Windows:
Windows XP
1. Select Start, select Control Panel. double click System, and select the Advanced tab.
2. Click Environment Variables. In the section System Variables, find
the PATH environment variable and select it. Click Edit. If the PATH environment
variable does not exist, click New.
3. In the Edit System Variable (or New System Variable) window, specify the value of
the PATH environment variable. Click OK. Close all remaining windows by
clicking OK.
Windows Vista:
Note: You may see a PATH environment variable similar to the following when editing it from
the Control Panel:
%JAVA_HOME%\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\
Wbem
Variables enclosed in percentage signs (%) are existing environment variables. If one of these
variables is listed in the Environment Variables window from the Control Panel (such
as JAVA_HOME), then you can edit its value. If it does not appear, then it is a special
environment variable that the operating system has defined. For example, SystemRoot is the
location of the Microsoft Windows system folder. To obtain the value of a environment variable,
enter the following at a command prompt. (This example obtains the value of
the SystemRoot environment variable):
echo %SystemRoot%
Update the PATH Variable (Solaris and Linux)
You can run the JDK just fine without setting the PATH variable, or you can optionally set it as a
convenience. However, you should set the path variable if you want to be able to run the
executables (javac, java, javadoc, and so on) from any directory without having to type the full
path of the command. If you do not set the PATH variable, you need to specify the full path to
the executable every time you run it, such as:
% /usr/local/jdk1.7.0/bin/javac MyClass.java
% java -version
This will print the version of the java tool, if it can find it. If the version is old or you get the
error java: Command not found, then the path is not properly set.
To set the path permanently, set the path in your startup file.
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH
For ksh, the startup file is named by the environment variable, ENV. To set the path:
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH
PATH=/usr/local/jdk1.7.0/bin:$PATH
export PATH
Then load the startup file and verify that the path is set by repeating the java command:
% source ~/.cshrc
% java -version
% . /.profile
% java -version
Checking the CLASSPATH variable (All platforms)
The CLASSPATH variable is one way to tell applications, including the JDK tools, where to
look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be
defined through other means, such as the bootstrap class path or the extensions directory.)
The preferred way to specify the class path is by using the -cp command line switch. This allows
the CLASSPATH to be set individually for each application without affecting other
applications. Setting the CLASSPATH can be tricky and should be performed with care.
The default value of the class path is ".", meaning that only the current directory is searched.
Specifying either the CLASSPATH variable or the -cp command line switch overrides this value.
To check whether CLASSPATH is set on Microsoft Windows NT/2000/XP, execute the
following:
% echo $CLASSPATH
If CLASSPATH is not set you will get a CLASSPATH: Undefined variable error (Solaris or
Linux) or simply %CLASSPATH% (Microsoft Windows NT/2000/XP).
To modify the CLASSPATH, use the same procedure you used for the PATH variable.
1)The main difference between PATH and CLASSPATH is that PATH is an environment
variable which is used to locate "java" or "javac" command used to run java program and
compile java source file. On the other hand, CLASSPATH, an environment variable is used by
System or Application ClassLoader to locate and load compile Java bytecodes stored in the .class
file.
2) In order to set PATH in Java, you need to include JDK_HOME/bin directory in PATH
environment variable while in order to set CLASSPATH in Java you need to include all those
directories where you have put either your .class file or JAR file which is required by your Java
application.
3) Another significant difference between PATH and CLASSPATH is that PATH cannot be
overridden by any Java settings but CLASSPATH can be overridden by providing command line
option -classpath or -cp to both "java" and "javac" commands or by using Class-Path attribute in
Manifest file inside JAR archive.
4) PATH environment variable is used by operating system to find any binary or command typed
in the shell, this is true for both Windows and Linux environment while CLASSPATH is only
used by Java ClassLoaders to load class files.
Important Packages
1. java.lang: This package got primary classes and interfaces essential for Java program. It
consists of wrapper classes (wrapper classes can be used to convert ordinary data into objects),
Strings, Threads etc.
2. java.util: This package contains useful classes and interfaces like Stack, LinkedList, Arrays,
ArrayList, List etc...
3. java.io: This package handles files and input output related tasks.
4. java.awt: This package helps to develop GUI. It consists of an important sub package
java.awt.event to handle the events for GUI elements.
5. java.swing: This package helps to develop GUI like java.awt. In fact, this an extension to
java.awt.
6. java.net: Client - server programming can be done using this package. This is a very
important package to develop any web program like web browse or web server.
7. java.applet: Applets are programs which come from a server into a client and get executed on
the client machine. This package was very well known to everyone before the development of
servlets.
Summary
------------------------
In this unit we learnt about java packages, packages are directories which store classes and
interfaces. Programmers create their own packages and store their classes and interfaces
Review Questions
-------------------------
1. What is the importance of CLASSPATH.
2. What is a package? How to define it and access it?
3. Explain the various access specifiers of packages used in java.
4. Expalin user defined packages
5. Explain pre defined packages
Programs related to the topics discussed in this unit>>>>>
---------------------------------------------------------------------------
1. With sample program explain the creation of packages. Accessing a package and hiding
classes with packages.
Multiple Choice Questions
-----------------------------------
1. Which of the following is/are true about
packages in Java?
package.
file
a)only 1,2,and 3
b)only 1,2,and 4
c)only 4
d)only 1 and 3
of packages?
outside.
4. A package is a collection of
public
private
accessibility modifiers
a) pkg
b) Pkg
c) package
d) Package
package?
a) Public
b) Protected
c) No Modifier
a) import pkg.
b) Import pkg.
c) import pkg.*
d) Import pkg.*
a) lang
b) java
c) util
d) java.packages
package pkg;
class output
args[])
{
StringBuffer s1 = new
StringBuffer("Hello");
s1.setCharAt(1, x);
System.out.println(s1);
a) xello
b) xxxxx
c) Hxllo
d) Hexlo
a)linux
b)operating system
c)unix
d)none
a)linux
b)java compiler
c)operating system
d)none
c)both a and b
d)only b
a)Built-in Package
b)User-defined-package
c)both a and b
d)only a
a)this
b)static
c)import
d)final
c)a or b
d)a and b
a)2
b)3
c)1
d)4
Packages?
easily maintained.
protection.
within it
c) Java uses file system directories to store
packages
are stored
its content?
a) Object
b) Packages
c) Interfaces
different package?
a) Public
b) Protected
c) Private
d) No Modifier
within it
store packages
package pkg;
class output
args[])
StringBuffer s1 = new
StringBuffer("Hello World");
s1.insert(6 ,
"Good ");
System.out.println(s1);
pkg.
a) HelloGoodWorld
b) HellGoodoWorld
c) Compilation error
d) Runtime error
a) java.util
b) java.lang
c) java.io
a) String
b) StringReader
c) Writer
d) File
a) DataInput
b) ObjectInput
c) ObjectFilter
d) FileFilter
A) uppercase, uppercase
B) lowercase, lowercase
C) uppercase, lowercase
D) lowercase, uppercase
A) i and ii only
D) i and iv only
....................... package.
A) java.io
B) java.awt
C) java.net
D) java.util
code
package P1;
Class Result{
student S1;
Test t1;
A) True, False
B) False, True
C) True, True
D) False, False
iii) final
A) i only
B) ii only
C) iii only
Process.
(e) java.util.package.
A. Methods
B. Objects
C. Classes
D. Variables
package
A. java.lang
B. java.util
C. java.io
D. java.net
A.java.io
B.java.util
C.java.lang
D.java.applet
answers: