Sie sind auf Seite 1von 310

JAVA

St. Angelos Computers Ltd.

Chapter - 1
INTRODUCTION TO JAVA
If you open a computer magazine that did not have a feature article on Java seemed impossible. As
Java is maturing, the technology is becoming a lot more stable and reliable, and expectations are
coming down to reasonable level, therefore Java is certainly a good programming language.
When the computer language will be remembered the following will be said: B led to C, C evolved
into C ++, set the stage of Java. To understand Java means to understand the reason that drove its
creation, the forces that shaped it and the legacy that it inherits. Like the successful computer
languages that came before, Java is a blend of the best elements of its rich heritage combined with
the innovative concepts required by its unique environment.
Java has become inseparably linked with the online environment of the Internet, it is important to
remember that Java is first and foremost a programming language.
The Creation of Java
Java is conceived by Games Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at
Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version .The original
name for Java was OAK.
Why Java Is Important to the Internet
Most programmers learn early in their careers that portable (Platform-independent) programs are as
elusive as they are desirable. While the quest for a way to create efficient, portable programs is
nearly as old as the discipline of programming itself, it had taken a back seat to other, more pressing
problems. Further much of the computer world had divided itself into the three computing camps of
Intel, Macintosh and UNIX, most programmers stayed within their fortified boundaries, and the
urgent need for portable code was reduced. However with the advent of the Internet and the web,
the old problem of portability returned with vengeance. After all, the entire Internet consists of a
diverse, distributed universe populated many type of computers, operating systems, and CPU's.
Presence of variety of computers and platforms, portable programs had become a high-profile
necessity. Java provides the solution for this problem. Given below are some features of Java, which
made this language important.
Features of Java Security
As you are likely aware, every time that you download a normal program, you are risking a viral
infection. Prior to Java, most users did not download executable programs frequently, and those who
did scanned them for viruses prior to execution. Even so most users still worried about the
possibility of infecting their system with a virus. In addition to viruses, another type of malicious
program exists that must be guarded against. This type of program can gather private information
such as credit card numbers, bank account balances, and password, by searching the contents of
your computers local file system. Java answers both of these concern by providing a firewall
between a networked application and your computer.
1

JAVA

St. Angelos Computers Ltd.

Portability
As discussed earlier, many type of computers and operating system are in use throughout the world
and are connected to the Internet. For programs to be dynamically downloaded to all the various
platforms connected to the Internet, some means of generating portable executable code is needed.
As you will soon see, the same mechanism that helps ensure security also helps create portability.
Simple
Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most
programmers have little trouble learning.
Object-Oriented
Almost every thing in Java is an object. All program code and data resides within the objects and
classes. Java comes with extensive set of classes, arranged in packages that can be used by the
principal of inheritance.
Robust
The multi-platform environment of the web, places extraordinary demands on a program, because
the program must execute reliably in a variety of systems. Thus, the ability to create robust
programs was given a high priority in the design of Java. To gain reliability, Java restricts in a few
key areas, to force you to find your mistake early in program development. At the same time, Java
frees you from having to worry about of many of the most common cause of programming errors.
Because Java is a strictly typed language, it checks your code at compile time. However, it also checks
your code at run time. In fact, many hard to track down bugs that often turn up in hard to
reproduce run time situation are simply impossible to create in Java. Knowing that what you have
written will behave in a predictable way under diverse condition is a key feature of Java.
To better understand how Java is robust, consider two of the main reason for program failure:
memory management mistake and mishandled exceptional conditions (that is, run-time errors).
Memory management can be a difficult, tedious task in traditional programming environments. For
example, in C/C++, the programmer must manually allocate and free all dynamic memory.
Multithreaded
Java was designed to meet the real world requirement of creating interactive network programs. To
accomplish this Java supports multithreaded programming which allows you to write programs that
do many things simultaneously. Java is the only language which provides inbuilt support for
multithreading.
Architecture-Neutral
A central issue of the java designer was that of code longevity and portability. One of the main
problems facing programmer is that no guarantee exist if you can write a program today, it will run
2

JAVA

St. Angelos Computers Ltd.

tomorrow even on the same machine. Operating system upgrades, processors upgrade, and change
in core system resources can all combine to make a program malfunction. The Java designer made
several hard decisions in the Java language Virtual Machine in an attempt to alter this situation.
Their goal was write once; run anywhere, any time, forever. To a great extent, this goal was
accomplished.
Distributed
Java is designed by the distributed environment of the Internet, because it handles TCP/IP protocols.
In fact, accessing a resource using a URL is not much different from accessing a file. The original
version of Java (OAK) included features for intra-space to space messaging. This allows object on to
different computers to execute to procedure remotely. Java has recently revived these interfaces in a
package called RMI (Remote Method Invocation). This feature brings an unparalleled level of
abstraction to client/ server programming.

Dynamic
Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve access to object at run time. This makes it possible to dynamically link code in a
safe and expedient manner. This is crucial to the robustness of the applet environment, in which
small fragments of byte code may be dynamically updated on a running system.
The Internet helped Java to the forefront of programming, therefore Java in turn has had a profound
effect on the Internet. The reason for this is quite simple: Java expands the universe of object that
can move about freely in cyber space, in a network, two very broad categories of object are
transmitted between the server and your personal computer passive information and dynamic (active
programs) information. For example, when you read your e-mail, you are viewing passive data. Even
when you download a program, the programs code is still only passive data until you execute it.
However a second type of object can be transmitted to your computer: a dynamic a self-executing
program. Such a program is an active agent on the client computer, yet the server initiates it. For
example program might be provided by the server to display properly the data that the server is
sending.
As desirable as dynamic, networked programs are, they also present serious problem in the areas of
security and portability. Java has solved this problem immensely.
Java Architecture
Java architecture provides a portable, robust, high performing environment for development.
Java provides portability by compiling the byte codes for the Java Virtual Machine, which is then
interpreted on each platform by the run time environment. Java also provides compile and runtime

JAVA

St. Angelos Computers Ltd.

checking, and automatic memory management in order to ensure solid code. Strong security features
protect system against ill-behaved programs.
Compilation of code:
When you compile the code, the java compiler creates machine code (called Byte code) for a
hypothetical machine called Java Virtual Machine code (JVM) .The JVM is supposed to execute the
byte code.
The JVM is created for overcoming the issue of portability. The code is written and compiled for one
machine and interpreted on all other machines. This machine is called Java Virtual Machine.
This byte code is then run through an interpreter on the actual hardware, which converts this byte
code into machine code required for that particular hardware, and executes it. By compiling the
program to the JVM, all code is guaranteed to run on any computer that has the interpreter ported
to it.
Javas Magic Platform Independence
The Byte code
Byte code is a highly optimized set of instruction designed to be executed by the Java run-time
system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an
interpreter for bytecode. Translating the Java program into bytecode helps make it much easier to
run a program in a wide variety of environments. The reason is only the JVM needs to be
implemented for each platform. Once the run-time package exists for a given system, any Java
program can run on it. Remember although the details of the JVM will differ from platform to
platform, all interpret the same Java byte code. If a Java program will compile to native code,
different versions of the same program would have to exist for each type of CPU connected to the
Internet. This is not a feasible solution. Thus, the interpretation of byte code is the easiest way to
create truly portable programs.
The fact that a Java program is interpreted also helps to make it secure. Because the execution of
every java program is under the control of JVM, the JVM contain the program and prevent it from
generating side effect outside of the system. As you will see safety is also enhanced by certain
restriction that exists in Java language.
When a program is interpreted, it generally runs substantially slower than it would run, if compiled
to execute code. However with Java the different between the two is not so great. The use of byte
code enables the Java run-time system executes program much faster than you might expect.
Java was designed for interpretation, there is technically nothing about Java that prevents
compilation of byte code in to native code. Along these lines Sun has just completed it. Just in Time
(JIT) compiler for byte code, which is included in the Java 2 release. The JIT compiles code, as it is
needed, during execution.

JAVA

St. Angelos Computers Ltd.

Source code

JAVA
PROGRAM

JAVA
COMPILER

Byte code

Virtual
Machine

Process of compilation

Java
Interpreter

Bytecode

Virtual

Machine
Code

Machine

Real Machine
Process of converting byte code into machine code
Java Development Environment
To code edit, debug and test the Java programs, one needs to have a Java development environment.
It consists of:
1) Java Compiler.
2) Java Interpreter.
3) Java enabled browser for applet.
Sun's Java Development Kit (JDK) latest version is JDK 1.3
Setting Up Your computer
Before you can write and run the simple Java program, you need to install the Java platform on your
computer system.
The Java platform is available free of charge from the java.sun.com web site. You can choose
between the Java 2 platform software for Windows 95/98/NT or for Solaris. The download page
contains information you need to install and configure the Java platform for writing and running Java
programs.
Hardware requirements are
Preferable a fast 486 or Pentium, 16MB RAM is ideal although a minimum of 4 MB RAM will do for
WIN 3.1. and a minimum of 50 MB free disk space.
Operating Systems

JAVA

St. Angelos Computers Ltd.

The most complete version of Java is available for Suns Solaris 2.x, Windows NT or windows 95/98.
Version's of Java in various state of development exists for Linux, OS/2,Machintosh, Windows3.1 and
many other platforms.
Object Oriented Programming Concepts:
Introduction:
We shall first have a look at the drawbacks of conventional structured programming languages.
Pitfalls of Process Centric Programming:
Conventional programming languages such as FORTRAN, Pascal, COBOL, C etc., although
structured, are not efficient in handling complex applications. They have many pitfalls and do not
lend themselves easily to real world modeling. These drawbacks are listed below. Concentration is on
the processes of the application. What this means is that greater importance is attached to function
and method than to the data.
Modules are tightly interwoven, interdependent and difficult to separate. Because modules (or
subprograms etc.) are dependent on each other, modification of one program could affect all other
programs dependent on it. This leads to complexity of code especially for huge programs.
Not suitable for server:
Programs written for one application cannot be easily used for other applications. Most often
applications with almost similar features have to be rewritten and recompiled.
Software maintenance costs are high.
As a result of the above points, it is very difficult to test and debug large programs. This inevitably
leads to high maintenance costs. As these languages are not modeled after real world situation, they
are not ideally suited for developing complex software.
OBJECT ORIENTED PROGRAMMING (OOP)
OOP languages such as C++, Smalltalk, Java etc. overcome these drawbacks. They are modeled after
real world characteristics and hence are simple and easy to understand.
What is an object?
An object is a distinguishable entity in the problem domain. An object has

A state
A behavior
An identity

For example: We need some information about cars. Cars can have the following features.
6

JAVA

St. Angelos Computers Ltd.

State
: Color, Size, Weight, Engine Capacity etc.
Behavior : Start, Stop, Accelerate etc.
Identity : Registration number, chassis number etc.
These characteristics define the car. But these things have different meanings to different people. A
mechanic in a garage will look at it differently as compared to a traffic police or the owner who
drives it. These represent problem domain. Therefore relevant features that are same are of
importance depending on who is using it.
Objects such as a car can be simple or they can be extremely complex. Object may be real or
imaginary.
Examples: Real Objects Fiat, car, Java classroom etc.
Imaginary: Record, Organization etc.
Complex: Databases and spreadsheets.
Software Object- In software terms an object is a bundle of variables and related methods.
Examples: Variables- Bank Account number, Bank Account holders name.
Methods- Deposit, Withdraw, etc.

Variables

Method

A software object: A collection of variables and related methods.


OOP FEATURES
Any OOP language should support the following features
1.
2.

Class
Abstraction
7

JAVA

3.
4.
5.
6.
7.

St. Angelos Computers Ltd.

Encapsulation
Messages
Polymorphism
Inheritance
Multiple Inheritance

Class
A class is a blue print that defines the variables and methods common to all objects of a certain
kind. For example, let us consider different kinds of cars such as Fiat, Maruti. All of them have a
general behavior and state. Fiat car is a particular case of the general category of the cars. Here cars
is a class. Similarly for the class bank accounts we can have savings bank account, current account
etc.
Therefore the class only forms a blue print or a prototype based on which objects can be derived. An
object is a particular instance of a class. For instance a fiat car bearing registration number MH 01A
3233 is a particular case of the class cars. It has a unique identity. A car with a different number is a
different object of the class cars.
Characteristics of instance variables and methods
1.
2.
3.

An object is an instance of the class.


The values for instance variables are provided by each instance of the class (Registration
numbers for each car is different).
Instances of the same class share the same instance methods. Implementations which reside
in the class (For e.g.: Start, stop, etc. for cars)

Characteristics of class variables and methods:


1.
2.

All instances of a class share its class variables and methods (For e.g. All cars have four
wheels).
It is not necessary to have objects of a class to use its variables and methods.
Class Diagram

accelerate
handle
brake
gear
accelerator

JAVA

St. Angelos Computers Ltd.

ABSTRACTION
A given object (such as car) has many features but we may not be interested in all of them.
Abstraction is concentrating on these features that are essential and relevant and ignoring the rest.
They are two kinds of abstraction.
Data Abstraction.
Functional Abstraction.
Example Car
Data Abstraction: Engine no, speed etc.
Functional Abstraction: Start, Stop, accelerate, etc.
ENCAPSULATION
In OOP data (i.e., variables) and methods are bound together. Variables represent the state of an
object and methods its behavior. Encapsulation is the binding of behavior and state to a particular
object. It embodies information hiding.
Object

Data

Methods

It hides the non-essential details of an object and shows only essential details. Encapsulation
promotes reuse of objects that perform certain well-defined tasks. Code can be used as a black box
technology.
MESSAGES
How do objects communicate with each other? If I wish to start a car then I have to send a message
start to the car object (by turning on the engine). This is called sending a message. Software objects
interact and communicate with each other by sending messages to each other. For each message
there must be a designated serving Class.
The components of a message are
9

JAVA

1.
2.
3.

St. Angelos Computers Ltd.

To whom the message is addressed


The name of the message (Start, stop etc.)
Any additional information

The additional information necessary for performing a task is sent as parameters or arguments.

Change Gear
(from 4th to 3rd)
You

Your Bicycle
BENEFITS OF MESSAGES
Message passing supports all possible interactions between objects.
Objects that send and receive messages need not have to be in the same process or even in
the same machine.

Exercise
1.

What is the concept of object oriented programming. Discuss the difference between
object-oriented programming and process oriented programming?

2.

What is the function of compiler and interpreter? Discuss the differences?

3.

What is Java Virtual Machine (JVM)? Discuss the security provided by java?

4.

Discuss the Low Level and High Level Language?


10

JAVA

St. Angelos Computers Ltd.

5.

How does Java achieve the feature Platform Independent?

6.

What is an Object? Discuss the various features of OOP?

7.

Why is Java Robust?

8.

What is the hardware requirement to run a Java program?

9.

What is abstraction? Explain with example?

10. What is JDK (Java Development Kit)?


11.

Java is
a) Interpreted language b) Compiled language
c) Compiled and interpreted language
d) None of the Above

12. Java compiler is


a) java

b) javac

c) javap d) javad
13. JVM stands for
a) Java Vanish Machine

b) Java Victory Machine

c) Java Virtual Machine

d) Java Virtual Mechanic

14. The latest version of Java is


a) jdk 1.3 b) jdk 1.2.2
c) jdk 1.1 d) jdk 1.2.3
15. Java is
a) Platform dependent

b) Platform Independent

c) Both

d) None of the Above

16. The Father of java is __________.


17. The first name of java is __________.
18.

Class is _________________.

19. Smalltalk is ___________ language.


20. Write True Or False for the following:
a) Java is a multithreaded language.
b) Object is an entity.
11

JAVA

St. Angelos Computers Ltd.

c) Byte code is machine code.

d) Java supports multiple Inheritance.

12

JAVA

St. Angelos Computers Ltd.

Chapter - 2
JAVA: OBJECT ORIENTED PROGRAMMING
The object oriented programming is an approach that provides a way of modularizing programs by
creating a partition memory area that stores the data and set of operations that can access the data.
Since the memory partitioned is independent the object can be used in variety of different programs
without modifications.
The Three OOP Principles
All object oriented programming language provide mechanisms that help you implement the objectoriented model. They are encapsulation, inheritance, and polymorphism. Lets take a look of these
concepts now.
Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps
both safe from outside interference and misuse. One way to think about encapsulation is as a
protective wrapper that prevents the code and the data from beginning arbitrarily accessed by other
code defined outside the wrapper.
In Java the basis of encapsulation is the class. A class defines the structure of behavior (data and
code) that will be shared by a set of object. Each object of a given class contains the structure and
behavior defined by the class as if it were stamped out by a mould in the shape of the class. For this
reason, objects are sometimes referred to as instances of a class. Thus, a class is a logical construct
an object is a physical reality.

Information "in Information

Data
and
Method

"out"

Encapsulation-Objects as "black boxes"


When you create a class you will specify the code and data, as if it constitutes that class. Collectively
these constitutes are called members of the class. Specifically the data defined by the class are
referred to as a variable member or instance variable. The code that operates on the data is referred
to as a member method or just method. In properly written Java programs the method defines how
the member variable can be used. This means that the behavior and the interference of the class are
defined by the method that operates on its instant data.
Inheritance
Inheritance in the process by which one object acquires the property of another object. This is
important because it supports the concept of hierarchical classification. As mentioned earlier, most
knowledge is made manageable by hierarchical (that is, top down) classification.
13

JAVA

St. Angelos Computers Ltd.

In OOPS the concept of inheritance provides reusability. This means that we can add features to the
existing class without modifying it. This is possible by deriving a new class from the existing one.
The new class thus has feature of both the classes, in such a way that it does not introduces any
desirable effect into the rest of the classes. In Java the derived class is known as subclass.

Bird
Attributes :
Feathers
Lay eggs

Robin
Attributes :
_________

Flying
Bird

Nonflying
Bird

Attributes:

Attributes :
_________

Swallow

Penguin

Attributes:
_________

Attibutes :
_________

Kiwi
Attibutes :
________

Polymorphism
Polymorphism is another important OOP's concept. Polymorphism means the ability to take more
than one form (many forms) for e.g.: An operation may exhibit different behavior in different
instances. The behavior depends upon the type of data used in the operation.
An object-oriented program consists of set of objects that communicate with each other. Therefore it
involves the following basic steps.
1.
2.
3.

Creating classes that defines objects and their behavior.


Creating objects from class definition.
Establishing communication among objects.

When properly applied, polymorphism, encapsulation, and inheritance combine to produce a


programming environment that supports the development of robust and scaleable programs.

14

JAVA

St. Angelos Computers Ltd.

Signature of class will be like this


[access specifer][modifier] class [classname]
First Java Program

//

Save this file as Example. java

class Example
{
//The program begins with the call to main ()
public static void main (String args[ ])
{
System.out.println ("This is a simple Java program.");
}
}
Let us understand the program and the various keywords
class Example {
This line uses the keyword class to declare that a new class is being defined. Example is an identifier
that is the name of the class. The entire class definition, inclusive of all its members, will be between
the opening curly brace ({) and the closing curly brace (}). Curly brace is a delimiter.
public static void main (String args [ ] ) {
This line begins the main( ) method. This is the line at which the program will be executing. All Java
application begins execution by calling main( ) method. The public keyword is an access specifier,
which allows the programmer to control the visibility of class members. When a class members is
preceded by public then that members may be accessed by code outside the class in which it is
declared. (The opposite of public is private which prevents a member from being used by the code
defined outside of this class.) In this case, main( ) must be declared as public, since it must be called
by code outside of its class when the program is started. The keyword static is a modifier, which
allows main( ) to be called without having to instantiate a particular instance of the class. This is
necessary since main( ) is called by the Java interpreter before any object is made. The keyword void
(return type of method) simply tells the compiler that main( ) does not return any value. Any
information that you need to pass a method is received by variables specified within the set of
parentheses that follow the name of the method. These variables are called parameters. In main( ),
there is only one parameter String args[ ]. This declares a parameter named args, which is an array
of String. (Arrays are collection of similar object). Object of types String store character strings. In
this case, args receives any command-line argument present when the program is executed. This
program does not make use of this information, but other programs show later in this book l. The
last character on the line is the ({). This symbol start of main( )s body. All of the code that
15

JAVA

St. Angelos Computers Ltd.

comprises a method will occur between the methods opening curly brace and its closing curly
brace.
Compiling the program
To compile the Example program, execute the compiler, javac, specifying the name of the source file
on the command line, as shown here:

javac Example.java
The javac compiler creates a file called Example.class that contains the byte code version of the
program.
To actually run this program you must use Java interpreter, called java. To do this pass the class
name as the command line argument as shown here.
java Example
Exercise
1.

What is Encapsulation? Explain with example?

2.

What is Polymorphism? Explain with example?

3.

What is Inheritance?

4.

What are the advantages of Encapsulation, Inheritance and Polymorphism?

5.

What is the exact signature of main() method? Explain each modifier used with main()
method?

6.

What are the various tools used to compile and interpret the java application?

7. The signature of the main() method in java is


a) void main()
b) public main()
c) public static void main(string args[])
d) public static void main(String args[])
8. The OOPs principle is
a) Inheritance

b) Abstraction

c) Encapsulation d) Above all


9. String is a __________.
16

JAVA

St. Angelos Computers Ltd.

10. Java Interpreter is __________.

17

JAVA

St. Angelos Computers Ltd.

Chapter - 3
KEYWORD, OPERATOR, CONDITIONAL STATEMENT
Keywords are an essential part of a language definition. They implement specific features of the
language. Java language has reserved 60 words as keywords. The following table lists these keywords.
These keywords, combined with operators and separators according to syntax, form definition of the
Java language. Understanding the meanings of all these words is important for Java programmers.
Since keywords have specific meaning in Java, we cannot use them as names for variables, classes,
methods and so on. All keywords are to be written in lower-case letters. Since Java is case-sensitive,
one can use these words as identifiers by changing one or more letters to upper case. However, it is
a bad practice and should be avoided.
Although Java has been modeled on C and C++ languages, Java does not use many of C/C++ keywords
and, on the other hand, have added as many as 27 new keywords to implement the new features of
the language.
Java Keywords
abstract
case
const*
else
float
if
int
null**
protected
static
threadsafe*
try

boolean
cast*
continue
extends
for
implements
interface
operator*
public
super
throw
var*

break
catch
default
false*
future*
import
long
outer*
rest*
switch
throws
void

* Reserved for future development of language.


** These are the values defined by java.

18

byte
char
do
final
generic*
inner*
native
package
return
synchronized
transient
volatile

byvalue*
class
double
finally
goto*
instanceof
new
private
short
this
true**
while

JAVA

St. Angelos Computers Ltd.

Java is a Strongly Typed Language


Data types specify the size and type of value that can be stored. Java language is rich in its data
types. The variety of types available allows programmer to select the type appropriate to the need of
the application. Every variable in Java has a data type.
The Java compiler checks all expression and parameters to ensure that the types are compatible. Any
type mismatches are errors that must be corrected before the compiler will finish compiling the
class.
The datatypes in Java
There are two basic data type in java
[1] Simple or primitive data type.
[2] Object data type or non-primitive data type.
[1]

Primitive data type

Primitive type defines eight simple (or elemental) types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
1.

Integers: This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.
Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean: This group includes boolean, which is a special type for representing true / false
values.

2.
3.
4.
Integers

Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values.
The width of an integer type should not be thought of as the amount of storage it consumes, but
rather as the behavior it defines for variables and expressions of that type. The Java run-time
environment is free to use whatever size it wants, as long as the types behave as you declared them.
In fact, at least one implementation stores bytes and shorts as 32-bit (rather than 8-bit and 16-bit)
values to improve performance, because that is the word size of most computers currently in use.
The width and ranges of these integer types very widely, as shown in this table:
Name
long

Width

Range
64

-9,223,372,036,854,775,808, to
19

JAVA

St. Angelos Computers Ltd.

9,223,372,036,854,775,807
int

32

short

16

byte

-2,147,483,648, to 2,147,483,647
-32,768 to 32,767
-128 to 127

byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from 128 to 127.
E.g.:

byte b, c;
short
short is a signed 16-bit type. It has range from-32,768 to 32,767.
E.g.:

short s;
short t;
int
The most commonly used integer type is int. It is a signed 32-bit type that has a range from
2,147,483,648 to 2,147,483,647.
long
long is a signed 64-bit type and is useful for those occasions an int type is not large enough to hold
the desired value. The range of a long is quite large. This makes it useful when big, whole number of
miles that light will travel in a specified number of days.
// Compute distance light travels using long variables.

class Light {
public static void main (String args[ ]) {
int lightspeed;
long days;
long second;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here

20

JAVA

St. Angelos Computers Ltd.

second = days * 24 * 60 * 60; // convert to seconds


distance = lightspeed * second; // compute distance
System. out. print ("In " + days);
System. out.print("days light will travel about ");
System. out. println(distance + " miles. ");
}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
Floating-Point Types
Floating-point numbers also known as real numbers, and are used when evaluating expressions that
require fractional precision.
Name

Width In Bits

Range

Double

64

1.7e-308 to 1.7e+308

Float
Character
char is an integer type that is 8 bits wide.

32

3.4e-038 to 4e+038

Boolean
Java has a simple type, called boolean, for logical values.
[2] Object data type:
Every object you create in your program is also a data type.
Operators:
Java provides a rich operator environment. Most of its operators can be divided into the following
four groups:
1.
2.
3.
4.

Arithmetic
Bitwise
Relation
Logical.

Java also defines some additional operators that handle certain special situations. This chapter
describes all of Java operator except for the type comparison operator instance of.
Arithmetic Operators

21

JAVA

St. Angelos Computers Ltd.

Arithmetic operators are used in mathematical expression in the same way they are used in algebra.
The following table lists the arithmetic operators.
Operator
+
-

Result
Addition
Subtraction (also unary minus)

*
/
%
++
+=
-=
*=
/=
%=
--

Multiplication
Division
Modulus
Increment
Addition assignment
Subtraction assignment
Multiplication assignment
Division assignment
Modulus assignment
Decrement

Relational Operators
The relational operators determine the relationship that one operand has to another. Specifically,
they determine equality and ordering. The relation operators are shown here.
Operator
==
!=
<
>
>=
<=

Result
Equal to
Not equal to
Greater Than
Less than
Greater than or equal to
Less than or equal to

Boolean Logical Operators


The boolean logical operators shown here operate only boolean operands. All of the binary logical
operators combine two boolean values to form a resultant boolean value.
Operator
&
|
^
|
&&
!
&=

Result
Logical AND
Logical OR
Logical XOR (exclusive OR)
Short- circuit OR
Short-circuit AND
Logical unary NOT
AND assignment
22

JAVA

St. Angelos Computers Ltd.

|=
^=
==
!=
?:

OR assignment
XOR assignment
Equal to
Not equal to
Ternary if-then-else

//Demonstrate the boolean logical operators.

class Boologic {
public static void main (String args []) {
boolean a = true;
boolean b= false;
boolean c= a | b
boolean d = a & b
boolean e = a ^ b
boolean f = (!a & b) | (a & !b );
boolean g = !a;
System. out. println ("a = " + a);
System. out. println ("b = " + b);
System. out. println (" a | b= "+ c);
System. out. println ("a&b = " + d);
System. out. println ("a^b =" + e);
System. out. println (" !a&b | a&!b = " +f);
System. out. println ("!a = " + g);
}
}
After running this program you will see that the same logical rules apply to boolean values as they
did to bit. As you can see from the following output, the string representation of a Java boolean
value is one of the literal vales true or false.

a = true
b = false
a | b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false
The Assignment Operator
The assignment operator in Java has this general form:

var =expression;
The type of var must be compatible with the type of expression. For example consider this fragment
int x, y, z :
23

JAVA

St. Angelos Computers Ltd.

x = y = z = 100; // set x, y, and z to 100


This fragment sets the variable x, y, and z to100 using a single statement.
Separators:
In Java there are few characters that are used as separators. The most commonly used separator in
Java is the semicolon. As you have seen, it is used to terminate statements. The separator are shown
in the following table:
Symbol
()

Name
Parentheses

{}

Braces

[]

Bracket

Semicolon

Comma

Period

Purpose
Used to contain list of parameters in
method definition and invocation. Also
used for defining precedence in
expression, containing expression in
control statements, and surrounding
cast types.
Used to contain the values of
automatically initialized arrays. Also
used to define a block of code, for
classes, methods and local scopes.
Used to declare arrays types. Also used
when referencing array values.
Terminates statements
Separates consecutive identifiers in a
variable declaration.
Used to separate package names from
sub packages and classes. Also used to
separate a variable or method from a
reference variable. This is also known as
a scope resolution operator.

Conditional Statements
Java Selection Statements
The if statement in Java conditional branch statement. It can be used to route the program execution
through two different paths. Here is the general from of the if statement.

if (condition) statement1;
else statement2;
If the condition is satisfied the statement 1 gets executed otherwise statement 2 gets executed.
The if-else-if Ladder

24

JAVA

St. Angelos Computers Ltd.

A common programming construct that is based upon a sequence of nested if's is the if-else-if
ladder. It looks like this:

if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
else
statement;
The if statement are executed from the top to down. As soon as one of the conditions controlling the
if is true, the statement associated with that if is executed and the rest of the ladder is bypassed. If
none of the conditions is true, then the final else statement will be executed. The final else act as a
default condition, that is, if all other conditional test fails then the last else statement is performed. If
there is no final else and all other conditions are false then no action will take place.

// Demonstrate if-else-if statements.


class ifelse{
public static void main (String args [ ] ) {
int month = 4;
// April
String season;
if (month == 12 | month ==1 | month ==2)
season = "Winter";
else if (month == 3 | month ==4 | month == 5)
season = "Spring";
else if (month == 6 | month ==7 | month == 8)
season = "summer";
else if (month == 9 | month ==10 | month == 11)
season = "Autumn";
else
season = "Bogus Month";
System .out. println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
switch
The switch is a nice replacement of multiple else if statements.

25

JAVA

St. Angelos Computers Ltd.

The switch statement works like this. The value of the expression is compared with each of the
literal values in the case statements. If a match is found, the code sequence following that case
statement is executed. If none of the constant matches the value of the expression, the default
statement is executed. However the default statement is optional. If no case matches and no default
is present then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence. When a break
statement is encountered, execution branches to the first line of code that follows the entire switch
statement. This has the effect of "jumping out of the switch.
Here is a simple example that uses a switch statement

// A simple example of the switch.


class SampleSwitch {
public static void main (String args [ ]) {
for (int i=0 ; i<6;i++)
switch(i)
{
case 0:
System. out. println("i is zero.");
break;
case 1:
System. out. println("i is one.");
break;
case 2:
System. out. println("i is two.");
break;
case 3:
System. out. println("i is three.");
break;
default:
System. out. println("i is greater than 3 .");
}
}
}
The output produced by this program is shown here:

i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
Iteration Statements

26

JAVA

St. Angelos Computers Ltd.

Iteration statement is needed when a programmer want to execute a particular statement multiple
times.
Java iteration statements are for, while and do-while
While
The while loop is Javas most fundamental looping statement. It repeats a statements or a block while
its controlling expression (condition) is true. Here is it general form.

while(conditon) {
// body of loop
}
The condition can be any boolean expression. The body of the loop will be executed as long as the
conditional expression is true. When condition becomes false, control passes to the next line of code
immediately following the loop. The curly braces are unnecessary if only a single statement is being
repeated.
Here is a while loop that counts down from 10, printing exactly ten lines of "tick":

// Demonstrate the while loop.


class While {
public static void main (String args [ ] ) {
int n = 10;
while (n > 0) {
System. out. println("tick " + n);
n--;
}
}
}
When you run this program, it will "tick" ten times

tick
tick
tick
tick
tick
tick
tick
tick
tick
tick

10
9
8
7
6
5
4
3
2
1

27

JAVA

St. Angelos Computers Ltd.

do-while
As you just saw, if the conditional expression controlling a while loop is initially false, then the body
of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a
while loop at least once, even if the conditional expression is false to begin with. In other words,
there are times when you would like to test the termination expression at the end of the loop rather
than at the beginning. Fortunately, Java supplies a loop that does do-while. The do-while loop always
executes its body at least once, because its conditional expression is at the bottom of the loop. Its
general form is

do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression. If this expression is true, the loop will repeat.
Otherwise, the loop terminates.

// Demonstrate the do-while loop.


class DoWhile {
public static void main (String args [ ] ) {
int n = 10;
do {
System. out. println( "tick " + n) ;
n--;
} while (n > 0);
}
}
The loop in the preceding program, while technically correct, can be written more efficiently as
follows:

do {
System.out.printIn ( "tick " + n) ;
} while(--n > 0) ;
In this example, the expression (--n > 0) combines the decrement of n and the text for zero into one
expression. Here is how it works. First, the --n statement executes, decrementing n and returning the
new value of n. This value is then compared with zero. If it is greater than zero, the loop continues;
otherwise it terminates.
Using continue
Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue
running the loop, but stop processing the reminder of the code in its body for this particular
28

JAVA

St. Angelos Computers Ltd.

iteration. The continue statement performs an action. In while and do-while loop's a continue
statement causes control to be transferred directly to the conditional expression that controls the
loop. In a for loop, control goes first to the iteration portion of the for statement and then the
conditional expression. For all three loops, any intermediate code is bypassed.
Here is an example program that uses continue to cause two numbers to be printed on each line:

// Demonstrate continue.
class Continue {
public static void main (String args [ ] ) {
for (int i = 0; i< 10; i++) {
System.out.print (i + " " ) ;
if (i%2 == 0)
continue;
System.out.println( " " ) ;
}
}
}
This code uses the condition (i%2==0) to check if i is even. If it is, the loop continues without
printing a new line. Here is the output from this program:
0
2
4
6
8

1
3
5
7
9

The for Loop


As you may know from your previous programming experience, loop statement is an important part
of nearly any programming language. Java has no exception. Java supplies a powerful as assortment
of loop construct. Perhaps, the most versatile is the for loop. If you are familiar with C or C++ then
you will be pleased to know that the for loop in Java works the same way it does in those languages.
If you dont know C/C++ the for loop is still easy to use. The simplest form of the for loop is shown
here:

for (initialization; condition; iteration) statement;


In its most common form, the initialization portion of the loop sets a loop control variable to an
initial value. The condition is a Boolean expression that tests the loop control variable. If the
outcome of that test is true the for loop continues to iterate. If it is false the for loop terminates.
The iteration expression determines how the loop control variable is changed each time the loop
iterates. Here is a short program that illustrate the for loop.

/*
29

JAVA

St. Angelos Computers Ltd.

Demonstrate the for loop.


Call this file ForTest. Java .
*/
class ForTest {
public static void main (String args[ ])
int x;

for (x = 0 ; x<10; x = x+1)


System.out. Println (This is x: + x);
}
}
This program generates the following output:
This is x: 0
This is x: 1
This is x: 2
This is x: 3
This is x: 4
This is x: 5
This is x: 6
This is x: 7
This is x: 8
This is x: 9
In this example, x is the loop control variable. It is initialized to zero in the initialization portion of
the for. At the start of each iteration (including the first one), the conditional test x < 10 is
performed. If the outcome of this test is true, the println ( ) statement is executed, and then the
iteration portion of the loop is executed. This process continues until the conditional test is false.
As a point of interest, in professionally written Java programs you will almost never see the iteration
portion of the loop written as shown in the preceding programs. That is you will seldom see
statement like this.
x = x + 1;
The reason is that Java includes a special increment operator, which perform this operation more
efficiently. The increment operator is ++. (That is two plus sign back to back.) The increment
operator increases its operand by one. By use of the increment operator, the preceding statement
can be written like this:
x++ ;
Thus the for in the preceding program will usually be written like this:
for (x = 0 ; x<10; x++)
30

JAVA

St. Angelos Computers Ltd.

You might want to try this. As you will see, the loop still runs exactly the same as it did before.
Java also provides a decrement operator, which is specified as - - .This operator decreases its operand
by one
Arrays
Introduction:
When you want to manage a large number of variables, you need to organize them in more efficient
manner. Declaring many variables, which are of the same data type, is one way of dealing with them.
Arrays provide an efficient alternative.
What is an Array?
An array is a group of variables of the same type that can be referred to by a common name. Arrays
make it possible to store and manipulate large amounts of data in an organized way. Array is a
collection of homogenous data. The Array elements will be stored in contiguous memory.
Each array is like a chain of identical slots called elements in which data is stored.
Array [ 1

Elements
Here in these slots we can store 4 values of same data type such as int i1 = 75, int i2 = 35, int i3=45,
int i4 = 89. The array entries are numbered from 0 to (n-1) where n= size of Array
Array Declaration

Data-type [ ] array name;


Or
Data-type array name [ ];

Both of the declarations are acceptable.


Example:

int Mark [ ]; or int[] Marks;

After declaring an array you have to reserve memory and assign values to each element. In order to
reserve memory for the arrays we use the operator new . (In Java arrays are objects and objects as
will be discussed later are instances of a class.)
Example:

array name = new data type [ no. of elements ];


31

JAVA

St. Angelos Computers Ltd.

Marks = new int [10 ];


This creates an array Marks with 10 elements of type int. That is 10 integer elements. You can declare
and also create instances of arrays in one statement.

int[ ] Marks = new int[ 10 ];

Example:

You can declare and also assign values to the elements in one statement.

int[ ] Marks = { 75, 99, 59, 86, 72, 13, 92, 88, 34, 23 };
Or
You can also initialize elements of the array using a loop. Consider the following example, which uses
a loop to initialize an array and also displays the initialized values.
Sample Program:

class ArrayInitialize
{
public static void main(String[] args)
{
int Marks [] = new int[ 10 ];
for ( int i=0; i<Marks.length; i++)
{
Marks[i] = i;
System.out.println(Marks[i];
}
}
}
This program generates the following out put:
Marks[0]
Marks[1]
Marks[2]
Marks[3]
Marks[4]
Marks[5]
Marks[6]
Marks[7]
Marks[8]
Marks[9]
Explanation: In the above sample program, an array Marks of type integer and size of 10 is declared.
Marks[ 0 ] is first element in the array.
32

JAVA

St. Angelos Computers Ltd.

Marks[ 9 ] is the 10th element.


Using a for loop the array elements are initialized with the value of i and are displayed on to enclose
using the println method of the output stream object. The conditional expression of the for loop
contains an instance variable length. In Java array is an object and provides only one instance
variable length to hold the size of the array.
Sample Program

class MarksTest
{
public static void main ( String args [ ] )
{
int Marks[] = { 83, 94, 72, 53, 91, 99, 47, 87 };
System.out.println ( This is list of my marks );
for ( int j=0; j<Marks.length; j++ )
{
System.out.println ( The marks in the + j++ + th test was + Marks [ j ]);
if ( Marks [j] > 90 )
{
System.out.println ( Thats great, I got more than 90 in this test );
System.out.println ( );
}
}
}
}
This program generates the following output:
This is list of my marks
The marks in the 0th test was 94
Thats great, I got more than 90 in this test
The marks in the 2nd test was 53
The marks in the 4th test was 99
Thats great , I got more than 90 in this test
The marks in the 6th test was 87
In this example there was no need to create an instance of array using new, because we assigned
values to the array directly.
Array of Objects
Just as you created an array of integers you can also create an array of objects. An array is itself is an
object. By creating an array of objects, you are creating objects that keep a list of other objects.
For example, consider the built in class Point
In order to create array of objects of type Point, we use the statement
33

JAVA

St. Angelos Computers Ltd.

Point [] pts = new Point [5];


In the above statement, an array pts is declared which can hold five objects of type Point. To create
these objects, we use a for loop
for ( int j=0; j<pts.length; j++ )

pts[ j ] = new Point ( );


Each iteration creates a new Point Object. Points. Length gives the number of elements of the array.
After creating the array, we need to access the objects stored in the array.
For example the class Point has two variables int x and int y, to assign variables belonging to a object
we use the notation

pts [ 3 ].x = 10;


pts [ 3 ].y = 20;
Sample Program

/*
<applet code=Gridlines width=300 height=300>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class Gridlines extends Applet
{
int NumLines = 11;
int BoxSize = 30;
int LineLen = BoxSize * ( NumLines 1 );
int DisplaySize = LineLen + 2;
Point [ ] Hor = new Point [ NumLines ];
Point [ ] Vert = new Point [ NumLines ];
public void init ( ) //Initialize the applet
{
super.init ( );
setSize( DisplaySize, DisplaySize );
//Over ride in init ( )
for ( int j=0; j < numLines; j++) )
{
Hor [ j ] = new Point ( 0, j * BoxSize );
Vert [ j ] = new Point ( j * Box Size, 0 );
}
}
public void paint ( Graphics g )
{
g.setColor ( Color.blue );
for ( int j=0; j < NumLines; j++ )
34

JAVA

St. Angelos Computers Ltd.

{
g.drawLine ( Hor [ j ].x, Hor [ j ].y, Hor [ j ].x+LineLen, Hor [ j ].y );
g.drawLine( Vert [ j ].x, Vert [ j].y, Vert [ j ].x, Vert [ j].y+LineLen );
}
}
}
This program generates the following out put :

Multidimensional Arrays
An array of arrays is a multidimensional array. That is each element in an array is an array by itself.
Let us consider a class of 5 students who have taken 10 tests and you want to store each of these
marks. The most efficient way is to use an array of arrays.
Example :

int [ ] [ ] TestMarks = new int [ 3 ] [ 4 ];

You can initialize a multi-dimensional array in two ways. One way is directly assigning the values, the
other way is using a control loop.
Sample program

class TwoDimArrayTest
{
public static void main( String argv[] )
{
35

JAVA

St. Angelos Computers Ltd.

int TestMarks1 [] []= { { 60, 89, 79, 74 },


{70, 78, 69, 76),
{90, 88, 89, 95}
};
int TestMarks2 [] [] = new int [3] [4];
for ( int i=0; i < 3; i++ )
{
for ( int j=0; j < 4; j++ )
{
TestMarks2 [ i ] [ j ] = TestMarks1 [i][j];
System.out.print( +TestMarks2[i][j];
System.out.flush();
}
System.out.println(\n);
}
This program generates the following out put :
60 89 79 74
70 78 69 76
90 88 89 95
Unlike C/C + + in Java we can create Multi dimensional Arrays in different manner. When you are
allocating memory, you need only specify the memory for the first dimension. Later in the Second
Dimension you can allocate memory in different sizes.
Ex:

int Tests [ ] [ ] = new int [3] [ ];


Tests [0] = new int [3];
Tests [1] = new int [1];
Tests [2] = new int [2];

Here, you are creating a 2 Dimensional Array with 3 rows and different columns.
Copying Arrays
We can assign one array Variable to another array Variable. However, also the variables will refer to
the same array.
Ex:

int a [] = { 1,15, 23, 0, 5};


int b [] = a;

In this statement we are referring the a reference to b. Therefore, a and b are referring to only
one Array when ever you want to change bs elements that automatically reflects in a also i.e.
Copying elements from one array to another array we can do in the following way using system.
Array copies system.Array copy (from which array, start pos, to which array, start pos, end pos).

36

JAVA

St. Angelos Computers Ltd.

When you want to manage a large number of variables, you need to organize them in more efficient
manner. Declaring many variables, which are of the same data type, is one way of dealing with them.
Arrays provide an efficient alternate.
Modifiers and Access Specefiers
A modifier assigns characteristics to the method. That is, it specifies the availability of the method to
other methods or classes.
Note: Other method or methods can be called from within a method.
Similarly you can have modifiers for data as well classes.
The modifiers in Java are
1)
2)
3)
4)

public
protected (Access specifier)
private
friendly

We will deal with each one of them in detail.


Public
The keyword public means that the variables or methods can be accessed by any class in any
package. Methods declared public are accessible to all.
Example: public void reset() { }
Note: Package is a collection of classes grouped together. Packages are convenient for organizing
your work and separating your code from libraries provided by others. For Example java.io is a
package, which contains a number of classes that deal with input/output operations.
Protected
Protected variables or methods can be accessed by any class in the same package as the declaring
class or any subclass of the declaring class even if it is in a different package. (Subclasses will be
covered in subsequent chapter)
Example

protected int minutes;


protected int getDiffMinutes()
{
return dmin;
}
37

JAVA

St. Angelos Computers Ltd.

Private
Private variables or methods can only be accessed within the confines of the declaring class. No
methods or classes, not even subclasses have any access to these data or methods. (It is always
advisable to have variables declared as private, so that they dont get corrupted.) Only methods
within the declaring class can access the variables or methods.
Example

private int empno;


private String getEmpName()
{
return ename;
}
Static
You can declare variables or methods static when you dont want to change them from one instance
of a class to another.
Static methods cannot be overloaded. (See overloading of methods.) Only static methods can access
static variables. These features are explained in next chapter.
Example

static int empNo()


{
return eno;
}
Final
Variables declared final cannot be changed. Variables declared final are actually constants. Methods
declared final cannot be overridden.
Method Signature
The combination of the method name and the parameter list is called the method signature.
Therefore methods having the same name can have different method signatures. This is called
method overloading. When a method is called, that method which corresponds to the method
signature is executed.
Scope of Variable
Where a variable is declared affects how the variable can be used. Variables that are declared outside
of the body of any method can be referenced by any method in the method in the program.
38

JAVA

St. Angelos Computers Ltd.

Variables defined inside a method body are only visible to that method and cannot be referenced
outside of the method.
Class Scope

{
int x;
.
{
int y;

scope of x
scope of y

}
Sample Program: Scope of variables

class Scope
{
static int outside = 999;
public static void main ( String args [ ] )
{
int inside = 100;
System.out.println ( I can access Outside from main ( ), it is + outside);
System.out.println ( Inside the main it is + inside);
System.out.println ( );
myMethod ( );
System.out.println ( Inside the main it is still + inside );
}
public static void myMethod ( )
{
int inside = 555;
System.out.println ( Value of Inside in myMethod is + inside );
System.out.println ( Value of Outside in myMethod is still + outside);
}
}
Result: I can access outside from main ( ), it is 999
inside the main it is 100
Value of Inside in myMethod is 555
Value of Outside in myMethod is still 999
inside the main it is still 100
Recursion

39

JAVA

St. Angelos Computers Ltd.

Recursion is a general method of solving problems by reducing them to simpler problems of a


similar type. A recursive subprogram constantly calls itself. Each time in a simpler situation until its
trivial case, at which point it stops. Recursive methods are of two types.
1.
2.

Direct recursion When a subprogram calls itself.


Indirect recursion When a subprogram calls another subprogram, which in turn calls the
first program?

Recursive methods are normally used in sort, search programs etc.


Sample Program: Recursion

Direct recursion.
static int recursion ( int x )
{
if ( x= 1 )
return x;
else
return x*recursion(x-1);
}
Indirect recursion.
static int even ( int x )
{
if ( x = 0 )
return true;
else
return odd(x-1);
}
static int odd ( int x )
{
if ( x = 0 )
return false;
else
return even(x-1);
}
Passing Objects to Methods
Just as we pass variables as arguments we can also pass objects as arguments. Passing an object as
an argument is different than passing a variable to method. Variables are passed by value, objects are
passed by reference.
Sample Program: Passing an object to a method
public void paint ( Graphics g )

40

JAVA

St. Angelos Computers Ltd.

Graphics class

Object name

Class Variables & Instance Variables


Instance Variables
Variables defined inside a class are called instance variables. With multiple instances of class, each
instance has variables stored in separate memory locations.
In case of objects that need to share data, that is, you want variables to be common to all classes,
then we create class variables. To create a class variable, put the keyword static before the variable
name. Example: static int x;
Sample Program for instance and class variables

public class TestVar


{
public static void main ( String args [ ] )
{
TwoKinds obj1 = new TwoKinds ( );
TwoKinds obj2 = new Twokinds ( );
System.out.println ( );
System.out.println ( Object1 data );
Obj1.dispVar ( );
System.out.println ( Object2 data );
Obj2.dispVar ( );
System.out.println ( );
Obj1.x = 500;
Obj1.y = 500;
System.out.println ( Object1 data now );
Obj1.dispVar ( );
System.out.println ( );
System.out.println ( Object2 data now );
Obj2.dispVar ( );
System.out.println ( );
}
}
class TwoKinds
{
int x;
static int y;
public TwoKinds ( )
{
x 10;
y = 50;
41

JAVA

St. Angelos Computers Ltd.

}
public void dispVar ( )
{
System.out.println ( x is equal to + x );
System.out.println ( y is equal to + y );
System.out.println ( );
}
}
Result:

Object1 data
X is equal to 10
Y is equal to 50
Object2 data
X is equal to 10
Y is equal to 50
Object1 data now
X is equal to 500
Y is equal to 500
Object2 data now
X is equal to 10
Y is equal to 500

Class variables are useful if you want to change a variable for all instances of a class. Instead of
changing in every instance, you change a class variable once and it will reflect the change in classes.
Class Methods and Instance Methods
Instance Methods
We define methods in classes. In order to use the methods we need to first create objects of the
classes. We can then make a call to such methods using the dot notation like
Objectname.methodname ( ).
These methods are called instance methods.
Class Methods
We create class methods to allow us to call a method without creating an instance of the class.
Therefore class methods are available to all classes. We call them by naming the class and not the
object as in
Class.methodname ( );
But to declare a method as a class method we use the keyword static. Example:
42

JAVA

St. Angelos Computers Ltd.

public static void myMethod( ).


Class methods dont require objects of a class. Class methods are useful for creating methods, which
you want to be universally available.
Sample Program: Class methods

public class ClassMethodTest


{
public static void main (String args [] )
{
int i = 10;
int j = 25;
System.out.println ( );
System.out.println ( Calling class method dispVar );
NiceClass.dispVar ( i,j );
}
}
class NiceClass
{
public static void dispVar ( int x, int y )
{
System.out.println ( );
System.out.println ( x is equal to + x );
System.out.println ( y is equal to + y );
}
}
Result: Calling class method dispVar

X is equal to 10
Y is equal to 25
Accessor and Mutator Methods:
Access or methods are those that only access instance variables and dont alter them. Mutator
methods are that change instance variables. Let us consider the class java.util.Date. This class Date
contains many methods to get the date or month or year etc.
Example of Accessor and Mutator Methods

int getDate ( )
int getMonth ( )
int getYear ( )

// These are accessor methods

43

JAVA

St. Angelos Computers Ltd.

void setDate ( int )


void setMonth ( int )
void setYear ( int )

// These are mutator methods.

this Object:
In classes where you want to access an entire object of a particular instance variable you use the
keyword this. The word this refers to the main class in which the members appear.
Example of this object

public class Myclass


{
int i;
public Myclass ( )
{
int i = 10; // local variable
this.i = 20; // global variable
}
public void addToi ( int j )
{
i = i + j;
}
}
Native
This is a keyword for defining a method as a C or C++ function, which can be included in a Java
program.
Dynamic Binding
Also called late binding. The compiler generates the code to call a method not at the compile time
but at the run time. This usually has slower response time.
Static Binding
The compiler generates the code to all its methods at compile time itself. This is much faster to
execute. Dynamic binding depends on the type of object and its position in the inheritance hierarchy.
Final Classes
Classes that cannot be parent classes are final classes. No sub classes can be derived from them.
They are created using the keyword final. Example: final class card;
All methods in a final class are automatically final. Classes are declared final to improve efficiency
and ensure safety of data or methods.
44

JAVA

St. Angelos Computers Ltd.

Abstract Classes
Abstract classes are classes from which no objects can be instantiated. Abstract classes cannot have
objects of their own. They are very general and are usually the upper most classes in the inheritance
hierarchy. Abstract classes can be sub classed, which in turn can instantiate and have objects of their
own. Abstract classes provide an efficient way to implement OOP concepts.

Abstract

MESSAGES

class

VOICE MESSAGES

FAX MESSAGES

TEXT MESSAGES
Subclasses that
use methods of
Messages
classes

An abstract class may not have abstract methods. (Once a class is mentioned as abstract; it cant be
institutional. Abstract methods ensure that non abstract sub classes will implement them. Abstract
classes need not have only abstract methods, they can have other methods as well. If a class has an
abstract method then the class should be mentioned as abstract. Non-abstract subclasses of an
abstracted class should implement all the abstract methods.
Examples of Abstract Classes:

abstract class Message


{
public Message ( String from )
{
sender = from;
}
public abstract void play ( );
public String getSender ( )
{
return sender;
}
private String sender;
}
Casting

45

JAVA

St. Angelos Computers Ltd.

As we have seen earlier, converting one data type to another is casting. For example an int can be
converted to double. Similarly a double can be converted to int.
For example

double pi = 3.142;
int pi = ( int ) pi;
Similarly you can convert one object of a class to an object of another class.
Example:

Dieselcars fiatDiesel = ( Dieselcars ) fiat;


Here Fiat is an object of the class cars, and it has been cast into fiatDiesel, which is an object of
Dieselcars.
You can only cast within the inheritance hierarchy. Here Dieselcars is a subclass of cars class. Casting
is not a good practice and should be avoided. It is better to design your classes properly to avoid
confusions as to what methods and classes an object actually belongs. It is also good practice to
check whether the object you wish to cat is an instance of another class or not. You use instanceof
operator to do this.
Example of instanceof operator

If ( Fiat instanceof Cars )


{
Fiatdiesel = ( Dieselcars ) Fiat ;
}
Object Wrappers
Primitive data types are not objects. However sometimes you may require to convert these into
objects. That is what Object Wrappers are meant for. You can convert int, long, float, double,
character and Boolean into objects using the corresponding wrappers. Integer, Long, Float, Double
are inherit from the parent wrappers Number. These wrapper classes are final.
Object wrappers find use in container classes where arbitrary objects can be stored. In order to place
your numbers there, you need to first create objects of the numbers. Wrapper classes also provide
basic functions like converting strings to digits etc.
Exercise
1. What is the datatype? Mention the datatypes in java ?
2.

Discuss the various kinds of operator found in java?

3.

What are the different conditional statements found in java? Explain in brief?

46

JAVA

St. Angelos Computers Ltd.

4.

What are the different loops in java?

5.

What are the differences between while loop and do while loop?

6.

What is an array? What is the need to use array?

7.

What is Modifier? Discuss each modifier in brief?

8.

What is recursion?

9.

Explain static and dynamic binding?

10. What is abstract class and final class? Why we use abstract class?
11.

Consider the following line of code:


Int x[]=new int[25];
After execution which statement or statements are true?
A. x[24] is 0.
B. x[24] is undefined.
C. x[25] is 0.
D. x[0] is null.
E. x.length is 25.

12. What is the range of values that can be assigned to a variable of type short?
A. It depends on the underlying hardware.
B.

0 through 216-1.

C. 0 through 232-1.
D. 215 through 215-1.
E.

231 through 231-1.

13. What is the range of values that can be assigned to a variable of type byte?
A. It depends on the underlying hardware.
B.

0 through 28-1.

C. 0 through 216-1.
D. 27 through 27-1.
E.

215 through 215-1.

47

JAVA

St. Angelos Computers Ltd.

14. Integer is _____________ class.


15. Casting is process converting one _______ to another ________.
16. Recursion is ___________.
17. Increment operator is _____.
18. Method signature is _______________________________.
19. Array is ____________________.
20. Access specifer is _________________.

48

JAVA

St. Angelos Computers Ltd.

Chapter - 4
CLASSES , METHODS AND INHERITANCE
The class is at the core of Java. It is the logical construct upon which the entire Java language is
built because it defines the shape and nature of an object. As such, the class forms the basis for
object-oriented programming in Java. Any concept you wish to implement in Java program must
be encapsulated within a class.
The General Form of a Class
A class is declared by use of the class keyword. The classes that have been used up to this point are
actually very limited examples of its complete form. Classes can (and usually do) get much more
complex. The general form of a class definition is shown here:

Declaration of class should be as given below


[access specifier] [modifier] class [class name]
class classname {
type instance-variable1;
type instance-variable2;
//
type instance-variableN;
type methodname1 (parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
//
type methodnameN (parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is contained
within methods. Collectively, the methods and variables defined within a class are called members of
the class. In most classes, the instance variables defined in a class can be accessed by the methods of
that class. Thus, it is the methods that determine how a class's data can be used.
A Simple Class
A class is collection of objects of similar type. A class is a logical construct and object has a physical
reality.
Here is an example of class called Box that defines three instance variables: width, height, and depth.
Currently, Box does not contain any methods (but some will be added soon).

class Box {
49

JAVA

St. Angelos Computers Ltd.

double width;
double height;
double depth;
}
As stated, a class defines a new type of data. In this case, the new type is called Box. You will use
name to declare objects of type Box. It is important to remember that a class declaration only creates
an actual object. Thus, the preceding code does not cause any objects of type Box to come into
existence.
To actually create a Box object, you will use a statement like the following.
Box mybox = new Box ( ) ; // create a Box object called mybox
After this statement executes, mybox will be an instance of Box(class). Thus, it will have "physical"
reality.
Again, each time you create an instance of a class, you are the creating an object that contains its
own copy of each instance variable defined by the class. Thus, every Box object will contain its own
copies of the instance variables width, height, and depth. To access these variables, you will use the
dot (.) operator links the name of the object with the name of an instance variable. For example, to
assign the width variable of mybox the value 100, you would use following statement:

mybox . width = 100;


This statement tells the compiler to assign the copy of width that is contained within the mybox
object the value of 100. In general, you use the dot operator to access both the instance variables and
the methods within an object.
Here is a complete program that uses the Box class.

/* A program that uses the Box class.


call this file BoxDemo. java
*/
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main (String args [ ] ) {
Box mybox = new Box ( ) ;
50

JAVA

St. Angelos Computers Ltd.

double vol;
// assign values to mybox's instance variables.
mybox.width = 10 ;
mybox.height = 20 ;
mybox.depth = 15 ;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth ;
System.out.println( "Volume is " + vol ) ;
}
}
You should call the file that contains this program BoxDemo.java, because the main( ) method is in
the class BoxDemo, not the class called Box. When you compile this program, you will find that two
.class files have been created, one for Box and one for BoxDemo. The Java compiler automatically
puts each class into its own .class file. It is not necessary for both the Box and the BoxDemo class to
actually be in the same source file. You could put each class in its own file, called Box.java and
BoxDemo.java,respectively.
To run this program, you must execute BoxDemo.class. When you do, you will see the following
output:

Volume is 3000.0
Declaring Objects
Obtaining objects of a class is a two-step process. First, you must declare a variable of the class type.
This variable does not define an object. Instead, it is simply a variable that can refer to an object.
Second, you must acquire an actual, physical copy of the object and assign it to that variable. You
can do this using the new operator. The new operator dynamically allocates (that is, allocates at run
time) memory for an object and returns a reference to it. This reference is, more or less, the address
in memory of the object allocated by new. This reference is then stored in the variable. Thus, in Java,
all class objects must be dynamically allocated.

Box mybox = new Box( ) ;


Box mybox; // declare reference to object
mybox = new Box( ) ; // allocate a Box objects
Garbage Collection
Since objects are dynamically allocated by using the new operator, you might be wondering how
such objects are destroyed and their memory released for later reallocation. In some languages, such
51

JAVA

St. Angelos Computers Ltd.

as C ++, dynamically allocated objects must be manually released by use of a delete operator. Java
takes a different approach; it handles deallocation for you automatically. The technique that
accomplishes this is called garbage collection. It works like this : when no references to an object
exist, that object is assumed to be no longer needed, and the memory occupied by the object can be
reclaimed. There is no explicit need to destroy objects as in C ++ Garbage collection only occurs
sporadically (if at all) during the execution of your program. It will not occur simply because one or
more objects exist that are no longer used. Furthermore, different Java run-time implementations will
take varying approaches to garbage collection, but for the most part, you should not to think about
it while writing your programs.

Method declaration

Declaration of method should be as given below


[access specifier] [modifier][return type] [method name()]
or
[access specifier] [modifier][return type] [method name(parameter list)]
Overloading Methods
In Java it is possible to define two or more methods within the same class that share the same name,
as long as their parameter declaration are different. When this is the case, the methods are said to
be overloaded, and the process is referred to as method overloading.

// Demonstrate method overloading.


class OverloadDemo {
void test ( ) {
System.out.println( "No parameters" );
}
// Overload test for one integer parameter.
void test (int a) {
System.out.println( "a: " + a) ;
}
// Overload test for two integer parameters.
void test (int a, int b) {
System.out.println( "a and b: " + a + "" + b) ;
}
// overload test for a double parameter
double test (double a) {
52

JAVA

St. Angelos Computers Ltd.

System.out.println( "double a: " + a);


return a*a;
}
}
class Overload {
public static void main (String args [ ] ) {
OverloadDemo ob = new OverloadDemo( ) ;
double result;
// call all version of test ( )
ob. test () ;
ob. test (10 );
ob. test (10, 20);
result = ob. test (123.2);
System.out.println("Result of ob. test(123.2):" + result);
}
}
This program generates the following output:

No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob. test ( 123.2) : 15178.24
test( ) is overloaded four times. The first version takes no parameters, the second takes one integer
parameter, and the third takes two integer parameters,
Constructor
It can be tedious job to initialize all of the variables in a class each time an instance is created
because the need of initialization is so common. Java allows objects to initialize themselves when they
are created. This automatic initialization is performed through the use of Constructor.
A constructor initializes an object immediately upon creation. It has the same name as class in which
it resides and is syntactically similar to method. Once defined, the constructor is automatically called
immediately after the object is created, before the new operator completes. Constructors have no
return type, not even void. This is because implicit return type of a class' constructor is the class
type. It is a constructors job to initialize the internal state of an object so that the code creating an
instance will have a fully initialized, usable object immediately.
Overloading Constructors

class Box {
53

JAVA

St. Angelos Computers Ltd.

double width;
double height;
double depth;
// This is the constructor for Box.
Box (double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box(){
width=-1;
height=-1;
depth=-1;
}
Box(double len) {
width=height=depth=len;
}
double volume(){
return width*height*depth;
}
}
class OverloadCons {
public static void main(String args[]) {
Box mybox1=new Box(10,20,15);
Box mybox2=new Box();
Box mycube=new Box(7);
double vol;
vol=mybox1.volume();
System.out.println("Volume of mybox1 is "+vol);
vol=mybox2.volume();
System.out.println("Volume of mybox2 is "+vol);
vol=mycube.volume();
System.out.println("Volume of mycube is "+vol);
}
}
T he program generates the fo llo wing out put:

54

JAVA

St. Angelos Computers Ltd.

Volume of mybox1 is 3000.0


Volume of mybox2 is 1.0
Volume of mycube is 34 3.0
Understanding static
When a member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object. You can declare both methods and variables to be static. The most
common example of a static member is main( ). main( ) is declared as static because it must be
called before any objects exist.
Instance variables declared as static are, essentially, global variables. When object of its class are
declared, no copy of a static variable is made. Instead all instances of the class share the same static
variable.
Methods declared as static have several restrictions:
1.
2.
3.

They can only call other static methods.


They must only access static data.
They cannot refer to this or super in any way.

If you need to do computation in order to initialize your static variables, you can declare a static
block, which gets executed exactly once when the class is first loaded. The following example shows a
class that has a static method some static variables, and a static initialization block.

// Demonstrate static variables, methods, and block.


class UseStatic {
static int a= 3;
static int b;
static void meth (int x) {
System.out.println("x = " +x);
System.out.println("a = " +a);
System.out.println("b = " +b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main (String args[]) {
meth (42);
}
}

55

JAVA

St. Angelos Computers Ltd.

As soon as the UseStatic class is loaded all of the static statement are run.
Here is the output of the programs:
Static block initialized.

x = 42
a=3
b = 12.
Inheritance
Inheritance is one of the corner stone of object-oriented programming since it allows the certain of
hierarchal classification. Using Inheritance you can create a general class that defines traits common
to a set of related items. In the terminology of Java a class that is inherited is called a super class.
The class that does the inheriting is called a subclass. The idea behind Inheritance is that you can
reuse or change the methods of existing classes, as well add new instance fields and new methods in
order to adapt them in new situation.
Inheritance Basics
To inherit a class, you simply incorporate the definition of one class into another by using the
extends keyword. The following program creates a super class called A and a subclass called B.
Notice how the keyword extends is used to create a subclass of A.

class A{
int length;
int breath;
A(int x,int y)
{
length=x;
breath=y;
}
int area()
{
return (length*breath);
}
}
class B extends A {
int height;
B(int x,int y,int z)
{
super(x,y);
height=z;
}
56

JAVA

St. Angelos Computers Ltd.

int volume()
{
return(length*breath*height);
}
}
class Inhertest {
public static void main(String args[])
{
B ob1=new B(14,12,10);
int area1=ob1.area();
int volume1=ob1.volume();
System.out.println("Area1= "+area1);
System.out.println("volume1= "+volume1);
}
}
The output of the following program is

Area1=168
Volume1=1680
Using super to call Superclass Constructor
A subclass can call a constructor method defined by its super class by use of the following form of
super

super (parameter-list);
Here, parameter-list specifies any parameter needed by the constructor in the super class. super ( )
must always be the first statement executed inside a subclass constructor.
When Constructor Are Called
When a class hierarchy is created, in what order are the constructors for the class that make up the
hierarchy called ? For example given a subclass B and a super class called A, is a constructor called
before B or vise versa ? The answer is that in a class hierarchy constructor are called in order of
derivation from super class to subclass. Further, since super ( ) must be the first statement executed
in a subclass' constructor, this order is the same whether or not super( ) is used. If super( ) is not
used, then the default or parameter less constructor of each super class will be executed. The
following program illustrates when constructors are executed:

// Demonstrate when constructors are called.


// Create a super class.

57

JAVA

St. Angelos Computers Ltd.

class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class callingCons {
public static void main(String args []) {
C c = new C ( );
}
}
The output from this program is shown here:
Inside A's constructor
Inside B's constructor
Inside C's constructor
As you can see, the constructors are called in order of derivation.
If you think about it, it makes sense that constructor functions are executed in order of derivation.
Because a super class has no knowledge of any subclass, any initialization it needs to perform is
separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it
must be executed first.
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a method
in its super class, then the method in the subclass is said to override the method in the super class.
When an overridden method is called from within a subclass, it will always refer to that method
58

JAVA

St. Angelos Computers Ltd.

defined by the subclass. The version of the method defined by the super class will be hidden.
Consider the following:

// Method overriding.
class A {
int i, j;
A(int a, int b) {
i= a;
j = b;
}
// display i and j
void show( ) {
System.out.println( "i and j: " + i + " " + j );
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super (a, b);
k=c;
}
// display k - this overrides show( ) in A
void show( ) {
System.out.println( "k: " + k );
}
}
class override {
public static void main(String args[] ) {
B subOb = new B(1, 2, 3);
// this calls show( ) in B
subOb.show( );
}
}
Here is the output of the program:
K:3

59

JAVA

St. Angelos Computers Ltd.

Using Abstract Classes


Java supports abstract class and abstract methods. Similar in nature to the interfaces, they declare
set of constants and methods but don't actually implement any of the methods. The class that
implements an interface is responsible for providing the implementation for each of its method's.

abstract class Figure {


double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an abstract method
abstract double area( );
}
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area( ) {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area( ) {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal now
60

JAVA

St. Angelos Computers Ltd.

Rectangle r = new Rectangle(9, 5);


Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created
figref = r;
System.out.println ("Area is " + figref.area( ) );
}
}
The output for the following program is
Inside Area for Rectangle.
Area is 45.0.
The variable figref is declared as reference to Figure, which may refer to an object of any class
derived from figure.

61

JAVA

St. Angelos Computers Ltd.

Exercise :
1. Define the class and object ? What is the process to create an object?
2. What is Garbage Collection?
3. What is difference between polymorphism and overloading ?
4. What is the Constructor ? What do you mean by overloading a Constructor?
5. Explain the modifier static ? What do you understand by instance variable and class
variable ?
6.What is Inheritance ?Explain the Keyword super ?
7.What is difference between method overloading and method
overriding ?
8.How can you force Garbage collection of an object?
A. Garbage collection cannot be forced .
B. Call System.gc().
C. Call System.gc(),passing in a reference to the object to be garbage collected.
D. Call Runtime.gc().
E. Set all references to the object to new values(null , for example).
9. After execution of the code fragment below, what are the values of the variables x, a and b?
1.

int x, a=6, b=7;

2.

x=a++ + b++;

F.

x=15,a=7,b=8

G. x=15,a=6,b=7
H. x=13,a=7,b=8
I.

x=13,a=6,b=7

10. Which of the following expression are legal ?(choose one or more)
A. int x=6; x= !x;

62

JAVA

St. Angelos Computers Ltd.

B. int x=6; if (!(x>3)){}


C. int x=6; x = ~x;
11.What is the output of this code fragment ?
1.

int x=3; int y=10;

2.

System.out.println(y % x);
A. 0
B. 1
C. 2
D. 3

12.Which of the following expression s are legal?


A. String x = Hello ; int y = 9; x += y ;
B. String x = Hello ; int y = 9 ; if ( x == y) { }
C. String x = Hello ; int y = 9 ; x = x + y;
D. String x = Hello ; int y = 9 ; y = x + y;
E. String x = null ; int y = ( x != null ) && ( x.length() > 0) ? x.length() ;
13.Which one of the following statement is true?
A. An abstract class may not have any final method.
B. A final class may not have any abstract methods.

14. Which of the following declaration are illegal ?(Choose one or more)
A. friendly String s;
B. transient int I=41;
C. public final static native intw();
J.

abstract double d;

15. Which one of the following statements is true?


63

JAVA

St. Angelos Computers Ltd.

A. Transient methods may not be overridden.


B. Transient methods must be overridden.
C. Transient classes may not be serialized.
D. Transient variables must be static.
E. Transient variables are not serialized.
16. Which modifier or modifiers should be used to denote a variable that should not be written
out as part of its class persistent state?
F.

private.

G. protected.
H. private protected .
I.

transient

J.

private transient

17. Final class cannot be ______________.


18. Abstract method means ______________.
19. Static variables can be accessed by ___________.
20. A class cannot be declared as _________.

Chapter - 5
PACKAGES AND INTERFACES
This chapter examines two of Java's most innovative features:
1.
2.

Packages
Interfaces.

Packages are containers for classes that are used to keep the class name space compartmentalized.
For example, a package allows you to create a class named List, which you can store in your own
package without concern that, it will collide with some other class named List stored elsewhere.
Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.
Thus, Java allows you to group classes in a collection called a package.

64

JAVA

St. Angelos Computers Ltd.

In previous chapter you have seen how methods define the interface to the data in a class through
the use of the interface keyword. Java allows you to fully abstract the interface from its
implementation. Using interface, you can specify a set of methods, which can be implemented by one
or more classes. The interface, itself, does not actually define any implementation. Although they are
similar to abstract classes, interfaces have an additional capability: A class can implement more than
one interface. By contrast, a class can only inherit a single super class (abstract or otherwise).
Packages and interfaces are two of the basic components of a Java program. In general, a Java source
file can contain any (or all) of the following four internal parts:
1.
2.
3.
4.

A single package statement (optional)


Any number of import statements (optional)
A single public class declaration (required)
Any number of classes private to the package (optional)

Defining a Package
To create a package is quite easy: simply include a package command as first statement in a Java
source file. Any classes declared within that file will belong to the specified package. 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.
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.
Example : A Short Package

// A simple package
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);
}
}
65

JAVA

St. Angelos Computers Ltd.

class AccountBalance {
public static void main(String args [ ] ) {
Balance current[ ] = new Balance[3];
current [0] = new Balance("K. J. Fielding", 123.23);
current [1] = new Balace ("Will Tell", 157.02);
current [2] = new Balance ("Tom Jackson", -12.33);
for (int i=0; i<3; i++) current (i) .show( );
}
}
Call this file AccountBalance.java, and put it in a directory called MyPack.
Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory. Then
try executing the AccountBalance class, using the following command line;

java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this command, or
to have your CLASSPATH environmental variable set appropriately.
As explained, AccountBalance is now part of the package MyPack. This means that it cannot be
executed by itself. That is, you cannot use this command line:

java AccountBalance
AccountBalance must be qualified with its package name.
Interfaces
Using the keyword interface, you can fully abstract a class interface from its implementation. That is,
using interface, you can specify what a class must do, but not how it does it. Interfaces are similar to
classes, but they lack instance variables, and their methods are declared without any body. In
practice, this means that you can define interfaces which don't make assumptions about how they
are implemented. Once it is defined, any number of classes can implement an interface. Also, one
class can implement any number of interfaces.
To implement an interface, a class must create the complete set of method defined by the interface.
Since interface describes only abstract methods this means that it does not specify any code to
implement these methods and data fields contains only constants.Therefore it's responsibility of the
class that implements an interface to define the code for the implementation of this methods.
The syntax for defining an interface is as follows.
Interface InterfaceName
{
66

JAVA

St. Angelos Computers Ltd.

variable declaration;
methods declaration;
}
Extending Interfaces
Like classes, interfaces can also be extended. That is, an interface can be sub interfaced from other
interfaces. The new sub interface will inherit all the members of the super interface in the manner
similar to subclasses. This is achieved using the keyword extends as shown below :
interface name 2 extends name
{
body of name 2
}
For example, we can put all the constants in one interface and the methods in the other. This will
enable us to use the constants in classes where the methods are not required.
Example :

interface ItemConstants
{
int code = 1001 ;
String name = "Fan" ;
}
interface Item extends ItemConstants
{
void display ( ) ;
}
The interface Item would inherit both the constants code and name into it. Note that the variables
name and code are declared like simple variables. It is allowed because all the variables in an
interface are treated as constants although the keywords final and static are not present.
We can also combine several interfaces together into a single interface. Following declarations are
valid :

interface ItemConstants
{
int code = 1001 ;
String name = "Fan" ;
}
interface ItemMethods
{
void display ( ) ;
}

67

JAVA

St. Angelos Computers Ltd.

interface Item extends ItemConstants, ItemMethods


{
.
.
}
While interfaces are allowed to extend other interfaces, sub interfaces cannot define the methods
declared in the super interfaces. After all, sub interfaces are still interfaces, not classes. Instead, it is
the responsibility of class that implements the interface to define all the methods. When an interface
extends two or more interface, they are separated by commas.
It is important to remember that an interface cannot extend classes. This would violate the rule that
an interface can have only abstract methods and constants.
Implementing Interfaces
Interfaces are used as "super classes" whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interface. This is done as follows:

class classname implements Interfacename


{
body of classname
}
Here the class classname "implements" the interface interfacename. A more general form of
implementation may look like this ;

class classname extends superclass


implements interfacel, interface2,
{
body of classname
}
This shows that a class can extend another class while implementing interfaces.
Implementation of interfaces as class types through the Program .
In this program, first we create an interface Area and implement the same in two different classes,
Rectangle and Circle. We create an instance of each class using the new operator. Then we declare
an object of type Area, the interface class. Now, we assign the reference to the Rectangle object rect
to area. When we call the compute method of area, the compute method of Rectangle class is
invoked. We repeat the same thing with the Circle object.
Implementing interfaces

/ / InterfaceTest.java

68

JAVA

St. Angelos Computers Ltd.

interface Area
{
final static float pi = 3.14F;
float compute(float x, float y) ;
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return (x*y) ;
}
}
class Circle implements Area
{
public float compute (float x, float y)
{
return (pi*x*x) ;
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area ;
area = rect ;
System.out.println("Area of Rectangle = "+area.compute(10,20)) ;
area = cir ;
System.out.println("Area of Circle = " + area.compute (10,0)) ;
}
}
The Output is as follows :

Area of Rectangle = 200


Area of Circle = 314
Exercise

1.

What is package ? What are the benefits the packages offer?

69

JAVA

St. Angelos Computers Ltd.

2.

What is Interface ? Why we use interface?

3.

How do you do multiple inheritance?

4. If all three top-level elements occur in a source file , they must appear in which order ?
A. Imports, package declaration, classes.
B. Classes, imports, package declarations.
C. Package declaration come first; order for imports and class definition is not significant.
D. Package declaration, imports, classes.
E. Imports must come first; order for package declaration and class definition is not
significant.
5. What is the output of the following code fragment?
Package A;
Package B;
class Hello
{
int i=0;
public void show()
{
System.out.println(i);
}
}
class ReHello
{
public static void main(String a[])
{
int j=10
Hello he=new Hello();
he.i=j++;
he.show();
}
}
A. 10
70

JAVA

St. Angelos Computers Ltd.

B. 11
C. 0
D. Error
6. What is the difference between Abstract class and Interface?
7. Following statement is true or false ?
8. Interface can have only abstract method.
K.

true

L.

false

9. Which one statement is true about the application below?


Class StaticStuff
{
static int x=10;
static {x += 5; }
public static void main(String a[])
{
System.out.println(x = + x);
}
static { x /= 5; }
}
A. Compilation error
B. The code compiles, and execution produces the output x=10.
C. The code compiles, and execution produces the output x=15.
D. The code compiles, and execution produces the output x=3.
10. Package is ______________________.
11. Interface can be implements from __________.
12. Class cannot be extended from more than ______ class.

71

JAVA

St. Angelos Computers Ltd.

Chapter - 6
EXCEPTION HANDLING
It is common to make mistakes while developing as well as typing a program.A mistake might lead to
an error causing the program to produce unexpected results.Errors are the wrongs that can make
the program go wrong.
An error produces an incorrect output or even terminate the execution of the program abruptly or
even may cause the system to crash.It is therefore important to detect and manage properly all the
possible error conditions in the program so that the program will not terminate or crash the
execution.
Thus, Java catches these exception. Therefore a Java exception is an object that describes an
exceptional (that is, error) condition that has occurred in a piece of code.
Exceptions in Java
Exceptions are part of the inheritance hierarchy and are derived from the Throwable class. That is,
an exception is an instance of the Throwable class. The exception hierarchy is given below.

THROWABLE

ERROR

EXCEPTION

IOEXCEPTION

RunTimeException

Implicit and Explicit Exception:


Any exceptions derived from Error class or Run time Exception are called implicit exceptions. These
exceptions are beyond your control or should not have occurred in the first place. All other
exceptions are explicit exceptions. A method must declare all the explicit exceptions it throws. If you
override a method from a parent class, the child class method cannot throw more explicit exceptions
than the parent class method. If the parent class throws no explicit exceptions at all, then even the
child class cannot throw explicit exception.
72

JAVA

St. Angelos Computers Ltd.

To throw an exception follow these steps.


1.
2.
3.

Find the appropriate exception class.


Make an object of that class.
Throw that object.

We will look at this in more detail when we study how to handle ( catch ) exceptions.
Note: You can create your Exception classes when the standard exception classes dont meet your
requirements.

public Throwable ( )

public Throwable (String message)

public String getMessage ( )

This constructs a new Throwable


object without any message.
This constructs a new throwable
object with the message given. It can be used
to provide information for debugging. All
derived exception classes support both a
default constructor with a detailed message.
This method obtains the detailed
message of the throwable object.

Catching Exceptions
Once an exception is thrown, you have to have a handler to process the exception. To do this you
have to catch the exception. This is done with the try catch block shown below.

try
{
// Code which could throw an exception
}
catch(Exception e )
{
// Handle the exception here ( this is the handler )
// The exception should match with what can thrown
}
If an exception occurs in the try block, the rest of the code is skipped and the catch block is
processed. If no exception occurs, the catch block is skipped. When an exception is thrown at
runtime, system does, in the order mentioned, the following:
1.
2.
3.

The catch statement that exactly matches the exception is executed.


The catch statement that matches the super class of the exception.
The catch statement that is an interface that the exception implementation.

Note: Objects created in the try block are garbage collected if an exception occurs in it.

73

JAVA

St. Angelos Computers Ltd.

The Finally Statement


The finally statement is used to include code that should be executed even if an exception is thrown.
Example

try
{
// code which might throw exception
}
finally
{
// clean up after it
}
This finally block will be executed under all circumstances.
Actually the try block executes first.
a) If no exception, then finally block executes and then execute the First line after try block.
b) If an exception occurs, then the catch block executes and then the code in the finally block
executes.
In case there is an exception, but there is no matching catch statement, then the code execution
skips the rest of code and executes the finally block. This exception is thrown back to the caller of
the method.
Guidelines to handle exceptions
1.
2.
3.
4.
5.

Use exceptions for exceptional circumstances only.


Always prefer to use simple tests in place of exception handling.
Do not have too many try/catch operations.
Separate normal processing from error handling.
Do not ignore/avoid exceptions, but handle them correctly.

Types of Errors:
Errors are broadly classified into two categories .
1) Compile-time errors.
2) Run-time errors.
Compile-Time Errors
All syntax errors will be detected and displayed by the Java compiler and therefore these errors are
knowm are compile-time errors.Whenever the compiler displays an error,it will not create .class file.It
74

JAVA

St. Angelos Computers Ltd.

is therefore necessary that we fix all the errors before we can sucessfully compile and run the
program.
Run-Time Errors
Sometimes, a program may compile sucessfully creating the .class file but may not run properly.Such
programs may produce wrong results due to wrong logic or may terminate due to errors Most of
the common run-time errors are :
1)
2)
3)
4)
5)
6)
7)
8)
9)

Dividing an integer by zero.


Acessing an element that is out of bound of an array.
Trying to store a value into an array of an incompatible class or type.
Trying to cast an instance of a class to one of its subclass.
Passing a parameter that is not valid .
Trying to illegally change the state of a thread.
Attemping to use a negative size for an array.
Acessing a character that is out of bounds of a string.
Converting invalid string to number.

Using Exceptions
Exception handling provides a powerful mechanism for controlling complex programs that have
many dynamic run-time characteristics. It is important to think try, throw, and catch as clean ways
to handle errors and unusual boundary conditions in your program's logic. If you are like most
programmers, then you probably are used to returning an error code when a method fails. When
you are programing in Java, you should break this habit. When a method can fail, have it throw as an
exception. This is a cleaner way to handle failure modes.
Uncaught Exceptions
It is useful to see what happens when you don't handle the exceptions. This small program includes
an expression that intentionally causes a divide-by-zero error.

class Exc0 {
public static void main(String args[ ] ) {
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a new exception
object and then throws this exception. This causes the execution of Exc0 to stop, because once an
exception has been thrown, it must be caught by an exception handler and dealt with immediately.
To guard against and handle a run-time error, simply enclose the code that you want to monitor
inside a try block. Immediately following the try block, include a catch clause that specifies the
exception type that you wish to catch. To illustrate how easily this can be done, the following
75

JAVA

St. Angelos Computers Ltd.

program includes a try block and a catch clause which processes the ArithmeticException generated
by the division-by-zero error:

class Exc2 {
public static void main(String args[ ] ) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println( "This will not be printed." );
} catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println( "Division by zero." );
}
System.out.println( "After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
Notice that call to println( ) inside the try block is never executed. Once an exception is thrown,
program control transfers out of the try block into the catch block. Put differently, catch is not
"called", so execution never "return" to the try block from a catch. Thus, the line "This will not be
printed." is not displayed. Once the catch satement has executed, program control continues with the
next line in the program following the entire try/catch mechanism. It is possible for your program to
throw a exception explicitly, using the throw statement. The general form of throw is shown here:

throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of Throwable. Simple
types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be
used as exceptions. There are two ways you can obtain a Throwable object: using a parameter into a
catch clause, or creating one with the new operator.
The flow of execution stops imediately after the throw statement; any subsequent statements are not
executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches
the type of the exception. If it does find a match, control is transferred to that statement. If not, then
the next enclosing try statement is inspected, and so on. If no matching catch is found, then the
default exception handler halts the program and prints the stack trace.
Here is a sample program that creates and throws an exception. The handler that catches the
exception rethrows it to the outer handler.

// Demonstrate thow.
76

JAVA

St. Angelos Computers Ltd.

class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException( "demo" );
} catch(NullPointerException e) {
System.out.println( "Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[ ] ) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println( "Recaught: " + e);
}
}
}
This program gets two chances to deal with the same error. First, main( ) sets up an exception
context and then calls demoproc( ). The demoproc( ) method then sets up another exceptionhanding context and immediately throws a new instance of NullPointerException, which is caught on
the next line. The exception is then rethrown. Here is the resulting output:

Caught inside demoproc.


Recaught: java.lang.NullPointerException: demo
The program also illustrates how to create one of Java's standard exception objects.Pay close
attention to this line:

throw new NullPointerException( " demo" );


Here new is used to construct an instance of NullPointerException. All of Java's built-in run-time
exceptions have two constructors: one with no parameter and one that takes a string parameter.
When the second form is used, the argument specifies a string that describes the exception. This
string is displayed when the object is used as an argument to print( ) or println( ) . It can also be
obtained by a call to getMessage( ), which is defined by Throwable.
finally creates a block of code that will be executed after a try/catch block has completed and before
the code following the try/catch block. The finally block will execute whether or not an exception is
thrown. If an exception is thrown, the finally block will excute even if no catch statement matches
the exception.

// Demonstrate finally.
class FinallyDemo {
77

JAVA

St. Angelos Computers Ltd.

// Throw an exception out of the method.


static void procA( ) {
try {
System.out.println( "inside proc" );
throw new RuntimeException ( "demo" );
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB( ) {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC( ) {
try {
System.out.println( "inside procC" );
} finally {
System.out.println( "procC's finally" );
}
}
public static void main (String args[]) {
try {
procA( );
} catch (Exception e) {
System.out.println( "Exception caught");
}
procB( );
procC( );
}
}
Here is the out put of the program:
inside proc
Proc As finally
Execption caught
inside proc B
Proc Bs finnaly
78

JAVA

St. Angelos Computers Ltd.

inside proc C
Proc Cs finnaly
Sample Program: Creating your own exception class

class BankAccount // Bank Account a general bank account class


{
private static int aids=0;
private int nAccountId; // Id- this is the account ID
private double dBalance; // balance- the open account with a balance
BankAccount( double dInitialBalance ) // constructor- open account with a balance
{
dBalance=dInitialBalance;
nAccountId=++aids;
}
public int Id( ) // Id- return the account ID
{
return nAccountId;
}
public double Balance() // Balance
{
return (int)((dBalance*100.0+0.5))/100.0;
}
public void Withdrawal (double dAmount) // Withdrawal-make a withdrawal
throws InsufficientFundsException
{
if (dBalance <dAmount) // if there are insufficient funds on hand
{
// throw an exception
throw new InsufficientFundsException (this, dAmount);
}
// otherwise, post the debit
dBalance =dAmount;
}
}
class InsufficientFundsException extends Exception
{
private BankAccount ba; // account with problem
private double dWithdrawalAmount;
InsufficientFundsException (BankAccount ba, double dAmount)
{
super (Insufficient funds in account);
this.ba = ba;
dWithdrawalAmount = dAmount;
}

79

JAVA

St. Angelos Computers Ltd.

public String toString ( )


{
StringBuffer sb = new StringBuffer( );
sb.append(Insufficient funds in account);
sb.append(ba.Id( ));
sb.append(\nBalance was);
sb.append(ba.Balance( ));
sb.append(\n Withdrawal was);
sb.append(dWithdrawalAmount);
return sb.toString ( );
}
}
public class test
{
public static void main ( String[ ] s )
{
try
{
// open a bank account with Rs. 250 in it
BankAccount ba = new BankAccount ( 250.0 );
Ba.Withdrawal ( 500.0 ); // try to take out Rs. 500 from it
System.out.println(Withdrawal successful !):
}
catch ( Exception e )
{
// output exceptions error message
System.out.println (e.toString ( ));
}
}
}
Here is the out put of the program:
Insufficient funds in account 1
Balance was 250.0
Withdraw was 500.0

Exercise
1.

Define the Exception in java?

2.

What are the different Exception Handling mechanisms in java?

3.

How can you make your own exception?

80

JAVA

St. Angelos Computers Ltd.

4. What is the difference between throw and throws clause. Explain finally clause?
i.

What is the super class of all the Exceptions

A. Throwable
B. Exception
C. Error
D. RunTimeException
5. What is the output of the following code?
class ExceptionDemo
{
public static void main(String a[] )
int I[] = new int[20];
I[20] = 20;
System.out.println(I[20]);
}
a.

20

b. ArrayIndexOutofBoundException
c.

d. null
6. What is the output of the following code fragment?
private class a
{
public static void main(String args[])
{
int i=20;
int j;
81

JAVA

St. Angelos Computers Ltd.

j=++i + i++;
System.out.println(j);
}
}
A. 21
B. 41
C. 42
D. Compile error
7.

What is the super class of all the Exceptions


A. Throwable
B. Exception
C. Error
D. RunTimeException

8. What is the output of the following code.


class ExceptionDemo
{
public static void main(String a[] )
int I[] = new int[20];
I[20] = 20;
System.out.println(I[20]);
}
e.

20

f.

ArrayIndexOutofBoundsException

g.

h. null
82

JAVA

St. Angelos Computers Ltd.

9. What is the output of the following code fragment.


private class A
{
public static void main(String args[])
{
int i=20;
int j;
j=++i + i++;
System.out.println(j);
}
}
E. 21
F.

41

G. 42
H. Compile error
10 SQLException are ___________ type of Exception.

Chapter - 7
MULTITHREADING
The modern operating systems such as Windows 95 may recognize that they can execute several
programs simultaneously. This ability is known as multitasking. In systems terminology, it is called
multithreading .
Java provides built-in support for multithreaded programmig. A multithreaded program contains two
or more parts that can run concurrently. Each part of such a program is called a thread, and each
thread defines a separate path of execution. Thus, multithreading is a specialized from of
multitasking.

83

JAVA

St. Angelos Computers Ltd.

A process is in essence, a program that is executing. Thus, process-based multitasking is the feature
that allows your computer to run two or more programs concurrently. For example, process-based
multitasking enables you to run the Java compiler at the same time that you are using a text editor.
In process-based multitasking, a program is the smallest unit of code that can be dispatched by the
scheduler.
A thread is similar to a program that has a single flow of control. It has a beginning ,a body, an end,
and executes command sequentially.
Multithreading enables you to write very efficient programs that make maximum use of the CPU,
beacause idle time can be kept to a minimum. This is especially important for the interactive,
networked environment in which Java operates, because idle time is common. For example, the
tansmission rate of data over a network is much slower than the rate at which the computer can
process it. Even local file system resources are read and written at a much slower pace than they can
be processed by the CPU.
Creating Threads
Creating threads in Java is simple. Threads are implemented in the form of objects that contain a
method called run ( ). The run( ) method is the heart and soul of any thread. It makes up the entire
body of a thread and is the only method in which the thread's behavior can be implemented. A
typical run( ) would appear as follows :

public void run ( )


{
.
(statements for implementing thread)

}
The run( ) method should be invoked by an object of the concerned thread. This can be achieved by
creating the thread and initiating it with the help of another thread method called start ( ).
A new thread can be created in two ways.
1.

By creating a thread class : Define a class that extends Thread class and override its run ( )
method with the code required by the thread.

2.

By converting a class to a thread : Define a class that implements Runnable interface. The
Runnable interface has only one method, run( ), that is to be defined in the method with
the code to be executed by the thread.

The approach to be used depends on what the class we are creating requires. If it requires to extend
another class, then we have no choice but to implement the Runnable interface, since Java classes
cannot have two super classes.
Extending the Thread Class
84

JAVA

St. Angelos Computers Ltd.

We can make our class runnable as a thread by extending the class java.lang.Thread. This gives us
access to all the thread methods directly. It includes the following steps :
1.

Declare the class as extending the Thread class.

2.

Implement the run ( ) method that is responsible for executing the sequence of code that
the thread will execute.

3.

Create a thread object and call the start ( ) method to initiate the thread execution.
class MyThread extends thread
{
.;
..;
}

Implementing the run( ) Method


The run( ) method has been inherited by the class MyThread. We have to override this method in
order to implement the code to be executed by our thread. The basic implementation of run( ) will
look like this :

public void run ( )


{

/ / Thread code here

When we start the new thread, Java calls the thread's run ( ) method, so it is the run ( ) where all
the action takes place.
Starting New Thread
To actually create and run an instance of our thread class, we must write the following :
MyThread aThread = new MyThread ( ) ;
aThread.start ( ) ;

/ / invokes run ( ) method

The first line instantiate a new object of class MyThread. This statement just creates the object. The
thread that will run this object is not yet running. The thread is in a newborn state.
The second line calls the start ( ) method causing the thread to move into the runnable state.

85

JAVA

St. Angelos Computers Ltd.

Life Cycle of a Thread


During the lifetime of a thread, there are many states it can enter. They include :
1.
2.
3.
4.
5.

Newborn state
Runnable state
Running state
Blocked state
Dead state

A thread is always in one of these five states. It can move from one state to another via a variety of
ways as shown in diagram.
Newborn

New Thread

stop
start

yield
Running

KKkkk

Runnable

Suspend
sleep
wait

resume
notify

Dead

stop

Blocked

Newborn State
When we create a thread object, the thread is born and is said to be in newborn state. The thread is
not yet scheduled for running. At this state, we can do only one of the following things with it :
1.
2.

Schedule it for running using start ( ) method.


Kill it using stop ( ) method.
86

JAVA

St. Angelos Computers Ltd.

Runnable State
The runnable state means that the thread is ready for execution and is waiting for the availability of
the processor. That is, the thread has joined the queue of threads that are waiting for execution. If all
threads have equal priority, then they are given time slots for execution in round robin fashion, i.e.
first-serve manner. The thread that relinquishes control joins the queue at the end and again waits
for its turn. This process of assigning time to threads is known as time-slicing.
However, if we want a thread to relinquish control to another thread of equal priority before its turn
comes, we can do so by using the yield ( ) method
yield

Running
Thread

Runnable Threads
Relinquishing control using yield ( )

Running State
Running means that the processor has given its time to the thread for its execution. The thread runs
until it relinquishes control on its own or a higher priority thread preempts it. A running thread may
relinquish its control in one of the following situations.
suspend
resume
Running

Runnable

Suspended

Relinquishing control using suspend ( ) method


1.

It has been suspended using suspend( ) method. A suspended thread can be revived by
using the resume( ) method. This approach is useful when we want to suspend a thread for
some time due to certain reason, but do not want to kill it.

2.

It has been made to sleep. We can put a thread to sleep for a specified time period using
the method sleep (time) where time is in milliseconds. This means that the thread is out of
the queue during this time period. The thread re-enters the runnable state as soon as this
time period is elapsed.
87

JAVA

St. Angelos Computers Ltd.

sleep (t)

after t
Running

Runnable

Sleeping

Relinquishing control using sleep ( ) method


3.

It has been told to wait until some event occurs. This is done using the wait ( ) method.
The thread can be scheduled to run again using the notify ( ) method.

Blocked State
A thread is said to be blocked when it is prevented from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, sleeping, or waiting in
order to satisfy certain requirements. A blocked thread is considered "not runnable" but not dead
and therefore fully qualified to run again.
Dead State
Every thread has a life cycle. A running thread ends its life when it has completed executing its run (
) method. It is a natural death. However, we can kill it by sending the stop message to it at any state
thus causing a premature death to it. A thread can be killed as soon it is born, or while it is running,
or even when it is in "not runnable" (blocked) condition.

Thread Priorites:
Java assigns to each thread a priority that determines how that thread should be treated with respect
to the others. Thread priorities are integers that specify the relative priority of one thread to
another. As an absolute value, a priority is meaningless; a higher-priority thead running. Instead, a
thread's priority is used to decide when to switch from one running thread to the next context.
Given below is methods related priority of threads.

public final void setPriority ( int newPriority ): Sets the priority for the thread.
New Priority

public final static int MIN_PRIORITY

public final static int MAX_PRIORITY

: This is the minimum priority a thread can have


which is 1.
: The maximum priority a thread can
have is 10.
88

JAVA

St. Angelos Computers Ltd.

public final static int NORM_PRIORITY : A default priority is equal to 5.

Messaging
After you divide your program into separate threads, you need to define how they will communicate
with each other. When programming with most other languages, you must depend on the operating
system to establish communication between threads. This, of course, adds overhead. By contrast, Java
provides a clean, low-cost way for two or more threads to talk to each other, via calls to predefined
methods that all objrct have. Java's messaging system allows a thread to enter a synchronized
method on an object, and then wait there until some other thread explicity notifice it to come out.
The thread class defines several methods that help manage threads. The ones that will be used in
this chapter are shown here:
Method

Meaning

getName
getPriority
isAlive
join
run
sleep
start
Using Thread Methods

Obtain a thread's name.


Obtain a threads priority.
Determine if a thread is still running.
Wait for a thread to terminate.
Entry point for the thread.
Suspend a thread for a period of time.
Start a thread by calling its run method.

class CurrentThreadDemo {
public static void main(String args[]) {
Thread t = Thread.currentThread( );
System.out.println("Current thread: " + t);
// change the name of the thread
t.setName ( "My Thread" );
System.out.println( "After name change: " + t);
try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println( "Main thread interrupted" );
}
}
}

89

JAVA

St. Angelos Computers Ltd.

A reference to the current thread (the main thread, in this case) is obtained by calling
currentThread( ), and this reference is stored in the local variable t Next, the program displays
information about the thread. The program then calls setName( ) to change the internal name of the
thread. Information about the thread is then redisplayed. Next, a loop counts down from five,
pausing one second between each line. The pause is accomplished by the sleep( ) method. The
argument to sleep( ) specifies the delay period in millseconds. Notice the try/catch block around this
loop.The sleep( ) method in Thread might throw an InterruptedException. This would happen if
some other thread wanted to interrupt this sleeping one. Here is the output generated by this
program:
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
5
4
3
2
1
The output produced when t is used as an argument to println( ). This displays, in order: the name
of the thread, its priority, and the name of its group. By default, the name of the main thread is
main. Its priority is 5, which is the default value, and main is also the name of the group of threads
to which this thread belongs. A thread group is a data structure that controls the state of a
collection of threads as a whole. This process is managed by the particular run-time environment
and is not discussed in detail here. After the name of the thread is changed, t is again output. This
time, the new name of the thread is displayed.
Implementing the runnable Interface
The thread can be created in two ways one by using extended Thread class and another by
implementing the runnable interface.
1.
2.
3.
4.

Declare the class as implementing the Runnable interface.


Implement the run( ) method.
Create a thread by defining an object that is instantiated from this "runnable" class as the
target of the thread.
Call thread's start method to run the thread.

Using isAlive( ) and join( )


Two ways exist to determine whether a thread has finished. First, you can call isAlive( ) on the
thread. This method is defined by Thread, and its general form is shown here:

final boolean isAlive( )


The isAlive( ) method returns true if the thread upon which it is called is still running. It returns
false otherwise.

90

JAVA

St. Angelos Computers Ltd.

While isAlive( ) is occasionally useful, the method that you will more commonly use to wait for a
thread to finish is called join( ), shown here:

final void join( ) throws InterruptedException


This method waits until the thread on which it is called terminates. Its name comes from the
concept of the calling thread waiting until the specified thread joins it. Additional forms of join( )
allow you to specify a maximum amount of time that you want to wait for the specified thread to
terminate..
The preceding example uses join( ) to ensure that the main thread is the last to stop. It also
demonstrates the method.

// Using join( ) to wait for threads to finish.


class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread (String threadname) {
name = threadname;
t= new Thread(this, name);
System.out.println( "New thread: " + t);
t.start( ); // Start the thread
}
// This is the entry point for thread.
public void run ( ) {
try {
for (int i=5;i>0;i--) {
System.out.println(name + " : " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + " interrputed.");
}
System.out.println(name + " exiting. ");
}
}
class DemoJoin {
public static void main (String args[ ] ) {
NewThread ob1 = new NewThread ( "One" );
NewThread ob2 = new NewThread ( "Two" );
NewThread ob3 = new NewThread ( "Three" );

91

JAVA

St. Angelos Computers Ltd.

System.out.println( "Thread One is alive: "


+ ob1.t.isAlive( ) );
System.out.println( "Thread Two is alive: "
+ ob2.t.isAlive( ) );
System.out.println( "Thread Three is alive: "
+ ob3.t.isAlive( ) );
// wait for threads to finish
try {

System.out.println( "Waiting for threads to finish. ");


ob1.t.join( );
ob2.t.join( );
ob3.t.join( );
catch (InterruptedException e) {
System.out.println("Main thread Interrupted" );

}
System.out.println( "Thread One is alive: "
+ ob1.t.isAlive( ) );
System.out.println( "Thread Two is alive: "
+ ob2.t.isAlive( ) );
System.out.println( "Thread Three is alive: "
+ ob3.t.isAlive( ) );
System.out.println( "Main thread existing. ");
}
}
Here is the out put of the program:
New Thread:[one,5,main]
New Thread:[Two,5,main]
One:5
New Thread:[Three,5,main]
Two: 5
Thread One is alive: true
Two: 5
Three: 5
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish
One: 4
Two: 4
Three: 4
One: 3
Two: 3
Three: 3
92

JAVA

St. Angelos Computers Ltd.

One: 2
Two: 2
Three: 2
One: 1
Two: 1
Three: 1
One exiting
Two exiting
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
Synchronization
When two or more threads need acess to a shared resourse, they need some way to ensure that the
resourse will be used by only one thread at a time. The process by which this is achieved is called
synchronization.
Key to synchronization is the concept of the monitor (also called a semaphore). A monitor is an
object that is used as a mutually exclusive lock, or mutex. Only one thread can own a monitor at a
given time. When a thread acquires a lock, it is said to have entered the monitor. All other threads
attempting to enter the locked monitor will be suspended until the first thread exits the monitor.
These other threads are said to be waiting for the monitor.
Using Synchronized Methods
When the thread tries to use data and methods outside themselves, on such a occasion they may
compete for the same resources and may lead to serious problems. For example one may try to read
record from a file while another is still writing to the same file. Java enables to overcome such
situation by the technique called synchronization.
Synchronized is easy in Java, because all objects have their own implicit monitor associated with
them. To enter an objects monitor, just call a method that has been modified with the synchronized
keyword. While a thread is inside a synchronized method, all other threads that try to call it (or any
other synchronized method) on the same instance have to wait. To exit the monitor and relinquish
control of the object to the next waiting thread, the owner of the monitor simply returns from the
synchronized method.

class Callme {
void call (String msg) {
System.out.print ("[" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println( "Interrupted" );
}
93

JAVA

St. Angelos Computers Ltd.

System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller (Callme targ, String s) {
target =targ;
msg =s;
t = new Thread(this);
t.start( );
}
//synchronised calls to call;
public void run( ) {
synchronized(target) {
target.call(msg);
}
}
}
class Synch1 {
public static void main(String args[ ] ) {
Callme target = new Callme( );
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join( );
ob2.t.join( );
ob3.t.join( );
} catch(InterruptedException e) {
System.out.println( "Interrupted" );
}
}
}
Here is the output of the program:
[Hello]
94

JAVA

St. Angelos Computers Ltd.

[Synchronized]
[world]
How Synchronization works?
1)

If a class has one or more synchronized methods each object of the class gets a queue that
holds all the threads waiting to execute one of the synchronized methods.
2) A thread can get into a queue two ways
a) By calling the method while another thread using the object or
b) By calling the wait while using the object.
3) The thread scheduler chooses the highest priority among those in the queue.
4) When a synchronized method call returns or when a method calls wait, another threads
gets access to the object.
5) If a thread is in a queue by a call to wait, then to activate it, a call to notify must be made.
o void notify ( ) : Notifies the threads waiting on the monitor object that the state of the
object has changed. This method must be called from within a synchronized method
otherwise an IllegalMonitorStateException is thrown.
o void wait ( ) : Causes a thread to wait until it is notified. This method must be called from
within a synchronized method only otherwise IllegalMonitorException is thrown.
Here are three general rules to be followed for threads.
i.
ii.

Declare the methods of different threads as synchronized, if they modify the same object.
In case a thread has to wait for it to modify an object, it should wait inside the object by
entering a synchronized method and a call to wait.
iii. Whenever a method changes the state of an object, it should call notify, so that waiting
threads get a chance to Access the Object.
Deadlocks
There is yet another problem with multithreading. A situation can arise when one thread waits for
another thread to complete, whereas the second thread waits for the first one to complete. Such
situation is called a deadlock and must be avoided while designing threads. Java cannot solve
deadlock problem.

Exercise
1.

What is Multitasking or Multijobbing?

2.

Explain the difference between multiprocessing and multithreading?

3.

What is thread?

4. Explain the various method of creating a thread ?


5. What is the lifecycle of the thread ?

95

JAVA

St. Angelos Computers Ltd.

6. What is synchronization ? State the difference between synchronized block and


synchronized method?
7.

What is deadlock ? How can you come out from this problem.?

8. A thread wants to make a second thread ineligible for execution. To do this, the first thread
can call the yield() method on the second thread.?
A. True.
B. False
9. A thread wants to make a second thread ineligible for execution. To do this, the first thread
can call the suspend() method on the second thread.?
A. True.
B. False
10. A java monitor must either extend Thread or implement Runnable?
A. True.
B. False

96

JAVA

St. Angelos Computers Ltd.

Chapter - 8
WORKING WITH STRING & I/O
Implementing string as builtin objects allows Java to provide a full complement of feature that
makes string handing convenient. For example, Java has methods to compare two strings, search for
a substring, concatenate two strings, and change the case of letters within a string. Also, String
objects can be constructed a number of ways, making it easy to obtain a string when needed.

class SubStringCons {
public static void main (String args[ ] ) {
byte ascii[ ] = {65, 66, 67, 68, 69, 70 };
String s1 = new String (ascii);
System.out.println (s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
This program generates the following output:

ABCDEF
CDE
The contents of the array are copied whenever you create a String object from an array. If you
modify the contents of the array after you have created the string, the String will be unchanged.
String Length
The length of a string is the number of characters that it contains. To obtain this value, call the
length ( ) method, shown here:

int length( )

The following fragment prints 3, since there are three character in the string S :

char chars[ ] = { a, b, c};


String s= new String(chars);
System.out.println(s.length( ) );
String Concatenation
The + operator, which concatenates two string, producing a String object as the result.
97

JAVA

St. Angelos Computers Ltd.

chartAt( )
To extract a single character from a string, you can refer directly to an individual character via the
charAt( ) method. It has this general form:
char charAt(int where)
Here, where is the index of the character that you want to obtain.
getChars( )
If you need to extract more than one character at a time, you can use the getChars( ) method. It has
this general form:
void getChars(int sourceStart,int sourceEnd,char target[ ], int targetStart)
getBytes( )
There is an alternative to getChars( ) that stores the characters in an array of bytes. This method is
called getBytes( ), and it uses the default character-to-byte conversions provided by the platform.
Here is its simplest form:
byte[ ] getBytes( )
Other forms of getBytes( ) are also available. getBytes( ) is most useful when you are exporting a
String value into an environment that does not support 16-bit Unicode characters. For example, most
Internet protocols and text file formats use 8-bit ASCII for all text interchange.

toCharArray( )
If you want to convert all the characters in a String object into a character array, the easiest way is
to call toCharArray( ). It returns an array of characters for the entire string. It has this general form:
char[ ] toCharArray( )
This function is provided as a convenience, since it is possible to use getChars( ) to achieve the same
result.
equals( ) and equalsIgnoreCase( )
To compare two strings for equality, use equals( ). It has this general form:

boolean equals(Object str)

98

JAVA

St. Angelos Computers Ltd.

Here, str is the String being compared with the invoking String object. It returns true if the string
contain the same order, and false otherwise. The comparision is case-sensitive.
equals( ) Versus = =
The = = operator compares two object references to see whether they refer to the same instance.
substring( )
You can extract a substring using substring( ). It has two forms. The first is
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the
substring that begins at startIndex and runs to the end of the invoking string.
The second form of substring( ) allows you to specify both the begining and ending index of the
substring:
String substring(int starIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string
returned contains all the characters from the beginning index, up to, but not including, the ending
index.
StringBuffer
StringBuffer is a peer class of String that provides much of the functionality of strings. As you know,
String represents fixed-length, immutable character sequences. In contrast, StringBuffer represents
growable and writeable character sequences. StringBuffer may have characters and substrings
inserted in the middle or appended to the end. StringBuffer will automatically grow to make room
for growth. Java uses both classes heavily, but many programmers deal only with String and let Java
manipulate StringBuffer behind the scenes by using the overloaded + operator.
StringBuffer Constructors
StringBuffer defines these three constructors:

StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
The default constructor (the one with no parameters) reserves room for 16 characters without
reallocation. The second version accepts an integer argument that explicitly sets the size of the
buffer. The third version accepts a String argument that sets the initial contents of the StringBuffer
object and reserves room for 16 more characters without reallocation. StringBuffer allocates room for
16 additional characters when no specific buffer is requested, because reallocation is a costly process
99

JAVA

St. Angelos Computers Ltd.

in terms of time. Also, frequent reallocations can fragment memory. By allocating room for a few
extra characters, StringBuffer reduces the number of reallocations that take place.
length( ) and capacity( )
The current length of a string buffer can be found via length method, the total allocated capacity can
be found through the capacity method.
ensureCapacity( )
To set the size of buffer ,this is useful when you will be appending large number of small strings to
a StringBuffer. The general form:

void ensureCapacity(int capacity)


capacity specifies the size of the buffer.
charAt( ) and setcharAt( )
The value of single character can be obtained from a string buffer via charAt( ) method. You can set
the value of the character within a StringBuffer using setCharAt( ). The general form is shown here.

char charAt(int where);


void setCharAt(int where,char ch);
append
The append method concatenates the string representation of any other type of data to the end of
evoking StringBuffer object. The general form is shown here.

StringBuffer append(String str);


StringBuffer append(int num);
StringBuffer append(object obj);
replace
It replaces one set of the character with another set inside a StringBuffer object.

StringBuffer replace(int startIndex,int endIndex,String str);


The substring being replaced is specified by the index startIndex and endIndex
Thus the substring at startIndex through endIndex-1 is replaced. The replacement string is passed in
str.
substring( )

100

JAVA

St. Angelos Computers Ltd.

The substring method returns a portion of the StringBuffer.

String substring(int startIndex);


String substring(int startIndex,int endIndex);
Example

Class Palindrome
{
public static void main(String args[])
{
String s=madam;
String rev=;
int l=s.length();
for(int i=l-1;i>=0;i--)
rev+=s.charAt(i);
if(s.equalsIgnoreCase(rev))
System.out.println(It is a Palindrome);
else
System.out.println(It is not a Palindrome);
}
}
Here is the output of the program:
It is a palindrome
I/O Basics
In this chapter, we cover how to handle the input and output . The input could be from a keyboard,
file or the network. The output destination could be screen or file. The chapter covers the methods
for handling files and directories as well as methods for actually writing and reading back the
information to and from files. Java provides strong, flexible support for I/O as it relates to files and
networks. Javas I/O system is cohesive and consistent. In fact, once you understand its fundamentals,
the rest of the I/O system is easy to master.
Concept of Streams
In file processing, input refers to the flow of data into a program and output means the flow of data
out of a program. Input to a program may come from the keyboard, the mouse, the memory, the
disk, a network, or another program. Similarly, output from a program may go to the screen, the
printer, the memory, the disk, a network, or another program. Although these devices look very
different at the hardware level, they share certain common characteristics such as unidirectional

101

JAVA

St. Angelos Computers Ltd.

movement of data, treating data as a sequence of bytes of characters and support to the sequential
access to the data.
Java uses the concept of streams to represent the ordered sequence of data, a common characteristic
shared by all the input/output devices as stated above. A stream presents a uniform, easy-to-use,
object-oriented interface between the program and the input/output devices.
Sources

Destinations

Keyboard

Screen

Mouse

printer
Java
program

Memory

Memory

Disk

Disk

Input

Network

Output

Network

Relationship of Java program with l /O devices


A stream in Java is a path along which data flows (like a river or a pipe along which water flows). It
has a source (of data) and a destination. Both the source and the destination may be physical devices
or programs or other streams in the same program.
The concept of sending data from one stream to another (like one pipe feeding into another pipe)
has made streams in Java a powerful tool for file processing. We can build a complex file processing
sequence using a series of simple stream operations. This feature can be used to filter data along the
pipeline of streams so that we obtain data in a desired format. For example, we can use one stream
to get raw data in binary format and then use another stream in series to convert it to integers.
Java streams are classified into two basic types, namely, input stream and output stream. An input
stream extracts (i.e. reads) data from the source (file) and sends it to the program. Similarly, an
output stream takes data from the program and sends (i.e. writes) it to the destination (file). The
figure illustrates the use of input and output streams. The program connects and opens an input
stream on the data source and then reads the data serially. Similarly, the program connects and
opens an output stream to the destination place of data and writes data out serially. In both the
cases, the program does not know the details of end points (i.e. source and destination).
Input stream

Reads

Source

program

(a) Reading data into a program

102

JAVA

St. Angelos Computers Ltd.

Output stream
program

Writes

Destination

(b) Writing data to a destination


Using input and output streams
Thus, a stream is an abstraction that either produces or consumes information. A stream is linked to
a physical device by the Java I/O system. All streams behave in the same manner, even if the actual
physical devices to which they are linked differ. Thus, the same I/O classes and methods can be
applied to any type of device. This means that an input stream can abstract many different kinds of
input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the
console, a disk file, or a network connection. Streams are a clean way to deal with input/output
without having every part of code understand the difference between a keyboard and a network, For
example, Java implements streams within class hierarchies defined in the java.io package.
Concepts Of Streams
Byte Streams and Character Streams
Java 2 defines two types of streams: byte and character. Byte streams provide a convenient means for
handing input and output of bytes. Byte streams are used, for example, when reading or writing
binary data. Character streams provide a convenient means for handling input and output of
characters. In some cases, character streams are more efficient than byte streams.
The original version of Java (Java 1.0) did not include streams and, thus, all I/O was byte-oriented.
Character streams were added by Java 1.1, and certain byte-oriented classes and methods were
deprecated. This is why older code that doesnt use character streams should be updated to take
advantage of them, where appropriate.
One other point: at the lowest level, all I/O is still byte-oriented. The character-based streams simply
provide a convenient and efficient means for handling characters.
The Byte Stream Classes
Byte streams are defined by using two class hierarchies. At the top are two abstract classes:
InputStream and OutputStream. Each of these abstract classes has several concrete subclasses that
handle the differences between various devices, such as disk files, network connections, and even
memory buffers.
The abstract classes InputStream and OutputStream define several key methods that the other
stream classes implement. Two of the most important are read( ) and write( ), which, respectively,
read and write bytes of data. Both methods are declared as abstract inside InputStream and
OutputStreams. They are overridden by derived stream classes.
The Character Stream Classes

103

JAVA

St. Angelos Computers Ltd.

Character streams are defined by using two class hierarchies. At the top are two abstract classes,
Reader and Writer. These abstract classes handle Unicode character stream. Java has several concrete
subclasses of each of these.
The abstract classes Reader and Writer define several key methods that the other stream classes
implement. Two of the most important methods are read( ) and write( ), which read and write
character of data, respectively. These methods are overridden by derived stream classes.
As all programmers learn early on, most programs cannot accomplish their goals without accessing
external data. Data is retrieved from an input source. The results of a program are sent to an output
destination. In Java, these sources or destinations are defined very broadly. For example, a network
connection, memory buffer, or disk file can be manipulated by the Java I/O classes.
The Byte Streams
The byte stream classes provide a rich environment for handling byte-oriented I/O. A byte stream
can be used with any type of object, including binary data. This versatility makes byte streams to
many types of programs. Since the byte stream classes are topped by InputStream and
OutputStream.
Input and Output Streams
Using standard Input/Output objects
Three static Input/Output (I/O) objects have been created by default. All three of these objects are
public static members of the System class. These are defined below.
Object

Type

Purpose

System.in
System.out
System.err

BufferdInputStream
PrintStream
PrintStream

standard input ( usually from the keyboard)


standard output ( usually to the screen)
error output (usually to the screen )

public abstract int read ( ) throws IOException

:Reads a byte of data and


returns the byte read or-1 if end of the
stream. Throws IOException in case of
any errors.

Example: System.in.read ( );

public int read ( byte[ ] ) throws IOException : Reads into an array of bytes
and returns the number of
bytes read. -1 denotes end of stream.

Example: byte buf [ ] = new byte [ 50 ];


System.in.read ( buf );
104

JAVA

St. Angelos Computers Ltd.

read ( byte b [ ] . int off, int len ) throws IOException : Reads into an array of bytes from
offset off. The
maximum number of bytes is
len.
Example: byte buf [ ] = new byte [ 50 ];
System.in.read ( buf, 5, 20 );
Here length 20 is to ensure you dont exceed the array length.

public void close ( ) throws IOException : Closes the input stream after the reading is over,
the resources must be released.
public long skip ( long n ) throws IOException : Skips in number of bytes.
public int available ( ) throws IOException :
Input operations can be blocked by
threads. This method returns the
number of bytes available without
blocking.
public void mark ( int readlimit ):
This method places a marker up to
where bytes can be read from input
stream. If the limit is exceeded then the
marker is not considered.
public void reset ( ) throws IOException:
This method returns to the last marker.
public boolean markSupported ( ) ers:
This method returns true if the stream
supports it.

The Reader Class


The Reader class is very similar to InputStream. The difference between Readers and InputStreams is
that Readers manage Characters while InputStream manage bytes. Reader has the following
subclasses.
Reader

CharArrayReader
InputStreamReader
File Reader
PipedReader
StringReader
FilterReader
PushbackReader
BufferedReader
LineNumberReader
The methods in Reader class are almost identical to InputStream class methods.

public int read() throws IOException: Read a single character. This method will block until
a character is available, an I/O error occurs, or the end of the stream is reached. The
105

JAVA

St. Angelos Computers Ltd.

character read, as an integer in the range 0 to 16383, or 1 if the end of the stream has
been reached

public abstract void close() throws IOException: Closes the stream. Once a stream has been
closed, further read(), ready(), mark(), or reset() invocations will throw an IOException.
Closing a previously closed stream, however, has no effect.

public void mark(int readAheadLimit ) throws IOException: Marks the present position in
the stream. Subsequent calls to reset() will attempt to reposition the stream to this point.
Not all character-input streams support the mark() operation.

public boolean markSupported(): Tell whether this stream supports the mark() operation.

public int read(char cbuf[]) throws IOException: Read characters into an array. This
method will block until some input is available, an I/O error occurs, or the end of the
stream is reached. The number of bytes read, or - 1 if the end of the stream has been
reached.

public abstract int read(char cbuf[], int off, int len) throws IOException: Read characters
into a portion of an array. This method will block until some input is available, an I/O error
occurs, or the end of the stream is reached. The number of characters read, or-1 if the end
of the stream has been reached.

ready()

Tell whether this stream is ready to be read.

reset()

Reset the stream.

skip(long) :

Skip characters.

Writer Class
The abstract Writer class is very similar to output stream. The difference between writer and output
stream is that, they write characters instead of bytes, one at a time or in blocks.

Writer has the following subclasses.


Writer

BufferedWriter
CharArrayWriter
FilterWriter
106

JAVA

St. Angelos Computers Ltd.

PipedWriter
PrintWriter
StringWriter
OutputStreamWriter
FileWriter
The methods of the writer class are as follows

public void write(int c) throws IOException: Writes a single character. The character to be
written is contained in the 16 low-order bits of the given integer value; the 16 high-order
bits are ignored. Subclasses that intend to support efficient single-character output should
override this method.

public void write(char cbuf[]) throws IOException: Write an array of characters.

public abstract void write(char cbuf[], int off, int len) throws IOException

Write a portion of an array of characters.

public void write(String str) throws IOException: Write a string.

public abstract void flush() throws IOException: Flush the stream. If the stream has saved
any characters from the various write() methods in a buffer, write them immediately to
their intended destination. Then, if that destination is another character or byte stream,
flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and
OutputStreams.

public abstract void close() throws IOException: Close the stream, flushing it first. Once a
stream has been closed, further write() or flush() invocations will cause an IOException to
be thrown. Closing a previously closed stream, however, has no effect.

public void write(String str, int off, int len) throws IOException: Writes a portion of a
string.
Print Streams
The PrintStream class has two methods that are normally overloaded for outputting text. Whereas
the methods of Input and Output Streams handle a byte or an array of bytes, these methods can
handle objects as well.

public void print ( type varname ) : This method sends the characters to a buffer where
they are stored until the buffer is flashed with a \n character. When characters are printed
out, they are in ASCII not UNICODE. Type can be
i.
ii.

object
integer

107

JAVA

St. Angelos Computers Ltd.

iii.
iv.
v.
vi.
vii.
viii.

long
float
double
boolean
String
Array of characters
Varname

: Name of the variable / data type.

Example

: System.out.print (Enter a number);


System.out.print ( name );
System.out.print ( double d );

public void println ( type varname ): This method not only prints out the characters but
also a new line thus flushing out the buffer.
Example

: System.out.println (Hello, World );


System.out.println (salary);
System.out.println ( ) prints a new line.

Data Streams
Both the input and output streams provided methods that could either read or write only. The
DataStream class provides the means to both write and read data.
Methods for reading

public final boolean readBoolean ()


throws IOException

: Reads a Boolean value.

public final byte readByte ()


throws IOException

: Reads an 8 bit byte.

public final char readChar ()


throws IOException

: Reads a 16 bit Unicode character.

public final double readDouble()


throws IOException

: Reads a 64 bit double.

public final float readFloat ()


throws IOException

: Reads a 32 bit float.

public final void readFully (byte b [ ])


throws IOException

: Reads bytes, blocking until all bytes are


read. Ties up resources.

108

JAVA

St. Angelos Computers Ltd.

public final void readFully (byte b [], int off, int len)
throws IOException
: Reads bytes, blocking till all bytes are read,
start from an offset for the maximum
number of bytes to be read.

public final int readInt ()


throws IOException

: Reads a 32 bit integer.

public final String readLine ()


throws IOException

: Returns a string until all bytes in a line,


converted to Unicode characters. A line is
terminated by \n, \r or EOF.

public final long readLong ()


throws IOException

: Reads a 64 bit long integer.

public final short readShort ()


throws IOException

: Reads a 16 bit short integer.

public final String readUTF ()


throws IOException

: Reads a string of characters in UTF format.

public final int skipBytes (int n)


throws IOException

: Skips bytes, blocking until all n bytes are


skipped.

InputStream is an abstract class that defines Javas model of streaming byte input. All of the methods
in this class will throw an IOExceptions on error conditions.
FileInputStream
The FileInputStream class creates class creates an InputStream that you can use to read bytes from a
file. Its two most common constructors are shown here:

FileInputStream(String filepath)
FileInputStream(File fileObj)
Either can throw a FileNotFoundException. Here, filepath is the full path name of a file, and fileObj is
a File object that describes the file.
The following example creates two FileInputStreams that use the same disk file and each of the two
constructors:

FileInputStream f = new FileInputStream(/autoexec.bat)


File f = new File(/autoexec.bat);
FileInputStream f1 = new FileInputStream(f);

109

JAVA

St. Angelos Computers Ltd.

FileOutputStream
FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most
commonly used constructors are shown here:

FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolen append)
They can throw an IOException or a SecurityException. Here, filePath is the full path name of a file,
and fileObj is a File object that describes the file. If append is true, the file is opened in append
mode.
Creation of a FileOutputStream is not dependent on the file already existing. FileOutputStream will
create the file before opening it for output when you create the object. In the case where you
attempt to open a read-only file, an IOException will be thrown.
The following example creates a sample buffer of bytes by first making a String and then using the
getBytes( ) method to extract the byte array equivalent. It then creates three files. The first, file1.txt,
will contain every other byte from the sample. the second, file2.txt, will contain the entire set of
bytes. The third and last, file3.txt, will contain only the last quarter. Unlike the FileInputStream
methods, all of the FileOutputStream methods have a return type of void. In the case of an error,
these methods will throw an IOException.

// Demonstrate FileOutputStream.
import java.io.*;
import java.io.*;
class FileOutputStreamDemo {
public static void main(String args[]) throws Exception
{
String source = "Now is the time for all good men\n"
+ " to come to the aid of their country\n"
+ " and pay their due taxes.";
byte buf[] = source.getBytes( );
OutputStream fo = new FileOutputStream("file1.txt");
for (int i=0; i < buf. length; i +=2)
{
fo.write(buf[i]);
}
fo.close( );
OutputStream f1 = new FileOutputStream("file2.txt");
f1.write (buf);
110

JAVA

St. Angelos Computers Ltd.

f1.close( );
OutputStream f2 = new FileOutputStream("file3.txt");
f2.write (buf, buf.length-buf.length/4, buf.length/4);
}
}
Here are the contents of each file after running this program:
First, file1.txt:

Nwi h iefralgo e
t oet h I ftercuty n a hi u ae.
Next, file2.txt:
Now is the time for all good men
to come to the aid of their country
and pay their due taxes.
Finally, file3.txt:
nd pay their due taxes.
Buffered Byte Streams
For the byte-oriented streams, a buffered stream extends a filtered stream class by attaching a
memory buffer to the I/O streams. This buffer allows Java to do I/O operations on more than a byte
at a time, hence increasing performance. Because the buffer is available, skipping, marking, and
resetting of the stream becomes possible. The buffered byte stream classes are BufferedInputStream
and BufferedOutputStream. PushbackInputStream also implements a buffered stream.
BufferedInputStream
Buffering I/O is a very common performance optimization. Java's BufferedInputStream class allows
you to "wrap" any InputStream into a buffered stream and achieve this performance improvement.
BufferedInputStream has two constructors:

BufferedInputStream (InputStream inputStream)


BufferedInputStream (InputStream inputStream, int bufSize)
BufferedOutputStream
A BufferedOutputStream is similar to any OutputStream with the exception of an added flush()
method that is used to ensure that data buffers are physically written to the actual output device.
111

JAVA

St. Angelos Computers Ltd.

Since the point of a BufferedOutputStream is to improve performance by reducing the number of


times the system actually writes data, you may need to call flush ( ) to cause any data that is in the
buffer to get written.
Unlike buffered input, buffering output does not provide additional functionality. Buffers for output
in Java are there to increase performance. Here are the two available constructors:

BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)
The first form creates a buffered stream using a buffer of 512 bytes. In the second form, the size of
the buffer is passed in bufSize.
File
A file object is used to obtain or manipulate the associated with a disk file, such as the permissions,
time, date, and directory path, and to navigate subdirectory hierarchies.
Files are a primary source and destination for data within many programs. Although there are severe
restrictions on their use within applets for security reasons, files are still a central resource for
storing persistent and shared information. A directory in Java is treated simply as a File with one
additional property - a list of filenames that can be examined by the list( ) method.
The following constructors can be used to create File objects:
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
// Demonstrate File
import java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
public static void main(String args[]) {
File f1 = new File("/java/COPYRIGHT");
p("File Name: " + f1.getName( ) );
p("Path: " + f1.getPath( ) );
p("Abs Path: " + f1.getAbsolutePath( ) );
p("Parent: " + f1.getParent( ) );
p(f1.exists( ) ? "exists" : "does not exist");
p(f1.canWrite( ) ? "is writeable" : "is not writeable");
p(f1.canRead( ) ? "is readable" : "is not readable");
p("is " + (f1.isDirectory( ) ?" ": "not" +" a directory") );
112

JAVA

St. Angelos Computers Ltd.

p(f1.isFile( ) ?"is normal file":"might be a named pipe");


p(f1.isAbsolute( ) ? " is absolute" : "is not absolute");
p("File last modified: " + f1.lastModified( ) );
p("File size: " + f1.length( ) + " Bytes");
}
}

When you run this program, you will see something similar to the following:

File Name: COPYRIGHT


Path: /java/COPYRIGHT
Abs Path: /java/COPYRIGHT
Parent: /java
exists
is writeable
is readable
is not a directory
is normal file
is absolute
File last modified: 812465204000
File size: 695 Bytes
A directory is a File that contains a list of other files and directories. When you create a File object
and it is a directory, the isDirectory( ) method will return true. In this case, you can call list( ) on
that object to extract the list of other files and directories inside. It has two forms. The first is shown
here:
String[] list( )
// Using directories.
import java.io.File;
class DirList {
public static void main(String args[ ] ) {
String dirname = "/java";
File f1 = new File(dirname);
if (f1.isDirectory( ) ) {
System.out.println("Directory of " + dirname);
String s[] = f1.list( );
for (int i=0; i< s.length; i++) {
File f = new File(dirname + "/" + s[i] );
if (f.isDirectory( ) ) {
System.out.println(s[i] + " is a directory");
}
else {
System.out.println(s[i] + " is a file");

113

JAVA

St. Angelos Computers Ltd.

}
}
}
else {
System.out.println(dirname + " is not a file directory");
}
}
}

Here is sample output from the program. (Of course, the output you see will be different, based on
what is your directory.)

Directory of java
bin is a directory
lib is a directory
demo is a directory
COPYRIGHT is a file
README is a file
index.html is a file
include is directory
src.zip is a file
.hotjava is a directory
src is a directory
Random Access File Streams
This class lets you to read or write data anywhere in a file. Disk files are random access files where
as network files are not. Random access Files can be either only read(r) or read and write (rw).
These files have pointers to indicate the nest record that will be accessed.

public RandomAccessFile ( String name, String mode ) : This constructor takes a filename
provided by name and opens a file for either read only or read write.
Name : System dependent file name.
Example : RandomAccessFile file = new RandomAccessFile ( input, rw );

public long getFilePointer ( )


throws IOException

: Returns the current location of the file


pointer in bytes.

public void seek ( long pos )


throws IOException

: This method moves the file pointer to the


specified position (pos) in the file.

public long length ()


throws IOException

: This method returns the length of the file in


bytes.
114

JAVA

St. Angelos Computers Ltd.

public int read ()

: Reads a single byte and moves the pointer


forward by a byte

public int read ( byte b [] )

: Reads and files a byte array from the file


and moves the pointer as many size as the
array size.

public int read ( byte b [] , int off, int len ) : Reads an array of bytes of length and places
them in the array at off. The pointer is
moved by len bytes.

public final String readLine ()

: Returns the entire line terminated


by \n\ or EOF.

public final String readUTF ()

: Returns a string from a UTF formatted file.

All the methods given below return a value of the type specified and move the file pointer forward
the same amount.
For Reading

public final boolean readBoolean ()


public final byte readByte ()
public final short readShort()
public final char readChar ()
public final int readInt ()
public final long readLong ()

For Writing

public void write ()


public void write ( byte b[ ] )
public void write ( byte b[], int off, int len )
public final void writeLine ( String line )
public final void writeUTF (String utf )
public final void writeBoolean ( Boolean b )
public final void writeByte ( byte b )
public final void writeShort ( short s )
public final void writeChar ( char c )
public final void writeInt ( int i )
public final void writeLong ( long l )
public final void writeBytes ( String s )
115

JAVA

St. Angelos Computers Ltd.

public void close ( )

Sample Programs:
import java.io.*;
class Main
{
public static void main( String[] args)
{
if (args.length != 1)
{
System.err.println(Usage: java Main <output file>);
System.exit(-1);
}
try {
RandomAccessFile raf = new RandomAccessFile(args[0], rw);
char a = a;
byte b = 2;
String c = abc;
short d = 4;
// write some stuff out
long file_start = raf.getFilePointer();
raf.writeBoolean(true);
raf.writeChar(a);
raf.writeBytes(c);
raf.writeChar(c);
raf.writeDouble(123.456);
raf.writeFloat(123.456f);
raf.writeInt(678);
raf.writeLong(678l);
raf.writeShort(d);
raf.writeUTF(c);
raf.writeUTF(abc\n);
raf.write (b);
raf.writeShort(d);
System.out.println(Length of file: + raf.length());
// read the stuff back
raf.seek(file_start);
b = raf.readByte();
System.out.println(Byte: + b);
raf.read(b2);
System.out.println(Byte[0]: + (char)b2[0]);
raf.read(b2, 0, b2.length);
System.out.println(Byte[0]: + (char)b2[0]);
int ub = raf.readUnsignedByte();
116

JAVA

St. Angelos Computers Ltd.

Sytem.outPrintln(Unsigned Byte: + b);


System.out.println(Boolean: + raf.readBoolean());
a = raf.readChar();
System.out.println(Char: + a);
byte[] b3 = new byte[3];
raf.readFully(b3);
System.out.println(readFully: + (char)b3[0] + (char)b3[1] + (char)b3[2]);
raf.skipBytes(6); // skip string a0bc
double d1 = raf.readDouble();
float f1 = raf.readFloat();
int i = raf.readInt();
long l = raf.readLong();
short s = raf.readShort();
String srt = raf.readUTF();
ub = raf.readUnsignedByte();
int us = raf.readUnsignedByte();
System.out.println(UTF String + str);
raf.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
Here is the output of the program:

Length of file: 42
Unsigned Byte: 1
Boolean : true
Char: ?
ReadFully: c@^
Java.io.EOFException.
Exercise
1.

What do you understand by stream .Explain Byte and character stream?

2.

Explain the InputStream and OutputStream?

3.

Explain the difference between String and StringBuffer class?

4.

What is the difference between equals() method and = = operator?

5.

Which of the statements below are true ? (choose all that apply)
117

JAVA

St. Angelos Computers Ltd.

a.

UTF(Universal Text Format) characters are all 8 bits.

b.

UTF characters are all 16 bits.

c.

UTF characters are all 24 bits.

d.

Unicode characters are all 16 bits.

e.

Unicode characters are all 16 bits.

6. Which of the statement below are true ?


a.

When you construct an instance of File, if you do not use the file naming
semantics of the local machine, the constructor will throw an IOException.

b.

When you construct an instance of File, if the corresponding file does not exists
on the local file system, one will be created ?

c.

When an instance of File is garbage collected, the corresponding file on the local
file system is deleted?

7. The File class contains a method that changes the current working
a.

True.

b.

False.

directory?

8. Is it possible to use the File class to list the contents of the current working directory?

9.

a.

True

b.

False

Readers have methods that can read and return floats and doubles?
a.

True

b.

False.

10. You execute the code below in an empty directory. What is the result ?
a.

File f1 = new File(dirname);

b.

File f2 = new File(f1,filename);

118

JAVA

11.

St. Angelos Computers Ltd.

c.

A new directory called dirname is created in the current working directory.

d.

A new directory called dirname is created in the current working directory . A


new file called filename is created in directory dirname.

What does the following code fragment print out at line 9?

1.

a.

FileOutputStream fos = new FileOutputStream(xx);

b.

for (byte b=10; b < 50; b++)

c.

fos.write(b);

d.

fos.close();

e.

RandomAccessFile raf = new RandomAccessFile(xx,r);

f.

raf.seek(10);

g.

int i=raf.read();

h.

raf.close();

System.out.println( i= + i);
a.

The output is i=30;

b.

The output is i=20;

c.

The output is i=10;

d.

There is no output because the code throws an exception at line 1.

e.

There is no output because the code throws an exception at line 5.

12. Given a String constructed by calling s=new String(xyzzy), which of the calls listed below
modify the string ?(choose all that apply)?
a.

s.append(aaa);

b.

s.trim();

c.

s.substring(3);

d.

s.replace(z,a);
119

JAVA

St. Angelos Computers Ltd.

e.

s.concat(s);

13. Which one statement is true about the code below?


a.

String s1=abc + def;

b.

String s2 = new String(s1);

c.

if(s1 = = s2)

d.

System.out.println( = = succeeded );

e.

if ( s1.equals(s2))

f.

System.out.println( .equals() succeeded );

g.

Lines 4 and 6 both execute.

h.

Lines 4 execute, and line 6 does not.

i.

Lines 6 executes, and line 4 does not.

j.

Neither lines 4 nor 6 execute.

14. In the code fragment below, after execution of line 1 ,sbuf references an instance of the
StringBuffer class. After execution of line 2,sbuf still references the same instance?
1.

StringBuffer sbuf = new StringBuffer(abcde);

2.

sbuf.insert(3,xyz);
a.

True.

b.

False.

15. In the code fragment below, after execution of line 1 ,sbuf references an instance of the
StringBuffer class. After execution of line 2,sbuf still references the same instance?
1. StringBuffer sbuf = new StringBuffer(abcde);
2. sbuf.append(3,xyz);
a.

True.

b.

False.
120

JAVA

St. Angelos Computers Ltd.

16.In the code fragment below, line 4 is executed?


String s1=xyz;
String s2=xyz;
if(s1 == s2)
System.out.println(Line 4);
a.

True.

b.

False.

In the code fragment below, line 4 is executed?


1.

String s1 = xyz;

2.

String s2 = new String(s1);

3.

if(s1 == s2)

4.

System.out.println(Line 4);
a.

True.

b.

False.

121

JAVA

St. Angelos Computers Ltd.

Chapter - 9
JAVA APPLETS
Applet
An applet is a small java program that can transmit through network. Java programs are of 2 types
one is application and another is applet.
Applet Basics
Any applet program should be a subclass of an java.applet.Applet class. This super class Applet
provides the basic functionality for any applet. Because this Applet extends from panel, which is a
container, an applet holds a physical place on the web page i.e. in the browser.
An applet is a program that executes on the web-browser. All applets must begin with import
java.applet.*; Applets must also import java.awt.* (Abstract Window Toolkit) Applets are executed
either by browser or an appletviewer(Testing Browser).
Execution of the applet does not begin at main( ). Output to your applet's window is provided with
various AWT method's ,such as drawString( ) method. The applet begins with two import
statements. The first imports the Abstract Window Toolkit (AWT) classes. Applets interact with the
user through the AWT, not through the console-based I/O classes. The AWT contains support for a
window-based, graphical interface. Every applet that is created must be a subclass of Applet.
Lets begin with the simple applet shown here:

import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint (Graphics g) {
g.drawString ( "A Simple Applet", 20, 20);
}
}
The program declares the class SimpleApplet. This class must be declared as public, because it will
be accessed by code that is outside the program.
Inside SimpleApplet, paint( ) is declared. This method is defined by the AWT and must be
overridden by the applet. paint( ) is called each time that the applet must redisplay its output. This
situation can occur for several reasons. For example, the window in which the applet is running can
be overwritten by another window and then uncovered. Or, the applet window can be minimized
and then restored. paint( ) is also called when the applet begins execution. Whatever the cause,
whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one
parameters of type Graphics. This parameter contains the graphics context, which describes the

122

JAVA

St. Angelos Computers Ltd.

graphics environment in which the applet is running. This context is used whenever output to the
applet is required.
Inside paint( ) is a call to method drawString( ), which is a member of the Graphics class. This
method output a string beginning at the specified X,Y location. It has the following general form:

void drawString(String message,int x,int y)


Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is
location (0,0). The call drawString( ) in the applet causes the message A Simple Applet to be
displayed beginning at location 20,20.
The applet does not have a main( ) method unlike Java programs, applets do not begin execution at
main( ). In fact, most applets dont even have a main( ) method. Instead, an applet begins execution
when the name of its class is passed to an applet viewer or to a network browser.
After you enter the source code for SimpleApplet, compile in the same way that you have been
compiling programs. However, running SimpleApplet involves a different process. In fact, there are
two ways in which you can run an applet:
1.

Executing the applet within a Java-compatible Web browser, such as Netscape


Navigator.

2.

Using an applet viewer, such as the standard JDK tool, appletviewer. An appletviewer
executes your applet in a window. This is generally the faster and easiest way to test your
applet.

To execute an applet in a Web browser, you need to write a short HTML text file that contains the
appropriate APPLET container tag. Here is the HTML file that executes
SimpleApplet:

<applet code=SimpleApplet width="200" height="60">


</applet>
The width and height statements specify the dimensions of the display area used by the applet. After
you create this file, you can execute your browser and then load this file, which causes SimpleApplet
to be executed.
The Applet Class
The Applet class provides all necessary support for an applet's execution, such as starting and
stopping. It also provides methods that load and display images, and methods that load and play
audio clips. Applet extends the AWT class Panel. In turn, Panel extends Container, which extends
Component. These classes provide support for java's window-based, graphical interface. Thus, Applet
provides all the necessary support for window-based activities.

123

JAVA

St. Angelos Computers Ltd.

Simple Applet Display Methods


To set the background color of an applet's window, use setBackground( ). To set the foreground
color (the color in which text is shown, for example), use setForeground( ). These methods are
defined by Component, and they have the following general forms:

void setBackground(Color newColor)


void setForeground (Color newColor)
Here, newColor specifies the new color. The class Color defines the constants shown here that can
be used to specify colors:
Color.black

Color.magenta

Color. blue

Color. orange

Color.cyan

Color. pink

Color.darkGray

Color.red

Color. gray

Color. white

Color. green

Color. yellow

Color.lightGray
For example, this sets the background color to green and the text color to red:

setBackground (Color. green) ;


setForeground (Color . red) ;
Requesting Repainting
As a general rule, an applet writes to its window only when its update( ) or paint( ) method is called
by AWT. This raises an interesting question: How can the applet itself cause its window to be
updated when its information changes? For example, if an applet is displaying a moving banner, what
mechanism does the applet use to update the window each time this banner scrolls? Remember, one
of the fundamental architectural constraints imposed on an applet is that it must quickly return
control to the AWT run-time system. It cannot create a loop inside paint( ) that repeatedly scrolls
the banner, for example. This would prevent control from passing back to the AWT. Given this
constraint, this is not the case. Whenever your applet needs to update the information displayed in
its window, it simply calls repaint( ).
The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a call
to your applet's update( ) method, which in its default implementation, calls paint( ). Thus, for
another part of your applet to output to its window, simply store the output and then call repaint( ).
The AWT will then execute a call to paint( ), which can display the stored information. For example,
124

JAVA

St. Angelos Computers Ltd.

if part of your applet needs to output a string, it can store this string in a String variable and then
call repaint( ). Inside paint(), you will output the string using drawString( ).
The repaint( ) method has four forms. Let's look at each one, in turn. The simplest version of
repaint( ) is shown here:

void repaint( )
This version causes the entire window to be repainted. The following version specifies a region that
will be repainted:

void repainted(int left, int width, int height)


Here, the coordinates of the upper-left corner of the region are specified by left and top, and the
width and height of the region are passed in width and height. These dimensions are specified in
pixels. You save time by specifying a region to repaint. Window updates are costly in terms of time.
If you need to update only a small portion of the window, it is more efficient to repaint only that
region.
Calling repaint( ) is essentially a request that your applet be repainted sometime soon. However, if
your system is slow or busy, update( ) might not be called immediately. Multiple requests for
repainting that occur within a short time can be collapsed by the AWT in a manner such that
update( ) is only called occasionally. This can be a problem in many situations, including animation,
in which a consistent update time is necessary. One solution to this problem is to use the following
forms of repaint( ):

void repaint(long maxDelay)


void repaint(long maxDelay, int x int y, int width, int height)
Here, maxDelay specifies the maximum number of milliseconds that can before update() is called. If
the time elapses before update( ) can be called, it isn't called. There's no return value or exception
thrown, so you must be careful.
It is possible for a method other than paint( ) or update( ) to output to an applet's window. To do
so, it must obtain a graphics context by calling getGraphics( ) (defined by Components) and then
use this context to the window. However, for most applications, it is better and easier to route
window output through paint( ) and to call repaint( ) when the contents of the window change.
Applet Security Features
Being one of the primary affairs of Java developers, they implemented several safeguards at several
levels. Thus some of the functionality of Java is totally blocked for applets.
Applets can be downloaded from anywhere in the network and thus should be declared as a public
class. Thus security is the prime concern to be bothered.
What the applets cannot do are plotted as
125

JAVA

1)

St. Angelos Computers Ltd.

Applets cannot read or write files on the web users disk i.e. the local file system.
Applets cannot read or write on to the local file system if it is executed in any browser. Applets
in any applet viewer can read files specified with full URLs, instead of by a filename. A work
around for not being to write files is to have the applet forward data to an application on the
host the applet came from. This application can write the data files on its own host. The JDK
Applet Viewer actually permits some user-specified exceptions to this rule.

2) Applets cannot use dynamic or shared libraries from any other programming language.
Applets can use only their own Java code and the Java API the applet viewer provides. At a
minimum, each applet viewer must provide access to the API defined in the java.* packages.
3) Applets cannot run any programs on the web users system.
4) Applets cannot find any information about the local system, except the version of Java used.
5) Applets cannot make network connections with any other host except from which its been
served, that server is called as origination host.
The workaround for this restriction is to have the applet work with an application on the host it
came from. The application can make its own connections anywhere on the network.
6) Applets that carry a popup window carry a warning message like untrusted Applet window.
Windows that an applet brings up look different than windows that an application brings up.
Applet windows have some warning text and either a colored bar or an image. This helps the
user distinguish applet windows from those of trusted applications.

NOTE: Applets that are loaded from the local file system (from a directory in the users
CLASSPATH) have none of the restrictions that applets loaded over the network do.
Hierarchy
Any Java based graphical application can easily be converted into an applet. This is because both
Frame and Applet are extended from the container class. So you can use same methods for both.

OBJECT
COMPONENT
126

CONTAINER
CONTAINER

JAVA

St. Angelos Computers Ltd.

Life Cycle of an Applet


The structure of an applet takes its form from four events that occur during the life of an applet.
1)

init() method: This initializes the applet and sets the stage for it. This includes things like
loading Graphics, creating objects, creating threads, and designing the user interface.

2)

start() method: This method starts the execution of an applet. The actual body of the
applet is placed here. This method is also used to restart the applet once its stopped.
Starting a thread, etc, can be placed here.

3)

stop() method: This method stops or interrupts the execution. But the resources will be
intact, so that it can start the execution again by calling the start() method of it. Stopping
a thread can be done here. Whenever user moves off the page on which the Applet sits or
when it is iconified. If the applet is not doing any time consuming activities like animation,
this need not be implemented.

4)

destroy() method: This method destroys the applet by clearing all the resources like
memory, processor time, etc. This is the last method that happens when the user leaves
the page containing the applet.

Along with the life cycle there are other methods like paint () and repaint () that are not directly
required for execution. These are the methods to the display of the applet. The applet calls the
repaint () and update () methods whenever the applet is resized, iconfied, or deiconified.
Methods for Using UI Components in Applet

127

JAVA

St. Angelos Computers Ltd.

Because the Applet class inherits from the AWT Container class, its easy to add components to
applets and to use layout managers to control the components on screen positions. Here are some of
the Container methods an applet can use:
add( )
Add s the specified Component.
remove ( )
Remove the specified Component.
setLayout ( )
Sets the layout manager.
Threads in Applets
Every applet can run in multiple threads. Applet drawing methods paint( ) and update ( ) are always
called from the AWT drawing and event handling thread. The threads that the major milestone
methods-init(), start(), stop(), and destroy()-are called from depends on the application thats
running the applet. But no application ever calls them from the AWT drawing and event handling
thread.

128

JAVA

St. Angelos Computers Ltd.

Specifying the Applet Directory with CODEBASE:


If the applet is in different directory from the web document which is holding the applet, the path of
the applet has to be given with an attribute of applet tag called CODEBASE. In the applet program
the path can be retrieved using a method called getCodeBase(). This gives the directory structure till
the applet class file.

<APPLET CODE = AppletSubclass.class CODEBASE=aURL WIDTH=anInt HEIGHT=anInt> </APPLET>


By making a URL an absolute URL, you can make a document loaded from your HTTP server run an
applet from another HTTP server. If a URL is a relative URL, then it is interpreted relative to the
HTML documents location.

<applet code=Simple.class codebase=example width=500 height=20>


</applet>
There is another method in applet class which gives the path of the web document which contains
the applet class file i.e. getDocumentBase()
Specifying Parameters with the <PARAM> tag:
Along with the <APPLET> tag the web page, which holds the applet, can have another tag called a
<PARAM> tag. This tag is used to provide a variable for an applet, each time it is initialized. There
can be any number of <PARAM> tags in an <APPLET> tag. These parameters are passed to the applet
when it is loaded in the applet.
The <PARAM> tag can be used for:
1)
2)
3)
4)

To display performance graph in sports updates.


To update stock portfolio dynamically.
To provide sleep span in Animation.
To communicate between two Applets.

Sample Program : Using the PARAM tag

import java.applet.*;
import java.awt.*;
public class Param extends Applet
{
int w,h;
String s1, s2;
public void init() {
try {
if(getParameter(s1)!=null)
w=Integer.parseInt(getParameter(s1)));
129

JAVA

St. Angelos Computers Ltd.

else w=500;
if(getParameter(s2)!=null)
h=Integer.parseInt((getParameter(s2)));
else h=300;
reSize(w,h);
} catch(Exception e)
{System.out.println(e);}
public void paint(Graphics g)
{
g.drawString(Testing for parameters, 100, 100);
}
}
<html>
<applet code=Param.class width=300 height=300>
<param name=s1value=300>
<param name=s2value=250>
</applet>
</html>
Interaction with the Brower and other Applets
AppletContext:
An Applet runs inside a browser. If it wants to communicate with the ambient browser, it calls a
method like getAppletContext() which returns an object that implement an interface of type
AppletContext. Now this acts as the channel for communication in which the applet sits.
The AppletContext object can be used to set the status of the browser using the showStatus()
method and also to show another document in the client work area using the showDocument()
method. The AppletgetDocumentBase methods get information from the browser or applet viewer
about where the applet and its HTML page came from. The Applet showStatus method tells the
browser or viewer to display a status message. The Applet getParameterInfo method can give a
browser a list of the parameters an applet understands.
Methods of AppletContext
Method

Function

Applet getApplet(String name);

Gets an applet named name. If not


found, null is returned

AudioClip getAudioClip(URL)

Gets an audio clip

Enumeration getApplets()

Lists the applets available in the


current context.

Image getImage(URL)

gets an image
130

JAVA

St. Angelos Computers Ltd.

public void showDocument(URL, String loc) Shows a new document in a target


window or frame.
void showDocument(URL)

Tells the browser to show a document of the


URL

void showStatus(String)

Shows the string in the status bar of


the browser.

Converting an Applet to a Standalone Application


An Applet as an Application too!
Can a program be an applet and an application too? Yes. It is possible to convert an applet into a
standalone application that can run independently of a browser.
In order to convert an applet to application,
1)
2)
3)
4)

The program should extend a Frame.


It should have a main method.
It should provide the basic framework for the applet.
It should explicitly invoke the applet life cycle by calling the init() method.

Sample Program: Converting applet to application


In the program below we view an applet in a frame.
import java.applet.*;
import java.awt.*;
public class StandaloneScribble extends Scribble {
public static void main(String args[] {
Applet applet = new StandaloneScribble();
Frame frame=new AppletFrame(Scribble, applet, 300, 300);
}
}
class AppletFrame extends Frame {
public AppletFrame(String title, Applet applet, int width, int height) {
super(title);
MenuBar menubar = new MenuBar();
Menu file=new Menu(File, true);
Menubar.add(file);
this.setMenuBar(menubar);

131

JAVA

St. Angelos Computers Ltd.

this.add(Center, applet);
this.reSize(width, height);
this.show();
applet.init();
applet.start();
}
public boolean action(Event e, Object org) {
if (e.target instanceof MenuItem) {
String label=String org;
if (label,equals (Quit))
System.exit(0);
}
return false;
}
}

Events:
The modern approach of handling events is based on the delegation event model. It defines a
standard process mechanism to generate and process event. In the delegation model, an event is an
object that describes a state change in a source. It can be generated as a consequence of a person
interacting with the elements in a graphical user interface. Some of the activities that cause events to
be generated are pressing a button, entering a character via the keyboard, selecting an item in a list,
and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface. For example,
an event may be generated when a timer expires, a counter exceeds a value, a software or hardware
failure occurs, or an operation is completed. You are free to define events that are appropriate for
your application.
Event Sources
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a specific
type of event. Each type of event has its own registration method. Here is the general form:

public void addTypeListener(TypeListener el)


Here, Type is the name of the event and el is a reference to the event listener. For example, the
method that registers a keyboard event, the listener is called by addKeyListener( ). The method that
registers a mouse motion, the listener is called by addMouseMotionListener( ). When an event
occurs, all registered listeners are notified and receive a copy of the event object. This is known as

132

JAVA

St. Angelos Computers Ltd.

multicasting the event. In all cases, notifications are sent only to listeners that register to receive
them.
The package java.awt.event defines several types of events that are generated by various user
interface elements. The following table enumerates the most important of these event classes and
provides a brief description of when they are generated. The most commonly used constructors and
methods in each class are described in the following sections.

Event Class

Description

Action Event

Generated when a button is pressed, a list item is doubleclicked, or a menu item is selected.

AdjustmentEvent

Generated when a scroll bar is manipulated.

ComponentEvent

Generated when a component is hidden, moved,


resized, or becomes visible.

ContainerEvent

Generated when a component is added to or


removed from a container.

FocusEvent

Generated when a component gains or loses


focus.

InputEvent

Abstract super class for all component input event classes.

ItemEvent

Generated when a check box or list item is clicked also


occurs when a choice selection is made or a checkable
menu item is selected or deselected.

KeyEvent

Generated when input is received from the keyboard.

MouseEvent

Generated when the mouse is dragged, moved, clicked,


pressed, or released also generated when the mouse enters
or exits a component.

TextEvent

Generated when the value of a text area or text field is


changed.

WindowEvent

Generated when a window is activated, closed, deactivated,


deiconified, iconified, opened, or quit.

Event Listeners
133

keyboard

JAVA

St. Angelos Computers Ltd.

A listener is an object that is notified when an event occurs. It has two major requirements. First, it
must have been registered with one or more sources to receive notifications about specific types of
events. Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event. For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved. Any object may receive and process one or both
of these events if it provides an implementation of this interface.
The ActionEvent Class
An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item
is selected.

ActionEvent(Object src,int type,String cmd);


ActionEvent(Object src,int type, String cmd,int modifiers);
Here, src is the reference to the object that generated this event. The type of the event is specified
by the type, and its command string is cmd. The argument modifier indicates which modifier key
keys (ALT,CTRL,META and/or SHIFT)
The AdjustmentEvent Class
An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.
BLOCK_DECREMENT

The user clicked inside the scrollbar to


decrease its value.

BLOCK_INCREMENT

The user clicked inside the scrollbar to


decrease its value.

TRACK

The slider was dragged.

UNIT_DECREMENT

The button at the end of scrollbar was clicked


to decrease its value.

UNIT_INCREMENT

The button at the end of scrollbar was clicked


to increase its value.

AdjustmentEvent has this constructor.


AdjustmentEvent(Adjustable src,int id,int type,int data)
Here, src is reference to the object that generated this event.id equals Adjustment_value_changed.
The type of the event is specified by type and its associated data is data.
The ComponentsEvent Class

134

JAVA

St. Angelos Computers Ltd.

A ComponentEvent is generated when the size, position, or visibility of a component is changed.


The ContainerEvent Class
A ContainerEvent is generated when a component is added to or removed from a container.
The FocusEvent Class
A FocusEvent is generated when a component gains or loses input focus. These events are identified
by the integer constants FOCUS_GAINED and FOCUS_LOST.
The InputEvent Class
The abstract class InputEvent is a subclass of ComponentEvent and is the superclass for component
input events.
The ItemEvent Class
An ItemEvent is generated when a check box or a list is clicked or when a checkable menu item is
selected or deselected.
The WindowEvent Class
There are seven types of window events. The WindowEvent class defines integer constants that can
be used to identify them. The constants and their meaning are shown here:
WINDOW_ACTIVATED
WINDOW_CLOSED
WINDOW_CLOSING
WINDOW_DEACTIVATED
WINDOW_DEICONIFIED
WINDOW_ICONIFIED
WINDOW_OPENED

The window was activated.


The window has been closed.
The user requested that the window be
closed.
The window was deactivated.
The window was deiconified.
The window was inconified.
The window was opened.

WindowEvent is a subclass of ComponentEvent and has this constructor:


WindowEvent(Window src, int type)
Here, src is a reference to the object that generated this event. The type of the event is type.
The most commonly used method in this class getWindow( ). It returns the Window object that
generated the event. Its general form is shown here:
Window getWindow( )
Sources of Events
135

JAVA

St. Angelos Computers Ltd.

The table lists some of the user interface components that can generate the events described in the
previous section. In addition to these graphical user interface elements, other components, such as
an applet, can generate events. For example, you receive key and mouse events from an applet.
Event Source

Description

Button
Checkbox

Generates action events when the button is pressed.


Generates item events when the check box is selected or
described.
Generates item events when the choice is changed.
Generates action events when an item is double-clicked,
generates item events when an item is selected or deselected.
Generates adjustment events when the scroll bar is manipulated.
Generates text events when the user enters a character.
Generates window events when a window is activated, closed,
Deactivated, deiconified, iconified, opened, or quit.

Choice
List
Scrollbar
Text components
Window

Event Listener Interfaces


The delegation event model has two parts; sources and listeners. Listeners are created by
implementing one or more of the interfaces defined by the java.awt.event package. When an event
occurs, the event source invokes the appropriate method defined by the listener and provides an
event object as its argument.
The ActionListener Interface
This interface defines the actionPerformed( ) method that is invoked when an action event occurs.
Its general form is shown here:

void actionPerformed(ActionEvent ae)


The AdjustmentListener Interface
This interface defines the adjustmentValueChanged( ) method that is invoked when an adjustment
event occurs. Its general form is shown here:

void adjustmentValueChanged(AdjustmentEvent ae)


The ComponentsListener Interface
This interface defines four methods that are invoked when a component is resized, moved, shown, or
hidden. Their general forms are shown here:

void componentResized(ComponentEvent ce)


136

JAVA

St. Angelos Computers Ltd.

void componentMoved(ComponentEvent ce)


void componentShown(ComponentEvent ce)
void componentHidden(ComponenEvent ce)
The AWT processes the resize and move events. The componentResized( ) and componentMoved( )
methods are provided for notification purposes only.
The ContainerListener Interface
This interface contains two methods. When a component is added to a container, componentAdded(
) is invoked. When a component is removed from a container, componentRemoved( ) is invoked.
Their general forms are shown here:

void componentAdded(ContainerEvent ce)


void componentRemoved(ContainerEvent ce)
The FocusListener Interface
This interface defines two methods. When a component obtains keyboard focus, focusGained( ) is
invoked. When a component loses keyboard focus, focusLost( ) is called. Their general forms are
shown here:

void focusGained(FocusEvent fe)


void focusLost(FocusEvent fe)
The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an item
changes. Its general form is shown is here:

void itemStateChanged(ItemEvent ie)


The KeyListener Interface
This interface defines three methods. If a user presses and releases the A key, Three events are
generated in sequences: keyPressed( ), keyTyped( ) and keyReleased( ). If a user presses and releases
the HOME key, two key events are generated in sequences: keyPressed and keyReleased .
The general forms of these methods are shown here.

void keyPressed(keyEvent ke)


void keyReleased(keyEvent ke)
void keyTyped(keyEvent ke)
Handling Mouse Events

137

JAVA

St. Angelos Computers Ltd.

To handle mouse events, you must implement the MouseListener and the MouseMotionListener
interfaces. The following applet demonstrates the process. It displays the current coordinates of the
mouse in the applets status window. Each time a button is pressed, the word Down is displayed at
the location of the mouse pointer. Each time the button is released, the word Up is shown. If a
button is clicked, the message Mouse clicked is displayed in the upper-left corner of the applet
display area.
As the mouse enters or exists the applet window, a message is displayed in the upper-left corner of
the applet display area. When dragging the mouse, a * is shown, which tracks with the mouse
pointer as it is dragged. Notice that the two variables, mouseX and mouseY, store the location of the
mouse when a mouse pressed, released, or dragged event occurs. These coordinates are then used by
paint( ) to display output at the point of these occurrences.
// Demonstrate the mouse event handlers.
import java.awt. * ;
import java. awt. event . * ;
import java. applet. *;
/*
<applet code = "Mouse Events" width = 300 height =100>
< / applet >
*/
public class MouseEvents extends Applet
implements MouseListener, MouseMotionListener {
String msg = " " ;
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init ( ) {
addMouseListener (this);
addMouseMotionListener (this);
}
// Handle mouse clicked.
public void mouseClicked (MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY =10;
msg = "Mouse clicked. ";
repaint ( ) ;
}
// Handle mouse entered.
public void mouseEntered (MouseEvent me) {
// save coordinates
mouseX = 0;
138

JAVA

St. Angelos Computers Ltd.

mouseY = 10;
msg = "Mouse entered. ";
repaint ( ) ;
}
// Handle mouse exited.
public void mouseExited (MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY=10;
msg = "Mouse exited.";
repaint ( );
}
// Handle button pressed.
public void mousePressed (MouseEvent me) {
// save coordinates
mouseX = me.getX ( );
mouseY = me. getY ( );
msg = " Down" ;
repaint ( );
}
// Handle button released.
public void mouseReleased (MouseEvent me) {
// save coordinates
mouseX = me. getX ( ) ;
mouseY = me. getY ( );
msg = "Up";
repaint ( ) ;
}
// Handle mouse dragged.
public void mouseDragged (MouseEvent me) {
// save coordinates
mouseX = me.getX ( );
mouseY = me.getY( );
msg = "*";
showStatus ("Dragging mouse at " + mouseX + ", " + mouseY);
repaint ( ) ;
}
// Handle mouse moved.

139

JAVA

St. Angelos Computers Ltd.

public void mouseMoved (MouseEvent me) {


// show status
showStatus ("Moving mouse at " + me.getX ( ) + ", " + me.getY ( ) ) ;
}
// Display msg in applet window at current X,Y location.
public void paint (Graphics g) {
g. drawString (msg, mouseX, mouseY);
}
}

Here is the out put of the program:

AWT Classes
The AWT classes are contained in the java.awt package. It is one of Java's largest packages.
Fortunately, because it is logically organized in a top - down, hierarchical fashion, it is easier to
understand and use than you might at first believe.
List of some of the AWT classes.
Class

Description

AWTEvent

Encapsulates AWT events.

AWTEventMulticaster

Dispatches events to multiple listeners.

140

JAVA

St. Angelos Computers Ltd.

BorderLayout

The border layout manager. Border layouts use five


components: North, South, East, West and Center.

Button

Creates a push button control

canvas

A blank, semantics-free window.

CardLayout

The card layout manager. Card layouts emulate index


cards. Only the one on top is showing.

Checkbox

Creates a check box control.

CheckboxGroup

Creates a group of check box controls.

CheckboxMenultem

Creates an on/off menu item.

Choice

Creates a pop-up list.

Color

Manages
fashion.

Component

An abstract superclass for various AWT components.

Container

A subclass
components.

Frame

Creates a standard window that has a title bar, resize corners, and
a menu bar.

Graphics

Encapsulates the graphics context. This context is used by the


various output methods to display output in a window.

GraphicsDevice

Describes a graphics device such as a screen or printer.

GraphicsEnvironment

Describes the collection of an available Font and GraphicsDevice


objects.

GridBagConstraints

Defines various constraints relating to the GridBagLayout class.

GridBagLayout

The grid bag layout manager. Grid bag layout displays


components subject to the constraints specified by
GridBagConstraints.

GridLayout

The gridlayout manager. Gridlayout displays components in a twodimensional grid.

Image

Encapsulates Graphical images.

colors

of

141

in

portable,

Component

that

platform-independent

can

hold

other

JAVA

St. Angelos Computers Ltd.

Insets

Encapsulates the borders of a container.

Label

Creates a label that displays a string.

List

Creates a list from which the user can choose. Similar to


the standard Windows list box.

Polygon

Encapsulates a polygon.

PopupMenu

Encapsulates a pop-up menu.

PrintJob

An abstract class that represents a print job.

Rectangle

Encapsulates a rectangle.

Scrollbar

Creates a scroll bar control.

ScrollPane

A container that provides horizontal and/or vertical Scroll bars for


anther component.

Systemcolor

Contains the colors of GUI widgets such as windows, scroll bars,


text, and others.

TextArea

Creates a multiline edit control.

TextComponent
TextField
Toolkit
Window

A superclass for TextArea and TextField.


Creates a single-line edit control.
Abstract class implemented by the AWT.
Creates a window with no frame, no menu bar, and no title.

Component
At the top of the AWT hierarchy is the component class. Component is an abstract class that
encapsulates all of the attributes of a visual component. All user interface elements that are displayed
on the screen and that interact with the user are subclasses of Component. It defines over a hundred
public methods that are responsible for managing events, such as mouse and keyboard input,
positioning and sizing the window, and repainting. A Component object is responsible for
remembering the current foreground and background colors and the currently selected text font.
Container
The Container class is a subclass of Component. It has additional methods that allow other
Component objects to be nested within it. Other Container objects can be stored inside of a
142

JAVA

St. Angelos Computers Ltd.

container (since they are themselves instances of Component.) This makes for a multileveled
containment system. A container is responsible for laying out (that is, positioning) any components
that it contains. It does this through the use of various layout managers.
Panel
The Panel class is a concrete subclass of Container. It doesnt add any new methods, it simply
implements Container. A Panel may be thought of as a recursively nestable, concrete screen
component. Panel is the superclass for Applet. When screen output is directed to an applet, it is
drawn on the surface of a Panel object. In essence, a Panel is a window that does not contain a title
bar, menu bar, or border. This is why you dont see these items when an applet is run inside a
browser. When you run an applet using an applet viewer, the applet viewer provides the title and
border.
Other components can be added to a Panel object by its add() method (inherited from Container).
Once these components have been added, you can position and resize them manually using the
setLocation(), setSize(), or setBounds() method defined by Component.
Window
The Window class creates a top-level window. A top-level window is not contained within any other
object; it sits directly on the desktop. Generally, you wont create Window objects directly. Instead,
you will use a subclass of Window called Frame, described next.
Frame
Frame encapsulates what is commonly thought of as a window. It is a subclass of Window and has
a title bar, menu bar, borders, and resizing corners. If you create a Frame object from within an
applet, it will contain a warning message, such as Warning: Applet Window, to the user that an
applet window has been created. This message warns users that the window they see was started by
an applet and not by software running on their computer. (An applet that could masquerade as a
host-based application could be used to obtain passwords and other sensitive information without
the users knowledge.) When a Frame window is created by a program rather than an applet, a
normal window is created.
Canvas
Although it is not part of the hierarchy for applet or frame windows, there is one other type of
window that you will find valuable: Canvas. Canvas encapsulates a blank window upon which you
can draw.
Creating a Frame Window in an Applet
Creating a new frame window from within an applet is actually quite easy. First, create a subclass of
Frame. Next, override any of the standard window method, such as init(), start(), stop(), and paint().
Finally, implement the windowClosing() method of the WindowListener interface, calling
setVisible(false) when the window is closed.
143

JAVA

St. Angelos Computers Ltd.

Once you have defined a Frame subclass, you can create an object of that class. This causes a frame
window to come into existence, but it will not be initially visible. You make it visible by calling
setVisible(true). When created, the window is given a default height and width. You can set the size
of the window explicitly by calling the setSize() method.
The following applet creates a subclass of Frame called SampleFrame. A window of this subclass is
instantiated within the init() method of AppletFrame. Notice that SampleFrame calls Frames
constructor. This causes a standard frame window to be created with the title passed in title. This
example overrides the applet windows start() and stop() method so that they show and hide the
child window, respectively.
This causes the window to be removed automatically when you terminate the applet, when you close
the window, or, if using a browser, when you move to another page. It also causes the child window
to be shown when the browser returns to the applet.
// Create a child frame window from within an applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=300 height=50>
</applet>
*/
class SampleFrame extends Frame {
SampleFrame (String title ) {
super(title) ;
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this) ;
// register it to receive those events
addWindowListener(adapter) ;
}
public void paint (Graphics g ) {
g. drawString ("This is in frame window", 10, 40) ;
}
}
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame ;
public MyWindowAdapter (SampleFrame sampleFrame) {
this. sampleFrame = sampleFrame ;
}
public void windowClosing(WindowEvent we) {
sampleFrame. setVisible (false) ;
144

JAVA

St. Angelos Computers Ltd.

}
}
// Create frame window.
public class AppletFrame extends Applet {
Frame f ;
public void init () {
f = new SampleFrame ("A Frame Window");
f. setSize (250, 250 ) ;
f. setVisible (true) ;
}
public void start () {
f. setVisible (true) ;
}
public void stop () {
f.setVisible (false);
}
public void paint (Graphics g) {
g. drawString ("This is in applet window", 10, 20 );
}
}

Here is the output of the program:

145

JAVA

St. Angelos Computers Ltd.

Working with Graphics


The AWT supports a rich assortment of graphics methods. All graphics are drawn relative to a
window. This can be the main window of an applet, a child window of an applet, or a stand-alone
application window. The origin of each window is at the top-left corner and is 0,0. Coordinates are
specified in pixels. All output to a window takes place through a graphics context. A graphics context
is encapsulated by the Graphics class and is obtained in two ways:

It is passed to an applet when one of its various methods, such as paint ( ) or update ( ), is
called.

It is returned by the getGraphics( ) method of Component.

The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or
filled. Objects are drawn and filled in the currently selected graphics color, which is black by default.
When a graphics object is drawn that exceeds the dimensions of the window, output is automatically
clipped. Let's take a look at several of the drawing methods.
Drawing lines
Lines are drawn by means of the drawLine( ), method, shown here:

146

JAVA

St. Angelos Computers Ltd.

void drawLine(int start X, int start Y, int endX, int endY )


drawLine ( ) displays a line in the current drawing color that begins at startX, startY and
ends at endX, endY.
The following applet draws several lines:

/ / Draw lines
import java .awt.*;
import java .applet. *;
/*
<applet code="Lines" width=300 height=200>
</applet>
*/
public class Lines extends Applet {
public void paint (Graphics g) {
g.drawLine (0, 0, 100, 100 );
g.drawLine (0, 100, 100, 0) ;
g.drawLine (40, 25, 250, 180 ) ;
g.drawLine (75, 90, 400, 400 ) ;
g.drawLine (20, 150, 400, 40 ) ;
g.drawLine ( 5, 290, 80, 19 );
}
}

Here is the output of the program:

147

JAVA

St. Angelos Computers Ltd.

Drawing rectangles
The drawRect( ) and fillRect ( ) methods display an outlined and filled rectangle, respectively. They
are shown here:

void drawRect(int top, int left, int width, int height)


void fillRect(int top, int left, int width, int height)
The upper-left corner of the rectangle is at top, left. The dimensions of the rectangle are specified by
width and height.
To draw a rounded rectangle, use drawRoundRect ( ) or fillRoundRect ( ), both shown here:

void drawRoundRect(int top, int left, int width, int height,


int xDiam, int yDiam)
void fillRoundRect (int top, int left, int width, int height,
int xDiam, int yDiam)
A rounded rectangle has rounded corner, the upper-left corner of the rectangle is at top, left. The
dimensions of the rectangle are specified by width and height. The diameter of the rounding arc
along the x axis is specified by xDiam. The diameter of the rounding arc along the y axis is specified
by yDiam.
The following applet draws several rectangles:
/ / Draw rectangles
148

JAVA

St. Angelos Computers Ltd.

import java. awt. *;


import java. applet .*;
/*
<applet code="Rectangles " Width=300 height=200>
</applet>
*/
public class Rectangles extends Applet {
public void paint ( Graphics g) {
g.drawRect (10, 10, 60, 50 );
g.fillRect (100, 10, 60, 50 );
g.drawRoundRect (19, 10 ,140, 100, 30, 40 );
}
}

Here is the output of the program:

Drawing Ellipses and Circles


To draw an ellipse, use drawOval( ). To fill an ellipse, use fillOver ( ). These methods are shown here
:

void drawOval (int top, int left, int width, int height )
void fillOval (int top, int left, int height )
The ellipse is drawn within a bounding rectangle whose upper-left corner is specified by top, left and
whose width and height are specified by width and height. To draw a circle, specify a square as the
bounding rectangle:

/ / Draw Ellipses
149

JAVA

St. Angelos Computers Ltd.

import java. awt. *;


import java. applet .*;
/*
<applet code="Ellipses" width=300 height=200>
</applet>
*/
public class Ellipses extends Applet {
public void paint (Graphics g ) {
g.drawOval (10, 10, 50, 50 );
g.fillOval (100, 10, 75, 50 );
g.drawOval (190, 10, 90, 30 );
g.fillOval (70, 90, 140, 100 ) ;
}
}

Here is the output of the program:

150

JAVA

St. Angelos Computers Ltd.

Working with Color


Java supports color in a portable, device-independent fashion. The AWT color system allows you to
specify any color you want. It then finds the best match for that color, given the limits of the display
hardware currently executing your program or applet. Thus, your code does not need to be
concerned with the differences in the way color is supported by various hardware devices. Color is
encapsulated by the Color class.
Color defines several constants (for example, Color.black) to specify a number of common colors.
You can also create your own colors, using one of the color constructors. The most commonly used
forms are shown here :

Color(int red, int green, int blue )


Color(int rgbValue )
Color(float red, float green, float blue )
The first constructor takes three integers that specify the color as a mix of red, green, and blue.
These values must be between 0 and 255, as in this example:

new Color (255, 100, 100 ) ; / / light red.

int newRed = (0xff000000 \ (0xc0 << 16 ) \ (0x00 << 8) \ 0x00 );


color darkRed = new Color (newRed) :
151

JAVA

St. Angelos Computers Ltd.

The final constructor, Color(float, float,float ), takes three float values (between 0.0 and 1.0) that
specify the relative mix of red, green, and blue.
One you have created a color, you can use it to set the foreground and/or background color by using
the setForeground ( ) and setBackgound ( ) methods. You can also select it as the current drawing
color.
Setting the current Graphics Color
By default, graphics objects are drawn in the current foreground color. You can change this color by
calling the Graphics method setColor ( ):

void setColor(Color newColor )


Here, newColor specifies the new drawing color.
You can obtain the current color by calling getColor( ), shown here:

Color getColor ( )
A Color Demonstration Applet
The following applet constructs several colors and draws various objects using these colors:

/ / Demonstrate color.
import java .awt.*;
import java .applet.*;
/*
<applet code="ColorDemo" Width=300 height = 200>
</applet>
*/
public class ColorDemo extends Applet {
// draw lines
public void paint (Graphics g) {
Color c1 = new Color (225, 100, 100) ;
Color c2 = new Color (100, 255, 100) ;
Color c3 = new Color (100, 100, 1550) ;
g. setColor (c1) ;
g. drawLine (0, 0, 100, 100) ;
g. drawLine (0, 100, 100, 0) ;
g. setColor (c2) ;
g.drawLine (40, 25, 250, 180) ;
g. drawLine (75, 90, 400, 400 ) ;
152

JAVA

St. Angelos Computers Ltd.

g. setColor (c3) ;
g. drawLine ( 20, 150, 400, 40) ;
g. drawLine (70, 90, 140, 100) ;
g. setColor (Color .red) ;
g. drawOval (10, 10, 50, 50) ;
g. fillOval (70, 90, 140, 100) ;
g. setColor (Color .blue) ;
g. drawOval (190, 10, 90, 30) ;
g. drawRect (10, 10, 60, 50) ;
g. setColor (Color .cyan) ;
g. fillRect (100, 10, 60, 50) ;
g. drawRoundRect (190, 10, 60, 50, 15,15) ;
}
}
Creating and Selecting a Font
To select a new font, you must first construct a Font object that describes that font. One of the
forms of the Font constructor has this general form:

Font(String fontName, int fontStyle, int pointSize)


Here, fontName specifies the name of the desired font. The name can be specified using either the
logical or face name. All Java environments will support the following fonts: Dialog, DialogInput, Sans
Serif, Serif, Monospaced, and Symbol. Dialog is the font used by your system's dialog boxes. Dialog is
also the default if you don't explicitly set a font. You can also use any other fonts supported by your
particular environment, but be careful, these other fonts may not be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. For example, Font.BOLD | Font.ITALIC specifies a bold,
italics style.
The size, in points, of the font is specified by pointSize.
To use a font that you have created, you must select it using setFont ( ), which is defined by
Component. It has this general form:

void setFont(Font fontObj)


Here, fontObj is the object that contains the desired font.
The following program outputs a sample of each standard font. Each time you click the mouse
within its window, a new font is selected and its name is displayed.
153

JAVA

St. Angelos Computers Ltd.

// Show fonts
import java .applet .*;
import java . awt .*;
import java .awt .event .*;
/*
<applet code="SampleFonts" width=200 height=100>
</applet>
*/
public class SampleFonts extends Applet {
int next = 0;
Font f;
String msg;
public void init ( ) {
f = new Font ("Dialog", Font .PLAIN, 12) ;
msg = " Dialog";
setFont (f) ;
addMouseListener (new MyMouseAdapter (this) ) ;
}
public void paint (Graphics g) {
g. drawString (msg, 4, 20);
}
}
class MyMouseAdapter extends MouseAdapter {
SampleFonts sampleFonts ;
public MyMouseAdapter (SampleFonts sampleFonts) {
this. sampleFonts = sampleFonts;
}
public void mousePressed (MouseEvent me) {
// Switch fonts with each mouse click.
sampleFonts. next++;
switch (sampleFonts.next) {
case 0 :
sampleFonts.f = new Font (" Dialog", Font.PLAIN,12) ;
sampleFonts.msg = "Dialog";
break ;
case 1 :
sampleFonts.f = new Font ("DialogInput ", Font. PLAIN, 12);
sampleFonts .msg = "DialogInput ";
break;
case 2 :
sampleFonts.f =new Font ("SansSerif", Font .PLAIN, 12);
sampleFonts.msg = "SansSerif";
154

JAVA

St. Angelos Computers Ltd.

break ;
case 3 :
sampleFonts.f = new Font ("Serif ", Font. PLAIN, 12) ;
sampleFonts.msg = "Serif" ;
break ;
case 4 :
sampleFonts.f = new Font ("Monospaced", Font . PLAIN, 12) ;
sampleFonts.msg = "Monospaced";
break;
}
if (sampleFonts.next==4) sampleFonts .next = -1;
sampleFonts.setFont (sampleFonts.f);
sampleFonts.repaint ( );
}
}
Here is the out put of the program:

FlowLayout
FlowLayout is the default layout manager for the Panels and Applets. FlowLayout simply places
components row-by-row into the container. When one row is full, a new one is started below it. Each
row is aligned to the left or right, or centered within the container, according to an alignment
parameter.

155

JAVA

St. Angelos Computers Ltd.

The constructors of the FlowLayout class are:


1.
2.
3.

FlowLayout( )
FlowLayout(int alignment)
FlowLayout(int alignment, int hgap, int vgap)

Alignment can be CENTER or LEFT or RIGHT.


GridLayout
GridLayout lays out components in a two-dimensional grid. When you instantiate a GridLayout, you
define the number of rows and columns. The constructors supported By GridLayout are shown here:

GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout. The second form creates a grid Layout with the
specified number of rows and columns. The third form allows you to specify the horizontal and
vertical space left between components in horizontal and vertical, respectively. Either numRows or
numColumns can be zero. Specifying numRows as zero Allows for unlimited-length columns.
Specifying numColumns as zero allows for unlimited-length rows.
Grid Layout Manager
When you want to arrange all components in rows and columns as in a calculator, you use this
manager.
Example: Panel p = new Panel ( );
p.setLayout ( new GridLayout 9 4, 4 ) );
This sets up a grid with four rows and four columns. You can then add buttons in the following
manner:

p.add ( new Button ( a ) );


p.add ( new Button ( b ) );

// a appears on the button


// b appears on the button

Sample Program:

import java.applet.Applet;
import java.awt.*;
public class Grid extends Applet
{
private Button button1, button2, button3, button4, button5;
public void init()
{
button1 = new Button(one);
button2 = new Button(two);
button3 = new Button(three);
button4 = new Button(four);
156

JAVA

St. Angelos Computers Ltd.

Button5 = new Button(five);


SetLayout(new GridLayout(2,3));
//order is important
add(button1);
// row 1 col 1
add(button2);
// row 1 col 2
add(button3);
// row 1 col 3
add(button4);
// row 2 col 1
add(button5);
// row 2 col 2
}
}
Grid Bag Layout Manager
This layout manager provides flexibility, but at the same time it is a complex layout manager. It is
different from the grid layout manager in that, you can gave the grids (rows and columns of
different sizes.) For example one component you can have a text field, another one can be a list box,
yet another one a check box and so on, as shown below.
My Grid Layout
Check Box

Bold

Times Roman
Helvetica
Courier
Dialog

List
Box

Italic
Text fields

Size

To describe a grid bag layout, you have to follow the procedure below.
I.

Create an object of type GridBagLayout. Java takes care of the number of rows and columns
and so you need not mention it.
II. Set the object to be the layout manager.
III. Create an object of type GridBag Constraints to specify how the components are laid on
the grid.
IV. For each component, fill up the GridBagConstraints object and call the set Constraints
object to pass this information to the GridBagLayout.
V. Then add the components.

Java.awt.GridBagConstraints

157

JAVA

St. Angelos Computers Ltd.

Public int gridx, gridy

Public int gridwidth, gridheight

Public int weightx, weighty


Public int anchor

:
:

Public int fill

Public int ipadx, ipady


Public int insets ( )

:
:

These indicate the starting column and row of a


cell.
These indicate the extent of the column and row
of a cell.
These indicate whether the cell can expand
Indicates the alignment of a component inside a
cell. One of CENTER, NORTH, NORTHEAST,
EAST, SORTHEAST, SOUTH, SOUTHWEST,
WEST or NORTHWEST.
Indicates the fill behavior of the component, one
of NONE, BOTH, HORIZONTAL or VERTICAL.
Indicates the internal padding of the component.
To indicate the external padding along the cell
boundaries.

Java.awt.GridBagLayout

Public void setConstraints ( Component comp, GridbagConstraints constraints ) Sets the


constraints for a component.
Comp

: The component for which constraint information is to


supplied.
Constraints : The constraints to be applied.

be

Example:

GridBagLayout layout = new GridBagLayout ( );


Panel p = new Panel ( );
// an instance of Panel GridBagConstraints constraints
= new GridBagConstraints ( ); // an instance of GridBagConstraints
Constraints.weightx = 100;
// must be set
Constraints.weighty = 100;
Constraints.gridx = 0
Constraints.gridy = 0;
Constraints.gridwidth = 1;
Constraints.gridheight = 3;
Life style = new List ( 4 );
Layout.setConstraints ( style, constraints );
P.add ( style );
Description of the parameters
The gridx and gridy parameters specify the row and column positions of the upper left corner of the
component to be added. The gridwidth and gridheight values determine how many rows and
columns it occupies. The weightx and weighty fields (called weight fields) have to be set for each

158

JAVA

St. Angelos Computers Ltd.

area in a grid bag. These parameters indicate how the area size changes if the window is re-sized.
Values of 0 mean that the size remains constant.
The fill parameter is used to specify whether or not you want a component to fill up the entire area.
In case the component doesnt fill up the entire area, then you use the anchor parameter to indicate
where you want the component to be filled with fields have to be set for each area in a grid bag.
These parameters indicate how the area size changes if the window is re-sized. Values of 0 mean
that the size remains constant.
The fill parameter is used to specify whether or not you want a component to fill up the entire area.
In case the component doesnt fill up the entire area, then you use the anchor parameter to indicate
where you want the component to be filled.
Custom Layout Manager
You can design your own layout manager, that is, customize the Layout Manager by overriding it.
This can then become your own custom layout manager, and lay the basis for designing the screens.

public abstract void addLayoutComponent


(String name, Component comp)
Name
Comp

: An identifier for the component placement.


: The component to be added.

public abstract void removeLayoutComponent


(Component comp)
: Removes the component from the layout.
Comp

: This adds a component to the layout.

: The component to be removed.

public abstract Dimension preferredLayoutSize


(Container parent): This returns the preferred size dimensions for the container under this
layout.
Parent : The container whose component is being laid out.

public abstract void layoutContainer (Container parent)


container.
Parent

: Lays out the components in a

: The container whose components are being laid out.

It is advisable not to customize layout managers unless absolutely necessary.


There is also no compulsion to use any layout manger at all. In such cases you just place a
component at a fixed place. You need to use the following method for this.

Java.awt.Component
159

JAVA

St. Angelos Computers Ltd.

public void reshape ( int x, int y, int w, int h)


: This moves and re-sizes a component.
x and y
: Coordinates of top left corner of the component.
w and h
: Width, and height of component.

The advantage of not using a layout manager is useful when you want to develop a quick prototype.
But it is not a good practice and must be avoided. You should prefer to use one of the layout
managers.
CardLayout
The CardLayout class is unique among the other layout managers in that it stores several different
layouts. Each layout can be thought of as being on a separate index Card in a deck that can be
shuffled so that any card is on top at a given time. This can be useful for user interfaces with
optional components that can be dynamically enabled and disabled upon user input. You can prepare
the other layouts and have them hidden, ready to be activated when needed.
CardLayout provides these two constructors :
CardLayout( )
CardLayout(int horz, int vert)
The first form creates a default card layout. The second form allows you to specify the horizontal
and vertical space left between components in horz and vert, respectively.
Use of a card layout requires a bit more work than the other layouts. The cards are typically held in
an object of type Panel. This panel must have CardLayout selected as its layout manager. The cards
that form the deck are also typically objects of type Panel. Thus, you must create a panel that
contains the deck and a panel for each card in the deck. Next, you add to the appropriate panel the
components that form each card. You then add these panels to the panel for which CardLayout is
the layout manager. Finally, you add this panel to the main applet panel. Once these steps are
complete, you must provide some way for the user to select between cards. One common approach
is to include one push button for each card in the deck.
When card panels are added to a panel, they are usually given a name. Thus, most of the time, you
will use this form of add( ) when adding cards to a panel :

void add(Component panelObj, Object name) ;


Here, name is a string that specifies the name of the card whose panel is specified by panelObj.
After you have created a deck, your program activates a card by calling one of the Following
methods defined by CardLayout:

void first(Container deck)


160

JAVA

St. Angelos Computers Ltd.

void last(Container deck)


void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
Here, deck is a reference to the container (usually a panel) that holds the cards, and CardName is
the name of a card. Calling first( ) causes the first card in the deck to be Shown. To show the last
card, call last( ). To show the next card, call next( ). To show the previous card, call previous( ). Both
next( ) and previous( ) automatically cycle back to the top or bottom of the deck, respectively. The
show( ) method displays the card whose name is passed in cardName.
Menu Bars and Menus
A top-level window can have a menu bar associated with it. A menu bar displays a list of top-level
menu choices. Each choice is associated with a drop-down menu. This concept is implemented in
Java by the following classes: MenuBar, Menu ,and MenuItem. In general, a menu bar contains one or
more Menu objects. Each Menu object contains a list of MenuItem. Objects represent something that
can be selected by the user. Since Menu is a subclass of MenuItem, a hierarchy of nested submenus
can be created. It is also possible to include menu items. These are menu options of type
CheckboxMenuItem and will have a check mark next to them when they are selected.
To create a menu bar, first create an instance of MenuBar. This class only defines the default
constructor. Next, create instances of Menu that will define the selections displayed on the bar.
Following are the constructors for Menu

Menu( )
Menu(String optionName)
Menu(String optionName, boolean removable)
Here,optionName specifies the name of the menu selection. If removable is true, the pop-up Menu
can be removed and allowed to float free. Otherwise, it will remain attached to the Menubar.
(Removable menus are implementation-dependent.) The first form creates an Empty menu.
Individual menu items are of type MenuItem. It defines these constructors :

MenuItem( )
MenuItem(String itemName)
MenuItem(String itemName, MenuShortcut keyAccel)
Here, itemName is the name shown in the menu, and keyAccel is the menu shortcut for this item.

You can disable or enable a menu item by using the setEnabled( ) method. Its form is shown here

void setEnabled(boolean enabledFlag)


161

JAVA

St. Angelos Computers Ltd.

If the argument enabledFlag is true, the menu item is enabled. If false, the menu item is disabled.
You can determine an items status by calling isEnabled( ). This method is shown here

Boolean isEnabled( )
IsEnabled( ) returns true if the menu item on which it is called is enabled. Otherwise, it returns
false.
You can change the name of a menu item by calling setLabel( ). You can retrieve the current name
by using getLabel( ). These method are as follows:

void setLabel(String newName)


String getLabel( )
Here, newName becomes the new name of the invoking menu item. getLabel( ) returns the current
name.
You can create a checkable menu item by using a subclass of MenuItem called CheckboxMenuItem. It
has these constructors:

CheckboxMenuItem( )
CheckboxMenuItem(String itemName)
CheckboxMenuItem(String itemName, boolean on)
Here, itemName is the name shown in the menu. Checkable items operate as toggles. Each time one
is selected, its state changes. In the first two forms, the checkable entry is unchecked. In the third
form, if on is true, the checkable entry is initially checked.
You can obtain the status of a checkable item by calling getState( ). You can set it to a known state
by using setState( ). These methods are shown here:

boolean getState( )
void setState(boolean checked)
If the item is checked, getState( ) returns true. Otherwise, it returns false. To check an item, pass
true to setState( ). To clear an item, pass false.
Once you have created a menu item, you must add the item to a Menu object by using add( ), which
has the following general form :
MenuItem add(MenuItem item)
Here, item is the item being added. Items are added to a menu in the order in which the calls to
add( ) take place. The item is returned.

162

JAVA

St. Angelos Computers Ltd.

Once you have added all items to a Menu object, you can add that object to the menu bar by using
this version of add( ) defined by MenuBar :

Menu add(Menu menu)


Here, menu is the menu being added. The menu is returned.
Menus only generate events when an item of type MenuItem or CheckboxMenuItem is selected. They
do not generate events when a menu bar is accessed to display a drop-down menu, for example.
Each time a menu item is selected, an ActionEvent object is generated. Each time a check box menu
item is checked or unchecked, an ItemEvent object is generated. Thus, you must implement the
ActionListener and ItemListener interfaces in order to handle these menu events. The getItem( )
method of ItemEvent returns a reference to the item that generated this event. The general form of
this method is shown here :

Object getItem( )
Dialog Boxes
Often, you will want to use a dialog box to hold a set of related controls. Dialog boxes are primarily
used to obtain user input. They are similar to frame windows, except that dialog boxes dont have
menu bars. In other respects, dialog boxes function like frame windows. (You can add controls to
them, for example, in the same way that you add controls to a frame window.) Dialog boxes may be
modal or modeless. When a modal dialog box is active, all input is directed to it until it is closed.
This means that you cannot access other parts of your program until you have closed the dialog box.
When a modeless dialog box is active, input focus can be directed to another window in your
program. Thus, other parts of your program remain active and accessible. Dialog boxes are of type
Dialog. The most commonly used constructors are shown here:

Dialog(Frame parentWindow, boolean mode)


Dialog(Frame parentWindow,String title, boolean mode)
Here, parentWindow is the owner of the dialog box. If mode is true, the dialog box is modal.
Otherwise, it is modeless. The title of the dialog box can be passed in title. Generally, you will
subclass Dialog, adding the functionally required by your application.
FileDialog
Java provides a built-in dialog box that lets the user specify a file. To create a file dialog box,
instantiate an object of type FileDialog. This causes a file dialog box to be displayed. Usually, this is
the standard file dialog box provided by the operating system. FileDialog provides these constructors:

FileDialog(Frame parent, String boxName)


FileDialog(Frame parent, String boxName, int how)
FileDialog(Frame parent)

163

JAVA

St. Angelos Computers Ltd.

Here, parent is the owner of the dialog box, and boxName is the name displayed in the boxs title
bar. If boxName is omitted, the title of the dialog box is empty. If how is FileDialog.LOAD, then the
box is selecting a file for reading. If how is FileDialog.SAVE, the box is selecting a file for writing. The
third constructor creates a dialog box for selecting a file for reading.
FileDialog( ) provides methods that allow you to determine the name of the file and its path as
selected by the user. Here are two examples:

String getDirectory( )
String getFile( )
//EXAMPLE FOR APPLET
import java.applet.*;
import java.awt.*;
public class apl extends Applet
{
Panel p,p1,p2;
Label l1,l2,l3,l4,l5,l6,l7;
TextField tf;
TextArea ta;
Checkbox cb1,cb2,cb3,cb4,cb5,cb6;
CheckboxGroup cbg;
Choice ch;
List l;
Button b1,b2;
public void init()
{
p=new Panel();
p.setLayout( new FlowLayout());
l1=new Label("PERSONAL INFORMATION");
p.add(l1);
add(p);
p1=new Panel();
p1.setLayout(new FlowLayout());
l6= new Label("name");
p1.add(l6);
tf=new TextField(20);
p1.add(tf);
l7=new Label("add");
p1.add(l7);
ta=new TextArea(5,20);
p1.add(ta);
164

JAVA

St. Angelos Computers Ltd.

l2=new Label("Gender");
p1.add(l2);
cbg=new CheckboxGroup();
cb5= new Checkbox("male",cbg,false);
p1.add(cb5);
cb6= new Checkbox("female",cbg,true);
p1.add(cb6);
add("North",p1);
p2=new Panel();
p2.setLayout(new FlowLayout());
l3=new Label("city you reside in");
p2.add(l3);
ch= new Choice();
ch.addItem("Mumbai");
ch.addItem("Delhi");
ch.addItem("Calcutta");
p2.add(ch);
l4=new Label("Hobbies");
p2.add(l4);
cb1=new Checkbox("Reading");
p2.add(cb1);
cb2=new Checkbox("Music");
p2.add(cb2);
cb3=new Checkbox("Singing ");
p2.add(cb3);
l5=new Label("Education");
p2.add(l5);
l=new List(6,true);
l.addItem("B.com");
l.addItem("B.Sc");
l.addItem("B.A");
l.addItem("B.E.");
l.addItem("Post Graduate");
l.addItem("student");
p2.add(l);
b1=new Button("click");
p2.add(b1);
b2=new Button("ok");
p2.add(b2);
add("South",p2);
}
}

165

JAVA

St. Angelos Computers Ltd.

Here is the out put of the program:

166

JAVA

St. Angelos Computers Ltd.

Exercise
1.

What is an Applet?

2.

What is the life cycle of an Applet?

3.

Explain the paint() and repaint() methods.

4.

What does the following paint() method draw?


1.

public void paint(Graphics g){

2. g.drawOval(100,100,44);
3. }
A. A circle at (100,100) with radius of 44
B. A circle at (100,44) with radius of 100
C. A circle at (100,44) with radius of 44
D. The code does not compile.
5.

How do you convert an Applet into java Application?

6.

What are the different layout managers in java? Explain in brief.

7.

What is a Canvas?

8.

What are the different kinds of window events?

9.

What is the default layout manager for an applet, for a frame and for a panel?

10. Write a program to applet animation?


11.

If a frame uses a Grid layout manager and does not contain any panel, then all the
components within the frame are the same width and height.
A. True.
B.

False.

12. If a frame uses its default layout manager and does not contain any panel, then all the
components within the frame are the same width and height.
167

JAVA

St. Angelos Computers Ltd.

A. True.
B.

False.

168

JAVA

St. Angelos Computers Ltd.

Chapter - 10
NETWORKING
The java.net package, which provides support of networking.
Networking Basics
Ken Thompson and Dennis Ritchie developed UNIX in concert with the C language at Bell Telephone
Laboratories, Murray Hill, New Jersey, in 1969. For many years, the development on UNIX remained
in Bell Labs and in a few universities and research facilities that had the DEC PDP machines it was
designed to be run on. In 1978, Bill Joy was leading a project at Cal Berkeley to add many new
features to UNIX, such as virtual memory and full-screen display capabilities. By early 1984, just as
Bill was leaving to found Sun Microsystems, he shipped 4.2BSD, commonly known as Berkeley UNIX.
4.2BSD came with a fast file system, reliable signals, interprocess communication, and, most
important, networking. The networking support first found in 4.2 eventually became the de facto
standard for the Internet. Berkeleys implementation of TCP/IP remains the primary standard for
communications within the Internet. The socket paradigm for interprocess and network
communication has also been widely adopted outside of Berkeley. Even Windows and the Macintosh
started talking Berkeley sockets in the late 80s.
Socket Overview
A network socket is a lot like an electrical socket. Various plugs around the network have a standard
way of delivering their payload. Anything that understands the standard protocol can plug in to the
socket and communicate.
The same idea applies to network sockets, except we talk about TCP/IP packets and IP addresses
rather than electrons and street addresses. Internet Protocol (IP) is a low-level routing protocol that
breaks data into small packets and sends them to an address across a network, which does not
guarantee to deliver said packets to the destination. Transmission Control Protocol (TCP) is a
higher-level protocol that manages to reliably transmit your data. A third protocol, user datagram
Protocol (UDP), sits next to TCP and can be used directly to support fast, connectionless, unreliable
transport of packets.
Client / Server
A server is anything that has some resource that can be shared. There are compute servers, which
provide computing power; print servers, which manage a collection of printers disk servers, which
provide networked disk space; and web servers, which store web pages. A client is simply any other
entity that wants to gain interaction between a lamp is a power client. The server is a permanently
available resource, while the client if free to unplug after it is has been served.
In Berkeley sockets, the notion of a socket allows a single computer to serve many different clients at
once, as well as serving many different types of information. This feat is managed by the
169

JAVA

St. Angelos Computers Ltd.

introduction of a port, which is a numbered socket on to it. A server is allowed to accept multiple
connected to the same port number, although each session is unique. To manage multiple client
connections, a server process must be multithreaded or have some other means of multiplexing the
simultaneous I / O.
Proxy Servers
A proxy server speaks the client side of a protocol to another server. This is often required when
clients have certain restrictions on which servers they can connect to. Thus, a client server would in
turn communicate for the client. A proxy server has the additional ability to filter certain requests or
cache the results of those requests for future use. A caching proxy HTTP server can help reduce the
bandwidth demands on a local networks connection to the Internet. When a popular web site is
being hit by hundreds of users, a proxy server can get the content of the web servers popular pages
once, saving expensive internetwork transfers while providing faster access to those pages to the
clients.
Internet Addressing
Every computer on the Internet has an address. An Internet address is a number that uniquely
identifies each computer on the Net. There are 32 bits in an IP address, and we often refer to them
as a sequence of four numbers between 0 and 255 separated by dots (.). This makes them easier to
remember, because they are not randomly assigned-they are hierarchically assigned. The first few
bits define which class of network lettered A, B, C, D, or E, the address represents. Most Internet
users are on a class C network, since there are over two million networks in class C. The first byte of
an individual computer among the 256 allowed on a single class C network. This scheme allows for
half a billion devices to live on class C networks.
Domain Naming Service(DNS)
The Internet wouldnt be a very friendly place to navigate if everyone had to refer to his or her
address as numbers. It is difficult to imagine seeing http//192.9.9.1/ at the bottom of an
advertisement. As an answer to it a parallel hierarchy of names to go with these numbers exists. It is
called as Domain Naming Service (DNS). Just as the four numbers of an IP address describe a
network hierarchy from left to right, the name of an Internet Address, called its domain name,
describes a machines location in a name space, from left to right.
E.g.: www.starwave.com is in the com domain, it is called starwave (after the companys name) and
www is the name of the specific computer that is Starwaves server .www corresponds to the
rightmost number in the equivalent IP address.
The Networking Classes and Interfaces
The classes contained in the java.net package are listed here:
Authenticator (Java 2)

Jar URLConnection (Java 2)

170

SocketPermission

JAVA

St. Angelos Computers Ltd.

ContentHandler

MulticastSocket

URL

DatagramPacket

NetPermission

URLClassLoader (Java 2)

DatagramSocket

PasswordAuthentication (Java 2)

DatagramSocketImpl

ServerSocket

URLDecoder (Java 2)

Http URLConnection

Socket

URLStreamHandler

URLConnetion

The java.net packages interfaces are listed here:


ContentHandlerFactory
FileNameMap

SocketImplFactory

URLStreamHandlerFactory

SocketOptions

InetAddress
Whether you are making a phone call, sending mail, or establishing a connection across the Internet,
addresses are fundamental. The InetAddress class is used to encapsulate both the numerical IP
address we discussed earlier and the domain name for that address. You interact with this class by
using the name of an IP host, which is more convenient and understandable than its IP address. The
InetAddress class hides the number inside Factory Methods. The InetAddress class has no visible
constructors. To create an InetAddress object, you have to use one of the available factory methods.
Factory methods
Factory methods are merely a convention whereby static methods in a class return an instance of
that class. This is done in lieu of overloading a constructor with various parameter lists when having
unique method names makes the results much clearer. In the case of InetAddress, the three methods
getLocalHost(), getByName() and getAllBy Name() can be used to create instances of InetAddress.
These methods are shown here:

static InetAddress getLocalHost()


throws UnknownHostException
static InetAddress getByName(String hostName)
throws UnknownHostException
static InetAddress[ ] getAllByName(String host Name)
thorws UnknownHostException
The getLocalHost() method simply returns the InetAddress object that represents the local host. The
getByName() method returns an InetAddress for a host name passed to it. If these methods are
unable to resolve the host name, they throw an UnknownHostException.

171

JAVA

St. Angelos Computers Ltd.

On the Internet, it is common for a single name to be used to represent several machines. In the
world of web servers, this is one way to provide some degree of scaling. The getAllByName() factory
method returns an array of InetAddresses that represent all of the addresses that a particular name
resolves to. It will also throw an UnknownHostException if it cant resolve the name to at least one
address.
The following example prints the addresses and names of the local machine and two well-known
Internet web sites:

/ / Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main (String args [ ]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost () ;
System.out.println (Address) ;
Address = InetAddress.getByName (starwave.com) ;
System.out.println (Address) ;
InetAddress SW[ ] = InetAddress.getAllByName (www.nba.com) ;
for (int i=0 ; i<SW.length ; i++)
System.out.println (SW[i]) ;
}
}
Here is the output produced by this program. (Of course, the output you see will be slightly
different.)
default / 206.148.209.138
starwave.com / 204.202.129.90
www.nba.com / 204.202.130.223
TCP / IP Client Sockets
There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The
ServerSocket class is designed to be a listener, which waits for clients to connect before doing
anything. The Socket class is designed to connect to server sockets and initiate protocol exchanges.
The creation of a Socket object implicitly establishes a connection between the client and server.
There are no methods or constructors that explicitly expose the details of establishing that
connection. Here are two constructors used to create client sockets:
Socket(String hostName, int port)

Creates a socket connecting the local host to the


172

JAVA

St. Angelos Computers Ltd.

named
host
and
port;
can
throw
UnknownHostException or an IOException.

an

Socket(InetAddress_ipAddress, int port) Creates a socket using a pre-existing InetAddress object and
a port; can throw an
IOException.
A socket can be examined at any time for the address and port information associated with it, by use
of the following methods:
InetAddress getInetAddress()

Returns the InetAddress associated with the


Socket object.

int getPort()

Returns the remote port to which this Socket


object is connected.

int getLocalPort()

Returns the local port to which this Socket


object is connected.

Once the Socket object has been created, it can also be examined to gain access to the input and
output streams associated with it. Each of these methods can throw an IOException if the sockets
have been invalidated by a loss of connection on the Net.
InputStream getInputStream()

Returns the InputStream associated with the


invoking socket.

OutputStream getOutputStream()

Returns the OutputStream associated with the


invoking socket.

void close()

Closes both the InputStream and OutputStream.

URL
The URL provides a reasonable intelligible form to uniquely identify or address information on the
Internet. URLs are ubiquitous every browser uses them to identify information on the Web. In fact,
the Web is really just that same old Internet with all of its resources addressed as URLs plus HTML.
Within Javas network class library, the URL class provides a simple, concise API to access
information across the Internet using UTLs.
TCP / IP Server Sockets
Java has a different socket class that must be used for creating server applications. The ServerSocket
class is used to create servers that listen for either local or remote client programs to connect to
them on published ports. Since the Web is driving most of the activity on the Internet, this section
develops an operational web (http) server.

173

JAVA

St. Angelos Computers Ltd.

ServerSockets are quite different from normal Sockets. When you create a ServerSocket, it will
register itself with the system as having an interest in client connections. The constructors for
ServerSocket reflect the port number that you wish to accept connections on and, optionally, how
long you want the queue for said port to be. The queue length tells the system how many client
connections it can leave pending before it should simply refuse connections. The default is 50. The
constructors might throw an IOException under adverse conditions. Here are the constructors:
ServerSocket(int port)

Creates server socket on the specified port


with a queue length of 50.

ServerSocket(int port, int maxQueue)

Creates a server socket on the specified port


with a maximum queue length of maxQueue.

ServerSocket(int port, int maxQuene,


InetAddress localAddress)

Creates a server socket on the specified


port with a maximum queue length of
maxQueue. On a multihomed host,
localAddress specifies the IP address to which
this socket binds.

ServerSocket has one additional method called accept(), which is a blocking call that will wait for a
client to initiate communications, and then return with a normal socket that is then used for
communication with the client.
Network with Java:
Introduction to Networking
A Network is defined as an interconnection of cooperative and autonomous computers. Simply
having connection is not sufficient in order to say it a network. But the important point is that they
should cooperate with each other to share the information. In order to have this cooperation we
need some software in all the computers that are connected in network. This software is often given
the name networking software. Hence we can broadly say that a network will have two parts namely
hardware and software.
Hardware
There are two types of discussions in the networking hardware. We can say that network
architecture and network topology is the two main points in a computer network. Both are having
the same importance in the design of the network applications. But the problem is that Internet is
not having a strict architecture and protocol. We are studying this only for an idea of networking.
The network architecture defines how the data will be physically sent to the receiver i.e. broadcasting
or point-to-point. If it is broadcast, all the computers in the network will receive the information and
the computer, to which it is intended will only respond. If it is point-to-point the information will be
sent to only those computers which need it. Most of the times broadcasting is used in computer
networks.

174

JAVA

St. Angelos Computers Ltd.

Network topology defines how the computers are physically connected. There are many possible
types of topologies. However we will restrict our self to only the primitive topologies.
The basic topologies are
1) Bus
2) Ring
3) Star
4) Physical star Logical Bus

a) Bus

Server
b) Star

Hub
c) Ring

Computers
d) Physical Star
Logical bus
175

JAVA

St. Angelos Computers Ltd.

In bus topology all the computer are connected to a common bus, which is shared by all the
computers. Whenever a computer wants to send some information it will pass it to bus, through
which it reaches all the computers. Above fig. will give you an idea of bus topology.
In Star Topology all the computers are connected to a central computer called as server. Whenever
there is need of communication server is contacted. Above fig. will give a better idea of star
topology.
In Ring Topology all the computers are connected to form a ring as shown in the fig . To send some
information, a computer will send it to the next computer, which will send it to the next and so on.
When it comes back to the computer that originated it stops. By that time it is assumed that it
reaches all the computers. Here the physical contacts are point to point but the information is
broadcaster.
In Physical Star and Logical Bus topology all the computers are connected to a central place called
HUB, which will internally contain a bus. Above fig. will give a better idea on this type of topology.
Software
In his famous book Inter networking with TCP/IP, Volume 1 comer says that the concept of
networking is first given be Julies Ceaser that is Divide and Rule
In general all the network software is divided into small parts which we call as layers. Each layer is
responsible for a specific type of work. If a layer becomes large it will be divided into sub layers as
well. Different layers in the Internet are shown in the fig. below. Thanks to internet there are no sub
layers. To be frank there are no layers in Internet when it is developed. But for a better
understanding of Internet protocols it is divided into layers by different authors in different ways. As
per Comer there is no division of internet protocols into layers.
Like any other networking software here also each layer is responsible for different works. Work of
each layer is outlined below. How ever we will not be going in depth into this as this is outside of
the scope of our chapter.

Application Layer
(FTP,Telnet etc..)
Transport Layer
(TCP, UDP)
Network Layer
(IP)
Link Layer
(ARP, RARP)

176

Physical Layer

JAVA

St. Angelos Computers Ltd.

1.

Application Layer: This layer will provide the user level services like e-mail, FTP and other
internet services we are aware. These are very high level services we are aware. There are
very high level services and generally every application will have its own services and
protocols.

2.

Transport Layer: Transport layer is responsible for providing all the network functions for
information movement of interchange to the networking programs. Internet provides two
types of services that are TCP and UDP. Generally programs should be aware of only these
protocols, because there is a direct connection from here to the programs. We will discuss
TCP and UDP later in this section.

3.

Network Layer: The network layer functions are provided by the Internet protocol (IP) in
Internet. However we are least bothered about IP because this is having least impact on our
programs. If you want develop new transport level protocols then only you need to know it.
If you want to have good understanding of what is an IP please refer to the book Inter
networking with TCP/IP, Volume 1, by Comer. This layer is responsible for finding an
appropriate route in the network for the packets (information) you are sending. This is
called as routing. Network layer also performs actions like breaking and rejoining the
packets if the following link layers capacity less that what the program is expected. Another
important function of this layer is providing uniformity across all the network adapters.

4.

Link Layer: This layer is responsible for different errors possible in physical communication.
This may use error detection and re-transmission or forward error correction. This is
generally built into the hardware (i.e. Into the network adapter cards we are using).

5.

Physical Layer: Strictly speaking this is not a layer, but for the sake of simplicity it is also
added into the other layers. The physical layer very from a simple serial port connector, to
a complex satellite.

Put together all these 5 layers will form the Internet. You can clearly observe that the work is being
divided and given to different layers. Among these the Network and Transport layers are built into
the Operating system. As I stated earlier, we need to bother about only transport layer functions,
because our program can communicate only with the transport layer.
Lecturer
Lecturer Enters the Hall

Student
Students will stand up with respect and greet
the lecturer
177

JAVA

St. Angelos Computers Ltd.

Lecturer will knot his head and sits down


in his chair

Students also sits in their respective seats

Lecturer starts lesson

Students will listen the lesson and ask any


doubts

Lecturer will clear the doubts


Lecturer ends his lesson

Students will thank lecturer for his lesson

Fig 13.3 A Sample Protocol


Protocol
We are using the term protocol very often. It is always better to have an insight of what it is. Ok,
then what is a protocol?
A protocol is simply a set of rules, which are expected to be followed by every computer in Internet,
or any network to be precise. Fig 13.3 shows a simple protocol example which may help you clarify
any doubts regarding what is a protocol.
Protocols are important part of the software. Each layer will have a number of protocols in it.
The example shows a general protocol between a lecturer and student and every student and
lecturer are expected to follow it. Here you should observe that there is nothing that forces the
lecturer and student to follow the same protocol. But it is generally followed by both students and
lecturers.
The above presented analogy can be used for our networking protocols. Here whenever a computer
needs some information, the possible flow can be like this.
1.
2.
3.
4.
5.
6.

Client sends a request to the server for some information


Server responds with the message what you want.
Client sends what it needs
Server either responds with an error message if the resource is not present, or with the
information that is requested.
Client acknowledges it with the thanks signal
Both server and client close the communication.

This is a general protocol between two computers in network. Whenever there is some
communication between two computers, automatically one delivers the information and the other
receives it. All the network applications are therefore client-server based only.
The protocol use din actual communication between different computers greatly very from
application to application. Design of protocol is based on many parameters that are out of the scope
of this chapter. Some of the parameters could be no. of computers involved, possibility of grouping,
error checking, integrity checking, security etc.
178

JAVA

St. Angelos Computers Ltd.

Port
Generally a computer will have a single network adapter and hence a single connection to the
Internet. Many programs can run simultaneously in the same computer which are accessing the
information from the Internet. In this situation assume that some information is received by the
network adapter. Now the OS should make a choice, that which program needs to access this
information.

Network

Network Adapter
Network Programs
Fig 13.4 Situation of different
programs and a single Network
adapter
To get away with this problem we use the concept of ports. Every incoming information carries
along with it the destination place within the computer also. This is called as the port. All the
programs will be connected to a port and based on the port number in the incoming information it
will be given to the corresponding program. Fig 13.5 explains this solution in a better way.

P
P1

25

80
7
Port no

Network
179

Pn

JAVA

St. Angelos Computers Ltd.

Network Adapter
Network Programs

Fig.13.5 situation of different


programs and a single Network
adapter with port numbers.

If the incoming data is having port number 8, it will be given to the program P1. Similarly if the
incoming data is having port number 25 it will be given to the program P2. And if the port number
is 7 it will be given to the program P.
URLs and URL Connections
A URL Abbreviated as Uniform Resource Locator is used to identify a resource in a network. URLs
will provide you with a general way of identifying different types of resources in the network (i.e.
Internet). In URL we will have three parts namely.
1.
2.
3.

How to get (Protocol)


Where to get (Computer address)
What to get (Exact file name)

However the protocol part and filename part or optional. If you omit the file name part a default file
is sent to you. The exact name of this file is dependent on the computer to which you are presently
connected.
Apart from this, sometimes you may need to identify the exact port in the destination machine to
reach the corresponding server program. (Discussion about ports can be found in the previous
section of this chapter). You can specify a port within a URL after the machine name or address
following a colon(:). The example given below will give you an idea on this.
Example: Sample URLs
http://java.www.com:80/ (The default file name is taken here)
ftp://ftp.microsoft.com:17/msdownlaod/word/patch1.exe
Creating URLs in Java
Java provides you with a way of representation of URLs using the URL class. You can represent URLs
by creating objects of class URL. URLs can be divided into two types namely absolute and relative.
An absolute URL can identify the resource by itself i.e. it contains the complete information to
identify the resource (all the three). However in relative URLs all the three may not present, and they
180

JAVA

St. Angelos Computers Ltd.

depend on some Absolute URL for those. In general, the relative URL contains the file name which is
added to the base URL which is absolute. Given below is an example to clarify this idea as well as
creating URL objects.
Example: Creating Absolute and Relative URLs.
Absolute: URL Ms = new URL(http://www.microsoft.com/);
Relative: URL index = new URL(Ms, index.html);
The above example shows the two basic ways of creating URL Objects. For other ways creating URLs
refer to the API given below.
Java.net.URL

public URL(String spec) throws MalformedURLException Parameters:


Spec : Specifies the URL to be represented

public URL (String protocol, String host, int port, String Filename) throws
MalformedURLException

Parameters:
Protocol : How to get
Host : Where to get (computer name or IP Address)
Port : Port no to be contacted in the destination machine
Filename : What to get (Exact file name in the destination machine)

public URL(String protocol, String host, String Filename) throws Malformed URL Exception

Parameters:
See the above function.

public URL(URL base, string spec) throws Malformed URL Exception


These constructors will create a new URL relative to base. And the relative file name is
taken from the spec.

Parameters:
Base : The base URL
Spec: Specifies file name relative to base.
MalformedURLException:
Each of the four constructors given above can throw Malformed URL Exception. Hence it is advised
that you use the try, catch pair whenever you want to create a URL Object.

181

JAVA

St. Angelos Computers Ltd.

Note: URLs are write-once objects. Once you create an URL Object you cant change it.
Using a URL Object:
You can get the individual components of a URL using the following functions.
Java.net.URL

public String getProtocol( )


public String getHost( )
public int getPort( )
public String getFile( )

You can display the URL using the toString function provided in the URL class.
Reading URLs:
Reading URLs is as easy as reading from local files in your machine. The procedure of reading the
URL is outlines below.
1.
2.
3.

Create a URL Object to represent the URL from which you want to read.
Call the openStream method of URL class to open the remote resource, like you open your
file. This will return you the object of type InputStream.
Read the network resource as if you read from a file i.e. use the read method of

InputStream.
4.

Close the remote resource using the close method of the InputStream.

Below given is an example to show how you can read from a remote file.
Example : Reading from a URL

import java.net.*;
import java.io.*;
class URLTest1 {
public static void main(String args[])
{
try {
URL sun = new URL(http://Java.sun.com/);
InputStream is = sun.openStream( );
try {
while(c = is.read( ) != -1) System.out.println((char)c);
}
182

JAVA

St. Angelos Computers Ltd.

catch(IOException e) { }
finally {
is.close( );
}
}
catch(MalformedURLException
System.out.println(MalformedURL :+e);
}
catch(Exception e)
{
System.out.println(Some other Exception : =e);
}
}
}
Java.net.URL

public final InputStream openStream( ) throws IOException


Opens the remote URL and returns InputStream which enables you to read from the
remote resource.

URL Connections
The advanced way of using the URLs is provided using the URL Connections. A URL Connection can
establish communication between two programs in the network. You can clearly see that there is a
tremendous difference between reading a URL and establishing URL Connection. The first one can
simply read something from network, but the second can really do wonders. Study fig 13.7 to get a
preliminary overview of URL Connection.

URL
Connection
Client

Server

183

JAVA

St. Angelos Computers Ltd.

Program
represented
by URL

Your
class file

Fig 13.7 URL Connection primary overview


A URL Connection does the following.
1.
2.

Start a program in the server.


Divert the standard output of the server side program into the client side program using an
InputStream.

Pass on the standard input of the server side program from the client program using an
OutputStream.
Fig 13.7 is modified and redrawn in Fig 13.8 to clearly explain this scenario.

Client

Server
OutputStream

Standard
Input

URL
Connection

Your
class file
InputStream

Standard
Output

Program
represente
d by URL

184

This is your
program

This program is started


by URL Connection

JAVA

St. Angelos Computers Ltd.

The procedure of using the URL Connections is outlined in the procedure given below.
1.

Create an URL Object that represent the program you want start in the server side.

2.

Start the program using the openConnection in the URL Class, which will return the
URLConnection Object.

3.

Pass standard input to the server side program using the OutputStream, which you can get
using the getOutputStream method of the URLConnection class. After you finish passing all
the parameters close the Output Stream.

4.

Get the standard output of the server side program using the getInputStream method of
the URLConnection class.

5.

At the end of close the input stream.

Note: It is important to see that the program you have started in the server side will terminate when
you close the streams. It should be done by you, and there is no automatic mechanism to take care
of this.
A program example is given below which may help you understand the procedure given above. More
than the procedure the concept should be clear here. Writing program in the server side is fairly
simple. To read the network input, read from standard input and to write into network just write
into the standard output. In the client side to write into the network use the output stream
extracted, and to read from the network read from the InputStream extracted from URLConnection
object.
In the example given below we assume the presence of a program in the server side, which will read
line by line and reverse each of the line read and write reversed line to the standard output. The
name of this program is backwards which is present in ogi-bin directory in the server. We will try to
send a string given as command line arguments to the server side program and display whatever
comes from the server side program. This may look like a simple reverse string program when you
run it. Please dont see the output but see the procedure involved in doing this. The difference is
that, we are running a program in server to reverse your string.
Example: Using URL Connections

import java.io.*;
import java.net.*;
185

JAVA

St. Angelos Computers Ltd.

public class netreverse {


public static void main(String args[ ])
{
try {
if(args.length != 1) {
System.err.println(One argument required);
System.exit(0);
}
URL url = new URL(http://java.sun.com/cgi-bin/backwards);
URLConnection c=url.openConnection( );
PrintStream os = new PrintStream(c.getOutputStream( ));
outstream.println(String = +argv[1]);
outstream.close();
String inputline;
DataInputStream is = new DataInputStream(c.getinputStream));
while((inputLine = inStream.readLine( ))!=null)
{
System.out.println(inputline);
}
instream.close( );
}
catch(MalformedURLException me )
{
System.err.println(URLException : +me);
}
catch(Exception e)
{
System.err.println(Exception : +e);
}
}
}
Sockets
You have already seen the amazing simplicity of the network programming in java using the URLs
and URL Connections. However not all problem can be solved with the URLs and URL Connections.
For these type of problems java provides an answer using sockets. Sockets provide a reliable stream
transport service between two computers in the internet. This section covers the sockets in depth.

186

JAVA

St. Angelos Computers Ltd.

Fig 13.9 gives an analogy between an electric socket and network socket. Like we can have any
number of electric sockets within a house, we can have any number of network sockets within a
computer. Like we have a single connection to Electricity Board, we have a single connection to the
Internet in general.

Electric
socket

Programs
Network
Socket

Information

Each socket is attached


one and only
one program.
However
a single
program can have more than
Fig 13.9to: Analogy
between
electric and
network
sockets
one socket attached to it. With this you may feel that there is some similarity between port and a
socket. In fact there is a relation between the two. A socket is an encapsulation of port and functions
that operate on it. Most of the time in java we are not worried about port nos. and other details. It
is taken care of. Only thing to be remembered is that a socket is your door to get the information
from internet. Both URLs and URL Connections internally use these sockets only.
Though fig 13.9 s a good analogy there are some differences between the two. When we use electric
power we are not bothered about from which place the energy is coming from. It is because, from
whatever place it comes energy is the same, but the information is not. Information coming from
Microsoft is definitely different from that of SUN. The first one talks about Active X, while the other
talks about Java.
Hence one important thing in sockets is that, it needs to be connected to some computer in the
Internet to be meaning full. Naturally it connects to a socket in the other machine. (Dont get
confused, by simples socket we always mean a network socket. At least as long as we are talking in
187

JAVA

St. Angelos Computers Ltd.

term of JAVA). Because of this reason we always call Sockets as half sockets. Fig 13.10 shows two half
sockets (or) a single connection between two computers.

Connection

Socket
Programs
Fig 13.10 A Connection and 2 half sockets

Concept of sockets is very important if you want to write network application. A URL can be used if
and only if the protocol presently exists. And there are only a few protocols that are accepted in a
URL. But if you want to have your own protocol, or if the protocol is not accepted by the URL?
Dont worry, sockets are there to help you.
Next important point in sockets is every socket will certainly have a program, which reads from it
and writes into it. We are going to use InputStreams and OutputSreams only for this purpose.
Finding the Server
The first and foremost problem in networking programs is finding the server program, which will
process your requests. We should first of all identify a program in the server machine, which is
designated to service our requests. Here we should observe the fact that all the programs in the
network are client server model only. Always there is server running which is waiting for requests.
The clients will come up and go down but the server remains the same. We can put it in another
way like this. In all network applications, we find two sort of programs where the first one delivers
information and the second one receives it.
Let us come back to our problem of identifying the server program on the destination machine. How
we can identify a program in the destination in general? Using the port numbers. Here is also the
same case. We use port numbers to identify the particular program in the destination computer. As
soon as the server program starts on some machine it acquires a standard port no. These port
numbers are standardized across the internet. Whenever a client program starts it tries to contact
through the same port number. We can say that both client and server programs will agree on some
special port numbers. Figure 13.11 will give a listing of commonly used port numbers.

Protocol

Port

HTTP

80

TELNET

23

ECHO

188

JAVA

St. Angelos Computers Ltd.

Accepting Requests
Not only clients, we need to write servers often. If you want to write a server program, the first
thing we should do is accept requests. To accept requests the procedure is fairly simple. Start a
listener socket on the predefined port. This is only a half socket and there is no connection
established. Whenever you receive something in that port, treat it as a request and start processing
that request. Once you have got a request it will become a full connection.
However, if the client is talking with server for too much time, the listener socket will not be
available for other requests. And we can only serve a single connection. Then what about the
requests from other clients? To solve this, java will not use the same socket. Rather it creates a new
socket, passes the new socket address to the client. From now onwards the communication is
between the new socket and the client, leaving the listener socket free.
Not only socket, even our software should be ready to accept new requests. Hence we will create a
new thread for each request, which will serve that particular request leaving the original thread
ready to receive further requests. Because of this reason, to write network programs you should be
good in threads. There is no way out.

189

JAVA

St. Angelos Computers Ltd.

Types of Sockets
In the previous sections we have seen the different implications involved in establishing
communication between two programs using sockets. In that process you can observe that, there are
two types of sockets present. The first one is used in communication and the other is used to accept
the requests. You may feel that we can divide sockets into two broad categories. In fact it is, and
there are two classes in Java to represent these two types of sockets.
1.

Socket: This is half part of a full connection and used at one end of the communication.
The other side is also expected to have the same type of socket.

2.

ServerSocket: This is to accept requests from the client. This is the listener socket, we have
discussed earlier. We call it a server socket because it will be used only when we want to
write network programs.

We use Socket at the client end, and we use both Socket and ServerSocket classes to write the server
program. Next section describes an outline of writing both server and client programs.
Building client server programs for internet
Using the information above we can outline the procedure of writing Client/Server programs for
internet. The simple steps are as follows:
Client Program
1.
2.
3.
4.
5.
6.
7.

Make necessary initialization for your program. This greatly depends on the particular
program.
Start a full connection socket. To start a full connection socket call the constructor of the
Socket class, passing the destination computer and the port number in that computer.
Extract the InputStream from socket, to read messages from the server. To extract the
InputStream make use of the getInputStream method of the Socket class.
Start a reader, passing this InputStream to start a new thread, which will act according to
the information coming from the server. It needs to accept the commands coming from the
server program.
Extract OutputStream from socket, which can be used to send messages to the server. To
extract the OutputStream call the getOutputStream method of the Socket class.
The main thread running will make use of this stream to send any information to server,
and the information sent is based on the user actions.
At the end close both the streams. The server automatically recognizes this and closes its
connection.

Server Program
1.

Make necessary initialization for your program. This greatly depends on the particular
program.

190

JAVA

2.
3.
4.

5.
6.

7.

St. Angelos Computers Ltd.

Create the listener socket, which can accept requests. To create a listener socket, create an
object of type ServerSocket by calling its constructor. In this constructor we should give the
mutually agreed port no.
Start accepting requests from the clients. To start accepting requests, call the accept
method of the ServerSocket class.
As soon as a request is accepted the accept function will return a full connection Socket,
which can be used for normal communication. Automatically the listener socket is free and
ready for accepting new requests. (However a ServerSocket will accept requests only if it is
running accept method.
Extract the OutputStream and InputStream from the returned socket using the
getInputStream and getOutputStream methods of the Socket class.
Depending of the application you need to start one or two threads. If your start one thread
it is responsible for communication in both ways through the socket. Use this only if there
are no servers initiated transfers. (Which is the most often case). If you start two treads,
each thread is responsible for communicating in one direction. Use this if there are server
and client initiated transfers.
Go to step 3 to accept the new connections.

Because the threads will stop automatically at the end of the request, there is no extra care taken for
clean up. However as the final step of each thread created, some clean up may be required.
The Socket API in Java
This section will give all the API details required to write the programs with sockets (I.e. TCP
protocol). Basically two classes are described here which are Socket and ServerSocket.
java.net.Socket

public Socket(String host, int port) throws


UnknownHostException, IOException

Creates a new socket, which is connected to the computer specified by the host (you can give either
an IP Address or an host name) and the port specified.
Parameters:
host the host name.
port the port number.
Throws:
IOException if an I/O error occurs when creating the socket.
UnknownHostException if the host cant be found in the network.

public Socket(InetAddress address, int port,


InetAddress localAddr, int localPort)
throws IOException

191

JAVA

St. Angelos Computers Ltd.

Creates a socket and connects it to the specified remote address on the specified remote port. The
Socket will also bind() to the local address and port supplied. The InetAddress Class is discussed in
the section Working With Datagrams. This constructor will not throw the HostUnknownException
because it is taken care by the InetAddress class.
Parameters:
address the remote address
port the remote port
localAddr the local address the socket is bound to
localPort the local port the socket is bound to

public InputStream getInputStream() throws IOException

Returns an input stream for this socket. This input stream is connected to the socket on the other
side as its output stream.
Returns: An input stream for reading bytes from this socket.
Throws: IOException if an I/O error occurs when creating the input stream.

public OutputStream getOutputStream() throws IOException


Returns an output stream for this socket.

Returns: An output stream for writing bytes to this socket.


Throws: IOException if an I/O error occurs when creating the output stream.

public InetAddress getInetAddress()


Returns the address of the host to which the socket is connected.

Returns: The remote IP address to which this socket is connected.

public InetAddress getLocalAddress()


Gets the local address to which the socket is bound.

public int getPort()


Returns the remote port to which the socket is connected.

Returns: The remote port number to which this socket is connected.

public int getLocalPort()


Returns the local port to which this socket is bound.

Returns: The local port number to which this socket is connected.

public void close() throws IOException


192

JAVA

St. Angelos Computers Ltd.

Closes this socket.


Throws: IOException if an I/O error occurs when closing the socket.
java.net.ServerSocket

public ServerSocket(int port) throws IOException

Creates a server socket on a specified port. A port of 0 creates a socket on any free port. The
maximum queue length for incoming connection indications (a request to connect) is set to 50. If a
connection indication arrives when the queue is full, the connection is refused.
Parameters:
port the port number, or 0 to use any free port.
Throws: IOException if an I/O error occurs when opening the socket.

public Socket accept() throws IOException

Listens for a connection to be made to this socket and accepts it. The method blocks until a
connection is made.
Throws: IOException if an I/O error occurs when waiting for a connection.

public InetAddress.getInetAddress()
Returns the local address of this server socket.

Returns: The address to which this socket is connected, or null if the socket is not yet connected.

public int getLocalPort()


Returns the port on which this socket is listening.

Returns: The port number to which this socket is listening.

public void close() throws IOException


Closes this socket.

Throws: IOException if an I/O error occurs when closing the socket.


Writing Client Programs Using Sockets (/Examples)
In this sub-section we will see how to write client program using sockets. This sub-section will show
two basic examples, where the first one is intended to show you how to read from the server and
the second one will demonstrate how one can send information to the server.
193

JAVA

St. Angelos Computers Ltd.

Our first example Qotd (Quotation of the day) client is intended to read a quotation from the server
and display it in the client. For this it opens a connection with the server program on port 17 and
extracts the input stream from the socket. Once the input stream is extracted the quotation is read
and displayed in the client.
Example: Reading from the server using sockets

import java.net.*;
import java.io.*;
public class Qotd
{
public static void main(String[] arg)
{
Socket es=null;
DataInputStream is=null;
try{
es=new Socket(server1, 17);
is=new DataInputStream(es.getInputStream());
}
catch(Exception e)
{
System.err.println(e);
}
if(es!=null && is!=null )
{
try{
String userInput;
while(userInput=is.readLine())!=null)
{
System.out.println(userInput);
}
is.close();
es.close();
}
catch(Exception e)
{
System.err.println(e);
}
}
}
}
The second example given below is an echo client. This will read the information from the client and
send it to the server. And then the response of the server is just displayed on the screen.
194

JAVA

St. Angelos Computers Ltd.

Example: Echo program (Reading from and writing to server)

import java.net.*;
import java.io*;
public class Echo
{
public static void main(String[] arg)
{
Socket es=null;
PrintStream os=null;
DataInputStream is=null;
DataInputStream stdIn=new
DataInputStream(System.in);
try{
es=new Socket(server 1, 7);
is=new
DataInputStream(es.getInputStream());
os=new PrintStream(es.getOutputStream());
}
catch(Exception e)
{
System.err.println(e);
}
if(es!null && os!=null && is!=null)
{
try{
String userInput;
while(
(userInput=stdIn.readLine())
!-null)
{
os.println(userInput);
String serverInput is.readLine();
System.out.println(echo: + serverInput);
}
os.close();
is.close();
es.close();
}
catch(Exception e);
{
System.err.println(e);
}
195

JAVA

St. Angelos Computers Ltd.

}
}
}
Writing Server programs using sockets (Examples)
This sub-section shows how to write the server program in Java. We will start with a simplest server
program and go till a complex server program. In this process we will see four servers. The first
server is the simple Qotd (Qotation of the day) server, which shows you how to send information to
the client. The second example is echo server which will show you how to read information and send
the same to the client. The third example is a simple file transfer server, which will take input a
filename from client and send the contents of the file as the response. The final example is same as
third one except that it how takes care of any no of requests simultaneously by implementing multi
threading
Let us have a look at the first server program, the Qotd server. In this server, we will first start a
listener socket on port no 8182 and start accepting requests. As soon as a request is accepted, server
will send a quotation to the client. Server program assumes that the quotation to be passed to the
client is given in the command line.
Example: Qotd Server (Sending information to client)

import java.net.*;
import java.io.*;
public class qotdser
{
public static void main(String args[])
{
ServerSocket ss=null;
try
{
System.out.println(Creating a server socket . . );
ss=new ServerSocket(8 182),
System.out.println(Done);
}
catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
while(true)
{
try
{
System.out.println(Waiting for a connection . . .);
Socket s=ss.accept();
196

JAVA

St. Angelos Computers Ltd.

PrintStream ps=new PrintStream(s.getOutputStream());


System,out.println(Passing the quote. . .);
for(int i=0; i<args.length; ++i)
ps.print(args[i] + );
ps.println();
ps.close();
s.close();
}
catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
}
}
}
Second example we will see is an echo server, which will read the information and send the same
thing back to the client. Writing this is easier and source code for this is given below.
Example: Echo sever (Reading and sending information to the client)

import java.net.*;
import.java.io.*;
public class echoser
{
public static void main(String args[])
{
ServerSocket ss=null;
try {
System.out.println(Creating a server socket . . );
Ss=new ServerSocket(8182);
System.out.println(Done);
}
catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
while(true)
{
try {
System.out.println(Waiting for a
connection . . . .);
Socket s=ss.accept();
PrintStream ps=new PrintStream(
197

JAVA

St. Angelos Computers Ltd.

s.getOutputStream());
InputStream is=s.getInputStream();
Int ch;
while((ch=is.read())!= -1)
{
ps.print((char)ch);
System.out.print((char)ch;
}
ps.close();
is.close();
}
catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
}
}
The next example shows how to use this communication for a simple useful purpose. This example
will read the filename from the client and send back the file contents to the client.
Example: Simple file transfer server

import java.net.*;
import java.io.*;
public class ftpser {
public static void main(String args[]) {
ServerSocket ss=null;
try {
System.out.println(Creating a server socket . . );
ss=new ServerSocket(8 182);
System.out.println(Done);
}
catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
while(true)
{
try {
System.out.println(Waiting for a connection ...);

Socket s=ss.accept();
PrintStream ps=new PrintStream(
198

JAVA

St. Angelos Computers Ltd.

s.getOutputStream());
DataInputStream ds=new DataInputStream(
s.getInputStream());
int ch;
String.fn=ds.readLine();
System.out.println(fn);
InputStream is=new FileInputStream(fn);
while((ch=is.read())!= -1) {
ps.print((char)ch);
}
ds.close();
ps.close();
is.close();
}
catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
}
}
}
The example program given above can be used to transfer files. However there are some important
points to be considered. The first problem is if the file is not there, server will exit the program
because of the exceptions. Further it can service only one client at a given time. If the file is long and
there is transfer from a remote place then it will take a long time, may be hours together. In such
cases other clients will loose a chance to get files from the server for that amount time. To solve this
we should introduce the concept of the multi-threaded server.
Given below are the steps that should be followed to easily implement these multi-threaded servers.
Each step is discussed in detail, after which a multi-threaded version of the above program is
presented. The steps given are just a single way to multi-thread your server. Yet there are some
more methods which are not discussed here. However basic understanding of the concept is
important here.
The basic idea is that, we will have a class, which serves the requests, which is extended from thread.
As soon a request comes, a new object of the service is created and thus a new thread is started.
1.

Create the service class, which takes the socket as the argument for its constructor, which
is extended from the Thread class.
a.

Store the socket that is passed as an argument to the constructor in some local
variable for future use. Because the only information that is present regarding the
client to whom a service is required is the newly created socket, either directly or
199

JAVA

St. Angelos Computers Ltd.

indirectly this information needs to be passed to the service object being created. In
general the socket is directly passed. Otherwise the socket is stored in an array and in
index to that array is passed. In an extreme case, we will have two threads running
simultaneously on the same socket, in which case the inputstream of socket is passed
to one thread and the outputstream to the other thread. This happens if they are both
server initiated and client initiated operations.

2.

b.

Override the run( ) method of the Thread class and code how to service the requests
in the method. Every rime a request is to be processed a new object of this service is
called and a new thread is started by calling the start() method of the thread class.
Hence it is appropriate to write how to service the request in the run() method.
However we need not bother about how to stop the thread. Since we will be keeping
only how to service in the run( ) method, as soon as the servicing of a particular
request is complete, the run method will return back which will automatically
terminate the thread.

c.

In the run method one may have to extract the streams from the socket and start
communication, if they are not already extracted. The actual protocol is implemented
in the run method of the service class. And at the end of the run method we have to
close the Streams and the socket.

In the server(or the server program) class the only modification needed is to start a new
service thread as soon as a request is accepted. The following code fragment shows how it
can be achieved.
ServerSocket ss = new ServerSocket(1111);
Socket s = ss.accept();
(new Service(s).start();
In this example the newly created thread is not assigned to any variable. In case you want
to control the threads being created, you may need to store all the threads (Service
Objects) in an array, so that they can be controlled later. A classical example is a chat
server, where information from one client needs to be transmitted to all other clients. In
such cases, we need to keep track of all the threads presently active so that the information
from one client can be passed to all the service objects.

3.

To control the amount the multi-threading (no of threads) in your server, you need a static
variable in your service class which is initialized to zero, which will keep track of no of
threads presently running. As soon as a request is accepted, then we have to check the no
of threads presently running. In case we are running less no of threads then the maximum
allotted, we can increment this number and start a new thread. In the run method of the
service () class we will decrement the value by one before coming out.

An example is given below to make this idea concrete. In this example we have service class which
extends Thread, and accepts the socket as the argument. And the protocol (how to service) is
implemented in the run () method. It uses the same code fragment shown above to implement the
multi-threading. However there is no control on the no of threads created.

200

JAVA

St. Angelos Computers Ltd.

Working with Datagrams


For most of the programs using sockets is a better way since they provide reliable and stream
oriented transportation service. However this will pose some overhead on the network for
retransmissions and acknowledgements, with which the reliability is ensured. Further more it is some
times not possible to design our protocols with Sockets, since they are connection oriented, you will
have atleast one and exactly one opposite side. The classical example is multi-casting. To solve such
problems a transportation service is provided at a low end, which is nothing but the UDP (User
Datagram Protocol) service. UDP service extends the IP to include ports and hence, it increases the
reachability of the information upto programs, rather than upto computer (Reachability upto
computers is solved by IP address).
To use UDP service using Java two basic classes are provided namely DatagramSocket and
DatagramPacket. DatagramSocket is also like ordinary socket, but now it is not connected to any
other socket. A Datagram Socket is just a means of sending and receiving information in the form of
packets. In case of UDP, a DatagramSocket is a true encapsulation of port into a class. On the other
hand any information that needs to be transmitted is formed to make a DatagramPacket, which can
be sent on the DatagramSocket.
To identify the destinations a class called InetAddr is provided which will consist of the name and IP
address of the destination. To create a InetAddr you cant call the constructor of it, however two
static methods are provided which can be used to create new InetAddr objects namely getByName ()
and getByAddr ().
One important thing here is that there is not guarantee that the information you are submitting to
the UDP will reach the destination. There is no confirmation or acknowledgment. Furthermore, the
information may reach the destination in any order.
Sending Data With UDP
To send data with UDP you have to create a DatagramSocket on some arbitrary port and formulate
a Datagrampacket. After you have a packet it can be sent to any destination using the socket. The
steps for doing are outlined below.
1.

Create a DatagramSocket by calling its constructor. You need not pass any parameters since
you need not create the socket on a specified port.

2.

Create a DatagramPacket which is bound to an destination address. Here the packets are
bound to destination unlike the case of sockets, where sockets are bound to destination. To
create a DatagramPacket call its constructor by passing the data as a byte array and the
destination address as a InetAddr and also the destination port.

3.

Call the send method of the socket created and pass the packet created.

Following is a code fragment that shows this.


DatagramSocket ds = new DatagramSocket();
201

JAVA

St. Angelos Computers Ltd.

DatagramPacket p = new DatagramPacket(data, InetAddr.getByName(server), 56);


ds.send(p);
Receiving Data with UDP
To receive data in UDP you need to create a socket to receive the information (probably) on a
accepted port no). Then you need to create an empty packet to receive the information and call the
receive method of socket. However note that the receive method is a blocking call, i.e. it keeps on
waiting till it receives a UDP packet. In JDK 1.1 onwards however you can set a timeout. The steps for
receiving a packet are outlined below.
1. Create a DatagramSocket on some port number, by passing the port number as the
argument. However there are some cases where we will not pass any port no when creating
the socket and still we can receive the information from it.
2. Create an empty DatagramPacket by passing a byte array to be used with the maximum
length of that byte array.
3. Call the receive method of the socket to receive the information.
The code fragment given below will show this:
byte[] x=new byte[1000];
// this can hold 1000 bytes
DatagramSocket ds = new DatagramSocket(100);
DatagramPacket p = new DatagramPacket(x,1000);
ds.receive(p);
Writing a UDP Server
To create a UDP server create a DatagramSocket on a specific port so that clients can send their
requests. A request is nothing but a DatagramPacket. This packet may contain any parameters of
that request. For example a UDP File Transfer Server may receive the file name in the packet being
sent as the request. Once the request is received it should be processed as usual. Steps to do this are
outlined below.
1.
2.
3.
4.
5.
6.
7.
8.

Create a DatagramSocket on a specified port.


Create an empty socket to receive the requests.
Call the receive method to listen for requests.
Once a packet is received extract the client address by calling the functions getAddr() and
getPort() to know the address and port of the client program.
Process the request based on the parameters in the packet received.
Create a new packet as the response.
Send the response by calling the send method of the socket created in the first step.
Go to step 3 to receive further requests.

Optionally you can multi-thread the server like the case in sockets. In which case before accepting
the new request, you may need to create a new empty packet, since the parameters in the old packet
202

JAVA

St. Angelos Computers Ltd.

are in use by the thread created to serve the request. And to the service class you need to pass the
packet (request) received so that thread can act based on the parameters in the request.
Writing a UDP Client
To write a UDP client you need to create a DatagramSocket which will be used to send the request.
Once the request is sent, server will give back its response to the same socket. So you need to create
an empty packet and receive the information from the server. The steps to do this are outlined
below.
1.
2.
3.
4.
5.
6.

Create a DatagramSocket by calling its constructor. You need not pass the port number
since the socket can be on any port.
Create a packet that represents your request, and keeps all the parameters required in the
same packet. The actual parameters differ from server to server you are going to connect.
While creating the packet pass the address and port number of the server in the
constructor.
Send the packet to its destination (i.e. to the server) by calling the send () method of the
socket.
Create an empty socket to receive the information (response of the server).
Call the receive () method to get the actual response.

public DatagramSocket() throws SocketException

Constructs a datagram socket and binds it to any available port on the local host machine.
Throws:
SocketException if the socket could not be opened, or the socket could not bind to the specified
local port.

public DatagramSocket(int port) throws SocketException

Constructs a datagram socket and binds it to the specified port on the local host machine.
Parameters:
local port to use.
Throws:
SocketException

public void send(DatagramPacket p) throws IOException

Sends a datagram packet from this socket. The DatagramPacket includes information indicating the
data to be sent, its length, the IP address of the remote host, and the port number on the remote
host.
Parameters:
p the DatagramPacket to be sent.
203

JAVA

St. Angelos Computers Ltd.

Throws:
IOException if an I/O error occurs.

Public synchronized void receive(DatagramPacket p) throws IOException

Receives a datagram packet from this socket. When this method returns, the DatagramPackets
buffer is filled with the data received. The datagram packet also contains the senders IP address, and
the port number on the senders machine.
This method blocks until a datagram is received. The length field of the datagram packet object
contains the length of the received message. If the message is longer than the buffer length, the
message is truncated.
Parameters:
p the DatagramPacket into which to place the incoming data.
Throws:
IOException if an I/O error occurs.

Exercise
1.

What is a protocol? Explain TCP/IP and HTTP protocol?

2.

What do you understand by socket? What are the basic classes that are necessary to build
network application?

3.

Explain Client/Server model? What is a proxy server?

4. What is an IP address? Which class is used for finding the IP address of your system?
5. Write a program to find out the IP address of the Computer?
6. What are the different network topologies?
7.

What is an URL? Which class is used for creating a URL and what is the possible Exception
in creating a URL?

8. Write a program for client server communication at port 7002?


9. What is the Userdatagram protocol ? What is difference between UDP and TCP/IP ?
10. Write a program to send a data through UDP ?

204

JAVA

St. Angelos Computers Ltd.

Chapter - 11
JDBC
The database is the most important component of a companys Information Services infrastructure.
It is the heart of the applications on which a company depends for its survival. Any programming
language must be able to provide an application with access to this database if it is to be considered
a serious programming language.
Before the release of the Java 1.1 API, database support in Java was extremely weak. Instead of
releasing a halfway solution in the original release, JavaSoft took the time to develop a set of key APIs
centered around enterprise systems development. Among these APIs Java 1.1 includes JDBC (Java
Database Connectivity), a unified API for accessing relational databases.
The issues surrounding database access are often very difficult, other languages use either
proprietary APIs specific to individual database or complex universal APIs such as ODBC. Before
even starting to program, though, you must weed through data modeling and database design. This
chapter does not attempt to address these issues; instead, it focuses on using the JDBC API to
provide your Java applications with database access.
The JDBC API
To provide a common base API for accessing data, Sun (with support from a number of
independent software vendors) developed JDBC. JDBC defines a number of Java interfaces to enable
developers to access data independently of the actual database product being used to store the data.
In theory, an application written against the basic JDBC API using only SQL-2 can function against
any database technology that supports SQL-2.
JDBC:

Access
Driver
Application

ODBC
Driver
Manager

SQL
Driver
ODBC Application Architecture

ODBC Application Architecture

JDBC
Driver
Manager

JDBCODBC
Bridge
Driver

Access
Driver

205

MS Access
Database

MS SQL
Database

St. AngelosMSComputers Ltd.

JAVA

ACCES
S

Applica
tion

SQL
Driver

Database
MS-SQL
Database

JDBC Application Architecture


Installing the ODBC Driver:
Steps for Configuring the ODBC Driver
1.

Click on the ODBC Data Sources icon in the control panel.

2.

Click on the ADD button in the ODBC Data Source Administrator dialog box.

206

JAVA

St. Angelos Computers Ltd.

3.

Select the SQL Server option from the list and click on Finish in the Create New Data
Source dialog box.

4.

Type a name for the data source in the Name text box, specify the name of the server you
want to connect to, and then, click on the Next button.

207

JAVA

St. Angelos Computers Ltd.

5.

Select the WITH SQL Server authentication using login ID and password entered by the
user option from the Microsoft SQL Server DSN Configuration dialog box and then click on
the Next button.

6.

Select the database that you want to use and click on the Next button.

208

JAVA

St. Angelos Computers Ltd.

7.

Click on the Finish button.

8.

Click on the Test Data Source to check for the proper connectivity with the database and
then click on OK to end the ODBC set up.

209

JAVA

St. Angelos Computers Ltd.

Once the ODBC driver is configured, your Java application can use the driver to communicate with
the database.
Database Requirements
Data can be stored in a wide variety of formats using various technologies. Most systems currently
use one of three major database management systems:

Relational database (RDBMS)


Object-oriented relational database (OORDBMS)
Object-oriented database (OODBMS)

Relational databases are overwhelmingly the most common. In addition to these systems, there are
other things to consider, such as hierarchical database and file systems. Any low-level API trying to
find a least common denominator among these data storage methods would end up with the null set.
JDBC, however, mandates no specific requirements on the underlying DBMS. Rather than dictating
what sort of DBMS an application must have to support JDBC, the JDBC specification places all its
requirements on the JDBC implementation.

210

JAVA

St. Angelos Computers Ltd.

The JDBC specification primarily mandates that a JDBC implementation support at least ANSI SQL-2
Entry Level. Because most common RDBMS and OORDBMS systems support SQL-2, this
requirement provides a reasonable baseline from which to build database access. In addition, because
SQL-2 is required only at the JDBC implementation level, that implementation can provide its own
SQL-2 wrapper around non-SQL data stores. Writing such a wrapper, however, likely would be a
huge task.
The JDBC Interfaces
JDBC defines eight interfaces that must be implemented by a driver in order to be JDBC- compliant:

java.sql.Driver
java.sql.Connection
java.sql.Statement
java.sql.PreparedStatement
java.sql.CallableStatement
java.sql.ResultSet
java.sql.ResultSetMetaData
java.sql.DatabaseMetaData

The JDBC object model


The central object around which the whole concept revolves is the java.sql.DriveManager object. It is
responsible for keeping track of the various JDBC implementations that might exist for an
application. If, for example, a system were aware of Sybase and Oracle JDBC implementations, the
DriverManager would be responsible for tracking those implementations. Any time an application
wants to connect to a database, it asks the DriverManager to give it a database connection, using a
database URL through the DriverManager.getConnection() method. Based on this URL, the
DriverManager searches for a Driver implementation that accepts the URL. It then gets a Connection
implementation from that Driver and returns it to the application.

What Is a Database URL?


To enable an application to specify the database to which it wants to connect, JDBC uses the
Internet standard Uniform Resource Locator system. A JDBC URL consists of the following pieces:
jdbc:<subprotocol>:<subname>
As with URLs youve seen all the Internet, the first element is the resource protocol--- in this case, a
JDBC data cases, it is the DBMS implementation. In many cases, it is the DBMS name and version;
for example, syb10 indicates Sybase System 10. The subname element is any information specific to
the DBMS that tells it. where it needs to connect. From SQL, the JDBC URL is in this format:
jdbc:msql://hostname:port/database
211

JAVA

St. Angelos Computers Ltd.

JDBC itself does not care what a database URL looks like. The important thing is simply that a
desired JDBC implementation can recognize the URL and get the information it needs to connect to
a database from that URL.
The DriverManager is the only instantiated class provided by JDBC other than exception objects and
a few specialized subclasses of java.util.Date. Additional calls made by an application are written
against the JDBC interfaces that are implemented for specific DBMSs.
The java.sql.Driver Interface
A Driver is essentially a Connection factory. The DriverManager uses a Driver to determine whether
it can handle a given URL. If one of the Drivers in its list can handle the URL, that Driver should
create a Connection object and return it to the DriverManager because an application only indirectly
references a Driver through the DriverManager, applications are rarely concerned with this interface.
The java.sql.Connection Interface
A Connection is a single database session. As such, it stores state information about the database
session it manages and provides the application with Statement, PreparedStatement, or
CallableStatement objects for making calls during the session.

The java.sql.Statement Interface


A Statement is an unbound SQL call to the database. It is generally a simple UPDATE, DELETE,
INSERT, or SELECT statement in which no columns must be bound to Java data. A Statement
provides methods for making such calls and returns to the application the results of any SELECT
statement or the number of rows affected by an UPDATE, DELETE, or INSERT statement.
Statement has the subclass PreparedStatement, which is in turn subclassed by CallableStatement is a
precompiled database call that requires parameters to be bound. An example of a PreparedStatement
is a stored procedure call that has no OUT or INOUT parameters. For stored procedure with OUT
or INOUT parameters, an application should use the CallableStatement inteface.
The java.sql.ResultSet Interface
An application gets data returned by a SELECT query through the implementer of the
java.sql.ResultSet interface. Specifically, the ResultSet object enables an application to retrieve
sequential rows of data returned from a previous SELECT call. TheResultSet provides a multitude of
methods that enable you to retrieve a given row as any data type to which it make sense to convert
it. For example, if you have a date stored in the database as a datetime, you can retrieve it through
the getString () method and use it as a String.
The Meta-Data Interfaces

212

JAVA

St. Angelos Computers Ltd.

Meta data is data about data. Specifically, it is a set of data that gives you information about the
database and data retrieved from the database. Java provides two meta-data interfaces:
java.sql.ResultSetMetaData and java.sql.DatabaseMetaData. The ResultSetMetaData interface
provides a means for getting information about a particular ResultSet. For example, among other
things, ResultSetMetaData provides information on the number of columns in the result set, the
name of a column, and its type. The DatabaseMetaData interface, on the other hand, gives the
application information on the database in general, such as what levels of support it has, its name,
version, and other bits. It is rare that you will actually need to use the DatabaseMetaData class
because most of the information it provides is useful only to automated tools such as VisualCafe and
Jbuilder.

Simple Database Access Using the JDBC Interfaces


An application for which database independence is paramount should be written to the JDBC
specification, using no database-specific calls and using only SQL that is part of the ANSI SQL-2
standard. In such code, no reference should be made to a specific implementation of JDBC. Writing a
simple database application using only. JDBC calls involve the following steps:
1.
2.
3.
4.
5.
6.
7.
8.

Ask the DriverManager for a Connection implementation.


Ask the Connection for a statement or subclass of Statement to execute your SQL.
For subclasses of Statement, bind any parameters to be passed to the prepared statement.
Execute the statement.
For queries, process the result set returned from the query. Do this for each result set (if
you have multiple result sets) until there are none left.
For other statement, check the return value for the number of rows affected.
Close the statement.
Process any number of such statements and then close the connection.

The Counter Applet Example


A simple sample applet that demonstrates bare database connectivity is a common Web counter. A
Web counter is an applet that keeps track of how many times a given Web page has been hit or
accessed. Using the JDBC interfaces, this applet connects to a database, determines how many times
the page on which it appears has been hit, updates the page to reflect the new hit, and finally
displays the number of hits. To use this example, you need a database engine to run your database
and a JDBC driver to access that database engine. If you do not have a database engine, download
mSQL and JDBC, which are both free for noncommercial use. Links to mSQL and the JDBC class are
located at http://www.imaginary.com/Java/. In addition, you need to create a table called t_counter
with the fields counter_file (CHAR(100), PRIMARY KEY) and counter_num (INT,NOT NULL). The
following mSQL script creates the table:
DROP TABLE t_counter\p\q
CREATE TABLE t_counter(
counter_file

CHAR(100)
213

PRIMARY KEY,

JAVA

St. Angelos Computers Ltd.

counter_num

INT

NOT NULL

)\p\q
The applet consists of two classes: Counter and Database. The Counter class is the subclass of the
Applet class that provides the user interface to the applet. It contains two instance variables. One,
count, is the number this applet is supposed to display-the number of page hits. The other, database,
is an instance of the Database class that provides wrappers for the JDBC access needed by the
applet.
The Counter class does not define any new methods; it simply overrides the java.applet.Applet.init()
and java.applet.Applet.paint() methods. The init() method is used to create a Database instance and
find out from it what the page-hit count is for display. The paint () method displays the page-hit
count.
The interesting JDBC-related work is all encapsulated inside the Database class. It has a single
instance variable, connection, which is an instance of a JDBC Connection implementation. The
connection variable is initialized in the Database class constructor:

public Database (String url, String user, String pass)


throws java.sql.SQLException {
connection =
DriverManager.getConnection (url, user, pass) ;
}
By getting an instantiated Connection object, the applet is ready to do whatever database access it
needs to do.
The applet uses the getCount () method to figure out how many page hits this particular access to
the Web page represents. That seemingly benign query actually represents several steps:
1.
2.
3.
4.
5.

Create a Statement object.


Formulate and execute the SELECT query.
Process the result.
Increment the hit count.
Format and execute an UPDATE or INSERT statement.

Lets look at a program to create table.


Before you start off, you have to create a SQL driver, which will be used by your java program.
Steps to be followed to create your own driver
Go to start menu, select settings, select control panel, click on ODBC Data drivers (32bit)
Choose User DSN click on add
Choose SQL Server and click ok
Enter name and select server to be [local] and click next.
Choose SQL Server authentication, enter user name and password (may be blank) and
click next.
214

JAVA

St. Angelos Computers Ltd.

At this stage you can change your default database (i.e. master) to any other database of
your choice and click next .
Click on finish
Click on test data source you will see a screen with a command Test completed
successfully click ok and your driver is ready.
The name you have chosen will be used in your SQL programs.
Example of creating a table:

import java.sql.*;
public class Create
{
public static void main(String args[])
{
String url=jdbc:odbc:abc;
String q=create table students (rollno int, stuname varchar(40),div varchar(2));
Statement stmt;
Connection con;
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
}
catch(ClassNotFoundException ce)
{
System.out.println(ce);
}
try
{
con=DriverManager.getConnection(url,sa,);
stmt=con.createStatement();
stmt.executeUpdate(q);
stmt.close();
con.close();
}
catch(SQLException se)
{
System.out.println (se);
}
System.out.println(Table Created);
}
215

JAVA

St. Angelos Computers Ltd.

}
Compile the program
javac Create.java
Run the program
java Create
o/p
Table created.
A table students will be created in master database of SQL Server 7.0 with three columns namely
rollno, stuname and div.
Lets have a look at how the program works:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver) is used to load and register the drivers.
DriverManager.getConnection(url,sa,) is used to connect to your own driver. createStatement()
creates a statement object for sending SQL statements to the database. executeUpdate() executes an
SQL CREATE, INSERT, UPDATE or DELETE statement. In addition, SQL statements that return
nothing can be executed.
stmt.close() and con.close() release statement and connection object's database and JDBC resources
immediately instead of waiting for this to happen when it is automatically closed. It is generally good
practice to release resources as soon as you are finished with them to avoid tying up database
resources.
Example of selecting value from a table

import java.sql.*;
public class SelectTest
{
public static void main(String a[]) throws Exception
{
try
{
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Connection conn=DriverManager.getConnection(jdbc:odbc:abc,sa,);
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(use xyz select
empno, empname, job, salary, hiredate from emp);
while (rs.next())
{
int eno=rs.getInt(1);
String name =rs.getString(2);

216

JAVA

St. Angelos Computers Ltd.

String job =rs.getString(3);


float salary =rs.getFloat(4);
Date d=rs.getDate(5);
System.out.println(emp no:+ eno+ name: + name+ job:+ job+
fsalary:+salary + Join Date: + d);
System.out.println();
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException e)
{
System.out.println(Error is: + e);}
}
}
}
Compile the program
javac SelectTest.java
Run the program
java SelectTest.java
o/p:
emp no:1 name: aaa job:manager fsalary:100000.0 Joi1n Date:2000-12-12
emp no:2 name: aaa job:clerk fsalary:10000.0 Joi1n Date:2000-12-12
Lets have a look at how the program works:
Drivers are loaded and registered as explained in the previous program.
Connection is established.
executeQuery() executes a SQL statement that returns a single ResultSet. We are using xyz database
instead of master and want to select empno, empname, job, salary, hiredate from the table emp
existing in xyz database.
A ResultSet provides access to a table of data. A ResultSet object is usually generated
by
executing a Statement. A ResultSet maintains a cursor pointing to its current row of data. Initially
the cursor is positioned before the first row. The 'next' method moves the cursor to the next row.
The getXXX (e.g. getInt for integer value etc.) methods retrieve column values for the current row.
You can retrieve values using either the index number of the column or the name of the column. In

217

JAVA

St. Angelos Computers Ltd.

general, using the column index will be more efficient. Columns are numbered from 1. Close the
resultset, statement. connection to free the resources.
Now lets solve an example, which lets the user choose what he wants i.e., create a table, insert values
into the table, select the value from the table or exit from the program.
According to the option he chooses, the particular method will be executed. When you run the
program input the name of the table you want to create and three columns of data types int, string,
string respectively.

import java.sql.*;
import java.io.*;
class InsTest12
{
String opno=;
String tabname,col1,col2,col3;
Connection conn;
PreparedStatement pst;
DataInputStream bf=new DataInputStream(System.in);
InsTest12(String tb,String c1,String c2,String c3)//constructor
{
tabname=tb;col1=c1;col2=c2;col3=c3;
System.out.println(Constructor is called);
try{
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
//load and register driver
conn = DriverManager.getConnection(jdbc:odbc:bhav,sa,);
//connection
}
catch(Exception aaa)
{
aaa.printStackTrace();//to display an error message.
}
}//constructor over
public static void main(String a[])
{
if(a.length !=4)
{
System.out.println(usage is:java filename <table name> <Column
name1> <Column name2> <Column name3>);
218

JAVA

St. Angelos Computers Ltd.

System.exit(0);
}
bf=new DataInputStream(System.in);
String tbn=a[0];
String cl1=a[1];
String cl2=a[2];
String cl3=a[3];
InsTest12 ins=new InsTest12(tbn,cl1,cl2,cl3);
ins.option();
}//main over
void option()
{
System.out.println(if you want to create a table type a:)
System.out.println(if you want to insert row into the table type b:);
System.out.println(if you want to retrieve data from table type c:);
System.out.println(if you want to exit from programm type e:);
try
{
opno =bf.readLine();
if(opno.equals(a))
{
createTable();//user defined method getting called
option();//user defined method getting called
}
if(opno.equals(b))
{
int i=insertValue();//user defined method getting called
System.out.println(i+ Value inserted:);
option();
}
if(opno.equals(c))
{
selectTable();//user defined method getting called
option();
}
if(opno.equals(e))
{
219

JAVA

St. Angelos Computers Ltd.

System.out.println(Bye);
pst.close();
conn.close();
System.exit(0);
}
}
catch(Exception ne)
{
System.out.println(ne);
System.exit(0);
}
}
int insertValue() throws IOException//user defined method
{
int rows=0;
try
{
System.out.println(Give a number to insert in table);
System.out.println(Give a string name to insert in table);
System.out.println(Give a string job to insert in table);
String en=bf.readLine();
String ena=bf.readLine();
String jb=bf.readLine();
pst = conn.prepareStatement(Insert into + tabname
+(+col1+,+col2+,+col3+)
values(+en+,+ena+,+jb+)); rows
=pst.executeUpdate();
}
catch(SQLException e)
{
System.out.println(Error is: + e);
}
return rows;
}
void createTable()//user defined method
{
try
{
pst = conn.prepareStatement(create table +tabname+(+col1+
int,+col2+ varchar(20),+col3+ varchar(20)));
pst.executeUpdate();
220

JAVA

St. Angelos Computers Ltd.

System.out.println(Table Created);
}
catch(SQLException e)
{
System.out.println(Error is: + e);
}
}
void selectTable()//user defined
{
try
{
String sql=select * from + tabname;
Statement stmt=conn.createStatement();
ResultSet rs= stmt.executeQuery(sql);
ResultSetMetaData rsmd =rs.getMetaData();
int cols=rsmd.getColumnCount();
for(int i=1;i<=cols;i++)
{
System.out.print(rsmd.getColumnName(i)+\t);
}
System.out.println();
while (rs.next())
{
System.out.println(rs.getInt(1) + \t+rs.getString(2)
+\t+rs.getString(3));
}
rs.close();
}
catch(SQLException e)
{
System.out.println(Error is: + e);}
}
}
Compile the program
javac InsTest12.java
run the program
java InsTest12 tab rn en j
221

JAVA

St. Angelos Computers Ltd.

o/p
Constructor is called
if you want to create a table type a:
if you want to insert row into the table type b:
if you want to retrieve data from table type c:
if you want to exit from programm type e:
a
Table created
if you want to create a table type a:
if you want to insert row into the table type b:
if you want to retrieve data from table type c:
if you want to exit from programm type e:
b
Give a number to insert in table
Give a string name to insert in table
Give a string job to insert in table
3
xyz
clerk
1 Value inserted:
if you want to create a table type a:
if you want to insert row into the table type b:
if you want to retrieve data from table type c:
if you want to exit from programm type e:
c
rn
3

en
xyz

j
clerk

if you want to create a table type a:


if you want to insert row into the table type b:
if you want to retrieve data from table type c:
if you want to exit from program type e:
Bye

222

JAVA

St. Angelos Computers Ltd.

Exercise
1.

What is Java DataBase Connectivity?

2.

What are the different kinds of drivers in JDBC? Explain in brief?

3.

Write down the various steps to make a connection to the database?

4. How do you create a DSN?


5. What is the difference between Statement and PrepareStatement ?
6. What are the possible exceptions found in making a connection to the database?
7.

What are the methods to get the number of columns in a database table?

8. What is the transaction? What are the services transaction offers?


9. What are the necessary packages to be imported for jdbc connectivity ?
10.

Explain ResultSet interface?

223

JAVA

St. Angelos Computers Ltd.

Chapter - 12
JAVA.UTIL PACKAGE
Introduction
In OOP languages data and methods are encapsulated. In Java these encapsulation leads to classes.
In this Chapter we study how to organize the data, especially when we have large volume of data
manipulate. Efficient management leads to better memory utilization as well faster retrieval speeds.
Just as in traditional programming in Java to we have data structures. Data structuring is important
to developing serious applications. The following data structures are covered in detail.

Vectors
Bitsets
Hash tables
Linked Lists
Stacks
Multidimensional Arrays

Vector
Vector is like arrays but with a variable array size For example, you use vectors when you are not
sure how many elements your array would contain as the applications needs grow. Similarly if you
have declared an array to contain 20 elements, and you need to use only one element in that object,
the vectors will re-size itself to save memory. Therefore vectors can grow or diminish in size as the
need arises. The vectors relocate and re-size themselves. There are two other differences between
vectors and arrays.

Arrays can hold any type primitive data types as well as class objects.
Vectors can hold objects only.
To hold primitive data types in vectors, the primitive data types must be cast using object
wrappers.

Declaring a Vector
Vector books = new Vector (3);
Initially vector holds no elements. You can add elements to it in the constructor. The above Vector
book is made to hold three books. Later you can insert more books to the list. You can allocate more
elements by giving a capacity increment. The methods given below explain how to use vectors.

java.util.Vector

224

JAVA

St. Angelos Computers Ltd.

Constructor:
public Vector ( )
: This constructs an empty vector. By default
the capacity doubles whenever current capacity has exceeded.

public Vector ( int initial capacity ) : You specify the initial storage capacity of the vector.
Example: Vector Books = new Vector ( 3 );

public Vector ( int initial capacity, int capacityIncrement )


: This constructs an empty
vector with an initial capacity and which subsequently expand in steps of capacityIncrement.
Example: Vector Books = new Vector ( 3, 5 );

Methods:

public final void addElement ( Object obj )


element is the last one in the vector.

: This adds an element to vector and the new

Example: Books.addElement ( new Book ( ABC of Java ) );


Constructing the object.

public final int size ( )


: This returns the number of elements in the vector, which can
never be larger than the capacity.

Example: Books size ( ) ;

public final void trimToSize ( )


thus releasing memory.

: This method shrinks the vector to its current size,

Example: Books.trimToSize ( );

public final void setElementAt ( Object o, int index ): This method places the object o at
the position specified by the index. It overwrites previous contents. The index must be
between 0 and one less than capacity.

Example: Books.setElementAt ( Book1, 3 );

public final Object elementAt ( int index ) : This returns the object stored at the specified
index. The index must be between 0 and size 1.

Example: Books cookbook = Books.elementAt ( 3 );

public final void insertElementAt (Object o, int index) : This inserts the element at the
index position and shifts up all elements above it. No elements are overwritten.

225

JAVA

St. Angelos Computers Ltd.

Example: Books.insertElementAt ( cookbook, b );

public final void removeElementAt ( int Index ) : This method removes the element from
specified index location. All elements above it are shifted down.
Example: Books.removeElementAt ( 3 );
Important Note: A vector has objects of the class Object set at and inserted into it. But while
returning the elements one should be careful and cast the returned object into the user defined one.
One has to be especially careful when using vectors to store primitive data types. Corresponding
Object wrappers must be used while getting elements from the vectors.
Example: double x = ( (Double) Marks.elementAt ( 5 )).doubleValue;
Casting Vector

Statement

Value of the double

Example:

import java.util.*;
import Granada.*;
public class My Vector
{
public static void main(String[] args)
throws java.io.IOException
{
char c;
String s, sl;
int j;
Vector v=new Vector();
do
{
System.out.println(1. Putting an element to
Vector);
System.out.println(2. Retrieving an element from Vector);
System.out.println(3.Removing an element from Vector);
System.out.println(4. Exiting from Vector);
System.out.println(Enter Your Choice);
int i=Input.readInt();
switch(i)
{
case 1:
System.out.println(Enter any String to be placed in Vector);
s=Input.readString();
v.addElements(s);
break;
case 2:
226

JAVA

St. Angelos Computers Ltd.

System.out.println(Enter the Index);


j=Input.readInt();
System.out.println(element at that index is +(String)v.elementAt(j));
break;
case 3:
System.out.println(Enter the Index for
removing element);
j=Input.readInt();
v.removeElementAt(j);
break;
case 4:
System.exit(0);
default:
System.out.println(Invalid Choice.
Try again. );
}
}while(true);
}
}
Bitset
The BitSet is a class in Java that stores a sequence of bits. It is similar to an array of bits except that
the bits in BitSet class are internally stored as bytes. This packing of bits and storing the sequence as
bytes makes BitSet more efficient. Handling of individual bits in this class is far easier. BitSet can be
used when you wish to store a series of flags.
Constructor:
public BitSet ( int n )
Example :
BitSet pnos = new BitSet ( 10 );

: Constructs a BitSet with n bits.

Methods:
public Boolean get ( int n )
Example :

: Returns the nth bit.


pnos.get ( n );

public void set ( n )


Example :

: Sets the nth bit to true. (That is 1)


pnos.set ( n );

public void clear ( int n )


Example :

: Makes the bit at n false (That is 0)


pnos.clear ( n );

227

JAVA

St. Angelos Computers Ltd.

public void and ( BitSet set )

: Performs a logical AND with the


BitSet called set and another BitSet.

Public void or ( BitSet set )

: Performs a logical OR with BitSet


set.

public void xor ( BitSet set )

: Performs a logical XOR with the BitSet set.

Sample Program: To find prime numbers using a BitSet

import java.util.*;
import Granada.*;
public class MyBitSet
{
public static final Boolean PRINT= false;
public static void main ( String[] s) throws java.io.IOException
{
System.out.println(Enter a Number);
int n = Input.readInt();
BitSet b = new BitSet ( n );
int count = 0;
int i;
for ( i = 2; i <= n; i++ )
b.set ( i );
i = 2;
while ( i * i <= n )
{
if ( b.get (i ) )
{
if(PRINT)
System.out.println(i);
count++;
int k = 2 * i;
while(k<=n)
{
b.clear(k);
k+=i;
}
}
i++;
}
while ( i <= n)
{
if ( b.get ( i ) )
{
if ( PRINT ) System.out.println ( i );
228

JAVA

St. Angelos Computers Ltd.

count++;
}
i++;
}
System.out.println ( The number of primes Between 1 to +n+ is.+count);
}
}
Hash Tables
Suppose you have a large amount of data to store, for example a list of books in a large library, then
you should not only have an efficient way of storing them, but also a very fast retrieval system. The
most efficient way to retrieve this information is with the help of an identification number for each
of the items stored. As an example, a book on English literature could have a unique identifier like
E_Lit_9001. This unique identifier is called a key. However, internally Java will assign integer to this
key, which is called a hash code. All this data stored in the form of an array with a key and a
corresponding hash code is called a hash table.
The way Java creates the hash code and the manner the actual data is stored is immaterial to the
user. All that the user needs to know that a particular item is stored at the corresponding location
provided by the key.
The hash table is created as below.
Hashtable Books = new Hashtable ( );
Just as in Vectors, Hash tables store only objects. And as in the case of Vectors, you must cast the
return value of get () to the correct type. Hash table methods came under the .util package.
java.util.Hashtable

Constuctor:
public Hashtable ( )
Example : private Hashtable Books = new Hashtable ( );

: Constructs an empty hash table.

public Hashtable ( int initialCapacity )


: Constructs an empty hash table with an
initial capacity. By giving the initial capacity you can improve the performance of the hash
table.
Example : Hashtable Books = new Hashtable ( 211 );

public Hashtable ( int initialCapacity, float loadFactor ) : This constructs an empty hash
table with the initial capacity and the load factor.

Load Factor

229

JAVA

St. Angelos Computers Ltd.

A load factor is a value between 0 and 1 that determines when the hash table should enlarge itself to
accommodate more objects. The default value is 0.75, which means when the items in a hash table
load up to 75% of its capacity, and then Java automatically doubles the capacity by allocating a larger
table. This greatly enhances the performance by reducing collisions. Collisions occur when two or
more keys have the same hash code, which is possible.
Methods:

public Object get ( Object key ): Returns the object identified with the key, null if no key is
found in the table.
Example : Book 1 = ( Books ) Book.get ( E_Lit_9001 );
Or Book2 = ( Books ) Book.get ( s );
Where s is the string which stores the key.

public Object put ( Object key, Object value ) : This places the object value at the location
specified by the key. This method return a null if the key is not present and if the key is
present, then the new object replaces the old one.
Example : Books.put ( E_Lit_9001, Book1 );

public Object remove ( Object key )


: This methods removes both the key and the
associated object. It a null if no key present.
Example : Book.remove ( E_Lit_9001 );

public int size ( )


elements contained in the hash table
Example: i = Book.size ( );

public int hashCode ( )


: This returns the hash code for this object.
This integer can be positive or negative number. Equal objects returns same hash codes.
You can define your own hash code for your own defined class.
Example:
class Books
{
public int hashcode
{
return bookTitle.hashValue ( );
}
}

: This method returns the number of

Here the hashValue() method returns an integer of the class Books which can be allotted the hash
code.
Sample Program:

import java.util.*;
import granada.*;
230

JAVA

St. Angelos Computers Ltd.

public class MyHashTable


{
public static void main(String[] args) throws java.io.IOException
{
char c;
String s, s1;
Hashtable ht=new Hashtable();
do
{
System.out.println(1. Putting an element to hashtable);
System.out.println(2. Retrieving an element from hashtable);
System.out.println(3. Removing an element from hashtable);
System.out.println(4. Existing from hashtable);
System.out.println(Enter Your Choice);
int i=Input.readInt();
{
case 1:
System.out.println(Enter any String to be place in Hashtable);
s=Input.readString();
System.out.println(Enter the key );
s1=Input.readString();
ht.put(s1,s);
break;
case 2:
System.out.println(Enter the key);
s1=Input.readString();
System.out.println(element with that key is+(String)ht.get(s1));
break;
case 3:
System.out.println(Enter the key for removing element);
s1=Input.readString();
ht.remove(s1);
break;
case 4:
System.exit(0);
default:
System.out.println(Invalid Choice.Try again. );
}
}
while(true);
}
231

JAVA

St. Angelos Computers Ltd.

}
Enumeration
Enumeration is an interface that can be used to store keys retrieved from a hash table. Take the case
of the Books hash table. It could consist of millions of books. To retrieve these objects efficiently we
need to have the keys for these. Enumeration provides the interface that can store these keys, and
then you can have the actual method that uses this interface to retrieve the data.
Example : Enumeration e = Books.element ( );
The interface Enumeration methods are described below. These come under the util package.
Methods:

Java.util.Enumeration

public abstract Boolean hasMoreElements ( ) : This method returns true if there are more
elements in the enumeration.
Example :
e.hasMoreElements ( );

public abstract Object nextElement ( )


element in the enumeration.

: This methods returns the next

public Enumeration Keys ( )


traverses the keys of the hash table.

: This returns an object that

public Enumeration elements ( )


:
This method returns an object of the type
enumeration that traverses the elements of the hash table. When the enumeration object
has all elements of the hash table, you can pass this object to a method that actually
returns data. This method doesnt have to know the origin of Enumeration object.
Example:
Enumeration e = Books.elements ( );

This method can also be used to return enumeration objects of a vector. Java.util.Vector
Example: Enumeration b1 = Books.elements ( );
( Here Books is a vector. )
Properties
Properties is a class in the Java.util package. You use this class to create properties. Properties are
structures that are basically hash tables. They are useful to
a) allow the user to customize applications,
b) specify configuration option for programs.
What this means is that when the user wants his application to run in a particular manner, he can
do so using the settings of the properties. The default settings in the Properties object will be used if
the user doesnt specify settings of his own. Similarly, the user can set up the configuration options
for this program. These could include, for example, the variables in an autoexec.bat file for DOS.

232

JAVA

St. Angelos Computers Ltd.

java.util.Properties

Constructor:

Properties ( )
Example:

: This creates an empty property list.


Property settings = new Properties( );

Properties( Properties defaults)


: This creates an empty property list with a set of
defaults.
Example: Property settings = new Properties( defaultSettings );

Methods:
getProperty(String key)
this property list.

: Searches for the property with the specified key in

getProperty(String key, String defaultValue): Searches for the property with the
specified key in this property list.

list(PrintStream)
stream.

: Prints this property list out to the specified output

list(PrintWriter)
stream.

: Prints this property list out to the specified output

load(InputStream)

property Names()
: Returns an enumeration of all the keys in this property list,
including the keys in the default property list.

save(OutputStream, String) : Stores this property list to the specified output stream.

: Reads a property list from an output stream.

Here an example of the Properties set. Java stores information about your system in a Properties
object that is returned by a method of the System class. The following code prints out the key value
pair in the Properties object that stores the system properties.
Sample Program:

import java.util.*;
public class SystemInfo
{
public static void main(String args[])
{
Properties ss=System.getProperties();
Enumeration enum=ss.propertyNames();

233

JAVA

St. Angelos Computers Ltd.

while(enum.hasMoreElements())
{
String key=(String)enum.nextElement();
System.out.println(key + value is +ss.getProperty(key));
}
}
}
Date
The Date class encapsulates the current date and time. Before beginning our examination of Date, it
is important to point out that it has changed substantially from its original version defined by Java
1.0. When Java 1.1 was released, many of the functions carried out by the original Date class were
moved into the Calendar and DateFormat classes, and as a result, many of the original 1.0 Date
methods were deprecated. Java 2 adds a few new methods to the time and date classes, but
otherwise implements them in the same form as did 1.1. Since the deprecated 1.0 methods should not
be used for new code, they are not described here.
Date supports the following constructions:
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 nondeprecated methods defined by Date are shown in Table 16-3. With the
advent of Java 2, Date also implements the Comparable interface.
/ / Show date and time using only Date methods.

import java.util.Date;
class DateDemo {
public static void main (string args []) {
/ / Instantiate a Date object
Date date = new Date ();
/ / display time and date using toString()
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);
}
}
Sample output is shown here:
234

JAVA

St. Angelos Computers Ltd.

Mon Jan 25 15:06:40 CST 1999


Milliseconds since Jan. 1, 1970 GMT = 917298400228
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. This is one aspect of the Java class library that enables you to write programs that can operate
in several international environments. An example of such a subclass is Gregorian Calendar.
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.

/ / 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};
/ / Create a calendar initialized with the
/ / current date and time in the default
/ / locate and timezone.
Calendar calendar = Calendar.getInstance ();
/ / Display current time and date information.
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) );
/ / Set the time and date information and display it.
235

JAVA

St. Angelos Computers Ltd.

calendar.set (Calendar.HOUR, 10);


calendar.set (Calendar.MINUTE, 29);
calendar.set (Calendar.SECOND, 22);
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) );
}
}
Sample output is shown here:
Date: Jan 25 1999
Time: 11:24:25
Updated time: 10:29:22

236

JAVA

St. Angelos Computers Ltd.

Exercise
1.

What is the difference between Vector and Array?

2.

Write a program to store some objects in Vector with initial capacity 10 and if the number
of objects is greater than the initial capacity, the Vector has to expand?

3.

What are the benefits Bitset class offers than the array of bits?

4.

Which method is used for Adding two Bitset objects?

5.

Explain HashTable ? What is the Hash code ?

6.

What is the Load Factor?

7.

What is the Enumeration? Which method is used to retrieve the data from the
Enumeration?

8.

Write a program to get the properties of the system?

9.

Vector is __________.

10. Enumeration is a class. (true/false)_______.

237

JAVA

St. Angelos Computers Ltd.

Chapter 13
JAVA SWING
This lesson will give you a quick introduction to using the Swing packages to create a programs GUI.
First, it tells you what the Swing is. Next, it helps you get the necessary releases and use them to
compile and run a Swing program. Then it shows you how to run applets. Finally, it takes you on a
whirlwind tour of a simple Swing application.
Swing is a diverse selection of light weight components that can be used to build sophisticated User
interfaces, Swing components are an enhancement to the existing Abstract Window Toolkit (AWT).
Swing components range from basic controls such as buttons, check boxes, scrollbars and sliders to
complex widgets like text panes and editor panes.
Swing features and Concepts
Swing provides many standard GUI components such as buttons, lists, menus, and text areas, which
you combine to create your programs GUI. It also includes containers such as windows and tool
bars.
Containers use layout managers to determine the size position of the components they contain.
Borders affect the layout of Swing GUIs by making Swing components larger. You can also use
invisible components to affect layout.
We will discuss the features of Swing one by one:
Layout Management
The following figures show the GUls of five programs, each of which displays five buttons. The
buttons are identical, and the code for the programs is almost identical. So why do they look so
different? That is because they use different layout managers to control the size and position of the
buttons.
Layout management is the process of determining the size and position of components. By default,
each container has a layout manageran object that performs layout management for the
components within the container. Components can provide size and alignment hints to layout
managers, but layout mangers have the final say on the size and position of those components. The
Java platform supplies five commonly used layout managers
BorderLayout, BoxLayout, Flowlayout, GridBagLayout, and GridLayout. These layout managers are
designed for displaying multiple components at once and are shown in the figure below. A sixth
provided class, CardLayout, is a special-purpose layout manager used in combination with other
layout managers.
Different Layout Management Schemes
Lets look at each layout Manager in detail by understanding how they are put to use.

238

JAVA

St. Angelos Computers Ltd.

Every container, by default, has a layout manager an object that implements the LayoutManager
interface. If containers default layout manager doesnt suit your needs, you can easily replace it with
another one. The Java platform supplies layout managers that range from the very simple
(FlowLayout and GridLayout) to the special purpose (BorderLayout and CardLayout) to the very
flexible (GridBagLayout and BoxLayout). This section gives you an overview of some layout managers
that the Java platform provides, gives you some general rules for using layout managers. and then
tells you how to use each of the provided layout mangers. It also points to examples of using each
layout manager.
FlowLayout
FlowLayout is the default layout manager for every Jpanel. It simply lays out components from left to
right, starting new rows if necessary.
The FlowLayout class provides a very simple layout manager that is used, by default, by JPanels. The
above applet shows a flow layout in action.
FlowLayout puts components in a row, sized at their preferred size. If the horizontal space in the
container is too small to put all the components in one row, FlowLayout uses multiple rows. Within
each row, components are centered (the default), left-aligned, or right-aligned as specified when the
FlowLayout is created.
Below is the code that creates the FlowLayout and the components it manages.
Container contentPane =getContentPane();
contentPane.setlayout(new FlowLayout();
contentPane.add(new Jbutton(Button 1));
contentPane.add(new JButton((2));
contentPane.add(new Jbutton(Button 3));
contentPane.add(new Jbutton(Long-Named Button 4));
contentPane.add(new Jbutton(Button 5));
The FlowLayout API
The FlowLayout class has three contructors:
public FlowLayout()
public FlowLayout(int alignment)
public FlowLayout(int alignment,
int horizontalGap, int verticalGap)
The alignment argument must have the value FlowLayout. LEFT, FlowLayout.CENTER, or
FlowLayout. RIGHT: The horizontalGap and verticalGap arguments specify the number of pixels to
put between components. If you dont specify a gap value, FlowLayout uses 5 for the default gap
value.
BorderLayout:

239

JAVA

St. Angelos Computers Ltd.

BorderLayout is the default layout manger for every content pane. A BorderLayout has five areas
available to hold components: north, south, east, west, and center. All extra space is placed in the
center area. Heres an applet that puts one button in each area:
BorderLayout
As the preceding applet shows, a BorderLayout has five areas: north, south, east, west, and center. If
you enlarge the window (i.e. it means that when this Layout manager is used in a full window then
the CENTER portion will use the maximum area of the window. the CENTER area gets as much
of the available space as possible. The other areas expand only as much as necessary to fill all
available space. Often, a container uses only or- two of the areas of the BorderLayoutjust the
center, or center and south, for example.
The following code creates the BorderLayout and the components it manages.
JButton b1=new JButton(Button1);
JButton b2=new JButton(Button2);
JButton b3 = new JButton(Button3);
JButton b4= new JButton(Button4);
JButton b5 = new JButton(Button5);
setSize(400,400);
Container c=getContentPane();
c.add(b3,Borderlayout.EAST);
c.add(b2,Borderlayout.WEST);
c.add(b1,BorderLayout.NORTH);
c.add(b4, BorderLayout.SOUTH) ;
c.add(b5,Borderlayout.CENTER) ;
It is important to note one thing that when adding a component to a container that uses
BorderLayout, specify the components location as one of the arguments to the add method. Do not
rely on the component being added to the center, by default. If you find that a component is missing
from a container controlled by a BorderLayout, make sure that you specified the components
location and that you dont put another component in the same location. When using BorderLayout
specify the component as the first argument to the add method. For example:
add(component, BorderlLayout.CENTER) //preferred
There are other alternative ways of achieving the same results as above
add(BorderLayout.CENTER! component) //valid but old-fashioned
or
add(Center , component)
//valid but error prone
Although the above fragment of codes are valid, but they are more error prone.
The BorderLayout API
240

JAVA

St. Angelos Computers Ltd.

By default, a BorderLayout puts no gap between the components it manages. In the preceding
example, any apparent gaps are the result of the button reserving extra space around their apparent
display area. You can specify gaps (in pixels) using the following constructor,
BorderLayout(int horizontalGap, int verticalGap)
void setHgap(int)
void setVgap(int)
You can also use the last two methods to set the horizontal and vertical gaps, respectively.
BoxLayout
The Swing package include a general purpose layout manager named BoxLayout either stacks its
components on top of each other (with the first component at the top) or places them in a tight
row from left to right-your choice. You might think of it as a full-featured version of FlowLayout.
Figure above demonstrates using BoxLayout to display various components:

BoxLayout
A BoxLayout arranges components either from top to bottom or from left to right. As it arranges
components, the box layout takes the components alignments and minimum, preferred, and
maximum sizes into account. In this section, well talk about top-to-bottom (Y axis) layout. The same
concept applies to left-to-right layout. You simply substitute X for Y, height for width, and so on.
When a BoxLayout lays out components from top to bottom, it tries to size each component at the
components preferred height. If the amount of vertical space is not ideal, the box layout tries to
adjust each components height so that the components fill the available amount of space. However,
the components might not fit exactly since BoxLayout respects each components requested
minimum and maximum heights. Any extra space appears at the bottom of the container.
The figure shows a GUI that uses two instances of BoxLayout. In the top part of the GUI a top-tobottom box layout places a label above a scroll pane. In the bottom part of the GUI, a left-to-right
box layout places two buttons next to each other. A BorderLayout combines the two parts of the GUI
and ensures that any excess space is given too the scroll pane.
The following code, lays out the GUI. This code is in the constructor for the SampleFrame, which
extends from JFrame as superclass.
import javax.swing.*;
import java.awt.*;
class SampleFrame extends JFrame
{
public static void main(String a[])
{

241

JAVA

St. Angelos Computers Ltd.

SampleFrame f=new SampleFrame (Layout);


f.show();
}
SampleFrame (String t)
{
super(t) ;
setSize(300,300)
JScrollPane listScroller = new JScrollPane();
listScroller.setPreferredSize(new Dimension(250,80));
listScroller.setMinimumSize(new Dimension(250,80));
listScroller.setAlignmentX(0);
//Layout the label add scroll pane from top to bottom.
JPanel listPane = new JPanel();
listPane.setlayout(new BoxLayout(listPane,1));
JLabel label = new JLabel(LabelText) ;
listPane.add(label);
listPane.add(Box.createRigidArea(new Dimension(0,5)));
listPane.add (listScroller);
listPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
//Layout the buttons from left to right.
JPanel buttonPane = new JPanel( );
buttonPane.setlayout(new BoxLayout(buttonPane,0) );
buttonPane.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
createHorizontalGlue()) ;
buttonPane.add(new JButton(cancelButton)) ;
buttonPane.add(Box.createRigidArea(new Dimension(10,0)));
buttonPane.add(new JButton(setButton));
//Put everything together, using the content panes BorderLayout.
Container contentPane= getContentPane();
contentPane .add(listPane, BorderLayout.CENTER) ;
contentPane.add(buttonPane.BorderLayout.SOUTH);
}

buttonPane.add(Box.

}
This first bold line creates top-to bottom box layout and sets it up as the manage: for listPane. The
two arguments to BoxLayout constructor are the container that it manages and the axis along with
the components will be laid out. The next three bold lines add the label and scroll pane to the
container, separating them with a rigid areaan invisible lightweight component used to add space
242

JAVA

St. Angelos Computers Ltd.

between components. In this case, the area has no width and puts exactly 5 pixels between the label
and scroll pane.
The next chunk of bold code creates a left-to-right box layout and sets it up for the buttonpane
container. Then the code adds two buttons to the container, using a rigid area to put 10 pixels
between the buttons. To make the buttons be placed at the right side of their container, the first
component added to the container is glue. This is an invisible lightweight component that grows as
necessary to absorb any extra space in its container.
CardLayout:
CardLayout helps you manage two or more (usually Jpanel instances) that share the same display
space. Another way to accomplish the same thing is to use a tabbedpane.
Conceptually, each component a CardLayout manages is like a playing card or trading card in a
stack, where only the top card is visible at any time. You can choose the card thats showing in any
of the following ways:

By asking for either the first or last card, in the order it was added to the container.

By flipping through the deck backwards or forwards.

By specifying a card with a specific name. This is the scheme the example program uses.
Specifically, the user can choose a card (component) by selecting it by name from as popup list of choices.

The following code creates the CardLayout and the components it manages.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*<appletcode Cardlayoutdemo width=300 height=100></applet>*/
public class Cardlayoutdemo extends JApplet implements ActionListener,MouseListener
{
JCheckBox win98,winnt,solaris,mac;
JPanel oscard;
CardLayout cardla;
JButton win,other;
Container c;
public void init()
{
win = new JButton(Windows);
other = new JButton(Other);
c=getContentPane();
cardla=new CardLayout();
oscard=new JPanel();
243

JAVA

St. Angelos Computers Ltd.

oscard.setlayout(cardla);
win98= new JcheckBox(Window98,null,true);
winnt= new JCheckBox( WindowNT);
solaris = new JCheckBox(Solaris );
mac = new JCheckBox( Machintosh );
//add window check boxes to a panel
JPanel winpane = new JPanel();
winpane.add(win98);
winpane.add(winnt)
//add other OS checkboxes to a panel
JPanel otherpane= new JPanel(),
otherpane.add(solaris);
otherpane.add(mac);
//add panel to card deck panel
oscard.add(winpane,Windows);
oscard.add(otherpane , Other);
//add cards and buttons to main panel
JPanel mainpane = new JPanel();
mainpane.add(win);
mainpane.add(other);
mainpane.add(oscard);
//add main panel to applet
c.add(mainpane) ;
//register to receive action listeners
win.addActionListener(this);
other.addActionListener(this) ;
//register mouse event
addMouselistener(this);
}//init over
public void mousePressed(MouseEvent me)
{
cardla.next(oscard);
}
public void mouseEntered(MouseEvent me){}
public void mouseExited(MouseEvent me){}
public void mouseClicked (MouseEvent me){}

244

JAVA

St. Angelos Computers Ltd.

public void mouseReleased(MouseEvent me){}


public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==win)
{
cardla.show(oscard, Windows);
}
else
{
cardla.show(oscard,Other );
}
}
}
When you add a component to a container that has CardLayout managers, you must specify a string
that identifies the component being added. For example, in this example, the first panel has the
string Windows and the second panel has the string Other.
To choose which component a CardLayout shows, you need some additional code. In above example
we were doing through action listeners. When you click on Windows button winpane panel will
appear else if user clicks on Other button otherpane will appear.
This example shows that you can use the CardLayout show method to set the currently showing
component. The first arguments the CardLayout manages. The second argument is the string that
identifies the component to show. This string is the same as was used when adding the component
to the container.
The CardLayout API
The following Cardlayout methods let you choose a component.
void first(Container)
void next(Container)
void previous(Container)
void last(Container)
void show(Container, String)
For each method, the first argument is the container for which the CardLayout is the layout manager
(the container of the cards the CardLayout controls).
GridLayout:
A GridLayout places components in grid of cells. Each component takes all the available space within
its cell, and each cell is exactly the same size. If you resize the GridLayout window, youll see that the

245

JAVA

St. Angelos Computers Ltd.

GridLayout changes the cell size so that cells are as large as possible, given the space available to the
container.
Below is the code that creates the GridLayout and the components it manages

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Gridlayoutdemo extends JFrame implements WindowListener
{
public static void main(String a[])
{
Gridlayoutdemo f = new Gridlayoutdemo( GridLayout );
f. show();
}
Gridlayoutdemo(String t)
{
super(t) ;
JButton bl = new JButton(Button 1);
JButton b2 = new JButton(Button2);
JButton b3 = new JButton(Button3);
JButton b4= new JButton(Button4);
JButton b5 = new JButton(Button5)
setSize(400,400);
Container c= getContentPane();
addWindowlistener(this);
c.setlayout(new GridLayout(2,3,1,1));
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
c.add(b5);
}
public void windowClosing(WindowEvent we)
{
System. exit(1);
}
public void windowClosed(WindowEvent we){}
public void windowOpened(WindowEvent we){}
246

JAVA

St. Angelos Computers Ltd.

public void windowActivated(WindowEvent we){}


public void windowIconified(WindowEvent we){}
public void windowDeiconified(WindowEvent we){}
public void windowDeactivated (WindowEvent we){}
}
The constructor tells the GridLayout class to create an instance that has three columns and two rows
with the horizontal and vertical gap of 1 pixel each.
The GridLayout API
The GridLayout class has two constructors:
public GridLayout(int rows, int columns)
public GridLayout(int rows, int columns,
int horizontalGap, int verticalGap)
At least one of the rows and columns arguments must be nonzero. The horizonatalGap and
verticalGap arguments to the second constructor allow you to specify the number of pixels between
cells. If you dont specify gaps, their values default to zero. In the applet above, any apparent gaps
are result of the buttons reserving extra space around their apparent display area.
GridBagLayout
GridBagLayout is the most flexibleand complexlayout manager the Java platform provides. A
GridBagLayout places components in a grid of rows and columns, allowing specified components to
span multiple rows or columns. Not all rows necessarily have the same height. Similarly, not all
columns necessarily have the same width. Essentially, GridBagLayout places components in rectangles
(cells) in a grid, and then uses the components preferred sizes to determine how big the cells should
be.
The previous figure shows the grid for the preceding applet. As you can see, the grid has three rows
and three columns. The button in the second row spans all the columns; the button in the third row
spans the two right columns.
If you enlarge the window as shown in the following figure, youll notice that the button row, which
contains Button 5, gets all the new vertical space. The new horizontal space is split evenly among all
the columns. This resizing behavior is based on weights the program assigns to individual
components in the GridBagLayout. Youll also notice that each component takes up all the available
horizontal spacebut not (as you can see with button 5) all the available vertical space.
The way you will specify the size and position characteristics of its components is by specifying
constraints for each component, To specify constraints, you set instance variables in a
GridBagContraints object and tell the GridBagLayout (with the setContraints method) to associate
the constraints with the component.
Specifying Contraints
The following code is typical of what goes in a contraints that uses a GridBagLayout
247

JAVA

St. Angelos Computers Ltd.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class GridbagDemo extends JFrame implements WindowListener
{
public static void main(String all)
{
GridbagDemo f=new GridbagDemo( GridBagLayout);
f.show();
}
GridbagDemo(String t)
{
super(t);
JButton b1= new JButton(Button1);
JButton b2 = new JButton(Button2);
JButton b3 = new JButton(Button3);
Jbutton b4= new JButton(Button4) ;
JButton b5 = new JButton(Button5 );
setSize(300,300);
getContentPane(),setLayout(new GridBagLayout());
GridBagConstraints gb=new GridBagConstraints();
gb.fill=GridBagConstraints.HORIZONTAL;
gb.weightx= 0;gb.weighty=0;
gb.weightx= 0
add(bl,gb,0,0,l,l);
gb.weightx= 100;
add(b1,gb,l,0,l,l);
gb.weightx= 0;
add(b3,gb,0,l,l,l);
gb.weightx= 100;
add(b4,gb,l,l,l,l);
gb.weightx= 0;
add(b5,gb,0,2,1,1);
gb.fill= GridBagConstraints.BOTH;
addWindowlistener(this) ;
}
private void add(Component c,GridBagConstraints gb,int x,int y,int w,int h)

248

JAVA

St. Angelos Computers Ltd.

{
gb.gridx=x;
gb.gridy =y;
gb.gridwidth=w;
gb.gridheight=h;
getContentPane().add(c,gb);
}
public void windowClosing(WindowEvent we)
{
System. exit(l);
}
public void windowClosed(WindowEvent we){}
public void windowOpened(WindowEvent we){}
public void windowActivated(WindowEvent we){}
public void windowIconified(WindowEvent we){}
public void windowDeiconified(WindowEvent we){}
public void windowDeactivated(WindowEvent we){}
}
As you might have guessed from the above example, you can reuse the same GridBagComtraints
instance for multiple components, even if the components have different contraints. The
GridBagLayout extracts the constraint values and doesnt use the GridBagContraints instance
variables to their default values when necessary.
You can set the following GridBagConstraints instance variables:
gridx, gridy
Specify the row column at the upper left of the component. The leftmost column has address
gridx=0 and the top row has address gridy=0. Use GridBagContraints. RELATIVE (the default value)
to specify that the component be placed just to the right of (for grids) or just below (for gridy) the
component that was added to the container just before this component was added. We recommend
specifying the gridx and gridy values for each component; this tends to result in more predictable
layouts.
gridwidth, gridheight
Specify the number of columns (for gridwidth) or rows (for gridheight) in the components display
area. These constraints specify the number of cells the component uses, not the number of pixels it
uses. The default value is 1. Use GridBagContraints. REMAINDER to specify that the component to be
the last one in its row (for gridwidth) or column (for gridheight). Use GridBagConstrainsts.
RELATIVE to specify that the component to be the next to last one in its row (for gridwidth) or
column (for gridheight).

249

JAVA

St. Angelos Computers Ltd.

Note: GridBagLayout doesnt allow components to span multiple rows unless the component is in the
leftmost column or youve specified positive gridx and gridy values for the component.
fill
Used when the components display area is remove larger than the components requested size to
determine whether and how to resize the component. Valid values (defined as GridBagConstraints
constants) are NONE (the default), HORIZONTAL (make the component tall enough to fill its display
area vertically, but dont change its width), and BOTH (make the component fill its display area
entirely).
ipadx, ipady
Specifies the internal padding: how much to add to the minimum size of the component. The default
value is zero. The width of the component will be at least its minimum width plus ipadx*2 pixels,
since the padding applies to both sides of the component. Similarly, the height of the component will
be at least its minimum height plus ipady*2 pixels.
insets
Specifies the external padding of the component - the minimum amount of space between the
component and the edges of its display area. The value is specified as an insets object. By default,
each component has no external padding.
anchor
Used when the component is smaller than its display area to determine where (within the area) to
place the component. Valid values (defined as GridBagConstraints constants) are CENTER (the
default),
NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHEAST, WEST, and
NORTHWEST.
weightx,weighty
Specifying weights is an art can have a significant impact on the appearance of the components a
GridBagLayout controls. Weights are used to determine how to distribute space among columns
(weightx) and among rows (weighty); this is important for resizing behavior.
Unless you specify at least one nonzero value for weightx or weighty, all the components clump
together in the center of their container. This is because when the weight is 0.0 (the default), the
GridBagLayout puts any extra space between its grid of cells and the edges of the container.
Generally weights are specified with 0.0 and l.0 as the extremes, the numbers in between are used as
necessary. Large numbers indicate that the components row or column should get more space. For
each column, the weight is related to the height weightx specified for a component within that
column, with each multicolumn components weight being split some how between the columns the
component is in. Similarly, each rows weightx is related to the highest weighty specified for a
component within that row. Extra space tends to go toward the rightmost column and bottom row.

Custom LayoutManager

250

JAVA

St. Angelos Computers Ltd.

You can make your own layout manager according to your specifications. Before you start creating a
custom layout manger, make sure that no existing layout manager will work. In particular, managers
from other sources, such as from the internet.
To create a custom layout manger, you must create a class that implements the LayoutManager
interface. You can either implement it directly, or implement its subinterface, layoutManager2.
Every layout manger must implement at least the following five methods, which are required by the
LayoutManager interface :
void addLayoutComponent(String, Component)
Called by the Container add methods. Layout mangers that dont associate strings with their
components generally do nothing in this method.
void removelayoutComponent(Component)
Called by the Container and remove all methods. Many Layout mangers do nothing in this method,
relying instead on querying the container for its components, using the Container getComponents
method.
Dimension preferredLayoutSite(Container)
Called by the Container getPreferredSize method, which is itself called under a variety of
circumstances. This method should calculate and return the ideal size of the container, assuming that
the components it contains will be at or above their preferred sizes. This method must take into
account the containers internal borders, which are returned by the getInsets method.
Dimension minimumLayoutSize(Container)
Called by the Container getMinimumSize method, which is itself called under a variety of
circumstances. This method should calculate and return the minimum size of the container,
assuming that the components it contains will be at or above their minimum sizes. This method
must take into account the containers internal borders, which are returned by the insets method.
void layoutContainer(container)
Called when the container is first displayed, and each time its size changes. A layout mangers
layoutContainer method doesnt actually draw components. It simply invokes each components
resize, move, and reshape methods to set the components size and position. This method must take
into account the containers internal borders, which are returned by the getInsets method. You cant
assume that the preferred layoutSize or minimumlayoutSize method will be called before
layoutContainer is called.
Besides implementing the preceding five methods, layout managers generally implement at least one
public constructor and the to string method.

addlayoutComponent(component, Object)
getlayoutAlignmentX(Container)
getlayoutAlignmentY(Container)

251

JAVA

St. Angelos Computers Ltd.

invalidatelayout( Container)

maximumLayoutSize(Container)

If you wish to support component constraints, maximum sizes, or alignment, then your layout
manager should implement the LayoutManager2 interface. That interface adds five methods to those
required by LayoutManager as mentioned above.
Swing development has its roots in the Model-View-controller (MVC) architecture. This architecture
allows swing components to be replaced with different data models and views. The pluggable look
and feel is a result of the MVC architecture.

Light Weight Components : Light weight components do not depend on any native system
classes, also called peer classes. In swing most of the components have their own view
supported by the Java look-and-feel classes.

Pluggable Look-and-feel : This feature enables the user to switch the look and feel of Swing
components without restarting the application.

When a program does not set its look and feel, the Swing U1 manager must figure out which look
and feel to use. It first checks whether the user has specified a preferred look and feel. If so, it
attempts to use that. If not, or if the users choice isnt valid, then the UI manager chooses the Java
Look & Feel.
Setting the Look and Feel
To programmatically specify a look and feel, use the UIManager.setLookAndFeel method. For
example, the bold code in the following snippet makes the program use the Java Look & Feel.
public static void main(String[ ]args) {
try{
UIManager.setLookAndFeel(
UIManager.getCrossP1atformLookAndFeelClassName());
} catch (Exception e) {}
new SwingApplication(); //Create and show the GUI.
}
The argument to setLookAndFeel is the fully qualified name of the appropriate subclass of Look and
Feel. To specify the java Look & Feel, we used the getCrossPlatfromLookAndFeelClassName method.
If you want to specify the native look the feel for whatever platform the user runs the
program dn, use getSytemLookAndFeelClassName, instead. To specify a particular UI, you can use
the actual class name. For example, if you design a program to look best with the Windows Look &
Feel, you can use this code to set the look and feel:
UIManager.setLookAndFeel(
com.sun.java.swing.plaf.windows.WindowsLookAndFeel);
252

JAVA

St. Angelos Computers Ltd.

Here are some of the arguments you can use for setlookAndFeel:
UIManager.getCrossPIatformLookAndFeelClassName()
Returns the string for the one look-and-feel guaranteed to workthe java Look & Feel.
UIManager.getSystemLookAndFeelClassAndName()
Specifies the look and feel for the current platform. On Win32 platforms, this specifies the Windows
Look & Feel. On Mac OS platforms, this specifies the Mac OS Look & Feel. On Sun platforms, it
specifies the CDE/Motif Look & Feel.
javax.swing.plaf.metal.MetalLookAndFeel
Specifies the Java Look & Feel. (The codename for this look and feel was Metal.) This string is the
value returned by the getCrossPlatformLookAndFeelClassName method.
com.sun.java.swing.plaf.windows.WindowslookAndFeel
Specifies the CDE/Motif Look & Feel, which can be used only on Mac OS platforms.
javax.swing.plaf.motif.MotifLookAndFeel
You arent limited to the preceding arguments. You can specify the name for any look and feel that is
in your programs class path.

Swing Packages
The Swing API is organized into a number of packages to support APls for various categories such
as components pluggable look-and-feel, events, component borders and so on.
The following is the list of package names of Swing:
javax. swing
javax.swing.border
javax. swing. colorchooser
javax. swing. event
javax.swing.filechooser
javax.swing.plaf
javax.swing.plaf.basic
javax.swing.plaf.metal
javax.swing.plaf.multi
javax.swing.table
253

JAVA

St. Angelos Computers Ltd.

javax. swing. text


javax.swing.text.html
java.swing.tree
javax.swing.undo
The JComponent Class
The class is used to serve as a parent of Swing components. This is an abstract class and
encapsulates the basic features and operations specific to Swing components. The AWT container
class is the parent of JComponent, as shown in figure below:
java.lang.Object

java. awt.Component

java.awt.Container

javax.swing.JComponent
The Class hierarchy Of JComponent
Because a Swing component extends from the AWT container, you can expect the components to
behave like containers. However, you should make use of this feature judiciously, depending on the
component.
Swing Components:
This section will provide an overview of Swing components

JApplet-This class represents Swing Applets and hierarchically extends the AWT Applet.

JButton-This class represents Swing Buttons. These buttons can possess an icon as well as
text with suitable positioning.

JCheckbox- This class represents the checkboxes in Swing.

JColorChooser-This class represents Swing color choosers. Color choosers are readymade
dialog boxes with a color palette.

JComboBox-A Swing combo box is an enhancement over the AWT component called choice.

JDesktopPane-This is a type of container to attach the internal frames in Swing.

254

JAVA

St. Angelos Computers Ltd.

JDialog-This class represents the Swing version of dialog boxes. It extends the AWT dialog
box and requires its components to be added to its content pane.

JFile Chooser-This class is a Dialog box that allows you to open or save information content.

JFrame-This class represents the swing frame that is more sophisticated than the AWT
frame. You can add components in layers, add a menubar, or paint over the component.

JInternalFrame -Internal frames are attached to the mainframe of an application. New


sessions can be started by using an internal frame in an application.

JLabel-This class represents swing labels that can display a piece of text as well as icons
with suitable positioning.

JLayeredPane -This class represents the layered panes in Swing Layered panes create the
dimensions along the depth of the components. You can position components on each layer
of the layered pane.

JList -This class represents components that can display a list of items in a user interface.
This component uses the M-UI (modified MVC) architecture.

JMenu -This class represents the Swing menus.

JMenuBar -This class represents a menubar over a Swing Applet or Frame.

JMenuItem -This class represents Swing menuitems.

JOptionPane -This class represents the option panes in Swing.

JPanel -This class represents Swing panels that have the capability of DoubleBuffering along
with the ability to group other components.

JPasswordFeild -This class represents a text field that does not display the text entered into
it. This is basically used for creating password field.

JPopupMenu -This class represents Swing pop-up Menus that contain functionality to be
accessed with a mouse-click.

JProgresBar -This class represents progress bars in Swing.

JRadioButton -This class Swing Radio Buttons.

JRadioButtonMenuItem - Radio button menu items that represents mutually exclusive


Terms. You can only select one item at a time.

JScrollBar - Scrollbars are used to scroll a child component horizontally or vertically in a


container.

JScrollPane - Swing scroll panes are containers with a ready-made scrolling Facility.

JSlider - This class can be used to create slider objects that allow you select specific values
in a specified interval.

255

JAVA

St. Angelos Computers Ltd.

JSplitPane - This class represents the split pane in Swing. The Split Pane provides
separation between two components positioned in it.

JTabbedPane - This class represents tabbed panes in swing. Tabbed panes are space savers
used to display child components.

JTable - This JTable class represents Swing tables.

JTextArea - This class represents text area components in Swing.

JTextPane - This class can be used to create sophisticated editors in Swing applications. A
text pane serves as graphics editor for text as well as pictures.

JToggleButton - This class represents Swing toggle buttons. Toggle buttons remains
depressed when you operate them once.

JToolBar - This represents Swing toolbar objects.

JToolTip - This class represents a ToolTip object that can display a small amount of text to
indicate the name or purpose of the component.

JTree - This are used to represent hierarchical data in user interface. This class represents
Swing tree objects.

Event Handling
User interface elements fire events in response to user input. The events are propagated down the
application, to execute the specified functionality.
Event handling is basically used to handle user interface events that are what the program should do
in response to the user input. The AWT in JDK1.1 introduced the delegation event model and
describes the high-level events generated by Swing components.
Delegation Model
The Delegation Event model supports a clean separation between the core program and user
interface. The delegation pattern allows robust event handling that is less error prone due to strong
compile-time checking. The Delegation event model support improves performance because the
toolkit can filter out undesirable events (like high frequency mouse events) that are not targeted to
execute any function.
Delegation event model consists of three separate objects as to deal with event handling
Swing Events, Sources and Listeners: Events are objects of specific class types that are extended from
the class java.util. EventObject.
Event listeners are objects that implements specific event listener interfaces extended from the root
interface java.util. EventListener.
To attend to the events generated by an event source, the listener object needs to be registered with
that source. There are no. of ways by which this can be achieved. First by using the method
setEventTypeListener( ) or other way by addEventTypeListener( )

256

JAVA

St. Angelos Computers Ltd.

Because it supports multi-casting, multiple listeners can be registered (added) or removed from the
source.
Swing components also depends on AWT events and listeners in addition to the events and listeners
supported by the Swing library.
Swing Sources

Event Listeners

AbstractButton
JTextField
JDirectoryPane
Jscrollbar
JComponent
DefaultCellEditor
AbstractButton
DefaultCaret
JprogressBar
JSlider
JTabbedPane
JViewPort
AbstractDocument
JComboBox
JList
Jmenu
AbstractAction
Swing Sources
JComponent
TableColumn
JTree
JpopupMenu
Getting Event Information: Event objects

ActionListener
AdjustmentListener
AncestorListener
CellEditorListener

ChangeListener

DocumentListener
ItemListener
SelectionListener
MenuListener
Event Listeners
PropertyChangeListener
SelectionListener
WindowListener

Every event-listener method has a single argument - an object that inherits from the EventObject
class. Although the argument always descends from EventObject, its type is generally specified more
precisely. For example, the argument for methods that handle mouse events is an instance of Mouse
event, where MouseEvent is an indirect subclass of EventObject,
The EventObject class defines one very useful method:
Object getSource()
Return the object that fired the event.
Note that the getSource, method returns an Object. Event classes sometimes define methods similar
to getSource, but that have more restricted return types. For example, the ComponentEvent class
defines a getComponent method that just like getSource--return the object that fired the event.
257

JAVA

St. Angelos Computers Ltd.

The difference is that getComponent always return a Component. Each how-to page in this lesson
describes whether you should use getSource or another method to get the event source.
Often, an event class defines methods that return information about the event. For example, you can
query a MouseEvent object for information about where the event occurred, how many clicks the
user made, which modifier keys were pressed, and so on.
Low-Level Events and Semantic Events
Events can he divided into two groups; low-level events and semantic events. Low-level events
represent window system occurrences or low-level input. Everything else is a semantic event.
Mouse and key events - both of which result directly from user input-are low-level events. Other
low-level events include component container, focuses, and window events. Component events let
you track changes to a components position, size and visibility. Container events let you know when
any component gains or loses the keyboard focus the ability to receive characters typed at the
keyboard. Window events keep you informed of the basic status of any kind of Window, such as a
Dialog or a Frame.
Examples of semantic events include action events, item events. and list selection events. The trigger
for a semantic event can differ by component. For example, a button customarily fires an action
event when the user clicks it, but a text field fires an action event when the user presses Return. The
trigger can also vary by look and feel. For example, an audio look and feel might implement a button
that fires an action event remove. For example, a table-model event might be fired when a table
model receives new data from a database.
Whenever possible, you should listen for semantic events rather than low-level events. That way, you
can make your code as robust and portable as possible. For example, listening for action events on
buttons, rather than mouse events, means that the button will react appropriately when the user
tries to activate the button using a keyboard alternative or a look-and-feel-specific gesture. When
dealing with a compound component such as a combo box, it is imperative that you stick to
semantic events, since you have no reliable way of registering listeners on all the look-and-feelspecific components that might be used to form the compound component.

List-Level Events and Listeners


Event

Listener

Java.awt.event.ComponentEvent
Java.awt. event. ContainerEvent
Java.awt.event.FocusEvent
Java.awt.event. KeyEvent
Java.awt.event.MouseEvent

Java.awt.event.ComponentListener
Java.awt.event.ContainerListener
Java.awt.event.FocusListener
Java.awt.event.KeyListener
Java.awt.event.MouseListener
Java.awt.event.MouseMotionListener

258

JAVA

St. Angelos Computers Ltd.

Java.awt.event.WindowEvent

Java.awt.event.WindowListener

Simple Event-Handling Examples


Here is a barebones applet that illustrates event handling. It contains a single button that beeps then
you click it.

Click Me

An Applet with Click Me Button


Heres the code that implements the event handling for the button:

public class Beeper ... implements ActionListener {


.
//where initialization occurs:
button.addActionlistener(this);
.
public void actionPerformed (ActionEvent e) {
...//make a beep sound...
}
}
Isnt that simple? The Beeper class implements the ActionListener interface, which contains one
method: actionPerformed. Since Beeper implements ActionListener, a Beeper object can register as a
listener for- the action events that button fire. Once the Beeper has been registered using the Button
addActionlistener method, the Beepers actionPerformed method is called every time the button is
clicked.
A Complex Example
The event model, which you saw at its simplest in the above example, is quite powerful and flexible.
Any number of event listener objects can listen for all kinds of events from any number of event
source objects. For example, a program might create one listener per event source. Or a program
might have a single listener for all events from all sources. A program can even have more than one
listener for a kind of event from a single event source.
The following applet gives an example of using multiple listeners per object. The applet contains two
event sources (JButton instances) and two event listeners (an instance of class called Multilisteners)
listen for events from both buttons. When it receives an event, it adds the events action command
(the text on the Buttons label) to the top text area. The second event listener (an instance of a class
called Eavesdropper) listens for events on only one the buttons. When it receives an event, it adds
the action command to the bottom text area.
259

JAVA

St. Angelos Computers Ltd.

Heres the code that implements the event handing for the button:

public class MultiListener ... implements ActionListener (


..
//where initialization occurs:
button1.addActionlistener(this):
button2.addActionlistener(this);
button23 .addActionListener(new Eavesdropper(bottomTextArea) ):
}
public void actionPerformed(ActionEvent e) {
topTextArea.append(e.getActionCommand()+new line);
}
}
class Eavesdropper implements ActionListener {
.
public void actionPerformed(ActionEvent e) {
myTextArea. appends(e .getActionCommand() + newline);
}
}
In the above code, both MultiListener and Eavesdropper implement the ActionListener interface and
registers action listeners using the JButton add Actionlistener method. Both classes implementations
of the actionPerformed method are similar, they simply add the events action command to a text
area.

Adapters
Most listener interfaces are designed to support multiple event subtypes, thus they contain multiple
abstract methods that need to be implemented by their listener classes. For example, the interface
java.awt.event. MouseListener contains the methods
mouseClicked(),
mouseEntered(),
mouseExited(), mousePressed() and mouseReleased()
To avoid the clutter of empty methods, adapters have been introduced. Adapters are classes that
readily implements interface with empty methods. This leads to a cleaner way of handling the
necessary events.
Using Adapters and Inner Classes to Handle Events
Most listener interfaces contain more than one method. For example, the MouseListener interface
contains five methods: mousePressed, mouseReleased, mouseEntered, mouseExited, and
mouseClicked. Even if you care only about mouse clicks, if your class directly implements
MouseListener, than you must implement all five MouseListener methods. Methods for those events
you dont care about can have empty bodies. Heres an example:

260

JAVA

St. Angelos Computers Ltd.

//An example with cluttered but valid code.


public class MyClass implements MouseListener {
..
someObject.addMouseListener(this)
.
/* Empty method definition,*/
public void mousePressed(MouseEvent e) {
}
/* Empty method definition.*/
public void mouseReleased(MouseEvent e) {
}
/* Empty method definition.*/
public void mouseEntered(MouseEvent e ) {
}
/* Empty method definition.*/
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e ) {
...//Event handler implementation goes here...
}
}
Unfortunately, the resulting collection of empty method bodies can make code harder to read and
maintain. To help you avoid cluttering your code with empty method bodies, the API generally
includes an adapter class for each listener interface with more than one method. (Handling Common
Events lists all the listeners and their adapters.) For example, the MouseAdapter class implements the
MouseListener interface. An adapter class implements empty versions of all its interfaces methods.
To use an adapter, you create a subclass of it, instead of directly implementing a listener interface.
For example, by extending MouseAdapter, you class inherits empty definitions of all five of the
methods that MouseListener contains.
/*
*An example of extending an adapter class instead of directly implementing a *listener
interface.
*/
public class MyClass extends MouseAdapter {
..
someObject .addMouseListener(this);
..
public void mouseClicked(MouseEvent e) {
261

JAVA

St. Angelos Computers Ltd.

.//Event handle implementation goes here.


}
}
What if you dont want your event-handling class to inherit from an adapter class? For example,
suppose you write an applet and you want your Applet subclass to contain some code to handle
mouse events. Since the Java language doesnt permit multiple inheritances, your class cant extend
both the applet and MouseAdapter classes. The solution is to define an inner class - a class inside of
your Applet subclass - that extends the MouseAdapter class.
//An example of using an inner class.

public class Myclass extends Applet {


.
someObject.addMouselistener(new MyAdapter());
.
class MyAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
//Event handier implementation goes here...
}
}
}
Heres an example of using an anonymous inner class:
//An example of using an anonymous inner class.

public class MyClass extends Applet {


..
someObject.addMouselistener(new MouseAdapter()) {
public void mouseClicked(MouseEvent e) {
...//Event handler implementation goes here...
}
});
.
}
}
Inner- classes work well even if your event handler needs access to provide instance variable from
the enclosing class. As long as you dont declare an inner to be static, an inner class can refer to
instance variable and methods just as if its code is in the containing class. To make a local variable
available to an inner class, just save a copy of the variable as a -final local variable.
To following adapters are used by Swing listeners.
Java.awt.event.ComponentAdapter

262

JAVA

St. Angelos Computers Ltd.

java. awt.event. ContainAdapter


Java.awt.event.FocusAdapter
Java.awt.event.KeyAdapter
Java.awt.event.MouseAdapter
Java.awt.event.MouseMotionAdapter
Java.awt.event.WindowAdapter

Frames
A Swing frame is a container that functions as the main window for programs that use Swing
components. Swing frames posses a title, border, buttons for iconifying maximizing and closing the
frame.
A Swing frame is extended by the class JFrame, which extends the AWT class Frame.
A frame, implemented as an instance of the JFrame class, is a window that has decorations such as a
border, a title, and buttons for closing and iconifying the window. Applications with a GUI typically
use at least one frame. Applets sometimes use frames as well.
To make a window thats dependent on another window - disappearing when the other window is
iconified, for example - use a dialog instead of a frame. To make a window that appears within
another window, use an internal frame.
The decorations on a frame are platform-dependent. You cannot change the decorations of a frame.
The following code creates and sets up the frame and make it visible onscreen.

import Javax.swing.*;
import Java.awt.event.*:
import java.awt.*;
class SampleFrame extends JFrame implements ActionListener
{
public static void main(String s[ ])
{
JLabel EmptyLabel = new JLabel();
JFrame frame = new JFrame(FrameDemo );
frame.addWindowlistener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);} }); //...create a blank label, set its preferred size..,
frarrme.getContentPane().add(EmptyLabel,new BorderLayout().CENTER);
frame.pack();
frame.setVisible(true);
263

JAVA

St. Angelos Computers Ltd.

}
public void action Performed (Action Event e ) {}
}
The second line of code creates a frame with the constructor that lets you set the frames title. The
only other constructor provided by JFrame is a no-argument constructor.
Next the code adds a window listener to the frame. The listeners implementation makes the
program exit when the user closes the frame. This behavior is appropriate for this program because
the program has only one frame, and closing the frame makes the program useless. If the program
didnt exit, then it would continue to run but have no visible GUI and no way of making any GUI
visible.
The bold line in the code segment adds a blank label to the frames content pane. The next line gives
the frame a size, using the pack() method. The pack method sizes the frame so that all its contents
are at or above their preferred sizes. An alternative to pack is to establish a frames size explicitly by
calling setSize. In general, using pack is preferable to calling setSize, since pack leaves the frames
layout manager in charge of the frames size, and layout mangers are good at adjusting to platform
dependencies and other factors that affect component size.
The last line uses the setVisible method to make the frame appear onscreen. Sometimes you might
see the show method used instead of setVisible(true). The two usage are equivalent, but we use
setVisible(true) for consistencys sake.
Swing Menus
A menu provides a space-saving way to let the user choose one of several options. Other components
with which the user can make a one-of-many choice include combo boxes, lists, radio buttons, and
tool bars.
Menus are unique in that, by convention, they arent placed with the other components in the UI.
Instead, a menu usually appears either in a menu bar or a popup menu. A menu bar contains one or
more menus and has a customary, platform-dependent locationusually along the top of a window.
A popup menu is a menu that is invisible until the user makes a platform-specific mouse action,
such as pressing the right mouse button, over a popup-enabled component. The popup menu then
appears under the cursor.
The Menu Component Hierarchy
Here is a picture of the inheritance hierarchy for the menu-related classes:
Object
Component
Container

264

JAVA

St. Angelos Computers Ltd.

JComponent

JmenuBar

JabstractButton

JPopMenu

JSeperator

JMenu Item

Jmenu

JcheckboxMenuItem

JRadioButtonMenuItem

As the figure shows, menu items (including menus) are simply buttons. You might be wondering
how a menu, if its only a button, shows its menu items. The answer is that when a menu is
activated, it automatically brings up a popup menu that displays the menu items.
Creating Menus
The following code the menus shown near the beginning of this section. The bold lines of code
create and connect the menu objects; the other code sets up or customizes the menu objects.
Because this code has no event handling, the menus do nothing useful except look like they should. If
you run the example, youll notice that despite the lack of custom event handling, menus and
submenus appear when they should, and the check boxes and radio buttons respond appropriately
when the user chooses them.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
classMenuTest extends JFrame
{
JMenu menu,submenu;
JMenuBar menuBar;
JMenuItem menuItem;
JCheckBoxMenuItem cbMenuItem;
JRadioButtonMenuItem rbMenuItem;
Container c;
Menu Test()
{
265

JAVA

St. Angelos Computers Ltd.

//Create the menu bar.


menuBar = new JMenuBar();
//setJMenuBar(menuBar);
//Buid the first menu.
menu = new JMenu(Amenu);
menu .setMnemonic(KeyEvent.VK_A) ;
menu .getAccessibleContext() .setAccessibleDescription(
The only menu in this program that has menu items);
menu Bar. add (menu);
//a group of JmenuItems
menuItem = new JmenuItem(A text-only menu item,
KeyEvent.VK_T);
menuItem .setAccelerator(KeyStroke .getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK) );
menultem.getAccessibleContext() .setAccessibleDescription(
This doesnt really do anything);
menu.add(menuItem)
menuItem = new JMenuItem(Both text and icon,
new ImageIcon(red-ball.gif ));
menuItem .setMnemonic(t(eyEvent.VKB);
menu .add (menuItem);
menuItem = new JMenuItem(new ImageIcon(blue-balI.gif ));
menultem .setMnemonic(KeyEvent.VK_D);
menu .add (menultem);
//a group of radio button menu items
menu .addSeparator();
ButtonGroup group = new ButtonGroup;
rbMenuItem = newJRadioButtonMenultem(A radio button menu item);
rbMenultem .setSelected(true);
rbMenultem .setMnemonic( KeyEvent.VK_R);
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem (Another one);
rbMenuItem .setMnemonic(KeyEvent.VK_ O);
group.add(rbMenuitem);
menu.add(rbMenuItem );
//a group of check box menu items

266

JAVA

St. Angelos Computers Ltd.

menu.addSeparator() ;
cbMenuItem = new JcheckBoxMenuItem(A check box menu item);
cbMenuItem .setMnemonic(KeyEvent.VK_C);
menu.add(cbMenuItem );
cbMenuItem = new JCheckBoxMenuItem( Another one);
cbMenuItem .setMnemonic(KeyEvent.VK_H);
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu(A SubMenu);
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem(A item in the submenu)
menuItem .setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_2,ActionEvent.ALT_MASK));
submenu.add (menuItem):
menuItem = new JMenuItem(Another item);
submenu. add(menuItem);
menu.add(submenu);
//Build second menu in the menu bar.
menu = new JMenu(Another Menu );
menu.setMnemonic( KeyEvent.VK_ N);
menu .getAccessibleContext() .setAccessibleDescription(
This menu does nothing);
menuBar.add(menu);
c = g etC o n te ntPan e ( );
c.setlayout(null) ;
c.add(menuBar);
menuBar.setBounds(0l,01,500,25);
setSize(300,300):
}
public static void main(String a[])
{
MenuTest t= new MenuTest();
t.show();
}
}

267

JAVA

St. Angelos Computers Ltd.

As the code shows, to set the menu bar for a JFrame, you use the setJMenuBar method. To add a
JMenu to a JMenuBar, you use the add(Jrvlenu) method. To add , menu items and submenus to a
Jmenu, you use the add(Jmenultem) method. Other methods in the preceding code include
setMnemonic.

Handling Events from Menu Items


The following picture shows a program that adds event detection to the preceding example

Amenu

Another Menu
A text-only menu item
Both text and icon

A radio button menu item


Another one

A check box menu item


Another one

Alt-1

A SubMenu

Here is the code that implements the event handling:

public class MenuDemo ..implements ActionListener,


ItemListener {
.
public MenuDemo() {
//...for each JMenuItem instance:
menuItem.addActionListener(this);
.
//for each JRadioButton instance:
rbMenuItem. addActionlistener( this);

268

JAVA

St. Angelos Computers Ltd.

.
//for each JCheckBoxMenuItem:
cbMenuItem.addItemListener(this) ;
..
public void actionPerformed(ActionEvent e) {
// Get information from the action event...
//.Display it in the text area...
}
public void itemStateChanged (ItemEvent e) {
//...Get information from the item event...
// Display it in the text area...
}
Enabling keyboard Operation
Menu supports two kinds of keyboard alternatives: mnemonics and accelerators. Mnemonics offer a
way to use the keyboard to navigate the menu hierarchy, increasing the accessibility of programs.
Accelerators, on the other hand, offer- keyboard shortcuts to bypass navigating the menu hierarchy.
Mnemonics are or all users, accelerators are for power users.
A mnemonic is a key that makes an already visible menu item be chosen. For example, in MenuDemo
the first menu has the mnemonic A, and its second menu item has the mnemonic B. This means
that, when you run menuDemo with the Java Look & Feel, pressing the Alt and A keys makes the
first menu appear. While the first menu is visible, pressing the E key (with or without Alt) makes the
second menu item be chosen. A menu item generally displays its mnemonic by underlining the first
occurrence of the mnemonic character in the menu items text, as the following snapshot shows.
An accelerator is a key combination that causes a menu item to be chosen, whether or not its
visible. For example, pressing the Alt and 2 keys in MenuDemo makes the first item in the first
menus submenu is chosen, without binding up any menus. Only leaf menu items - menus that dont
bring up other menus - can have accelerators. The following snapshot shows how the Java look &
Fell displays a menu item that has an accelerator.
You can specify a mnemonic either when constructing the menu item or with the setMnemonic
method. To specify an accelerator, use the setAcclerator method. Here are examples of setting
mnemonics and accelerators:
//setting the mnemonic when constructing a menu item:
menultem = new JmenuItem( A text-only menu item
KeyEvent.VK_T),
//Setting the mnemonic after creation time:
menultem .setMnemonic( KeyEvent.VK_T),
//Setting the accelerator:
menultem .setAccelerator(KeyStroke.getKeyStroke(
269

JAVA

St. Angelos Computers Ltd.

KeyEvent.VK_T, ActionEvent.ALT MASK));


As you can see, you set a mnemonic by specifying the KeyEvent constant corresponding to the key
the user should press. To specify an accelerator you must use a Keystroke object, which combines a
key (specified by a KeyEvent constant) and a modifier-key mask (specified by an ActionEvent
constant.)
Bringing Up a Popup Menu
To bring up a popup menu (JPopupMenu), you must register a mouse listener on each component
that popup menu should be associated with. The mouse listener must detect user requests that the
popup menu be brought up. On Windows and Motif platforms, the user brings up a popup menu by
pressing the right mouse button while cursor is over a component that is popup-enabled.
The mouse listener brings up the popup menu by invoking the show method on the appropriate
JPopupMenu instance. The following code, shows how to create and show popup menus

//...where instance variables are declared:


JPopupMenu popup;
//...where the GUI is constructed:
//Create the popup menu.
popup = new JPopupMenu();
menuItem = new JMenuItem( A popup menu item):
menuItem. addActionlistener(this);
popup.add(menuItem);
menultem = new JmenuItem(Another popup menu item );
menuItem .addActionListener(this);
popup.add(menu Item);
//Add listener to components that can bring up popup menus.
MouseListener popuplistener = new PopupListener();
output.addMouselistener(popuplistener);
menuBar.addMouselistener(popupListener()
.
class PopupListener extends MouseAdapter {
( public void mousePressed(MouseEvent e) {
maybeShowpopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
public void maybeShowPopup(MouseEvent e) {
if (e.isPopupTriger()) {
270

JAVA

St. Angelos Computers Ltd.

popup.show.getComponent(),
e.getX(). E.getY():
}
}
}
Popup menus have a few interesting implementation details. One is that every menu has an
associated popup menu. When the menu is activated, it uses its associated popup menu to show its
menu items.
Another detail is that a popup menu itself uses another component to implement the window
containing the menu items. Depending on the circumstances under which the popup menu is
displayed, the popup menu might implement its window using a lightweight component window
(something that inherits from Window).
Lightweight popup windows are more efficient than heavyweight windows, but they dont work well
if you have any heavyweight components inside your GUI. Specifically, when the lightweight popups
display area intersects the heavyweight components display area, the heavyweight component is
drawn on top. This is one of the reasons we recommend against mixing heavyweight and lightweight
components. If you absolutely need to use a heavyweight component in your GUI, then you can
invoke JPopupMenu.setLightWeightPopupEnabled(false)to disable lightweight popup windows.
Customizing menu Layout
Because menus are made up of ordinary Swing components, you can easily customize them. For
example, you can add any lightweight component to a JMenu or JMenuBar. And because JMenuBar
uses BoxLayout, you can customize a menu bars layout just by adding invisible components to it.
Here is an example of adding a glue component to a menu bar, so that the last menu is at the right
edge of the menu bar.
//...create and add some menus...
menuBar. add(Box, createHorizontalGlue( ));
//...create the rightmost menu...
menu Bar.add(rightMenu) ;
Another way of changing the look of means is to change the layout managers used to control them.
For example, you can change a menu bars layout manager from the default left-to right BoxLayout
to something such as GridLayout. You can also change how an activated menu or other popup menu
lays out its items.
The Menu API
Creating and Setting Up Menu Bars
Constructor or Method
JmenuBar()

Purpose
Creates a menu bar.

271

JAVA

St. Angelos Computers Ltd.

JMenu adci(Jmenu)
Void setJMenuBarJmenuBar) JmenuBar
getJMenuBar() (in JApplet, JDialog,
JFrame, JinternalFrame, JRootPane)

Creates a menu.
Set or gets the menu bar of an
applet, dialog, internalframe, or root
pane.

Creating and Populating Menus


Constructor or Method

Purpose

JMenu()
JMenu(String)
JMenuItem add(JmenuItem,)
JMenuItem add(Action)

Creates a menu.
The string specifies the test to display for the Menu.
Adds a menu item to the current end of the menu .
If the argument is an Action object, then the menu creates a
menu item.
If the argument is a string, then the menu automatically
creates a JmenuItem object that displays the specified text.
Adds a separator to the current end of the menu.
Inserts a menu item or separator into the menu at the
specified position.
The first menu item is at position 0,the second at position 1,
and so on.
The JMenultem Action, and String arguments are treated the
same as in the corresponding add methods.
Removes the specified item(s) from the menu.
If the argument is an integer, then it specifies the position of
the menu item to be removed.
Removes all menu items

JMenuItem add(String)
Void addSeparator()
JMenuItem insert(JmenuItem, int)
JMenuItem insert (Action, int)
void lnsert(String, int)
void remove(JmenuItem)
void remove(int)
void removeAll()

The Above tables lists the methods as defined by the Menu API and can be used in your Swing
based Menu Development.
After discussing the Components Of the Swing, which are put in an Applet or in a Frame window,
we will discuss about Swing Applets next.
Swing applets
The Swing set introduces its own version of the Applet, whose parent is the AWT Applet. Swing
applets are made more sophisticated, so that they can support menubars and layering of components
in the dimension of depth. Swing Applets are represented by the class extending JApplet which is
stored in the package javax.swing. A Swing Applet can be created by class extending JApplet. While
adding children to it, you need to add them something called a content pane, which receives the
applets children.
Lets look at a simple Swing Applet. and thereby try to find how they differ from normal applets.
Lets now take a look at the Hello! Swing World, It is coded both to function as an applet and as an
application.
272

JAVA

St. Angelos Computers Ltd.

This section covers JApplet -a class that enables applets to use Swing components. JApplet is a
subclass of java.applet.Applet. Any applet that contains Swing components must be implemented
with a subclass of Japplet.
Features Provided by JApplet:
JApplet adds two major features to the functionality that it inherits from Java.applet.Applet. First
Swing applets provide support for assistive technologies. Second, because JApplet is a top-level Swing
container, each Swingapplet has a root pane. The most noticeable result of the root panes presence
is support for adding menubar and the need to use a content pane.
The content pane makes Swing applets different from regular applets in the following ways:

You add components to a Swing applets content pane, not directly to the applet

You set the layout manager on a Swing applets content pane, not directly on the applet.

The default layout manager for a Swing applets content pane is BorderLayout. This differs
from the default layout manger for Applet, which is FlowLayout.

You should not put painting code directly in a JApplet object.

If you run a Swing Applet using JDK 1.1 JFC 1.1, then you might see an error message that looks like
this:
Swing: checked access to system event queue.
You can often avoid this message by telling the applet not to check whether it has access to the
system event queue. To do so, put the following code in the constructor for the applet class:
getRootPane().putClientProperty(
defeatSystemEventQueueCheck,
Boolean.TRUE);

Threads in Applets
Because applets inherently use multiple threads and Swing components arent thread safe, you
should take care with threads in Swing applets. Its generally considered safe to create and
manipulate Swing components directly in the init method. However, the other milestone methods start, stop, and destroy -might cause trouble when the browser invokes them after the applets
already visible. To avoid trouble, you should make these methods thread safe.
For example, when you implement a stop or start method, be aware that the browser doesnt call
them from the event-dispatching thread. Thus, those methods shouldnt affect or query Swing
components directly. Instead they should use techniques such as using the SwingUtilities.invokelater
method to affect components.
The JApplet API

273

JAVA

St. Angelos Computers Ltd.

The next table lists the interesting methods that JApplet adds to the applet API. They give you access
to features provided by the pane. Other methods you might use are defined by the Component and
Applet classes.

Method
Void setContentPane(Container)
Conteainer getContentPane()

Purpose
Set or get the applets content pane.
The content pain contains the applets visible GUI
components and should be opaque.

JRootPane createRootPane()
Void setRootPane(JrootPane)
JRootPane getRootPane()

Create, set, or get the applets root pane.


The root pane manages the interior of the applet
including the content pane, the glass pane, and so
on.

Void setJMenuBar(JmenuBar)
JMenuBar setJMenuBar()

Set or get the applets menu bar to manage a set


of menus for the frame.

Void setGlassPane ( Component)


Component getGlassPane()

Set or get applets glass pane. You can use the


glass pane to intercept mouse events.

Void setLayeredPane(JLayeredPane) Set or get the applets layered pane. You can JLayeredPane

getLayeredPane()

use the frames layered pane to put components


on top of or behind other components.

Example:
AppletDemo.Java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
/*< applet code = AppletDemo height= 300 width = 300 > < /applet > */
public class AppletDemo extends JApplet
implements ActionListener{
protected JButton bl.b2.b3;
protected static final String DISABLE = disable
274

JAVA

St. Angelos Computers Ltd.

protected static final String ENABLE - enable


protected String leftButtonFilename = blue-ball.gif
protected String middleButtonFilename = red -ball .gif
protected String rightButtonFilename = yellow-ball.gif
private boolean inAnApplet =true;
URL_ codeBase;//used for applet version only
//Hack to avoid ugly message about system event access check.
public AppletDemo() {
this(true);
}
public AppletDemo(boolean inAnApplet) {
this.inAnApplet= inAnApplet;
If(inAnapplet) {
getRootPane().putClientProperty(defeatSystemEventQueueCheck,
Boolean.TRUE);
}
}
Public void init() {
setContentPane(makeContentPane());
}
public Container makeContentPane() {
ImageIcon leftButtonIcon;
ImageIcon middleButtonIcon;
ImageIcon rightButtonIcon;
if(inAnApplet){
URL leftButtonURL = getURL(leftButtonFilename);
URL middleButtonURL = getURL(middleButtonFilename):
URL rightButtonURL = getURL(rightButtonFilename);
leftButtonlcon = new ImageIcon(leftButtonURL);
middleButtonIcon= new ImageIcon(middleButtonURL);
rightButtonIcon = new Imageicon(rightButtonURL);
} else {
leftButtonIcon = new ImageIcon (leftButtonFilename);
middleButtonIcon= new ImageIcon(middleButtonFilename);
rightButtonIcon = new ImageIcon(rightButtonFilename);
}
b1 = new JButton( disable middle button, leftButtonIcon):

275

JAVA

St. Angelos Computers Ltd.

b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition (AbstractButton.LEFT);
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand(DISABLE);
b2 = new JButton(Middle button, middleButtonlcon);
b2.setVerticalTextPosition(AbstractButton.BOTTOM)
b2.setHorizontalTextPosition(AbstractButton.CENTRE)
b2.setMnemonic(KeyEvent.VK_M);
b3=new JButton(Enable middle button. rightButtonIcon);
//Use the default text position of CENTER / RIGHT>
b3 setMnemonic(KeyEvent.VK_E);
b3.setActionCommand(ENABLE);
b3.setEnabled(false) ;
//Listen for actions on buttons 1 and 3.
b1.addActionListener(this);
b3.addActionListener(this) :
b1.setToolTipText(click this button to disable the middle button.: );
b2.setToolTipText( This middle button does nothing when you click it),
b3.setToolTipText(Click this button to enable the middle button.);
//Add Components to JPanel, using the default FlowLayout.
JPanel pane = new JPanel();
pane.add(b1):
pane.add(b2);
pane.add(b3):
pane.setBackground(new Color(255,255.204));
pane.setBorder(BorderFactory.createMatteBorder(1,1,2,2,Color.black));
return pane:
}
public void actionPerformed (ActionEvent e) {
if (e.getActionCommand().equals(DISABLE)) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);

276

JAVA

St. Angelos Computers Ltd.

b1.setEnabled(true):
b3.setEnabled(false );
}
}
/*One day, Japplet will make this method obsolete.*/
protected URL. getURL(String filename) {
URL url= null;
if (codeBase = = null)
codeBase=getCodeBase();
}
try {
url = new URL(codeBase, filename);
}catch (java. net.MalformedURLException e) {
System.out.println(Couldnt create image:badly specified URL);
return null;
}
return url;
}
public static void main(String[] args) {
JFrame frame = new JFrame( Application version:AppletDemo );
frame. addWindowlistener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
AppletDemo applet = new AppletDemo(false):
frame.setContentPane(applet.makeContentPane()):
frame.pack();
frame.setVisible(true);
}
}
Example

import.javax.swing.*;
import java.awt.*;

277

JAVA

St. Angelos Computers Ltd.

//<Applet Code = HelloSwingApplet.classwidth =400 height=500><Applet>Add this line in the


program.
public class HelloSwingApplet extends JApplet
{
public HelloSwingApplet()
{
getRootPane().putClientProperty(defeatSystemEventQueueCheck,Boolean.TRUE);

}
public void init()
{
JLabel label = new JLabel(You are successfully running a Swing applet!);
label.setHorizontalAlignment(JLabel.CENTER);
label.setBorder(BorderFactory.createMatteBorder(1,1,2,2,Color.black));
getContentPane().add(label.Borderlayout.CENTER);
}
}
Example

import javax.swing.*;
//This is the final package name.
//import com.sum.java.swing.*; //Used by JDK 1.2 Beta 4 and all
//Swing releases before Swing1.1 Beta 3.
import java.awt.*;
import java.awt.event.*;
public class SwingApplication {
private static String labelPrefix = Number of button clicks:;
private int numClicks =0:
public Component createComponents() {
final JLAbel label = new Jlable(lablePrefixc + 0 );
JButton button = new JButton(Im a Swing button!);
button.setMnemonic(KeyEvnt.VK_I );
button.addActionListener(new ActionListener() {
public void actionPerfromed(ActionEevnt e) {
numClicks + +;
lable.setText(labelPrefix + numClicks);
}

278

JAVA

St. Angelos Computers Ltd.

});
lable.setLableFor(button);
/*
*An easy way to put space between a top-level container
*and its content is to put these contents in a JPanel
*that has an empty border.
*/
JPanel pane = new JPanel():
pane.setBorder(BorderFactory.createEmptyBorder(
30, //top
30,//left
10,//bottom
30)//right
);
pane.setlayout(new GridLayout(0,l));
pane .add(button):
pane .add(label):
return pane;
}
public static void main (String[] args) {
try{
UIManager.setLookAndFeel(
UIManayer.get.getCrossPlatformLookand FeelClassName());
}catch (Exception e) {}
//Create the top-level container and add contents to it.
JFrame frame = new JFrame(SwingApplication );
Swing Application app = new SwingApplication ();
Component content = app.createComponents():
frame.getContentPane().add(Contents,BorderLayout.CENTER);
//Finish setting up the frame, and show it.
frame addWindowlistener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
279

JAVA

St. Angelos Computers Ltd.

frame.pack();
frame.setVisible (true) :
}
}
The above examples implements or employs the contents and features of JFC Swing,
The last example(example no.3) is a Swing Application which runs inside a Frame created by
using the Swings Jframe class.
Exercise
1.

What is the difference between AWT and Swing?

2.

Write the names of Swing components and pure Swing components?

3.

Write a program to add ImageButton to a Jframe?

4.

Write a program to create a Jtable which contains minimum 3 fields?

5.

Swing is extension of _________.

6.

Japplet subset of__________.

7.

Swing is used to develop___________ based application.

8.

Swing is a part of
a)
Java
b)

9.

c)

JavaFoundationClass

d)

Advance Java

JVM

Swing elements are


a)
Light weight elements

c) Heavy weight elements

b)

d) None

Light&Heavy weight elements

10. getContentPane method is present in


a) Component c)
Container
b) Class

d)

Connection

280

JAVA

St. Angelos Computers Ltd.

Appendix
Java Keywords
This appendix lists the keywords in Java. They are grouped according to their meaning function.
___________________________________________________________________________
Group
Keyword
Meaning / Function
___________________________________________________________________________
Class Organization
package
specifies the class in a particular
Source file should belong to the
Named package.
Import

Class Definition

requests the named class or classes


be imported into the current
application.
interface

defines global data and method


signatures that can be shared among
classes.

Class

defines a collection of related data


behavior.

Extends

indicates which class to subclass.

Implements

indicates the interface for which a


new class will supply methods.

Keywords for Classes


and Variables abstract

specifies the class cannot be


instantiated directly.

Public

means the class, method, or variable


can be accessed from anywhere.

Private

means only the class defining the


method or variable can access it.

Protected

means only the defining class and its


subclasses can access the method
variable.
specifies a class method or variable.

Static
Synchronized

indicates only one object or class


can access this variable or method at
time.

Volatile

tells the compiler this variable may


change asynchronously due to
281

or

JAVA

threads

St. Angelos Computers Ltd.

final

means this variable or method


cannot be changed by subclasses.

Native
Simple Data Types

links a method to native code.


long

is a 64-bit integer value.

Int

is a 32-bit integer value.

Short

is a 16-bit integer value.

Byte

is a 8-bit integer value.

Double

is a 64-bit floating-point value.

Float

is a 32-bit floating-point value.

Char

is a 16-bit Unicode character.

void

indicates a method does not return


a value.

Values and Variables

false

is a Boolean value.

true

is a Boolean value.

this

refers to the current instance in an


instance method.

super

refers to the immediate superclass in


an instance method.

null

represents a nonexistent instance.


Exception Handling

throw

throws an exception.

throws

throws an exception.

try

marks a stack so that if an exception


is thrown, it will unwind to this
point.

catch

catches an exception.

finally

says execute this block of code


282

JAVA

St. Angelos Computers Ltd.

Regardless of exception error


handling flow.
Instance Creating
and Testing new

creates new instances.

instanceof

tests whether an instance derives


from a particular class or inter-face .

Control Flow

switch

tests a variable.

case

executes a particular block of code


according to the value tested in the
switch.

default

means the default block of code


executes if no matching case
statement was found.

break

breaks out of a particular block of


code.

continue

continues with the next iteration of


loop.

return

returns from a method, optionally


passing back a value.

do

performs come statement or set of


statements.

if

tests for a condition and performs


some action if true.

else

performs some action if the above


test was false.

for

signifies iteration.

while

performs some action while a


condition is true.

Not Used Yet,


But Reserved

byvalue

Const

goto

283

JAVA

St. Angelos Computers Ltd.

Cast
generic

future

threadsafe
inner
operator
outer
rest
var
___________________________________________________________________________

Differences Between Java and C /C ++


Data Types

All Java primitive data types (char, int, short, long, byte, float, double and boolean) have
specified sizes and behaviour that are machine-independent.
Conditional expression can only be boolean, not integral.
Casting between data types is much more controlled in Java. Automatic conversion occurs
only when there is no loss of information. All other casts must be explicit.
Java supports special methods to convert values between class objects and primitive types.
Composite data types are accomplished in Java using only classes. Structures and unions are
not supported.
Java does not support typedef and enum keywords.
All non-primitive types can only be created using new operator.
Java does not define the type modifiers auto, extern, register, signed, and unsigned.

Pointers
Java does not support pointers. Similar functionality is accomplished by using implicit references to
objects. Pointer arithmetic is not possible in Java.
Operators

Java adds a new right shift operator >>> which inserts zeros at the top end.

284

JAVA

St. Angelos Computers Ltd.

The + operator can be used to concatenate strings.


Operator overloading is not possible in Java.
The operator of C has been deleted.
Java adds another operator instanceof to identify objects.
The modulus division may be applied to float values in Java which is not permitted in C /
C++.

Functions and Methods

All functions are defined in the body of the class. There are no independent functions.
The functions defined inside a class are known as methods.
Although function overloading in Java works virtually identical to C ++ function overloading,
there are no default arguments to functions.
No inline functions in Java.
Java does not support variable-length argument lists to functions. All method definitions
must have a specific number of arguments.
Java requires that methods with no arguments must be declared with empty parenthesis
(not with void keyword).

Preprocessor

Java does not have a preprocessor, and as such, does not support # define or macros.
Constants can be created using the final modifier when declaring class and instance
variables.
Java programs do not use header files.

Classes

Class definitions take the similar form in Java as in C+ +, but there is no closing semicolon.
There is no scope resolution operator :: in Java.
No forward references of classes are necessary in Java.
No destructors in Java.
Java has no templates.
No nested classes in Java.
Inheritance in Java has the same effect as in C + +, but the syntax is different.
Java does not provide direct support for multiple inheritance. We can accomplish multiple
inheritance by using interfaces.
Access specifiers (public, private, protected and private protected) are placed on each
definition for each member of a class.
A class in Java can have an access specifier to determine whether it is visible outside the
file.
There is no virtual keyword in Java. All non-static methods always use dynamic binding.

285

JAVA

St. Angelos Computers Ltd.

Initialization of primitive class data member is guaranteed in Java. We can initialize them
directly when we define them in the class, or we can do it in the constructor.
We need not externally define storage for static members like we do in C + +.

Strings

String in C and C + + are arrays of characters, terminated by a null character. But strings in
Java are objects. They are not terminated by a null. Therefore, strings are treated differently
in C + + and Java.
Strings can be concatenated using + operator

Arrays

Arrays are quite different in Java. Array boundaries are strictly enforced. Attempting to read
past the end of an array produces an error.
One array can be assigned to another in Java.
Java does not support multidimensional arrays as in C and C + +. However, it is possible to
create arrays of arrays to represent multidimensional arrays.

Control Flow

There is no goto in Java. We can, however, use labeled break and continue statements to
jump out of the loops.
The test expressions for control flow constructs return a boolean value (true or false) in
Java. In C and C + +, they return an integer value.
The control variable declared in for loop is not available after the loop is exited in Java.

Command-Line Arguments

The command line arguments passed from the system into a Java program differ in a
couple of ways compared to that of C + + program.
In C and C + +, two arguments are passed. One specifies the number of arguments and the
other is a pointer to an array of characters containing the actual arguments. In Java, a
single argument containing an array of strings is passed.
The first element in the arguments vector in C and C + + is the name of the program itself.
In Java, we do not pass the name of the program as an argument. We already know the
name of the program because it is the same name as the class.

OtherDifferences

Java supports multithreading.


Java supports automatic garbage collection and makes a lot of programming problems
simply vanish.

286

JAVA

St. Angelos Computers Ltd.

The destructor function is replaced with a finalize function.


Exception handling in Java is different because there are no destructors. A finally also
contain its own documentation.

287

JAVA

St. Angelos Computers Ltd.

Java API Packages


Java API is implemented as packages, which contain group of related classes. Along with
classes, they also include interfaces, exception definitions and error definitions. Java API is composed
of a large number of packages .The most commonly used packages are:
Stand-alone Application Programming
1.
2.
3.

java.lang
java.util
java.io

Applet and Network Programming


4.
5.
6.

java.awt
java.applet
java.net

This appendix lists the frequently used interfaces and classes contained in the above
packages.
java.lang Package
___________________________________________________________________________
Interfaces
___________________________________________________________________________
Cloneable

Interface indicating that an object may be copied or cloned

Runnable
Methods for classes that want to run as threads
___________________________________________________________________________
Classes
___________________________________________________________________________
Boolean

Object wrapper for boolean values

Character

Object wrapper for char values

Class

Run-time representations of classes

ClassLoader

Abstract behavior for handling loading of classes.

Compiler

System class that gives access to the Java compiler

Double

Object wrapper for double values


288

JAVA

St. Angelos Computers Ltd.

Float

Object wrapper for int values

Integer

Object wrapper for int values

Long

Object wrapper for long values

Math

Utility class for math operations

Number

Abstract superclass of all number classes (Integer, Float, and so


on)

Object

Generic object class, at top of inheritance hierarchy

Process

Abstract behavior for processes such as those spawned using


methods in the System class

Runtime

Access to the Java runtime

SecurityManager

Abstract behavior for implementing security policies

String

Character strings

StringBuffer

Mutable strings

System

Access to Java's system-level behavior, provided in a platform


Independent way

Thread

Methods for managing threads and classes that run in threads

ThreadDeath

Class of object thrown when a thread is asynchronously


terminated

ThreadGroup

A group of threads

Throwable

Generic exception class; all objects thrown must be a


Throwable.
________________________________________________________________________
java.util Package
________________________________________________________________________
Interfaces
________________________________________________________________________
Enumeration
Observer

Methods for enumerating sets of values


Methods for enabling classes to be Observable objects
289

JAVA

St. Angelos Computers Ltd.

________________________________________________________________________
Classes
________________________________________________________________________
BitSet

A set of bits

Date

The current system date, as well as methods for generating and parsing
Dates.

Dictionary

An abstract class that maps between keys and values (superclass of


HashTable)

Hashtable

A hash table

Observable

An abstract class for observable objects

Properties

A hash table that contains behavior for setting and retrieving persistent
Properties of the system or a class

Random

Utilities for generating random numbers

Stack

A stack (a last-in-first-out queue)

Stringtokenizer

Utilities for splitting strings into individual "token"

Vector

A growable array of Objects

________________________________________________________________________
java.io Package
______________________________________________________________________
Interfaces
________________________________________________________________________
DataInput

Methods for reading machine-independent typed input streams

DataOutput

Methods for writing machine-independent typed output streams

FilenameFilter

Methods for filtering file names

Classes
________________________________________________________________________
BufferedInputStream

A buffered input stream

290

JAVA

St. Angelos Computers Ltd.

BufferedOutputStream

A buffered output stream

ByteArrayInputStream

An input stream from a byte array

ByteArrayOutputStream

An output stream to a byte array

Data Input Stream

Enables you to read primitive Java type (int, chars, boolean, and so on)
From a stream in a machine-independent way

DataOutputStream

Enables you to write primitive Java data types (ints, chars, booleans, and
So on) to a stream in a machine-independent way

File

Represents a file on the host's file system

FileDescriptor

Holds onto the UNIX-like descriptor of a file or socket

FileOutputStream

An input stream from a file, constructed using a filename of descriptor

FileOutputStream

An output stream to a file, constructed using a filename or descriptor

FilterInputStream

Abstract class that provides a filter for input streams (and for adding
Stream functionality such as buffering)

FilterOutputStream

Abstract class which provides a filter for output streams (and for adding
Stream functionality such as buffering)

InputStream

An abstract class representing an input stream of bytes; the parent of all


Input streams in this package

LineNumberInput
Stream

An input stream that keeps track of line numbers

OutputStream

An abstract class representing an output stream of bytes, the parent of


all Output stream in this package

PipedInputStream

A piped input stream, which


PipedOutputStream to be useful

PipedOutputStream

A piped output stream, which should be connected to a


PipeOutputstream to be useful (together they provide safe
communication between threads)

PrintStream

An output stream for printing (used by System.out.println())

PushbackInputstream

an input stream with a 1-byte push back buffer

291

should

be

connected

to

JAVA

St. Angelos Computers Ltd.

RandomAccessFile

Provides random access to a file, constructed from filenames, descriptors,


or objects

SequenceInputStream

Converts a sequence of input streams into a single input stream

StreamTokenizer

Converts an input stream into a series of individual tokens

StringBufferInputStream

An input stream from a String object

___________________________________________________________________________
java.awt Package
Interfaces
LayoutManager

Methods for laying out containers

MenuContainer

Methods for menu-related containers

Classes
BorderLayout

A layout manager for arranging items in border formation

Button

A UI pushbutton

Canvas

A canvas for drawing and performing other graphics operations

CardLayout

A layout manager for HyperCard-like metaphors

Checkbox

A checkbox

CheckboxGroup

A group of exclusive checkboxes (radio buttons)

CheckboxMenuItem

A toggle menu item

Choice

A popup menu of choices

Color

An abstract representation of color

Component

The abstract generic class for all UI components

Container

Abstract behavior for a component that can hold other components or


containers

292

JAVA

St. Angelos Computers Ltd.

Dialog

A window for brief interactions with users

Dimension

An object representing width and height

Event

An object representing events caused by the system or based on user


input

FileDialog

A dialog for getting filenames from the local file System

FlowLayout

A layout manager that lays out objects from left to right in rows

Font

An abstract representation of a font

FontMetrics

Abstract class for holding information about a specific fonts character


shapes and height and width information

Frame

A top-level window with a title

Graphics

Abstract behavior for representing a graphics context, and for drawing


and painting shapes and objects

GridBadConstraints

Constraints for components laid out using GridBagLayout

GridBagLayout

A layout manager that aligns components horizontally and vertically


based on their values from GridBagConstraints

GridLayout

A layout manager with rows and columns, elements are added to each
cell in the grid

Image

An abstract representation of a bitmap image

Insets

Distances from the outer border of the window, used to layout


components

Label

A text label for UI components

List

A scrolling list

MediaTracker

A way to keep track of the status of media objects


being loaded over the Net

Menu

A menu, which can contain menu items and is a container on a menubar

MenuBar

A menubar (container for menus)

MenuComponent

The abstract superclass of all menu elements

293

JAVA

St. Angelos Computers Ltd.

MenuItem

An individual menu item

Panel

A container that is displayed

Point

An object representing a point (x and y coordinates)

Polygon

An object representing a set of points

Rectangle

An object representing a rectangle (x and y coordinates for the top


corner, plus width the height)

Scrollbar

A UI scrollbar object

TextArea

A multiline, scrollable, editable, text field

TextComponent

The superclass of all editable text components

TextField

A fixed-size editable text field.

Toolkit

Abstract behavior for binding the abstract AWT classes to a platformspecific toolkit implementation

Window

A top-level window, and the superclass of the Frame and Dialog classes
java.awt.image Package

Interfaces
ImageConsumer

Methods for receiving image created by an ImageProducer

ImageObserver

Methods to track the loading and construction of an Image

ImageProducer

Methods for producing image data received by an ImageConsumer

Classes
ColorModel

An abstract class for managing color information for Images

CropImageFilter

A filter for cropping images to a particular size

DirectColorModel

A specific color model for managing and translating pixel color values

FilteredImageSource

An ImageProducer that takes an image and an ImageFilter object, and


produces an image for an ImageConsumer

294

JAVA

St. Angelos Computers Ltd.

ImageFilter

A filter that takes image data from an ImageProducer, modifies it in


some way, and hands it off to an ImageConsumer

IndexColorModel

A specific color model for managing and translating color values in a


fixed-color map

MemoryImageSource

An image producer that gets its image from memory; used after
constructing an image by hand

PixelGrabber

An ImageConsumer that retrieves a subset of the pixels in an image

RGBImageFilter

Abstract behavior for a filter that modifies the RGB values of pixels in
RGB images
java.applet Package

Interfaces
AppletContext

Methods to refer to applets context

AppletStub

Methods to implement applet viewers

AudioClip

Methods to play audio files

Classes
Applet

The base applet class


java.net Package

Interfaces
ContentHandler Factory

Methods for creating ContentHandler objects

SocketImplFactory

Methods for creating socket implementations (instance of the


SocketImpl class)

URLStreamHandlerFactory

Methods for creating URLStreamHandler objects

295

JAVA

St. Angelos Computers Ltd.

Classes
ContentHandler

Abstract behavior for reading data from a URL connection and


constructing the appropriate local object, based on MIME types

DatagramPacket

A datagram packet (UDP)

DatagramSocket

A datagram Socket

InetAddress

An object representation of an Internet host (host name, IP address)

ServerSocket

A server-side socket

Socket

A socket

SocketImpl

An abstract class for specific socket implementations URL and object


representation of a URL

URLConnection

Abstract behavior for a socket that can handle various Web-based


protocols (http, ftp and so on)

URLEncoder

Turns strings into x-www-form-url encoded format

URLStreamHandler

Abstract class for managing streams to object referenced by URLs

Java Classes and Their Packages


This appendix lists the frequently used classes in an alphabetical order and indicates in which
package a given class is defined. It also lists the classes that extend them.
Class
Package
___________________________________________________________________________
AbstractMethodError

java.lang

AppletContext

java.applet

AppletStub

Java.applet

Applet

java.applet

ArithmeticException

java.lang

296

JAVA

ArrayIndexOutofBoundsException

St. Angelos Computers Ltd.

java.lang

ArrayStoreException

java.lang

AudioClip

java.applet

AWTError

java.awt

AWTException

java.awt

BitSet

java.util

Boolean

java.lang

BorderLayout

java.awt

BufferedInputStream

java.io

BufferedOutputStream

java.io

ButtonPeer

java.awt.peer

Button

java.awt

ByteArrayInputStream

java.io

ByteArrayOutputStream

java.io

CanvasPeer

java.awt.peer

Canvas

java.awt

CardLayout

java.awt

Character

java.lang

CheckboxGroup

java.awt

CheckboxMenuItemPeer

java.awt.peer

CheckboxMenuItem

java.awt

CheckboxPeer

java.awt.peer

Checkbox

java.awt

ChoicePeer

Java.awt.peer
297

JAVA

St. Angelos Computers Ltd.

Choice

java.awt

ClassCastException

java.lang

ClassCircularityError

java.lang

ClassFormatError

java.lang

ClassLoader
ClassNotFoundException

java.lang
java.lang

Class

java.lang

Cloneable

java.lang

CloneNotSupportedException

java.lang

ColorModel

java.awt.image

DirectColorModel,
IndexColorModel
Color

java.awt

Compiler

java.lang

ComponentPeer

java.awt.peer

ButtonPeer, Canvas
Peer,CheckboxPeer,
ChoicePeer,
ContainerPeer,
LabelPeer,ListPeer,
ScrollbarPeer, Text
ComponentPeer
Component

java.awt

298

JAVA

St. Angelos Computers Ltd.

Button,Canvas,
Checkbox,Choice,
Container,Label,List,
Scrollbar,Text
Component
ContainerPeer

java.awt.peer

PanelPeer,WindowPeer
Container

java.awt

Panel,Window
ContentHandlerFactory

java.net

ContentHandler

java.net

DatagramPacket

java.awt.image

DatagramSocket

java.net

DataInputStream

java.io

DataInput

java.io

DataOutputStream

java.io

DataOutput

java.io

Date

java.util

DialogPeer

java.awt.peer

FileDialogPeer
Dialog

java.awt

FileDialog
Dictionary

java.util

Hashtable
299

JAVA

St. Angelos Computers Ltd.

Dimension
DirectColorModel

java.awt
java.awt.image

Double

java.lang

EmptyStackException

java.util

Enumeration

java.util

EOFException

java.io

Error

java.lang

AWTError,LinkageError
ThreadDeath,VirtualMachine
Event

java.awt

Exception

java.lang

AWTException
ClassNotFoundException
CloneNotSupportedException
IllegalAccessException
InstantiationException
InterruptedException

IOException

NoSuchMethodException
RuntimeException
FileDescriptor

java.io

FileDialogPeer

java.awt.peer

FileDialog

java.awt

FileInputStream

java.io

300

JAVA

St. Angelos Computers Ltd.

FilenameFilter

java.io

FileNotFoundException

java.io

FileOutputStream

java.io

File

java.io

FilteredImageSource

java.awt.image

FilterInputStream

java.io

BufferedInputStream
DataInputStream
LineNumberInputStream
PushbackInputStream
BufferedOutputStream
DataOutputStream,PrintStream
Float

java.io

FlowLayout
FontMetrics

java.awt
java.awt

Font
FramePeer

java.awt
java.awt.peer

Frame
Graphics
GridBagConstraints

java.awt
java.awt
java.awt

GridBagLayout
Hashtable

java.awt
java.util

IllegalAccessError
IllegalAccessException
IllegalArgumentException

java.lang
java.lang
java.lang

IllegalThreadStateException
NumberFormatException

301

JAVA

St. Angelos Computers Ltd.

IllegalMonitorStateException
IllegalThreadStateException
ImageConsumer

java.lang
java.lang
java.awt.image

ImageFilter

java.awt.image

CropImageFilter,
RGBImageFilter
ImageObserver

java.awt.image

ImageProducer

java.awt.image

Image

Java.awt

IncompatibleClassChangeError

java.lang

AbstractMethodError
IllegalAccessError
InstantiationError
NoSuchFieldError
NoSuchMethodError
IndexColorModel

java.awt.image

IndexOutOfBoundsException

java.lang

ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
InetAddress

java.net

InputStream

java.io

ByteArrayInputStream
FileInputStream
FilterInputStream
PipedInputStream
SequenceInputStream
302

JAVA

St. Angelos Computers Ltd.

StringBufferInputStream
Insets
InstantiationError

java.awt
java.lang

InstantiationException
Integer
InternalError
InterruptedException

java.lang
java.lang
java.lang
java.lang

InterruptedIOException

java.io

IOException

java.io

FileNotFoundException
InterruptedIOException
MalformedURLException
ProtocolException
SocketException
UnknownHostException
UnkonwnServiceException
UTFDataFormatException
LabelPeer

java.awt.peer

Label
LayoutManager

java.awt
java.awt

LineNumberInputStream

java.io

LinkageError

java.lang

ClassCircularityError
ClassFormatError
IncompatibleClassChangeError,
UnsatisfiedLinkError,VerifyError

303

JAVA

St. Angelos Computers Ltd.

ListPeer

java.awt.peer

List
Long

java.awt
java.lang

MalformedURLException

java.net

Math
MediaTracker

java.lang
java.awt

MemoryImageSource

java.awt.image

MenuBarPeer

java.awt.peer

MenuBar
MenuComponentPeer

java.awt
java.awt.peer

CheckboxMenuItemPeer
MenuPeer
MenuComponent

java.awt

MenuBar,MenuItem
MenuContainer
MenuItemPeer

java.awt
java.awt.peer

CheckboxMenuItemPeer
MenuPeer
MenuItem

java.awt

CheckboxMenuItem, Menu
MenuPeer

java.awt.peer

Menu
NagativeArraySizeException
NoClassDefFoundError
NoSuchElementException

java.awt
java.lang
java.lang
java.util

NoSuchFieldError
NoSuchMethodError
NoSuchMethodException

java.lang
java.lang
java.lang

NullPointerException
NumberFormatException

java.lang
java.lang
304

JAVA

St. Angelos Computers Ltd.

Number

java.lang

Double, Float, Integer, Long


Object

java.lang

BitSet, Boolean, BorderLayout,


CardLayout, Character,
CheckboxGroup, Class,
ClassLoader, Color,
ColorModel, Compiler,
Component, ContentHandler,
DatagramPacket,
DatagramPacket, Datagram
Socket, Data, Dictionary,
Dimension, Event, File,
FileDescriptor,
FilteredImageSource,
FlowLayout, Font, FontMetrics,
Graphics, GridBagLayout,
GridLayout, Image, ImageFilter,
InetAddress, InputStream,
InputSteam, Insets, Math,
MediaTracketer,
MemoryImageSource,
MenuComponent, Number,
Observable, OutputStream,
PixelGrabber, Point, Polygon,
305

JAVA

St. Angelos Computers Ltd.

Process. Random,
RamdomAccessFile, Rectangle,
Runtime, SecurityManager,
ServerBuffer, Socket,
SocketImpl, StreamTokenizer,
String, StringBuffer,
StringTokenizer, System,
Thread, ThreadGroup,
Throwable, Toolkit, URL,
URLConnection, URLEncoder,
URLStreamHandler, Vector
Observable

java.util

Observer
OutOfMemoryError

java.util
java.lang

OutputStream

java.io

ByteArrayOutputStream,
FileOutputStream,
FilterOutputStream,
PipedOutputStream
PanelPeer

java.awt.peer

Panel

java.awt

Applet
PipedInputStream

java.io

PipedOutputStream

java.io

306

JAVA

St. Angelos Computers Ltd.

PixelGrabber

java.io

Point

java.awt.image

Polygon
PrintStream

java.awt
java.io

Process
Properties

java.lang
java.util

ProtocolException

java.net

PushbackInputStream

java.io

RandomAccessFile

java.io

Random
Rectangle

java.util
java.awt

RGBImageFilter

java.awt.image

Runnable

java.lang

RuntimeException

java.lang

ArithmeticException,
ArrayStoreException,
ClassCastException,
EmptyStackException,
IllegalArgumentException,
IllegalMonitorStateException,
IndexOutOfBoundsException,
NegativeArraySizeException,
NoSuchElementException,
NullPointerException,
SecurityException

307

JAVA

St. Angelos Computers Ltd.

Runtime
ScrollbarPeer

java.lang

Scrollbar

java.awt

SecurityException
SecurityManager
SequenceInputStream

java.lang
java.lang

java.awt.peer

java.io

ServerSocket

java.net

SocketException

java.net

SocketImplFactory
SocketImpl

java.net
java.net

Socket

java.net

StackOverflowError

java.lang

Stack

java.util

StreamTokenizer

java.io

StringBufferInputStream

java.io

StringBuffer

java.lang

StringIndexOutOfBoundsException
StringTokenizer

java.lang
java.util

String

java.lang

System

java.lang

TextAreaPeer

java.awt.peer

TextArea

java.awt

TextComponentPeer

java.awt.peer

TextAreaPeer, TextFieldPeer
TextComponent

java.awt

TextArea, TextField

308

JAVA

St. Angelos Computers Ltd.

TextFieldPeer

java.awt.peer

TextField
ThreadDeath

java.awt
java.lang

ThreadGroup

java.lang

Thread

java.lang

Throwable

java.lang

Error, Exception
Toolkit

java.awt

UnknownError

java.lang

UnkonwnHostException

java.net

UnknownServiceException

java.net

UnsatisfiedLinkError

java.lang

URLConnection
URLEncoder

java.net

URLStreamHandlerFactory

java.net

java.net

URLStreamHandler

java.net

URL

java.net

UTFDataFormatException
Vector

java.io
java.util

Stack
VerifyError

java.lang

VirtualMachineError

java.lang

InternalError, OutOfMemory
Error, StackOverflowError,
UnknownError
WindowPeer

java.awt.peer

309

JAVA

St. Angelos Computers Ltd.

DialogPeer, FramePeer
Window

java.awt

Dialog, Frame
___________________________________________________________________________

310

Das könnte Ihnen auch gefallen