0% found this document useful (0 votes)
28 views18 pages

Packages

The document explains the concept of packages in Java, which are used to encapsulate classes, interfaces, and sub-packages to avoid name-space collisions and enhance code reusability. It covers the creation, access, and protection of packages, along with built-in packages and examples of user-defined packages. Additionally, it discusses the CLASSPATH environment variable, importing packages, and utility classes like StringTokenizer and BitSet.

Uploaded by

usharanikondrasi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views18 pages

Packages

The document explains the concept of packages in Java, which are used to encapsulate classes, interfaces, and sub-packages to avoid name-space collisions and enhance code reusability. It covers the creation, access, and protection of packages, along with built-in packages and examples of user-defined packages. Additionally, it discusses the CLASSPATH environment variable, importing packages, and utility classes like StringTokenizer and BitSet.

Uploaded by

usharanikondrasi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT-III

PACKAGES
Defining a Package
Packages are containers for classes that are used to keep the class name space
compartmentalized. It is a mechanism to encapsulate a group of classes, interfaces and sub
packages. Many implementations of Java use a hierarchical file system to manage source and
class files. It is easy to organize class files into packages. All the related class files are placed
in the same directory, the directory is given a name that relates to the purpose of the classes,
and a line is added at the top of each class file that declares the package name, which is the
same as the directory name where they reside.

Advantages of using a package

 Reusability: Reusability of code is one of the most important requirements in the


software industry. Reusability saves time, effort and also ensures consistency. A class
once developed can be reused by any number of programs wishing to incorporate the
class in that particular program.
 Easy to locate the files.
 In real life situation there may arise scenarios where we need to define files of the
same name. This may lead to “name-space collisions”. Packages are a way of
avoiding “name-space collisions”.

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some
of the commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

To create a package is quite easy: simply include a package command as the first statement
in a Java source file. The package statement defines a name space in which classes are
stored. If you omit the package statement, the class names are put into the default package,
which has no name. This 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 called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be 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 the same package statement. The
package statement simply specifies to which package the classes defined in a file belong. It
does not exclude other classes in other files from being part of that same package.
A hierarchy of packages can also be created. To do so, simply separate each package
name from the one above it by use of a period. The general form of a multileveled package
statement is as follows:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system.
For example, a package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment.

Creating and Accessing a Package

Steps for creating user-defined packages:


 Select a name for the package.
 Create a directory with the package name.
 Write the Java source file with the required classes which are to be a part of the
package. The first statement in the Java source file must be the package statement and
the syntax is:
package pack-name;
 Compile the Java source file such that the .class files are stored in the package
directory.
Program 1: Demonstrating package creation

package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current = new Balance("K. J. Fielding", 123.23);
current.show();
}
}

To compile the above code use the following statement:


Javac –d . AccountBalance.java
Here –d specifies the compiler to create a directory and . species that the directory
should be created in the current working directory. The directory name is the name of the
package itself. Instead of .(dot), we can specify the path where the directory is to be created.

To execute the above code, qualifiy the class name with the package name as follows:
Java MyPack.AccountBalance
Output:

C:\Users\hp\Desktop\JAVA\JavaPrograms>javac -d . AccountBalance.java

C:\Users\hp\Desktop\JAVA\JavaPrograms>java MyPack.AccountBalance
K. J. Fielding: $123.23

Access Protection in Packages


Classes and packages are both means of encapsulating and containing the name space
and scope of variables and methods. Packages act as containers for classes and other
subordinate packages. Classes act as containers for data and code. The class is Java’s smallest
unit of abstraction. Because of the interplay between classes and packages, Java addresses
four categories of visibility for class members:

• Subclasses in the same package


• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses

The three access specifiers, private, public, and protected, provide a variety of ways
to produce the many levels of access required by these categories. The following table
summarizes these access levels:

From the above table the following conclusions are drawn:

 Anything declared public can be accessed from anywhere.


 Anything declared private cannot be seen outside of its class.
 When a member does not have an explicit access specification, it is visible to
subclasses as well as to other classes in the same package. This is the default access.
 If you want to allow an element to be seen outside your current package, but only to
classes that subclass your class directly, then declare that element protected.

Program 2: Subclasses in the same package

File Name-Protection.java
package p1;
public class Protection
{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
File Name-Derived.java:
package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("derived constructor");
System.out.println("n = " + n);
// class only
// System.out.println("n_pri = "4 + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
Non-Subclasses in the same package

File Name-SamePackage.java:
package p1;
class SamePackage
{
SamePackage()
{
Protection p = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
Sub classes in the Different Package

File Name-Protection2.java:
package p2;
class Protection2 extends p1.Protection
{
Protection2()
{
System.out.println("derived other package constructor");
// class or package only
// System.out.println("n = " + n);
// class only
// System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " + n_pub);
}
}
Non Sub Class in the Different Package
File Name-OtherPackage.java:
package p2;
class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class or package only
// System.out.println("n = " + p.n);
// class only
// System.out.println("n_pri = " + p.n_pri);
// class, subclass or package only
// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}
In order to execute the above programs, the following two programs are to be executed:
// Demo package p1.
package p1;
// Instantiate the various classes in p1.
public class Demo
{
public static void main(String args[])
{
Protection ob1 = new Protection();
Derived ob2 = new Derived();
SamePackage ob3 = new SamePackage();
}
}
The test file for p2 is shown next:
// Demo package p2.
package p2;
// Instantiate the various classes in p2.
public class Demo
{
public static void main(String args[])
{
Protection2 ob1 = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}

Understanding CLASSPATH

The CLASSPATH environment variable tells the Java Virtual Machine and other
Java applications (for example, the Java tools located in the jdk1.1.x\bin directory) where to
find the class libraries, including user-defined class libraries. It tells the Java run-time system
where to look for packages that are created by the users. By default, the Java run-time
system uses the current working directory as its starting point. Thus, if the package is in a
subdirectory of the current directory, it will be found. The other option is that we can specify
a directory path or paths by setting the CLASSPATH environmental variable or can use the -
classpath option with java and javac to specify the path to the classes.

Importing a Package
In order to access the members of a package, an import statement is to be used. In a
Java source file, import statements occur immediately following the package statement
(if it exists) and before any class definitions. This is the general form of the import
statement:
import pkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.). There is no practical limit on the depth of a
package hierarchy, except that imposed by the file system. Finally, you specify either an
explicit classname or a star (*), which indicates that the Java compiler should import the
entire package.
Example
import java.util.Date;
This statement tells the compiler to import only Date class from util package.
import java.io.*;
This statement tells the compiler to import the entire io package.

Program 3: Demonstrating importing a package

Filename- Balance.java
package MyPack;
public class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if(bal<0)
System.out.print("--> ");
System.out.println(name + ": $" + bal);
}
}
Another File- TestBalance.java
import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show(); // you may also call show()
}
}
In the above program, in the file TestBalance.java, the class Balance which is in
package MyPack is used by importing the package

Utility Classes

StringTokenizer:

The processing of text often consists of parsing a formatted input string. Parsing is the
divisionof text into a set of discrete parts, or tokens, which in a certain sequence can convey a
semantic meaning. The StringTokenizer class provides the first step in this parsing process,
often called the lexer (lexical analyzer) or scanner. StringTokenizer implements the
Enumeration interface. Therefore, given an input string, you can enumerate the individual
tokens contained in it using StringTokenizer.
To use StringTokenizer, you specify an input string and a string that contains delimiters.
Delimiters are characters that separate tokens. Each character in the delimiters string is
considered a valid delimiter—for example, “,;:” sets the delimiters to a comma, semicolon,
and colon. The default set of delimiters consists of the whitespace characters: space, tab,
newline, and carriage return.

The StringTokenizer constructors are shown here:


StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)

In all versions, str is the string that will be tokenized. In the first version, the default
delimitersare used. In the second and third versions, delimiters is a string that specifies the
delimiters. In the third version, if delimAsToken is true, then the delimiters are also returned
as tokens when the string is parsed. Otherwise, the delimiters are not returned. Delimiters are
not returned as tokens by the first two forms. consecutive tokens. The hasMoreTokens( )
method returns true while there are more tokens to be extracted. Since StringTokenizer
implements Enumeration, the hasMoreElements( ) and nextElement( ) methods are also
implemented, and they act the same as hasMoreTokens( ) and nextToken( ), respectively.

Program to demonstrate StringTokenizer class:


import java.util.StringTokenizer;
class STDemo
{
static String in = "title=Java: The Complete Reference;" +"author=Schildt;" +
"publisher=Osborne/McGraw-Hill;" +"copyright=2007";
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens())
{
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}
The output from this program is shown here:
title Java: The Complete Reference
author Schildt
publisher Osborne/McGraw-Hill
copyright 2007

The following tables shows the methods of StringTokenizer class:


BitSet:
A BitSet class creates a special type of array that holds bit values. This array can increase in
size as needed. This makes it similar to a vector of bits. The BitSet constructors are shown
here:
BitSet( )
BitSet(int size)
The first version creates a default object. The second version allows you to specify its
initial size (that is, the number of bits that it can hold). All bits are initialized to zero.

BitSet defines the methods listed in the following table:


Program to demonstrate the BitSet class:
import java.util.BitSet;
class BitSetDemo
{
public static void main(String args[])
{
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i=0; i<16; i++)
{
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
OUTPUT:
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}

Date:
The Date class encapsulates the current date and time. Date also implements the
Comparable interface.

Date supports the following constructors:


Date( )
Date(long millisec)

The first constructor initializes the object with the current date and time. The second
constructor accepts one argument that equals the number of milliseconds that have elapsed
since midnight, January 1, 1970.
The following are the methods of Date class:

Program to demonstrate the Date class:


import java.util.Date;
class DateDemo
{
public static void main(String args[])
{
Date date = new Date();
System.out.println(date);
// Display number of milliseconds since midnight, January 1, 1970 GMT
long msec = date.getTime();
System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);
}
}
OUTPUT:
Mon Jan 01 16:28:16 CST 2007
Milliseconds since Jan. 1, 1970 GMT = 1167690496023

Calendar:
The abstract Calendar class provides a set of methods that allows you to convert a time in
milliseconds to a number of useful components. Some examples of the type of information
that can be provided are year, month, day, hour, minute, and second. It is intended that
subclasses of Calendar will provide the specific functionality to interpret time information
according to their own rules. An example of such a subclass is GregorianCalendar.
Calendar provides no public constructors.
Calendar defines several protected instance variables. areFieldsSet is a boolean that
indicates if the time components have been set. fields is an array of ints that holds the
components of the time. isSet is a boolean array that indicates if a specific time component
has been set. time is a long that holds the current time for this object. isTimeSet is a boolean
that indicates if the current time has been set
Calendar defines the following int constants, which are used when you get or set components
of the calendar:

The following program demonstrates several Calendar methods:


// Demonstrate Calendar import java.util.Calendar;
class CalendarDemo
{
public static void main(String args[])
{
String months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"};.
Calendar calendar = Calendar.getInstance();
System.out.print("Date: ");
System.out.print(months[calendar.get(Calendar.MONTH)]);
System.out.print(" " + calendar.get(Calendar.DATE) + " ");
System.out.println(calendar.get(Calendar.YEAR));
System.out.print("Time: "); System.out.print(calendar.get(Calendar.HOUR) + ":");
System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
System.out.print("Updated time: "); System.out.print(calendar.get(Calendar.HOUR) +
":"); System.out.print(calendar.get(Calendar.MINUTE) + ":");
System.out.println(calendar.get(Calendar.SECOND));
}
}
OUTPUT:
Date: Jan 1 2007 Time: 11:24:25 Updated time: 10:29:22

Random:
The Random class is a generator of pseudorandom numbers. These are called pseudorandom
numbers because they are simply uniformly distributed sequences. Random defines the
following constructors:
Random( )
Random(long seed)
The first version creates a number generator that uses the current time as the starting or seed,
value. The second form allows you to specify a seed value manually.

If you initialize a Random object with a seed,you define the starting point for the random
sequence. If you use the same seed to initialize another Random object, you will extract the
same random sequence. If you want to generate different sequences, specify different seed
values.
// Demonstrate random Integer values.
import java.util.Random;
class RandDemo
{
public static void main(String args[])
{
Random r = new Random();
double sum = 0;
for(int i=0; i<100; i++)
{
val = r.nextInt();
sum += val;
}
System.out.println("Average of values: " + (sum/100));
}
OUTPUT:
Average of values: 0.0702235271133344

Scanner:

Scanner can be used to read input from the console, a file, a string, or any source that
implements the Readable interface or ReadableByteChannel. For example, you can use
Scanner to read a number from the keyboard and assign its value to a variable.

The Scanner Constructors

Scanner defines the constructors shown in following table. In general, a Scanner can be
created for a String, an InputStream, a File, or any object that implements the Readable
or ReadableByteChannel interfaces. Here are some examples.

The following sequence creates a Scanner that reads the file Test.txt:
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
This works because FileReader implements the Readable interface. Thus, the call to
the constructor resolves to Scanner(Readable).

This next line creates a Scanner that reads from standard input, which is the keyboard
by default:
Scanner conin = new Scanner(System.in);
This works because System.in is an object of type InputStream. Thus, the call to the
constructor maps to Scanner(InputStream).

The next sequence creates a Scanner that reads from a string.


String instr = "10 99.88 scanning is easy.";
Scanner conin = new Scanner(instr);

Scanning Basics
Once you have created a Scanner, it is a simple matter to use it to read formatted input. In
general, a Scanner reads tokens from the underlying source that you specified when the
Scanner was created. As it relates to Scanner, a token is a portion of input that is delineated
by a set of delimiters, which is whitespace by default. A token is read by matching it with a
particular regular expression, which defines the format of the data.
In general, to use Scanner, follow this procedure:
1. Determine if a specific type of input is available by calling one of Scanner’s hasNextX
methods, where X is the type of data desired
2. If input is available, read it by calling one of Scanner’s nextX methods.
3. Repeat the process until input is exhausted.
As the preceding indicates, Scanner defines two sets of methods that enable you to
read input. The first are the hasNextX methods, which are shown in Table 18-15. These
methods determine if the specified type of input is available. For example, calling
hasNextInt( ) returns true only if the next token to be read is an integer. If the desired data is
available, then you read it by calling one of Scanner’s nextX methods, for example, to read
the next integer, call nextInt( ). The following sequence shows how to read
a list of integers from the keyboard.
Scanner conin = new Scanner(System.in);
int i;
// Read a list of integers.
while(conin.hasNextInt()) {
i = conin.nextInt();
// ...
}
OUTPUT:
Enter numbers to average.
10
20
30
40
Done
Average is 25.00
OUTPUT:
String: Testing
String: Scanner
int:10
double:12.2
String:one
Boolean:true
String:two
Boolean:false

You might also like