[go: up one dir, main page]

0% found this document useful (0 votes)
8 views335 pages

Java Programming

The document is a course outline for an M.Sc in Computer Science focusing on Java Programming at Annamalai University. It covers various topics including Java features, data types, object-oriented programming, exception handling, multithreading, and JDBC. The structure includes multiple units with objectives, content, revision points, and suggested readings to facilitate learning and understanding of Java programming.

Uploaded by

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

Java Programming

The document is a course outline for an M.Sc in Computer Science focusing on Java Programming at Annamalai University. It covers various topics including Java features, data types, object-oriented programming, exception handling, multithreading, and JDBC. The structure includes multiple units with objectives, content, revision points, and suggested readings to facilitate learning and understanding of Java programming.

Uploaded by

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

DMSCSE21

ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION

M.Sc COMPUTER SCIENCE


SECOND SEMESTER

JAVA PROGRAMMING
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Copyright Reserved
(For Private Circulation Only)
Java Programming

Table of Contents

UNIT - I

1.0 Introduction 1
1.1 Objective 2
1.2 Content 2
1.2.1 Features of Java 2
1.2.2 Variables and Data Types 6
1.2.3 Java Operators 8
1.2.4 Literals 10
1.2.5 Identifiers 11
1.2.6 Control Statements 17
1.2.7 Arrays 37
1.2.8 Object-Oriented Programming Concepts 41
1.2.9 Inheritance 61
1.2.10 Package 73
1.2.11 Interfaces 79
1.3 Revision Points 81
1.4 Intext Questions 82
1.5 Summary 82
1.6 Terminal Exercises 83
1.7 Supplementary Materials 83
1.8 Assignment 83
1.9 Suggested Reading 84
1.10 Learning Activities 84
1.11 Keywords 84

UNIT - II

2.0 Introduction 85
2.1 Objective 85
2.2 Content 85
2.2.1 Exception Handling 85
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
2.2.2 Multithreading
2.2.3 Input/Output Streams
93
103
2.2.4 Applets 113
2.2.5 AWT 118
2.2.6 Layout Manager 136
2.2.7 Event Handling 143
2.2.8 Socket Programming 148
2.3 Revision Points 153
2.4 Intext Questions 154
2.5 Summary 154
2.6 Terminal Exercises 155
2.7 Supplementary Materials 155
2.8 Assignment 155
2.9 Suggested Reading 156
2.10 Learning Activities 156
2.11 Keywords 156

UNIT - III

3.0 Introduction 157


3.1 Objective 157
3.2 Content 158
3.2.1 Database Foundation 158
3.2.2 Concepts of hierarchical, network and relational DBMS 158
3.2.3 Introduction - OODBMS and ORDBMS 168
3.2.4 Data Modeling 173
3.2.5 Relationships 176
3.2.6 Normalization 179
3.2.7 Denormalization 188
3.2.8 Components of Database 189
3.2.9 Database Engine 191
3.2.10 SQL 197
3.2.11 Oracle Data Types 199
3.3 Revision Points 206
3.4 Intext Questions 207
3.5 Summary 207
3.6 Terminal Exercises 208
3.7 Supplementary Materials 208
3.8 Assignment 208
3.9 Suggested Reading 209
3.10 Learning Activities 209
3.11 Keywords 209

UNIT - IV

4.0 Introduction 210


4.1 Objective 210
4.2 Content 210
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4.2.1 Client/Server Software Architectures-An Overview
4.2.2 ODBC and JDBC drivers
210
213
4.2.3 Architecture Model 215
4.2.4 Types of JDBC technology drivers 215
4.2.5 Connecting to an ODBC DATA SOURCE 218
4.2.6 Developing JDBC based application 220
4.2.7 Examples 231
4.3 Revision Points 238
4.4 Intext Questions 239
4.5 Summary 239
4.6 Terminal Exercises 240
4.7 Supplementary Materials 240
4.8 Assignment 240
4.9 Suggested Reading 240
4.10 Learning Activities 241
4.11 Keywords 241

UNIT - V

5.0 Introduction 242


5.1 Objective 243
5.2 Content 243
5.2.1 Client side and server side JavaScript 243
5.2.1.1 Incorporating JavaScript into HTML 245
5.2.1.2 Data Types in JavaScript 248
5.2.1.3 Declaring variables 249
5.2.1.4 Operators 250
5.2.1.5 Statements 263
5.2.1.6 Core Objects 272
5.2.1.7 JavaScript Objects 272
5.2.1.8 Form Objects 278
5.2.1.9 Event Handling 287
5.2.1.10 What JavaScript is not? 295
5.2.2 Introduction to VBScript 295
5.2.3 Introduction to Servlets 308
5.2.3.1 Use of Servlets 309
5.2.3.2 Servlet Architecture Overview 310
5.2.3.3 Servlet Lifecycle 310
5.2.3.4 Writing the Servlet 311
5.2.3.5 Lifecycle methods 313
5.2.3.6 Servlet Chaining 315
5.2.3.7 Servlet Features 317
5.2.4 Introduction to JSP 322
5.2.5 Servlet and JDBC 325
5.3 Revision Points 327
5.4 Intext Questions 328
5.5 Summary 328
5.6 Terminal Exercises 329
5.7
5.8 ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Supplementary Materials
Assignment
329
329
5.9 Suggested Reading 330
5.10 Learning Activities 330
5.11 Keywords 330
Java Programming

UNIT – I

Snapshot

 Introduction
 Features of Java
 Variables and Data Types
 Java Operators
 Literals
 Identifiers
 Control Statements
 Arrays
 Inheritance
 Classes and Methods
 Package
 Interfaces

1.0 Introduction
Java is a high-level, programming language, like C, FORTRAN, Smalltalk, Perl,
and many others. Java is used to write computer applications that crunch numbers,
process words, play games, store data, or do any of the thousands of other things
computer software can do.

Compared to other programming languages, Java is most similar to C. However


although Java shares much of C's syntax, it is not C. Knowing how to program in C or,
better yet, C++, will certainly help to learn Java more quickly, but there is no need to
know C, to learn Java. Unlike C++ Java is not a superset of C. A Java compiler won't
compile C code, and most large C programs need to be changed substantially before they
can become Java programs.

What is most special about Java in relation to other programming languages is


that it lets to write special programs called applets that can be downloaded from the
Internet and played safely within a web browser. Traditional computer programs have far
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
too much access to the system to be downloaded and executed willy-nilly. Although the
maintainers of various ftp archives and bulletin boards are generally trusted, to do basic
virus checking and not to post destructive software, a lot still slips through the cracks.
Even more dangerous software would be promulgated if any web page that has been
visited could run programs on the system. There is no way of checking these programs
for bugs or for out-and-out malicious behavior before downloading and running them.
Java solves this problem by severely restricting what an applet can do. A Java
applet cannot write to one’s hard disk without their permission. It cannot write to
arbitrary addresses in memory and thereby introduce a virus into the computer. It cannot
crash the system.

Page 1
Java Programming

1.1 Objective
The objective of this lesson is to understand the fundamentals of Java, which
include a wide range of topics from fundamentals of Java and control statements to
packages. The fundamental concepts include variables, operators, exception handling and
methods and classes. At the end of the lesson you learn about constructors and
inheritance.
1.2 Content
1.2.1 Features of Java
Java is a Platform
Java is a platform for application development. A platform is a loosely defined
computer industry buzzword that typically means some combination of hardware and
system software that will mostly run all the same software. For instance PowerMacs
running System 7.5 would be one platform. DEC Alphas running Windows NT would be
another.
There's another problem with distributing executable programs from web pages.
Computer programs are very closely tied to the specific hardware and operating system
they run. A Windows program will not run on a computer that only runs DOS. A Mac
application can't run on a Unix workstation. VMS code can't be executed on an IBM
mainframe, and so on. Therefore major commercial applications like Microsoft Word or
Netscape have to be written almost independently for all the different platforms they run
on. Netscape is one of the most cross-platform of major applications, and it still only runs
on a minority of platforms.
Java solves the problem of platform-independence by using byte code. The Java
compiler does not produce native executable code for a particular machine like a C
compiler would. Instead it produces a special format called byte code. Java byte code
written in hexadecimal, byte by byte, looks like this:
CA FE BA BE 00 03 00 2D 00 3E 08 00 3B 08 00 01 08 00 20 08
This looks a lot like machine language, but unlike machine language Java byte
code is exactly the same on every platform. This byte code fragment means the same
thing on a Solaris workstation as it does on a Macintosh PowerBook. Java programs that
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
have been compiled into byte code still need an interpreter to execute them on any given
platform. The interpreter reads the byte code and translates it into the native language of
the host machine on the fly. The most common such interpreter is Sun's program java
(with a little j). Since the byte code is completely platform independent, only the
interpreter and a few native libraries need to be ported to get Java to run on a new
computer or operating system. The rest of the runtime environment including the
compiler and most of the class libraries are written in Java. All these pieces, the javac
compiler, the java interpreter, the Java programming language, and more are collectively
referred to as Java.

Page 2
Java Programming

Simple
Java was designed to make it much easier to write bug free code. According to
Sun's Bill Joy, shipping C code has, on average, one bug per 55 lines of code. The most
important part of helping programmers write bug-free code is keeping the language
simple.
Java has the bare bones functionality needed to implement its rich feature set. It
does not add lots of syntactic sugar or unnecessary features. Despite its simplicity Java
has considerably more functionality than C, primarily because of the large class library.
Because Java is simple, it is easy to read and write. Obfuscated Java isn't nearly as
common as obfuscated C. There are lots of special cases or tricks that will confuse
beginners.
About half of the bugs in C and C++ programs are related to memory allocation
and deallocation. Therefore the second important addition that Java makes to provide
bug-free code is automatic memory allocation and deallocation. The C library memory
allocation functions malloc() and free() are gone as are C++'s destructors.

Java is an excellent teaching language, and an excellent choice with which to


learn programming. The language is small so it's easy to become fluent. The language is
interpreted so the compile-run-link cycle is much shorter. The runtime environment
provides automatic memory allocation and garbage collection so there's less for the
programmer to think about. Java is object-oriented unlike Basic so the beginning
programmer doesn't have to unlearn bad programming habits when moving into real
world projects. Finally, it's very difficult (if not quite impossible) to write a Java program
that will crash a system.

Object-Oriented

Object oriented programming is the catch phrase of computer programming in the


1990's. Although object oriented programming has been around in one form or another,
since the Simula language was invented in the 1960's, it's really begun to take hold in
modern GUI environments like Windows, Motif and the Mac. In object-oriented
programs, objects represent data. Objects have two sections, fields (instance variables)
and methods. Fields tell - what an object is? Methods tell - what an object does? These
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
fields and methods are closely tied to the object's real world characteristics and behavior.
When a program is run messages are passed back and forth between objects. When an
object receives a message it responds accordingly as defined by its methods. Object
oriented programming is alleged to have a number of advantages including:

1. Simpler, easier to read programs


2. More efficient reuse of code
3. Faster time to market
4. More robust, error-free code

Page 3
Java Programming

In practice object-oriented programs have been just as slow, expensive and buggy
as traditional non-object-oriented programs. In large part this is because the most popular
object-oriented language is C++. C++ is a complex, difficult language that shares all the
obfuscation of C while sharing none of C's efficiencies. It is possible in practice to write
clean, easy-to-read Java code. In C++ this is almost unheard.

Platform Independent
Java was designed not only to be cross-platform in source form like C, but also in
compiled binary form. Since this is frankly impossible across processor architectures Java
is compiled to an intermediate form called byte-code. A Java program never really
executes natively on the host machine. Rather a special native program called the Java
interpreter reads the byte code and executes the corresponding native machine
instructions. Thus to port Java programs to a new platform all that is needed is to port the
interpreter and some of the library routines. Even the compiler is written in Java. The
byte codes are precisely defined, and remain the same on all platforms.
The second important part of making Java cross-platform is the elimination of
undefined or architecture dependent constructs. Integers are always four bytes long, and
floating point variables follow the IEEE 754 standard for computer arithmetic exactly.
No need to worry that the meaning of an integer is going to change if moved from a
Pentium to a PowerPC. In Java everything is guaranteed.

However the virtual machine itself and some parts of the class library must be
written in native code. These are not always as easy or as quick to port as pure Java
programs. This is why for example, there's not yet a version of Java 1.2 for the Mac.

Safe
Java was designed from the ground up to allow for secure execution of code
across a network, even when the source of that code was untrusted and possibly
malicious.
This required the elimination of many features of C and C++. Most notably there
are no pointers in Java. Java programs cannot access arbitrary addresses in memory. All
memory access is handled behind the scenes by the (presumably) trusted runtime

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
environment. Furthermore Java has strong typing. Variables must be declared Casts are
strictly limited to casts between types that make sense. Thus cast such as int to a long or a
byte to a short can be done but not a long to a boolean or an int to a String.

Java implements a robust exception handling mechanism to deal with both


expected and unexpected errors. The worst that an applet can do to a host system is
bringing down the runtime environment.
Most importantly Java applets can be executed in an environment that prohibits
them from introducing viruses, deleting or modifying files, or otherwise destroying data
and crashing the host computer. A Java enabled web browser checks the byte codes of an
applet to verify that it doesn't do anything nasty before it will run the applet.

Page 4
Java Programming

However the biggest security problem is not hackers. It's not viruses. It's not even
insiders erasing their hard drives and quitting the company to go to and work for the
competitors. The biggest security issue in computing today is bugs. Regular, ordinary,
non-malicious unintended bugs are responsible for more data loss and lost productivity
than all other factors combined. Java, by making it easier to write bug-free code,
substantially improves the security of all kinds of programs.

High Performance
Java byte codes can be compiled on the fly to code that rivals C++ in speed using
a "just-in-time compiler." Several companies are also working on native-machine-
architecture compilers for Java. These will produce executable code that does not require
a separate interpreter, and that is indistinguishable in speed from C++.

It is certainly possible to write large programs in Java. The HotJava browser, the
Java Workshop integrated development environment and the javac compiler are large
programs that are written entirely in Java.

Multi-Threaded

Java is inherently multi-threaded. A single Java program can have many different
threads executing independently and continuously. Three Java applets on the same page
can run together with each getting equal time from the CPU with very little extra effort
on the part of the programmer.

This makes Java very responsive to user input. It also helps to contribute to Java's
robustness and provides a mechanism whereby the Java environment can ensure that a
malicious applet doesn't steal all of the host's CPU cycles.

Unfortunately multithreading is so tightly integrated with Java, that it makes Java


rather difficult to port to architectures like Windows 3.1 or the PowerMac that don't
natively support preemptive multi-threading.

There is a cost associated with multi-threading. Multi-threading is to Java what


pointer arithmetic is to C, that is, a source of devilishly hard to find bugs. Nonetheless, in
simple programs it's possible to leave multi-threading alone and normally be OK.
ANNAMALAI
ANNAMALAI UNIVERSITY
Dynamic UNIVERSITY
Java does not have an explicit link phase. Java source code is divided into .java
files, roughly one per each class in the program. The compiler compiles these into .class
files containing byte code. Each .java file generally produces exactly one .class file.

The compiler searches the current directory and directories specified in the
CLASSPATH environment variable to find other classes explicitly referenced by name in
each source code file. If the file that is compiled depends on other, non-compiled files the
compiler will try to find them and compile them as well. The compiler is quite smart, and

Page 5
Java Programming

can handle circular dependencies as well as methods that are used before they're declared.
It also can determine whether a source code file has changed since the last time it was
compiled.

More importantly, classes that were unknown to a program when it was compiled
can still be loaded into it at runtime. For example, a web browser can load applets of
differing classes that it's never seen before without recompilation.

Furthermore, Java .class files tend to be quite small, a few kilobytes at most. It is
not necessary to link in large runtime libraries to produce a (non-native) executable.
Instead the necessary classes are loaded from the user's CLASSPATH.

Garbage Collected

There is no need to explicitly allocate or deallocate memory in Java. Memory is


allocated as needed, both on the stack and the heap, and reclaimed by the garbage
collector when it is no longer needed. There's no malloc(), free(), or destructor methods.

There are constructors and these do allocate memory on the heap, but this is
transparent to the programmer.

Most Java virtual machines use an inefficient, mark and sweep garbage collector.

1.2.2 Variables and Data Types

There are eight primitive data types in Java:

boolean
byte
short
int
long
float
double
char

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
However there are only seven kinds of literals and one of those is not a primitive data
type:

boolean: true or false


int: 89, -945, 37865
long: 89L, -945L, 5123567876L
float: 89.5f, -32.5f,
double: 89.5, -32.5, 87.6E45
char: 'c', '9', 't'
String: "This is a string literal"

Page 6
Java Programming

There are no short or byte literals.

Strings are a reference or object type, not a primitive type. However the Java
compiler has special support for strings.

class Variables {
public static void main (String args[])
{
boolean b = true;
int low = 1;
long high = 76L;
long middle = 74;
float pi = 3.1415292f;
double e = 2.71828;
String s = "Hello World!";
}
}

Primitive Data Types in Java

Java's primitive data types are very similar to those of C. They include boolean,
byte, short, int, long, float, double, and char.

Where C and C++ leave a number of issues to be machine and compiler


dependent (for instance the size of an int). Java specifies everything.

Java prevents casting between arbitrary variables. Only casts between numeric
variables and between sub and superclasses of the same object are allowed.

All numeric variables in Java are signed.

Size isn't necessary in Java because all sizes are precisely defined. For instance,
an int is always 4 bytes. This may not seem to be adequate when dealing with objects that
aren't base data types. However even if the size of a particular object is not known,
anything couldn't be done with it anyway. An arbitrary object cannot be converted into
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
bytes and back again.
boolean

1-bit. May take the value, true or false.


true and false are defined constants of the language and are not the same as True
and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value.
Booleans may not be cast into any other type of variable nor may any other variable be
cast into a boolean.

byte
Page 7
Java Programming

1 signed byte (two's complement). ranges values from -128 to 127.

short
2 bytes, signed (two's complement), ranges from -32,768 to 32,767
int
4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all
numeric types ints may be cast into other numeric types (byte, short, long, float, double).
When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of
the smaller type.

long

8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to


+9,223,372,036,854,775,807.
float

4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to


3.40282346638528860e+38 (positive or negative).

Like all numeric types floats may be cast into other numeric types (byte, short,
long, int, double). When lossy casts to integer types are done (e.g. float to short) the
fractional part is truncated and the conversion is done modulo the length of the smaller
type.

double

8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to


1.79769313486231570e+308d (positive or negative).

char

2 bytes, unsigned, Unicode, 0 to 65,535


Chars are not the same as bytes, ints, shorts or Strings.

1.2.3 Java Operators


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
An operator is a symbol that operates on one or more arguments to produce a
result. Almost all programs uses operators.

Operator Purpose
+ addition of numbers, concatenation of Strings
+= add and assign numbers, concatenate and assign Strings
- Subtraction
-= subtract and assign
* Multiplication

Page 8
Java Programming

*= multiply and assign


/ Division
/= divide and assign
| bitwise OR
|= bitwise OR and assign
^ bitwise XOR
^= bitwise XOR and assign
& bitwise AND
&= bitwise AND and assign
% take remainder
%= take remainder and assign
> greater than
>= greater than or equal to
< less than
<= less than or equal to
! boolean NOT
!= not equal to
++ increment by one
-- decrement by one
>> shift bits right with sign extension
>>= shift bits right with sign extension and assign
<< shift bits left
<<= shift bits left and assign
>>> unsigned bit shift right
>>>= unsigned bit shift right and assign
&& boolean AND
|| boolean OR
== boolean equals
= Assignment
~ bitwise NOT
?: Conditional
instanceof type checking

White Space

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
White space consists mostly of the space character that is produced by hitting the
space bar on the keyboard and that is commonly used to separate words in sentences.
There are four other white space characters in Java, the horizontal tab, the form feed, the
carriage return, and the linefeed. Depending on the platform, when the return key is hit,
either a carriage return (the Mac), a linefeed (Unix) or both (DOS, Windows, VMS) is
got. This produces a hard line break in the source code text.

Outside of String literals Java treats all white space and runs of white space (more
than one white space character in immediate succession) the same. It's used to separate
tokens, and one space is as good as seven spaces, a tab and two carriage returns. Exactly

Page 9
Java Programming

with white space characters that has been used is primarily a result of what's convenient
for human beings reading the code. The compiler doesn't care.

Inside String and character literals the only white space permitted is the space
character. Carriage returns, tabs, line feeds and form feeds must be inserted with special
escape sequences like \r, \t, \f, and \n. A String cannot be broken across a line like this:

String poem = "Mary had a little lamb


whose fleece was white as snow
and everywhere that Mary went
the lamb was sure to go.";

Instead, \n and the string concatenation operator, + are used like this:

String poem = "Mary had a little lamb\n" +


"whose fleece was white as snow\n" +
"and everywhere that Mary went\n" +
"the lamb was sure to go.";

Note that a statement can be broken across multiple lines, but a String literal
cannot be.

Also note that \n only works on UNIX. Probably the


System.getProperty("line.separator") should be used instead to return the proper line
separator string for the platform that the program is running on.

Java does not have all the escape sequences C has. Besides those already
mentioned it has only \b for backspace, \\ for the backslash character itself.

There are also \u escapes that let to include any Unicode character.

1.2.4 Literals

Literals are pieces of Java source code that mean exactly what they say. For
instance "Hello World!" is a String literal and its meaning is the Hello World!

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The string "Hello World!" looks like as it is several things; but to the compiler it
is just one thing, a String. This is similar to how an expression like 1,987,234 may be
seven digits and two commas but is really just one number.

The double quote marks tells that this is a string literal. A string is an ordered
collection of characters (letters, digits, punctuation marks, etc.). Although the String may
have meaning to a human being reading the code, the computer sees it as no more than a
particular set of letters in a particular order. It has no concept of the meaning of the
characters. For instance it does not know that "two" + "two" is "four." In fact the
computer thinks that "two" + "two" is "twotwo"

Page 10
Java Programming

The quote marks show where the string begins and ends. However the quote
marks themselves are not a part of the string. The value of this string is Hello World!, not
"Hello World!" The output of the program can be changed from Hello World to some
other line of text.

A string in a Java program has no concept of italics, bold face, font family or
other formatting. It cares only about the characters that compose it.

char literals are similar to string literals except they're enclosed in single quotes
and must have exactly one character. For example 'c' is a char literal that means the letter
c.
true and false are boolean literals that mean true and false.

Numbers can also be literals. 34 is an int literal and it means the number thirty-
four. 1.5 is a double literal. 45.6, 76.4E8 (76.4 times 10 to the 8th power) and -32.0 are
also double literals.

34L is a long literal and it means the number thirty-four. 1.5F is a float literal.
45.6f, 76.4E8F and -32.0F are also float literals.

1.2.5 Identifiers in Java

Identifiers are the names of variables, methods, classes, packages and interfaces.
Unlike literals they are not the things themselves, just ways of referring to them.

Identifiers must be composed of letters, numbers, the underscore _ and the dollar
sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.

Each variable has a name by which it is identified in the program. It's a good idea
to give mnemonic names to variables that are closely related to the values they hold.
Variable names can include any alphabetic character or digit and the underscore. The
main restriction on the names that are given to the variables is that they cannot contain
any white space. A variable name cannot begin with a number. It is important to note that
as in C but not as in Fortran or Basic, all variable names are case-sensitive. MyVariable is
not the same as myVariable. There is no limit to the length of a Java variable name. The
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
following are legal variable names:

MyVariable
myvariable
MYVARIABLE
x
i
_myvariable
$myvariable
_9pins

Page 11
Java Programming

andros
ανδρος
OReilly
This_is_an_insanely_long_variable_name_that_just_keeps_going_and_going_an
d_going_and_well_you_get_the_idea_The_line_breaks_arent_really_part_of_the_variabl
e_name_Its_just_that_this_variable_name_is_so_ridiculously_long_that_it_won't_fit_on
_the_page_I_cant_imagine_why_you_would_need_such_a_long_variable_name_but_if_
you_do_you_can_have_it
The following are illegal variable names.
My Variable // Contains a space
9pins // Begins with a digit
a+c // The plus sign is not an alphanumeric character
testing1-2-3 // The hyphen is not an alphanumeric character
O'Reilly // Apostrophe is not an alphanumeric character
OReilly_&_Associates // ampersand is not an alphanumeric character
How to Begin a Variable Name with a Number
To begin a variable name with a digit, prefix the name (e.g. 8ball) with an
underscore, e.g. _8ball. The underscore can also be used to act like a space in long
variable names.
Keywords
Keywords are identifiers like public, static and class that have a special meaning
inside Java source code and outside of comments and Strings.
Keywords are reserved for their intended use and cannot be used by the
programmer for variable or method names.

There are fifty reserved keywords in Java 1.1 (51 in Java 1.2). The forty-eight that
are actually used in are listed below.
Keywords Used in Java 1.1
Keyword Purpose
Abstract declares that a class or method is abstract
boolean declares a boolean variable or return type
break
byte
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
prematurely exits a loop
declares a byte variable or return type
case one case in a switch statement
catch handle an exception
char declares a character variable or return type
class signals the beginning of a class definition
continue prematurely return to the beginning of a loop
default default action for a switch statement
do begins a do while loop
double declares a double variable or return type
else signals the code to be executed if an if statement is not true

Page 12
Java Programming

extends specifies the class which this class is a subclass of


declares that a class may not be subclassed or that a field or method may
final
not be overridden
finally declares a block of code guaranteed to be executed
float declares a floating point variable or return type
for begins a for loop
if execute statements if the condition is true
implements declares that this class implements the given interface
import permit access to a class or group of classes in a package
instanceof tests whether an object is an instanceof a class
int declares an integer variable or return type
interface signals the beginning of an interface definition
long declares a long integer variable or return type
native declares that a method is implemented in native code
new allocates a new object
package defines the package in which this source code file belongs
private declares a method or member variable to be private
protected declares a class, method or member variable to be protected
public declares a class, method or member variable to be public
return returns a value from a method
short declares a short integer variable or return type
declares that a field or a method belongs to a class rather
static
than an object
super a reference to the parent of the current object
switch tests for the truth of various possible cases
synchronized Indicates that a section of code is not thread-safe
this a reference to the current object
throw throw an exception
throws declares the exceptions thrown by a method
transient This field should not be serialized
try attempt an operation that may throw an exception
void declare that a method does not return a value
volatile Warns the compiler that a variable changes asynchronously
while begins a while loop

Two other keywords, const and goto, are reserved by Java but are not actually
implemented. This allows compilers to produce better error messages if these common
C++ keywords are improperly used in a Java program.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Java 1.2 adds the strictfp keyword to declare that a method or class must be run
with exact IEEE 754 semantics.
true and false appear to be missing from this list. In fact, they are not keywords
but rather boolean literals. But still it can't be used as a variable name.
Separators in Java
Separators help define the structure of a program. Parentheses ( ), braces { }, the
period ., and the semicolon ;. The table lists the six Java separators (nine if counted
opening and closing separators as two).
Page 13
Java Programming

Separator Purpose
Encloses arguments in method definitions; adjusts
precedence in arithmetic expressions; surrounds
()
cast types and delimits test expressions in flow
control statements
defines blocks of code and automatically initializes
{}
arrays
[] declares array types and dereferences array values
; terminates statements
separates successive identifiers in variable
, declarations; chains statements in the test,
expression of a for loop
Selects a field or method from an object; separates
.
package names from sub-package and class names
: Used after loop labels

Addition of Integers in Java

class AddInts
{
public static void main (String args[])
{
int i = 1;
int j = 2;
int k;
System.out.println("i is " + i);
System.out.println("j is " + j);
k = i + j;
System.out.println("i + j is " + k);
k = i - j;
System.out.println("i - j is " + k);
}
}

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Here's what happens when AddInts is run.

>javac AddInts.java
>java AddInts
i is 1
j is 2
i + j is 3
i - j is -1

The Remainder or Modulus Operator in Java

Page 14
Java Programming

Java has one important arithmetical operator one may not be familiar with, %,
also known as the modulus or remainder operator. The % operator returns the remainder
of two numbers. For instance 10 % 3 is 1 because 10 divided by 3 leaves a remainder of
1. % is used as any other more common operator like + or -.

class Remainder {
public static void main (String args[]) {
int i = 10;
int j = 3;
int k;

System.out.println("i is " + i);


System.out.println("j is " + j);

k = i%j;
System.out.println("i%j is " + k);
}
}

Here's the output:


>javac Remainder.java
>java Remainder
i is 10
j is 3
i%j is 1
%

Perhaps surprisingly the remainder operator can be used with floating point values
as well. It's surprising because normally don’t think of real number division as producing
remainders. However there are rare times when it's useful to ask exactly how many times
does 1.5 go into 5.5 and what's left over? The answer is that 1.5 goes into 5.5 three times
with one left over, and it's that one which is the result of 5.5 % 1.5 in Java.

Converting Strings to Numbers

When processing user input it is often necessary to convert a String that the user
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
enters into an int. The syntax is straightforward. It requires using the static
Integer.valueOf(String s) and intValue() methods from the java.lang.Integer class. To
convert the String "22" into the int 22 could be written as:

int i = Integer.valueOf("22").intValue();

Doubles, floats and longs are converted similarly. To convert a String like "22"
into the long value 22 would be written as:

long l = Long.valueOf("22").longValue();

Page 15
Java Programming

To convert "22.5" into a float or a double, it would be written as:

double x = Double.valueOf("22.5").doubleValue();
float y = Float.valueOf("22.5").floatValue();

The various valueOf() methods are relatively intelligent and can handle plus and
minus signs, exponents, and most other common number formats. However if a
completely non-numeric like "pretty in pink," is passed it will throw a
NumberFormatException. So it is better to avoid passing theses methods non-numeric
data.

The char data type in Java

A char is a single character, that is a letter, a digit, a punctuation mark, a tab, a


space or something similar. A char literal is a single one character enclosed in single
quote marks like this

char myCharacter = 'g';

Some characters are hard to type. For these Java provides escape sequences. This
is a backslash followed by an alphanumeric code. For instance '\n' is the newline
character. '\t' is the tab character. '\\' is the backslash itself. The following escape
sequences are defined:

\b backspace
\t tab
\n linefeed
\f formfeed
\r carriage return
\" double quote, "
\' single quote, '
\\ backslash, \

The double quote escape sequence is used mainly inside strings where it would
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
otherwise terminate the string. For instance

System.out.println("And then Jim said, \"Who's at the door?\"");

It isn't necessary to escape the double quote inside single quotes. The following
line is legal in Java

char doublequote = '"';

Page 16
Java Programming

Unicode

Java uses the Unicode character set. Unicode is a two-byte character code set that
has characters representing almost all characters in almost all human alphabets and
writing systems around the world including English, Arabic, Chinese and more.

Unfortunately many operating systems and web browsers do not handle Unicode.
For the most part Java will properly handle the input of non-Unicode characters. The first
128 characters in the Unicode character set are identical to the common ASCII character
set. The second 128 characters are identical to the upper 128 characters of the ISO Latin-
1 extended ASCII character set. It's the next 65,280 characters that present problems.

A particular Unicode character can be referred by using the escape sequence \u


followed by a four digit hexadecimal number. For example

\u00AE © The copyright symbol


\u0022 " The double quote
\u00BD ½ The fraction ½
\u0394 Δ The capital Greek letter delta
\u00F8 Ø A little o with a slash through it

The full Unicode character sequence can be used to name the variables.

String Mj\u00F8lner = "Hammer of Thor";

but frankly this is way more trouble than it's worth.

1.2.6 Control Statements

if
else
else if
while
for
do while

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
switch case
break
continue

The if statement in Java


All but the most trivial computer programs need to make decisions. They test a
condition and operate differently based on the outcome of the test. This is quite common
in real life. For instance we stick our hand out the window to test if it's raining. If it is
raining then we take an umbrella with us. If it isn't raining then we won't.

Page 17
Java Programming

All programming languages have some form of an if statement that tests


conditions. Generally the command line arguments must be tested before they are used.

Arrays have lengths and can access that length by referencing the variable
arrayname.length, the length of the args array is tested as follows.

// This is the Hello program in Java

class Hello {

public static void main (String args[]) {

if (args.length > 0) {
System.out.println("Hello " + args[0]);
}
}

System.out.println(args[0]) was wrapped in a conditional test, if (args.length > 0)


{ }. The code inside the braces, System.out.println(args[0]), now gets executed if and
only if the length of the args array is greater than zero.

The arguments to a conditional statement like if must be a boolean value, that is


something that evaluates to true or false. Integers are not permissible.

In Java numerical greater than and lesser than tests are done with the > and <
operators respectively. A number is less than or equal to or greater than or equal to
another number can be tested with the <= and >= operators .

Testing for Equality

Testing for equality is a little trickier. One would expect to test if two numbers
are equal by using the = sign. However the = sign has already been used as an assignment
operator that sets the value of a variable. Therefore a new symbol is needed to test for
equality. Java borrows C's double equals sign, ==, for this purpose.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
It's not uncommon for even experienced programmers to write == when they
mean = or vice versa. In fact this is a very common cause of errors in C programs.
Fortunately in Java, we are not allowed to use == and = in the same places. Therefore the
compiler can catch the mistake and helps to fix it before the program is executed.

However there is one way still to get into trouble:

boolean b = true;
if (b = false) {

Page 18
Java Programming

System.out.println("b is false");
}

To avoid this, some programmers get in the habit of writing condition tests like
this:

boolean b = true;
if (false = b) {
System.out.println("b is false");
}

Since you can't assign to a literal, this causes a compiler error if you misuse the =
sign when you mean to write ==.

The else statement in Java

// This is the Hello program in Java

class Hello {

public static void main (String args[]) {

if (args.length > 0) {
System.out.println("Hello " + args[0]);
}
else {
System.out.println("Hello whoever you are.");
}
}

else if

if statements are not limited to two cases. An else and an if can be combined to
make an else if and test a whole range of mutually exclusive possibilities. For instance,
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
here's a version of the Hello program that handles up to four names on the command line:

// This is the Hello program in Java

class Hello {

public static void main (String args[]) {

if (args.length == 0) {
System.out.println("Hello whoever you are");

Page 19
Java Programming

}
else if (args.length == 1) {
System.out.println("Hello " + args[0]);
}
else if (args.length == 2) {
System.out.println("Hello " + args[0] + " " + args[1]);
}
else if (args.length == 3) {
System.out.println("Hello " + args[0] + " " + args[1] + " " + args[2]);
}
else if (args.length == 4) {
System.out.println("Hello " + args[0] +
" " + args[1] + " " args[2] + " " + args[3]);
}
else {
System.out.println("Hello " + args[0] + " " + args[1] + " " args[2]
+ " " + args[3] + " and all the rest!");
}
}
}

The for loop in Java

Another useful instruction to control the logic flow of the program, is the for
instruction. It allows software developers to demand the execution of one or more
instructions more times, until a particular condition, called condition of escape (or exit
condition) of the loop, returns a true value. The Java syntax of a for loop instruction is the
following one:

for (v=startValue; condition_on_v; instruction_on_v)


{
BodyOfCycle;
}
where v is the control variable of the cycle. v is initialized to the value startValue
when the cycle begins. condition_on_v is the condition of control of the cycle. The cycle
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
ends when condition_on_v returns a false value (that is when the condition_on_v is no
more verified, therefore false). The first check on the condition is carried out before the
first iterance, it is therefore possible that the instructions held in the body of the cycle
(BodyOfCycle) are never executed. This happens when condtion_on_v immediately
returns a false value. instruction_on_v is an instruction that modifies the value of the
control variable v. Such instruction generally makes v to move to a value that makes
condition_on_v false to stop the loop execution. This should happen after a certain
number of iterances. If it is not so, the risk would be the one to generate an infinite loop,
that is a never ending loop.

Here are some examples in which for instruction is used.


Page 20
Java Programming

The first example simply prints the numbers from one to ten.

int k;
for (k=0;k<10;k++)
System.out.println (k+1);

The control variable of the cycle is k. k is first declared and then initialised on a
zero value at the cycle's beginning. The control condition of the cycle returns a true value
until k is smaller than 10. The instruction on k consists in its increment at every iterance.
The body of the cycle is a print instruction. At the first iterance k has been just initialised
and is value is zero. The output of the first iterance will be (k+1), that is 1. In the second
iterance, k has assumed value 1, therefore the output of the print instruction in the body
of the cycle will be 2. The cycle repeats until k does not assume value 10. At this step the
condition of control (k < 10) turns out false and the cycle exits. The output of the
program is:

1
2
3
4
5
6
7
8
9
10
If we prefer to write the same numbers on a single line we could use of the print()
method instead of println() one. print() differs from println() just because after having
written its parameter it does not add a carriage return ending the current output line. The
code would be:

int k;
for (k=0;k<10;k++) {
System.out.print (k+1);
if (k<9) System.out.print(", ");
ANNAMALAI
ANNAMALAI UNIVERSITY
} UNIVERSITY
System.out.println(".");

whose output it is:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10.

The if... instruction in the body of the cycle has the task of positioning commas
correctly in order to separate any printed number to the next one. At the end of the cycle
a println() method adds a point (.) and a carriage return to complete the program's output.

Page 21
Java Programming

We had pointed out to the chance to write a cycle whose instructions are never
executed. An example of this kind of cycle is the following one:

int k;
for (k=0;false;k++)
System.out.println("This instruction is never executed");

The print instruction in the body of this cycle will never be executed because the
exit condition of the cycle has been replaced by a constant false value. The fields of
initialization and increment of the control variable are uninfluent here, as well as that
they would have been omitted as we'll do in the following example.
int k;
for (;false;)
System.out.println("This instruction is never executed");

Semicolon characters (;) cannot be omitted because they indicate to the Java
interpreter, to which field (initialization, control or increment) the false value refers to.
Obviously it has no sense to write a for cycle like the described one. Generally it is
marked at compilation time with a "Statement not reached" error message.
In the same way we built an null cycle it is possible to write an infinite loop too. Observe
the following code:

for (;true;)
System.out.println("Warning! This is a never ending loop!");

That for convention it is often used with the following syntax:

for (;;)
System.out.println("Warning! This is a never ending loop!");

that is a for cycle in which all the three fields (initialization, control, increment)
are missing. While null cycles are never used, it is not so for infinite cycles. This is due to
the simple reason that in truth... they are not infinite! It is in fact possible to interrupt the
execution of a cycle through a particular command placed in cycle's body. Observe the
following example whose output is the same of the examples introduced previously:

ANNAMALAI
ANNAMALAI UNIVERSITY
int k=0;
for (;;) {
UNIVERSITY
if (k==10) break;
System.out.print (k+1);
if (k<9) System.out.print(", ");
k++;
}
System.out.println(".");

it supplies the output:

Page 22
Java Programming

1, 2, 3, 4, 5, 6, 7, 8, 9, 10.

In the body of the cycle is the instruction break, whose task is to interrupt the
execution of the cycle. Such instruction arranged with the if... instruction makes the cycle
to stop when the variable k reaches the value 10. This is a little twisted way to set up a
cycle, however sometimes infinite loops with a break instruction inside can be useful.
Generally break instruction is used in order to stop the execution of a loop if a particular
event has occurred and there is no need to continue the cycle execution.

Another instruction one can use inside the body of a for cycle is continue.
Continue suspends the actual iterance and immediately jumps the successive one. Look at
this example:

int k;
for (k=0;k<10;k++) {
if (k==4) continue;
System.out.print (k+1);
if (k<9) System.out.print(", ");
}
System.out.println(".");

it is the same example code that writes the numbers from one to ten on a line. The
difference is in the instruction

if (k==4) continue;
whose effect is to discard the fifth iterance (k starts from 0) of the loop, jumping
next one. The output of the program is:

1,2,3,4,6,7,8,9,10.
where number 5 lacks. This is the number that would have been printed in the
fifth iterance.

Often it turns out useful to make use of what we call nested cycles, that are loops
definded in the body of another cycle. The following example shows how to use a nested
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
cycle to generate one Pythagorean table.

int k;
int j;
for (k=1;k<10;k++) {
for (j=1;j<=10;j++) {
System.out.print(j*k);
System.out.print (" ");
}
System.out.println();
}
Page 23
Java Programming

The output of the program it will be:

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 10 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90

For every iterance of the first cycle, all the iterances of second, nested loop are
executed. In our example in every iterance of the first cycle all the ten iterances of the
second one are executed. Every complete execution of the second nested loop create one
of the nine output lines.

Multiple Initializers and Incrementers

Sometimes it's necessary to initialize several variables before beginning a for


loop. Similarly you may want to increment more than one variable. Java lets you do this
by placing a comma between the different initializers and incrementers like this:

for (int i = 1, j = 100; i < 100; i = i+1, j = j-1) {


System.out.println(i + j);
}

However multiple test conditions cannot be included.

The following line is illegal and will generate a compiler error.

for (int i = 1, j = 100; i <= 100, j > 0; i = i-1, j = j-1) {

To include multiple tests, the boolean logic operators && and || need to be used .

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The while loop in Java

A while cycle is a little less sophisticated than a for cycle, but it carries out
approximately the same function. It is composed by a body containing some instructions
and a exit condition. At the beginning of the cycle and every time that all the instructions
in the body are executed, the exit condition, which constitutes of a boolean expression, is
checked. The cycle ends when the condition returns a false value.
The syntax of a while cycle is the following:

Page 24
Java Programming

while (condition)
{
BodyOfCycle;
}

where condition is the control condition of the cycle. The first check of the
condition's validity takes place at the beginning of the cycle, before the first iterance. In
this case too, it can happen that the instructions included in the cycle's body are never
executed. This happens when the condition immediately returns a false value. As it is for
the for cycles, also with while cycles there is the danger to create a never ending loop.
This happens when iterance after iterance, the exit condition never returns a false value.

The first example that we are going to propose supplies the same output of the
first example proposed in the previous chapter: it prints the numbers from one to 10.

int k = 0;
while (k>10) {
System.out.println(k+1);
k++;
}

observe that in this case it is necessary to supply to the increment of the control
variable k, by adding an instruction to the inside of the body of the cycle. The output of
the program it is:

1
2
3
4
5
6
7
8
9
10
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
If we prefer to have the ten numbers written on one single line we can edit the
code as it follows:

int k = 0;
while (k>10) {
System.out.print(k+1);
If (k<9) System.out.print (",");
k++;

Page 25
Java Programming

}
System.out.println (".");

now the output is:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10.

As it happened with the for instruction, also using while cycles it is possible to
generate null or infinite loops. In the first case we will write:

while (false)
System.out.println ("This instruction is never executed");
in the second:

while (true)
System.out.println ("Warning! This is a never ending loop!");

continue and break instructions work with while cycles in the same way too.
Nested while cycles are less frequent but however realizable.

In table below for and while loops code is compared. Each couple of cycles
executes the same operations and returns exactly the same output.

Cycle for Cycle while


i=0;
for (i=0; i<10; i++) while (i<10)
{ {
System.out.println("Iteraton n° "+i); System.out.println("Iteration n° "+i);
} i++;
}
i=0;
for (i=0;; i++)
while (i<10)
{
{ System.out.println("Iteration n° "+i);
System.out.println("Iteration n° "+i);
i++;
if (i==8)
if (i==9)
} ANNAMALAI
ANNAMALAI UNIVERSITY
break;
UNIVERSITY }
break;

i=0;
for (i=0;i<10; i++)
while (i<10)
{
{ if (i==6)
if (i==6)
continue;
continue;
System.out.println("Iteration n° "+i);
System.out.println("Iteration n° "+i);
i++;
}
}
for (;;) ; while (true);

Page 26
Java Programming

for and while cycles comparison

The do while loop in Java

// This is the Hello program in Java

class Hello {

public static void main (String args[]) {

int i = -1;
do {
if (i == -1) System.out.print("Hello ");
else {
System.out.print(args[i]);
System.out.print(" ");
}
i = i + 1;
} while (i < args.length);
System.out.println(); // Finish the line
}

Booleans
Booleans are named after George Boole, a nineteenth century logician. Each
boolean variable has one of two values, true or false. These are not the same as the
Strings "true" and "false". They are not the same as any numeric value like 1 or 0. They
are simply true and false. Booleans are not numbers; they are not Strings. They are
simply booleans.
Boolean variables are declared just like any other variable.
boolean test1 = true;
boolean test2 = false;

Note that true and false are reserved words in Java. These are called the Boolean
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
literals. They are case sensitive. True with a capital T is not the same as true with a little
t. The same is true of False and false.
Relational Operators
Java has six relational operators that compare two numbers and return a boolean
value. The relational operators are <, >, <=, >=, ==, and !=.

x < y Less than True if x is less than y, otherwise false.


x > y Greater than True if x is greater than y, otherwise false.
x <= y Less than or equal to True if x is less than or equal to y, otherwise

Page 27
Java Programming

false.
True if x is greater than or equal to y,
x >= y Greater than or equal to
otherwise false.
x == y Equal True if x equals y, otherwise false.
x != y Not Equal True if x is not equal to y, otherwise false.

Here are some code snippets showing the relational operators.

boolean test1 = 1 < 2; // True. One is less that two.


boolean test2 = 1 > 2; // False. One is not greater than two.
boolean test3 = 3.5 != 1; // True. One does not equal 3.5
boolean test4 = 17*3.5 >= 67.0 - 42; //True. 59.5 is greater than 5
boolean test5 = 9.8*54 <= 654; // True. 529.2 is less than 654
boolean test6 = 6*4 == 3*8; // True. 24 equals 24
boolean test7 = 6*4 <= 3*8; // True. 24 is less than or equal to 24
boolean test8 = 6*4 < 3*8; // False. 24 is not less than 24

This, however, is an unusual use of booleans. Almost all use of booleans in


practice comes in conditional statements and loop tests. You've already seen several
examples of this. Earlier you saw this

if (args.length > 0) {
System.out.println("Hello " + args[0]);
}

args.length > 0 is a boolean value. In other words it is either true or it is false. You
could write
boolean test = args.length > 0;
if (test) {
System.out.println("Hello " + args[0]);
}
instead. However in simple situations like this the original approach is customary.
Similarly the condition test in a while loop is a boolean. When you write while (i <
args.length) the i < args.length is a boolean.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Relational Operator Precedence

Whenever a new operator is introduced you have to ask yourself where it fits in
the precedence tree. If you look back at the example in the last section, you'll notice that
it was implicitly assumed that the arithmetic was done before the comparison. Otherwise,
for instance
boolean test8 = 6*4 < 3*8; // False. 24 is not less than 24

4 < 3 returns false which would then be multiplied by six and eight which would
generate a compile time error because you can't multiply booleans. Relational operators

Page 28
Java Programming

are evaluated after arithmetic operators and before the assignment operator. == and !=
have slightly lower precedences than <, >, <= and >=. Here's the revised order:

*, /, % Do all multiplications, divisions and remainders from left to right.


+, - Next do additions and subtractions from left to right.
<, >, >=, <= Then any comparisons for relative size.
==, != Then do any comparisons for equality and inequality
= Finally assign the right-hand side to the left-hand side
For example,
boolean b1 = 7 > 3 == true;
boolean b2 = true == 7 > 3;
b = 7 > 3;

Testing Objects for Equality


<, >, <= and >= can only be used with numbers and characters. They cannot be
used with Strings, booleans, arrays or other compound types since there's no well-defined
notion of order for these objects. Is true greater than false? Is "My only regret is that I
have but one life to give for my country" greater than "I have a dream"?. Equality is a
little easier to test however. true is equal to true and true is not equal to false. Similarly
"My only regret is that I have but one life to give for my country" is not equal to "I have a
dream." However you might be surprised if you ran this program:
class JackAndJill {

public static void main(String args[]) {

String s1 = new String("Jack went up the hill.");


String s2 = new String("Jack went up the hill.");

if ( s1 == s2 ) {
System.out.println("The strings are the same.");
}

else if ( s1 != s2 ) {

ANNAMALAI
ANNAMALAI UNIVERSITY
}
} UNIVERSITY
System.out.println("The strings are not the same.");

}
The result is
The strings are not the same.

Testing for Equality with equals()

That's not what you expected. To compare strings or any other kind of object you
need to use the equals(Object o) method from java.lang.String. Below is a corrected

Page 29
Java Programming

version that works as expected. The reasons for this odd behavior go fairly deep into Java
and the nature of object data types like strings.
class JackAndJill {

public static void main(String args[]) {


String s1 = new String("Jack went up the hill.");
String s2 = new String("Jack went up the hill.");
if ( s1.equals(s2) ) {
System.out.println("The strings are the same.");
}
else {
System.out.println("The strings are not the same.");
}
}
}

Break
A break statement exits a loop before an entry condition fails. For example, in this
variation on the CountWheat program an error message is printed, and you break out of
the for loop if j becomes negative.
class CountWheat {
public static void main (String args[]) {
int total = 0;
for (int square=1, int grains = 1; square <= 64; square++) {
grains *= 2;
if (grains <= 0) {
System.out.println("Error: Overflow");
break;
}
total += grains;
System.out.print(total + "\t ");
if (square % 4 == 0) System.out.println();
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
}
System.out.println("All done!");
}
}

Here's the output:


>javac CountWheat.java
>java CountWheat
2 6 14 30
62 126 254 510
1022 2046 4094 8190
Page 30
Java Programming

16382 32766 65534 131070


262142 524286 1048574 2097150
4194302 8388606 16777214 33554430
67108862 134217726 268435454 536870910
1073741822 2147483646 Error: Overflow
All done!
%

The most common use of break is in switch statements.


Continue
It is sometimes necessary to exit from the middle of a loop. Sometimes you'll
want to start over at the top of the loop. Sometimes you'll want to leave the loop
completely. For these purposes Java provides the break and continue statements.
A continue statement returns to the beginning of the innermost enclosing loop
without completing the rest of the statements in the body of the loop. If you're in a for
loop, the counter is incremented. For example this code fragment skips even elements of
an array
for (int i = 0; i < m.length; i++) {

if (m[i] % 2 == 0) continue;
// process odd elements...

The continue statement is rarely used in practice, perhaps because most of the
instances where it's useful have simpler implementations. For instance, the above
fragment could equally well have been written as

for (int i = 0; i < m.length; i++) {

if (m[i] % 2 != 0) {
// process odd elements...

}
ANNAMALAI
ANNAMALAI UNIVERSITY
}
UNIVERSITY
There are only seven uses of continue in the entire Java 1.0.1 source code for the
java packages.

Labeled Loops
Normally inside nested loops break and continue exit the innermost enclosing
loop. For example consider the following loops.
for (int i=1; i < 10; i++) {
Page 31
Java Programming

for (int j=1; j < 4; j++) {


if (j == 2) break;
System.out.println(i + ", " + j);
}
}
This code fragment prints
1, 1
2, 1
3, 1
4, 1
5, 1
6, 1
7, 1
8, 1
9, 1
because you break out of the innermost loop when j is two. However the
outermost loop continues.
To break out of both loops, label the outermost loop and indicate that label in the
break statement like this:
iloop: for (int i=1; i < 3; i++) {
for (int j=1; j < 4; j++) {
if (j == 2) break iloop;
System.out.println(i + ", " + j);
}
}
This code fragment prints
1, 1

and then stops because j is two and the outermost loop is exited.

The switch statement in Java


Switch statements are shorthands for a certain kind of if statement. It is not

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
uncommon to see a stack of if statements all relate to the same quantity like this:
if (x == 0) doSomething0();
else if (x == 1) doSomething1();
else if (x == 2) doSomething2();
else if (x == 3) doSomething3();
else if (x == 4) doSomething4();
else doSomethingElse();

Java has a shorthand for these types of multiple if statements, the switch-case
statement. Here's how you'd write the above using a switch-case:

Page 32
Java Programming

Switch – case
switch (x) {
case 0:
doSomething0();
break;
case 1:
doSomething1();
break;
case 2:
doSomething2();
break;
case 3:
doSomething3();
break;
case 4:
doSomething4();
break;
default:
doSomethingElse();
}
In this fragment x must be a variable or expression that can be cast to an int
without loss of precision. This means the variable must be or the expression must return
an int, byte, short or char. x is compared with the value of each the case statements in
succession until one matches. This fragment compares x to literals, but these too could be
variables or expressions as long as the variable or result of the expression is an int, byte,
short or char. If no cases are matched, the default action is triggered.
Once a match is found, all subsequent statements are executed until the end of the
switch block is reached or you break out of the block. This can trigger decidedly
unexpected behavior. Therefore it is common to include the break statement at the end of
each case block. It's good programming practice to put a break after each one unless you
explicitly want all subsequent statements to be executed.
It's important to remember that the switch statement doesn't end when one case is
matched and its action performed. The program then executes all statements that follow

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
in that switch block until specifically told to break.
The ? : operator in Java

The value of a variable often depends on whether a particular boolean expression


is or is not true and on nothing else. For instance one common operation is setting the
value of a variable to the maximum of two quantities. In Java you might write

if (a > b) {
max = a;
}
Page 33
Java Programming

else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a
common use of if-else that a shortcut has been devised for it, the conditional operator, ?:.
Using the conditional operator you can rewrite the above example in a single line like
this:
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The
condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the
second value, b, is returned. Whichever value is returned is dependent on the conditional
test, a > b. The condition can be any expression which returns a boolean value.
The ? : operator in Java
The conditional operator only works for assigning a value to a variable, using a
value in a method invocation, or in some other way that indicates the type of its second
and third arguments. For example, consider the following
if (name.equals("Rumplestiltskin")) {
System.out.println("Give back child");
}
else {
System.out.println("Laugh");
}

This may not be written like this:


name.equals("Rumplestiltskin")
? System.out.println("Give back child")
: System.out.println("Laugh");

First of all, both the second and third arguments are void. Secondly, no
assignment is present to indicate the type that is expected for the second and third
arguments (though you know void must be wrong).

The first argument to the conditional operator must have or return boolean type
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
and the second and third arguments must return values compatible with the value the
entire expression can be expected to return. You can never use a void method as an
argument to the ? : operator.

Logical Operators in Java


The relational operators you've learned so far (<, <=, >, >=, !=) are sufficient
when you only need to check one condition. However what if a particular action is to be
taken only if several conditions are true? You can use a sequence of if statements to test
the conditions, as follows:

Page 34
Java Programming

if (x == 2) {
if (y != 2) {
System.out.println("Both conditions are true.");
}
}

This, however, is hard to write and harder to read. It only gets worse as you add
more conditions. Fortunately, Java provides an easy way to handle multiple conditions:
the logic operators. There are three logic operators, &&, || and !.
&& is logical and. && combines two boolean values and returns a boolean which
is true if and only if both of its operands are true. For instance
boolean b;
b = 3 > 2 && 5 < 7; // b is true
b = 2 > 3 && 5 < 7; // b is now false

|| is logical or. || combines two boolean variables or expressions and returns a


result that is true if either or both of its operands are true. For instance
boolean b;
b = 3 > 2 || 5 < 7; // b is true
b = 2 > 3 || 5 < 7; // b is still true
b = 2 > 3 || 5 > 7; // now b is false
The last logic operator is ! which means not. It reverses the value of a boolean
expression. Thus if b is true !b is false. If b is false !b is true.
boolean b;
b = !(3 > 2); // b is false
b = !(2 > 3); // b is true

These operators allow you to test multiple conditions more easily. For instance
the previous example can now be written as
if (x == 2 && y != 2) {
System.out.println("Both conditions are true.");
}

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
That's a lot clearer.

The Order of Evaluation of Logic Operators

When Java sees a && operator or a ||, the expression on the left side of the
operator is evaluated first. For example, consider the following:

boolean b, c, d;
b = !(3 > 2); // b is false
c = !(2 > 3); // c is true
d = b && c; // d is false

Page 35
Java Programming

When Java evaluates the expression d = b && c;, it first checks whether b is true.
Here b is false, so b && c must be false regardless of whether c is or is not true, so Java
doesn't bother checking the value of c.

On the other hand when faced with an || Java short circuits the evaluation as soon
as it encounters a true value since the resulting expression must be true. This short circuit
evaluation is less important in Java than in C because in Java the operands of && and ||
must be booleans which are unlikely to have side effects that depend on whether or not
they are evaluated. Still it's possible to force them. For instance consider this code.

boolean b = (n == 0) || (m/n > 2);

Even if n is zero this line will never cause a division by zero, because the left
hand side is always evaluated first. If n is zero then the left hand side is true and there's
no need to evaluate the right hand side. Mathematically this makes sense because m/0 is
in some sense infinite which is greater than two.

This isn't a perfect solution though because m may be 0 or it may be negative. If


m is negative and n is zero then m/n is negative infinity which is less than two. And if m
is also zero, then m/n is very undefined.

The proper solution at this point depends on your problem. Since real world
quantities aren't infinite, when infinities start popping up in your programs, nine times out
of ten it's a sign that you've lost too much precision. The remaining times are generally
signals that you've left out some small factor in your physical model that would remove
the infinity.

Therefore if there's a real chance your program will have a divide by zero error
think carefully about what it means and how you should respond to it. If, upon reflection,
you decide that what you really want to know is whether m/n is finite and greater than
zero you should use a line like this

boolean b = (n != 0) && (m/n > 0);

Avoiding Short Circuits


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
If you want all of your boolean expressions evaluated regardless of the truth value
of each, then you can use & and | instead of && and ||. However make sure you use these
only on boolean expressions. Unlike && and ||, & and | also have a meaning for numeric
types which is completely different from their meaning for booleans.

Precedence

Finally let's add the &&, ||, &, | and ? operators to the precedence table
*, /, % Multiplicative operators

Page 36
Java Programming

+, - Additive operators
<, >, >=, <= Relational operators
==, != Then do any comparisons for equality and inequality
& Bitwise and
| Bitwise or
&& Logical and
|| Logical or
? : Conditional operator
= Assignment operator

1.2.7 Arrays

Like all other variables in Java, an array must have a specific type like byte, int,
String or double. Only variables of the appropriate type can be stored in an array. One
array cannot store both ints and Strings, for instance.

Like all other variables in Java an array must be declared. When you declare an
array variable you suffix the type with [] to indicate that this variable is an array. Here are
some examples:

int[] k;
float[] yt;
String[] names;

This says that k is an array of ints, yt is an array of floats and names is an array of
Strings. In other words you declare an array like you declare any other variable except
that you append brackets to the end of the type.

You also have the option to append the brackets to the variable instead of the
type.

int k[];
float yt[];
String names[];

The choice is primarily one of personal preference. You can even use both at the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
same time like this

int[] k[];
float[] yt[];
String[] names[];

Creating Arrays

Declaring arrays merely says what kind of values the array will hold. It does not
create them. Java arrays are objects, and like any other object you use the new keyword

Page 37
Java Programming

to create them. When you create an array, you must tell the compiler how many
components will be stored in it. Here's how you'd create the variables declared on the
previous page:

k = new int[3];
yt = new float[7];
names = new String[50];

The numbers in the brackets specify the length of the array; that is, how many
slots it has to hold values. With the lengths above k can hold three ints, yt can hold seven
floats and names can hold fifty Strings. This step is sometimes called allocating the array
since it sets aside the memory the array requires.

Initializing Arrays

Individual components of an array are referenced by the array name and by an


integer which represents their position in the array. The numbers you use to identify them
are called subscripts or indexes into the array.

Subscripts are consecutive integers beginning with 0. Thus the array k above has
components k[0], k[1], and k[2]. Since you start counting at zero there is no k[3], and
trying to access it will throw an ArrayIndexOutOfBoundsException. You can use array
components wherever you'd use a similarly typed variable that wasn't part of an array.
For example this is how you'd store values in the arrays above:

k[0] = 2;
k[1] = 5;
k[2] = -2;
yt[17] = 7.5f;
names[4] = "Fred";

This step is called initializing the array or, more precisely, initializing the
components of the array. Sometimes the phrase "initializing the array" is used to mean
when you initialize all the components of the array.

For even medium sized arrays, it's unwieldy to specify each component
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
individually. It is often helpful to use for loops to initialize the array. Here is a loop
which fills an array with the squares of the numbers from 0 to 100.

float[] squares;
squares = new float[101];

for (int i=0; i <= 100; i++) {


squares[i] = i*i;
}

Page 38
Java Programming

Two things you should note about this code fragment:

Watch the fenceposts! Since array subscripts begin at zero you need 101
components if you want to include the square of 100.

Although i is an int, it is promoted to a float when it is stored in squares, since


squares is declared to be an array of floats.

Multi-Dimensional Arrays

So far all these arrays have been one-dimensional. That is, a single number could
locate any value in the array. However sometimes data is naturally represented by more
than one number. For instance a position on the earth requires a latitude and a longitude.

The most common kind of multidimensional array is the two-dimensional array. If


you think of a one-dimensional array as a column of values, you can think of a two-
dimensional array as a table of values like this

c0 c1 c2 c3
r0 0 1 2 3
r1 1 2 3 4
r2 2 3 4 5
r3 3 4 5 6
r4 4 5 6 7

Here we have an array with five rows and four columns. It has twenty total
elements. However we say it has dimension five by four, not dimension twenty. This
array is not the same as a four by five array like this one:

c0 c1 c2 c3 c4
r0 0 1 2 3 4
r1 1 2 3 4 5

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
r2
r3
2
3
3
4
4
5
5
6
6
7

We need to use two numbers to identify a position in a two-dimensional array.


These are the element's row and column positions. For instance if the above array is
called J then J[0][0] is 0, J[0][1] is 1, J[0][2] is 2, J[0][3] is 3, J[1][0] is 1, and so on.

Here's how the elements in a four by five array called M are referred to:

Page 39
Java Programming

M[0][0] M[0][1] M[0][2] M[0][3] M[0][4]


M[1][0] M[1][1] M[1][2] M[1][3] M[1][4]
M[2][0] M[2][1] M[2][2] M[2][3] M[2][4]
M[3][0] M[3][1] M[3][2] M[3][3] M[3][4]

Declaring, Allocating and Initializing Two Dimensional Arrays

Two dimensional arrays are declared, allocated and initialized much like one
dimensional arrays. However you have to specify two dimensions rather than one, and
you typically use two nested for loops to fill the array.

This example fills a two-dimensional array with the sum of the row and column
indexes

class FillArray {

public static void main (String args[]) {

int[][] matrix;
matrix = new int[4][5];

for (int row=0; row < 4; row++) {


for (int col=0; col < 5; col++) {
matrix[row][col] = row+col;
}
}
}
}

Of course the algorithm you use to fill the array depends completely on the use to
which the array is to be put. The next example calculates the identity matrix for a given
dimension. The identity matrix of dimension N is a square matrix which contains ones
along the diagonal and zeros in all other positions.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
class IDMatrix {

public static void main (String args[]) {

double[][] id;
id = new double[4][4];

for (int row=0; row < 4; row++) {


for (int col=0; col < 4; col++) {
if (row != col) {
id[row][col]=0.0;

Page 40
Java Programming

}
else {
id[row][col] = 1.0;
}
}
}
}
}

In two-dimensional arrays ArrayIndexOutOfBoundsExceptions occur whenever


you exceed the maximum column index or row index.
You can also declare, allocate, and initialize a a two-dimensional array at the
same time by providing a list of the initial values inside nested brackets. For instance the
three by three identity matrix could be set up like this:
double[][] ID3 = {
{1.0, 0.0, 0.0},
{0.0, 1.0, 0.0},
{0.0, 0.0, 1.0}
};

The spacing and the line breaks used above are purely for the programmer. The
compiler doesn't care. The following works equally well:

double[][] ID3 = {{1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{0.0, 0.0, 1.0}};

1.2.8 Object-Oriented Programming Concepts:

We've heard it a lot in the past several years. Everybody is saying it.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

What is all the fuss about objects and object-oriented technology? Is it real? Or is
it hype? Well, the truth is--it's a little bit of both. Object-oriented technology does, in fact,
provide many benefits to software developers and their products. However, historically a

Page 41
Java Programming

lot of hype has surrounded this technology, causing confusion in both managers and
programmers alike. Many companies fell victim to this hardship (or took advantage of it)
and claimed that their software products were object-oriented when, in fact, they weren't.
These false claims confused consumers, causing widespread misinformation and mistrust
of object-oriented technology.

However, in spite of overuse and misuse of the term object-oriented, the computer
industry is now beginning to overcome the hype. Understanding is growing about this
technology and its benefits.

Let us see the key concepts behind object-oriented programming, design, and
development.

What Is an Object?

An object is a software bundle of variables and related methods. Software objects


are often used to model real-world objects you find in everyday life.

What Are Classes?

A class is a blueprint or prototype that defines the variables and the methods
common to all objects of a certain kind.

Classes and objects in detail

Let us learn how to define classes and to use objects. We said that an object is a
collection of data and functions that define its state and its way of working (behavior).

A class is a blueprint or prototype that you can use to create many objects. The
implementation of a class is comprised of two components: the class declaration and the
class body.

classDeclaration {
classBody
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The Class Declaration

The class declaration component declares the name of the class along with other
attributes such as the class's superclass, and whether the class is public, final, or abstract.

The Class Body

The class body follows the class declaration and is embedded within curly braces
{ and }. The class body contains declarations for all instance variables and class variables

Page 42
Java Programming

(known collectively as member variables) for the class. In addition, the class body
contains declarations and implementations for all instance methods and class methods
(known collectively as methods) for the class.

Declaring Member Variables

A class's state is represented by its member variables. You declare a class's


member variables in the body of the class. Typically, you declare a class's variables
before you declare its methods, although this is not required.

classDeclaration {
member variable declarations
method declarations
}

Note: To declare variables that are members of a class, the declarations must be
within the class body, but not within the body of a method. Variables declared within the
body of a method are local to that method.

Implementing Methods

As you know, objects have behavior that is implemented by its methods. Other
objects can ask an object to do something by invoking its methods.
In Java, you define a class's methods in the body of the class for which the
method implements some behavior. Typically, you declare a class's methods after its
variables in the class body although this is not required.
Controlling Access to Members of a Class
Member variables and methods are known collectively as members. When you
declare a member of a Java class, you can allow or disallow other objects of other types
access to that member through the use of access specifiers.

Instance and Class Members

A Java class can contain two different types of members: instance members and
class members.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
In Java classes are models for objects, a sort of structures used in order to define
the characteristics and the functionalities of a particular type of object. A class, once
defined, can be instantiated to create an object. It is important not to make confusion
between the class's definition and objects' instantiation. Defining a class means listing a
series of properties and functions, instantiating an object instead consists in creating a
sort of variable that has the characteristics of the class from which it has been generated.

We could assert that a class is the definition of a structured datatype, created in


order to represent a complex entity. For instance we would have the need of representing
a bank account, a commercial product, a person, and so on. All these objects cannot be

Page 43
Java Programming

represented through one of the datatypes we have learnt ealier in other languages like
basic, or c, therefore it is necessary to create a new datatype to represent each of them.

First of all we must ask ourselves which information are of our interest when we
have to represent an employee, then we'll start the class's definition according to the listed
properties. We'll call this class Employee. Here we will simplify the definition of the
Employee class, supposing that an employee can be characterized only by few
information relative to his name, last name, year of birth, wage and position in the
company. We could begin to write the class's code by translating what we said till now in
the Java syntax.

public class Employee {


private String name;
private String lastName;
private int birthYear;
private int wage;
private String position;
final int maxWage;
final int minWage;
}

The first line contains the declaration of the class. The keyword class indicates to
the Java compiler which kind of operation that we are executing. It is a class's
declaration. The Employee class is defined as public. This means that it can be used by
external projects and/or included in other classes, without any restriction. The
parentheses ({, }) enclose the class's body that defines the class. By now it consist only of
the listed properties. The properties which represents the name, last name and position in
the company are represented by three variables of String datatype called name, lastName
and position. The information on the year of birth and the wage are represented by two
more variables of integer type called birthYear and wage. Finally are two integer
constants called maxWage and minWage which represent the maximum and minimal
wage that an employee can receive. Observe that none of this variable has been initialized
in this phase of definition of the class.

Now that class's properties has been defined we have to add some functions.
Functions are generally called as methods in Java. Through methods it is possible to
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
perform the desired operations on the objects generated by the class. The methods that we
are interested in defining for the Employee class are listed below in the table.

printName() it prints name and last name of the employee


it computes and returns the employee's
getAge()
current wage
it computes and returns the employee's
getWage(int currentYear)
current age
changeWage(int variation) if modifies the employee's current wage

Page 44
Java Programming

increaseWage(int aumento) It increases the employee's current wage


reduceWage(int reduction) It reduces the employee's current wage

Employee class's methods

Once completed the definition of the Employee class it will be possible to


instantiate some objects of Employee datatype, everyone characterized by its own state.
With the term state we indicate the collection of values assigned to the property of the
object. For instance we could create a first object to represent the employee Mark Red,
born in 1964... a second one to represent the employee Luigi Green, born in 1970... and
so on. To each of these objects, as it happens for variables, is identified by a name, we'll
apply the listed methods. According to the object to which we have applied a particular
method we will get as result a different value, depending to the object's internal state. For
instance applying the getName() method to the object which represent Mark Red
employee, it will return the string "Mark Red"; while the same method applied to another
object representing Luigi Green, will return a string "Luigi Green".

We have listed three methods that modify the wage property, while probably one would
have been enough. This choice was made in order to underline some characteristics of the
methods that will be evidenced in the due course.

Let's start to define the methods' code. To implement the method printName() we
will write:

public void printName()


{
System.out.println(name + " " + lastName);
}

The method consist of an heading and a body enclosed between parentheses ).


Look at the heading:

public void printName()

The keyword public defines the visibility of the method. When this visibility is
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
defined as public, the method is visible, and so accessible, from the outside of the class in
which it has been defined. Shortly this means that once instantiated an object, each public
method can be invoked on it. Other than public methods, private ones exist. A method,
when defined as private, by the use of the private keyword, cannot be invoked to operate
on any instantiated object from the outside of the class. private methods are defined to be
used only inside the class. For instance they can be recalled by another method belonging
to the same class.

The second keyword, we find in the printName() method's heading, is void. It


indicates the type of data returned by the method when it exits. Generally a method
executes a processing on received data (input parameters) and/or the object's properties, it
Page 45
Java Programming

gets a result and send it back as output. This value can be an Integer (int), a floating point
number (float or double), a string (String), or whichever other type of data. While
planning a method it is necessary to declare the type of value that it will return at the end
of its processing as output. If the method does not return any value the keyword void is
used. This is our case, in fact the printName() method visualises the name and last name
of the Employee object on which it has been recalled without returning any value.
Finally, in the heading line, is the name of the method, followed from a couple of
parentheses. In the inside of the parentheses requested input parameters are indicated.
printName() has no input parameters, so nothing has been specified.

The body of the function is only constituted by the instruction:

System.out.println(name + " " + lastName);

that is an instruction, whose task is to print a string containing the value of the
properties name and lastName of the Employee object on which the method has been
invoked.

Let's start defining the second class's method: getWage().

public int getWage()


{
return wage;
}

In this case too, we want to analyse the heading and the body of the method.
Unlike the previous method now we have declared a method which returns an
information (output). It is an integer value representing the employee's current wage. This
kind of declaration has to be respected in the body of the method by the use of the return
keyword. return in fact, followed by a variable or a constant value, gives back the
specified value before exiting the method. getWage() uses the return statement to give
back, as output, the value stored in the wage property. It is important to be sure that the
declared method's output type was the same type of the effectively returned variable. In
getWage() heading we've declared that an int value is returned which is the type of the
effectively returned wage property.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Let's go on to write our methods with getAge().

public int getAge (int currentYear)


{
int age = currentYear - birthYear;
if ((age>=16) && (age<=90))
return age;
else
return 0;
}

Page 46
Java Programming

We have a public method returning an integer (int) value. This time some
information are requested as input to start the method's computation. The type of the
requested input parameter is indicated between the parentheses that follow the name of
the method. This mean that when invoking getAge() on a Employee object we need to
add an additional information that is an integer value representing the curent year. For
instance, if we are in 2001 and we need to know how many years old Mr. Mark Red is,
we'll write something like this:

mrRed.getAge(2001);

getAge() method will execute a computation on the input value and mrRed
object's birthYear property, returning the employee's age as output.

Beyond to the type it is the name through which the input parameter will referred
to, inside of the method's body. The method declares and initialise a new integer variable
called age. The age variable is initialised according to the input parameter currentYear
and the object's property BirthYear. The age variable, after its initialisation, stores an
integer value representing the employee's age. An if... then... else... instruction follows,
whose purpose is to check that the input parameter is valid. The if...than...else...
instruction executes a check on the age variable verifying its value is in the range 16-90.
The age of 16 is the minimal working age, as it has been supposed not to have employee
over 90 years old. If the check is ok the age variable is returned, otherwise the error is
signalled by returning a zero value.

We define the method changeWage(), now.

private void changeWage (int variation)


{
if (wage + variation > minWage)
wage = wage + variation;
else
wage = minWage;
if (wage > maxWage)
wage = maxWage;
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
changeWage() is a private method. private keyword has been used instead of the
public one. This means that after having generated an Employee object by instantiating
the Employee class it will not be possible to directly recall on the object the
changeWage() method. A private method can be invoked only by other methods
belonging to the same class. changeWage() in fact, will be used by increaseWage() and
reduceWage() methods, in order to modify the wage property. The method receives in
input an integer parameter, to which the name variation is attributed. variation can be a
positive or negative integer and represent the increase/reduction of the employee's wage.
In the body of the method a first check is performed to verify that an excessive reduction

Page 47
Java Programming

of the wage does not make it to turn out inferior to the minWage value that indicates the
minimal wage for an employee. A second check assures that the employee's wage does
not exceed the defined maximum value maxWage.

Now we are going to define the increaseWage() and reduceWage() methods.


Observe how both the methods make use of the private changeWage() method in order to
get their task. By the use of changeWage() we have not to worry about executing any
kind of check on possible excessive variations of the wage property. changeWage()
methods performs all these checks as already described.

public void increaseWage (int increment)


{
changeWage (increment);
}

The increaseWage() method is a public method that does not return any value but
it demands an input parameter of integer (int) type. To the inside of the method the input
parameter is called increment. The method operates on the wage property of the object by
recalling changeWage().

The method reduceWage() is defined as it follows.

public void reduceWage (int reduction)


{
if (reduction>0) changeWage (reduction*(-1));
else changeWage (reduction);
}

reduceWage() is a public method, which does not returns any value, but it
demands in input of integer (int) type. The input parameter, to which the reduction name
is given, has to represent the employee's wage reduction. The method operates on the
wage property of the object on which it has been recalled using the private changeWage()
method.

Till now we have defined properties and methods of Employee class, but we have
never written any code which specifies how to initialise the Employee objects we'll
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
create. To this purpose we need to write the class's constructor.

A constructor is a particular method recalled every time a new object is


generated. Each class has its own constructor. The constructor, in order to be
distinguished from the other methods belonging to the same class, must have the same
name of the class, so that the name of the Employee class constructor will be Employee().
We can define the it as it follows:

public Employee (String name, String lastName, int birthYear, String position)
{

Page 48
Java Programming

minWage = 750;
maxWage = 2000;
this.name = name;
this.lastName = lastName;
this.birthYear = birthYear;
wage = minWage;
this.position = position;
}

Constructors has to be defined as public and they can't return any type of data.
All constructors must have these two characteristics. It is not possible to define private
constructors or constructors that returns any kind of data. The constructor of the
Employee class requires four input parameters to initialise a Employee object: name, last
name, year of birth and position. Observe that the input parameters have the same name
of the properties of the class. This procedure, than otherwise could generate confusion,
comes resolved using the keyword this to the inside of the body of the constructor. The
use of this is a way in order to make reference to a property of the object we are
generating. In this way, also having both the same name, it is possible to distinguish
between the constructor's input parameters and the corresponding object's properties. In
order to avoid the use of the keyword this we could write:

public Employee (String n, String l, int a, String p)


{
stipendioMin = 750;
stipendioMax = 2000;
name = n;
lastName = l;
birthYear = a;
wage = minWage;
position = p;
}

At beginning this could seem the easier way to proceed, however once learned
how to use the keyword this, it will come to you more natural to write the constructors,
and every other method, as described in the first example.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Inside the body of the constructor we can demand the execution of whichever
type of operation, on the other hand it is good norm to use constructors just to the
initialization of the object's properties.

It is ordered to according to the conventions in use between the Java developers:


first the constructor, than public and private methods, public and private properties and
finally the constants.

public class Employee


{

Page 49
Java Programming

public Employee (String name, String lastName, int birthYear, String position)
{
minWage = 750;
maxWage = 2000;
this.name = name;
this.lastName = lastName;
this.birthYear = birthYear;
wage = minWage;
this.position = position;
}

public void printName()


{
System.out.println(name + " " + lastName);
}

public int getWage()


{
return wage;
}

public int getAge (int currentYear)


{
int age = currentYear - birthYear;
if ((age>=16) && (age<=90))
return age;
else
return 0;
}

public void increaseWage (int increment)


{
changeWage (increment);
}

public void reduceWage (int reduction)


ANNAMALAI
ANNAMALAI UNIVERSITY
{ UNIVERSITY
if (reduction>0)
changeWage (reduction*(-1));
else
changeWage (reduction);
}

private void changeWage (int variation)


{
if (wage + variation > minWage)

Page 50
Java Programming

wage = wage + variation;


else
wage = minWage;
if (wage > maxWage)
wage = maxWage;
}
private String name;
private String lastName;
private int birthYear;
private int wage;
private String position;
final int maxWage;
final int minWage;
}

we'll learn how to instantiate some Employee objects and then we'll execute some
operations on them.

Instantiating and using objects

We'll learn how to instantiate a class to create an object, then we'll write a short
program that instantiate the Employee class to create two Employee object. The program
we are going to develop executes some operations on these objects by invoking their
methods. The instruction to use to instantiate an object is new, whose syntax is:

ObjectType varName = new ObjectType (par1, par2..., parN);

Where ObjectType is the type of the object we are going to create and varName is
the name of the object variable in which we'll store a reference to the object and through
which we will refer to it. At the right of the equal "=" symbol is a call to the constructor
of the class ObjectType, preceded by the keyword new that indicates which kind of
operation we are going to perform. The constructor is a particular method defined in each
class and, as any other methods, is invoked specifying the requested parameters. It is
possible to distinguish the declaration of the object variable from the operation of
generation of the object. This is done by writing the two instructions:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
ObjectType varName;
varName = new ObjectType (par1, par2..., parN);

This performs exactly the same operation. Take just a moment to analyse the
instructions proposed and the effect of each of them. The first instruction is the
declaration of an object variable of ObjectType type. This variable will store a reference
to the object that we will create with the second instruction. The object variable varName
does not contain and it will never contain object's data effectively. An object variable is
only a way to make reference to the particular object it is linked to. Who knows C++ or

Page 51
Java Programming

Pascal programming languages, can consider the object variable as a pointer internally
managed by the Java interpreter. The second instruction is the one which effectively
instantiated the ObjectType class to create an object:

new ObjectType (par1, par2..., parN);

the object is created and initialised according to the parameters specified by


invoking its constructor. The instruction returns the reference we have just talked about.
In order not to loose the reference to this new object, the line of code commonly used to
create an object is the following one:

varName = new ObjectType (par1, par2..., parN);

that means: "create and initialise an object of type ObjectType, then store the
reference to the new object in the variable varName".
Graphically the situation could be represented as in fig.below

Object instantiation

After this short introduction about the right way to create objects, we can start to
write the code for the application through which we'll test Employee class. Applying
what we have just said, to create an object of Employee type we will write:

Employee red = new Employee ("Mario", "Red", 1974, "Master");

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The effect of the instruction is to generate an object of Employee type, whose
property will be initialised according to the constructor's input parameters, and whose
reference will be stored in the object variable we have called red .
Graphically the situation can be outlined as given below.

Page 52
Java Programming

Employee Object instantiation

The Life Cycle of an Object

An object is a software module that has state and behavior. An object's state is
contained in its member variables and its behavior is implemented through its methods.

Typically, Java programs that we write will create many objects from prototypes
known as classes. These objects interact with one another by sending each other
messages. The result of a message is a method invocation which performs some action or
modifies the state of the receiving object. Through these object interactions, the Java
program can implement a graphical user interface, run an animation, or send and receive
information over the network. Once an object has completed the work for which it was
created, it is garbage collected and its resources recycled for the use of other objects.

Creating Objects

In Java, we create an object by creating an instance of a class or, in other words,


instantiating a class.

Often, we will see a Java object created with a statement like this one:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Date today = new Date();

This statement creates a new Date object (Date is a class in the java.util
package). This single statement actually performs three actions: declaration, instantiation,
and initialization. Date today is a variable declaration which simply declares to the
compiler that the name today will be used to refer to an object whose type is Date, the
new operator instantiates the Date class (thereby creating a new Date object), and Date
initializes the object.

Page 53
Java Programming

Declaring an Object

While the declaration of an object is not a necessary part of object creation, object
declarations often appear on the same line as the creation of an object. Like other variable
declarations, object declarations can appear alone like this:

Date today;

Either way, declaring a variable to hold an object is just like declaring a variable
to hold a value of primitive type:

type name

where type is the data type of the object and name is the name to be used for the
object. In Java, classes and interfaces are just like a data type. So type can be the name of
a class such as the Date class or the name of an interface.

Declarations notify the compiler that you will be using name to refer to a variable
whose type is type. Declarations do not create new objects. Date today does not create a
new Date object, just a variable named today to hold a Date object. To instantiate the
Date class, or any other class, use the new operator.

Instantiating an Object

The new operator instantiates a class by allocating memory for a new object of
that type. new requires a single argument: a call to a constructor method. Constructor
methods are special methods provided by each Java class that are responsible for
initializing new objects of that type. The new operator creates the object, the constructor
initializes it.

Here's an example of using the new operator to create a Rectangle object


(Rectangle is a class in the java.awt package):

new Rectangle(0, 0, 100, 200);

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
In the example, Rectangle(0, 0, 100, 200) is a call to a constructor for the
Rectangle class.

The new operator returns a reference to the newly created object. This reference
can be assigned to a variable of the appropriate type.

Rectangle rect = new Rectangle(0, 0, 100, 200);

Page 54
Java Programming

Initializing an Object

As mentioned previously, classes provide constructor methods to initialize a new


object of that type. A class may provide multiple constructors to perform different kinds
of initialization on new objects. When looking at the implementation for a class, you can
recognize the constructors because they have the same name as the class and have no
return type. Recall the creation of the Date object used at the beginning of this section.
The Date constructor used there doesn't take any arguments:

Date()

A constructor that takes no arguments, such as the one shown, is known as the
default constructor. Like Date, most classes have at least one constructor, the default
constructor.

If a class has multiple constructors, they all have the same name but a different
number or type of arguments. Each constructor initializes the new object in a different
way. Besides the default constructor used to initialize a new Date object earlier, the Date
class provides another constructor that initializes the new Date with a year, month, and
day:

Date MyBirthday = new Date(1996, 8, 30);

The compiler can differentiate the constructors through the type and number of
the arguments.

This section talked about how to use a constructor. Constructors later in this
lesson explains how to write constructor methods for your classes.

Using Objects

Once we’ve created an object, we'll probably want to use it for something.
Suppose, for example, that after creating a new Rectangle object, you would like to
move it to a different location. Say, the rectangle is an object in a drawing program and
the user just clicked the mouse over the rectangle and dragged it to a new location.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The Rectangle class provides two equivalent ways to move the rectangle:

Manipulate the object's x, y variables directly.


Call the move method.

Option 2 is often considered "more object-oriented" and safer because you


manipulate the object's variables indirectly through its protective layer of methods rather
than twiddling directly with them. Manipulating an object's variables directly is often
considered error-prone; you could potentially put the object into an inconsistent state.
However, a class would not (and should not) make its variables available for direct

Page 55
Java Programming

manipulation by other objects if it were possible for those manipulations to put the object
in an inconsistent state. Java provides a mechanism whereby classes can restrict or allow
access to its variables and methods by objects of another type.

Rectangle's x and y are accessible to other classes, so we can assume that


manipulating a Rectangle's x and y variables directly is safe.

Referencing an Object's Variables

First, let's focus on how to inspect and modify the Rectangle's position by
modifying its x and y variables directly. Now we will see to move the rectangle by
calling its move method.

To access an object's variables, simply append the variable name to an object


reference with an intervening '.' (period).

objectReference.variable

Suppose you have a rectangle named rect in your program. You can access its x
and y variables with rect.x and rect.y, respectively. Now that you have a name for
rect's variables, you can use those names in Java statements and expressions as though
they were the names of "regular" variables. Thus to move the rectangle a new location
you would write:

rect.x = 15; // change x position


rect.y = 37; // change y position

The Rectangle class has two other variables--width and height--that are
accessible to objects outside the Rectangle. You can use the same notation to access
them: rect.width and rect.height. So you could calculate the rectangle's area using
this statement:

area = rect.height * rect.width;

When you access a variable through an object, you are referencing that particular
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
object's variables. If bob is also a rectangle with a different height and width than rect,
then the following instruction, which calculates the area of the rectangle named bob, will
give a different result than the previous instruction, which calculates the area of the
rectangle named rect:

area = bob.height * bob.width;

Note that the first part of the name of an object's variables (the objectReference in
objectReference.variable) must be a reference to an object. While you can use a variable
name here, you can also use any expression that returns an object reference. Recall that

Page 56
Java Programming

the new operator returns a reference to an object. So you could use the value returned
from new to access a brand new object's variables:

height = new Rectangle().height;

Calling an Object's Methods

Calling an object's method is similar to getting an object's variable. To call an


object's method, simply append the method name to an object reference with an
intervening '.' (period), and provide any arguments to the method within enclosing
parentheses. If the method does not require any arguments, just use empty parentheses.

objectReference.methodName(argumentList);
or
objectReference.methodName();

Let's see what this means in terms of moving the rectangle. To move rect to a
new location using its move method write the following Java statement:

rect.move(15, 37);

This Java statement calls rect's move method with two integer parameters, 15 and
37. This statement has the effect of moving the rect object by modifying its x and y
variables and is equivalent to the assignment statments used previously:

rect.x = 15;
rect.y = 37;

If you want to move a different rectangle, the one named bob, to a new location
you would write:

bob.move(244, 47);

As you see from these examples, method calls are directed at a specific object; the
object specified in the method call is the object that responds to the instruction. Method

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
calls are also known as messages. Like real-world messages, object messages must be
addressed to a particular recipient. You get different results depending on which object is
the recipient of the message. In the example above, when you send the object named
rect a move message, rect moves to the new location. When you send the object named
bob a move message, bob moves. Very different results.

A method call is an expression and evaluates to some value. The value of a


method call is its return value, if it has one. You will often wish to assign the return value
of a method to a variable or use the method call within the scope of another expression or
statement. The move method doesn't return a value (it's declared void). However,
Rectangle's inside method does. The inside method takes an x, y coordinate and

Page 57
Java Programming

returns true if that point lies within the rectangle. So you could use the inside method
to do something special if some point, say the current mouse location, were inside the
rectangle:

if (rect.inside(mouse.x, mouse.y)) {
...
// mouse is in the rectangle
...
} else {
...
// mouse is outside of the rectangle
...
}

Remember that the method call is a message to the named object. In this case, the
object named is the Rectangle named rect. Asking rect if the mouse cursor location
represented by mouse.x and mouse.y is in it is a message to rect--the named object:

rect.inside(mouse.x, mouse.y)

You will likely get a different response if you send the same message to bob.

As stated previously, the objectReference in the method call


objectReference.method() must be an object reference. While you can use a variable
name here, you can also use any expression that returns an object reference. Recall that
the new operator returns a reference to an object. So you could use the value returned
from new to call a brand new object's methods:

new Rectangle(0, 0, 100, 50).equals(anotherRect)

The expression new Rectangle(0, 0, 100, 50) evaluates to an object


reference that refers to a Rectangle object. So, as you can see, you can use the dot
notation to call the new rectangle's equals method to determine if the new rectangle is
equal to the one specified in equals's argument list.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Cleaning Up Unused Objects

Many other object-oriented languages require that you keep track of all the
objects you create and that you destroy them when they are no longer needed. Writing
code to manage memory in this way is tedious and often error-prone. Java saves you from
this by allowing you to create as many objects as you want (limited of course to whatever
your system can handle) but never having to destroy them. The Java runtime environment
deletes objects when it determines that they are no longer being used. This process is
known as garbage collection.

Page 58
Java Programming

An object is eligible for garbage collection when there are no more references to
that object. References that are held in a variable are naturally dropped when the variable
goes out of scope. Or you can explicitly drop an object reference by setting the value of a
variable whose data type is a reference type to null.

The Garbage Collector

The Java runtime environment has a garbage collector that periodically frees the
memory used by objects that are no longer needed. The Java garbage collector is a mark-
sweep garbage collector that scans Java's dynamic memory areas for objects, marking
those that are referenced. After all possible paths to objects are investigated, those objects
that are not marked (that is, not referenced) are known to be garbage and are collected. (A
more complete description of Java's garbage collection algorithm might be "a
compacting, mark-sweep collector with some conservative scanning".)

The garbage collector runs in a low priority thread and runs both synchronously
and asynchronously depending on the situation and the system on which Java is running.

The garbage collector runs synchronously when the system runs out of memory or
in response to a request from a Java program. Java program can ask the garbage collector
to run at any time by calling System.gc.

Note: Asking the garbage collection to run does not guarantee that your objects
will be garbage collected.

On systems that allow the Java runtime to note when a thread has begun and to
interrupt another thread (such as Windows 95/NT), the Java garbage collector runs
asynchronously when the system is idle. As soon as another thread becomes active, the
garbage collector is asked to get to a consistent state and then terminate.

Finalization

Before an object gets garbage collected, the garbage collector gives the object an
opportunity to clean up after itself through a call to the object's finalize method. This
process is known as finalization.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
During finalization an object may wish to free system resources such as files and
sockets or drop references to other objects so that they in turn become eligible for
garbage collection.

The finalize method is a member of the Object class. A class must override the
finalize method to perform any finalization necessary for objects of that type

A Java object is an instance of a class. Frequently, we say that an object's class is


the object's type. The Java environment comes with many classes that you can use in
your programs. Or you can write your own.

Page 59
Java Programming

Example

class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World!");
}

Hello World is very close to the simplest program imaginable. When you
successfully compile and run it, it prints the words "Hello World!" on your display.
Although it doesn't teach very much programming, it gives you a chance to learn the
mechanics of typing and compiling code. The goal of this program is not to learn how to
print words to the terminal. It's to learn how to type, save and compile a program. This is
often a non-trivial procedure, and there are a lot of things that can go wrong even if your
source code is correct.

To write the code you need a text editor. You can use any text editor like
Notepad, Brief, emacs or vi. Personally I use BBEdit on the Mac and Notepad on
Windows.

Like C and unlike Fortran, Java is case sensitive so System.out.println is not


the same as system.out.println. CLASS is not the same as class, and so on.
However, white space is not significant except inside string literals. The exact
number of spaces or tabs you use doesn't matter.

Save this code in a file called HelloWorld.java. Use exactly that name including
case.
Compiling and Running Hello World

To make sure the Java environment is correctly configured, bring up a command-

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
line prompt and type

javac HelloWorld.java

If your computer responds with


error: Can't read: nofile.java

you're ready to begin. If, on the other hand, it responds


javac: Command not found
or something similar, then you need make sure you have the Java environment properly
installed and your PATH configured.

Page 60
Java Programming

Assuming that Java is properly installed on your system there are three steps to creating a
Java program:
1. writing the code
2. compiling the code
3. running the code
Under Unix, compiling and running the code looks like this:
% javac HelloWorld.java
% java HelloWorld
Hello World
%

Under Windows, it's similar. You just do this in a DOS shell.


C:> javac HelloWorld.java
C:> java HelloWorld
Hello World
C:>

Notice that you use the .java extension when compiling a file, but do not use the
.class extension when running a file.

1.2.9 Inheritance

The ability to derive one class from another and inherit its state and behavior is
one of object-oriented programming most powerful paradigms. Inheritance provides a
powerful and natural mechanism for organizing and structuring software programs. The
most general classes appear higher in the class hierarchy and the most specific classes
appear lower in the class hierarchy. In addition, because classes inherit state and behavior
from their super classes you don't have to write that code again--inheritance allows you to
reuse code over and over again in each subclass you create.
Classes can be derived from other classes. The derived class (the class that is
derived from another class) is called a subclass. The class from which it's derived is
called the superclass. The following figure illustrates these two types of classes:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY A class

Super class

Another class

Sub class

Page 61
Java Programming

Types of Inheritance

Single Inheritance
In single inheritance, the subclasses are derived from one super class. For
example, Waiting list is the class created from Ticket class.

Ticket
Ticket

Waiting list

Single Inheritance

Multiple Inheritance

In multiple inheritance subclasses are derived from more than one class. The
derived class inherits the data members and methods of all its super classes. For example,
the subclass Child inherits the properties from the classes, Father and Mother.

Father Mother

Child

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Multiple Inheritance

Note: Java does not support Multiple Inheritance. However, the benefits of
multiple inheritance through interfaces. In fact, in Java, all classes must be derived from
some class. Which leads to the question "Where does it all begin?" The top-most class,
the class from which all other classes are derived, is the Object class defined in
java.lang. Object is the root of a hierarchy of classes, as illustrated in the following
figure.

Page 62
Java Programming

The subclass inherits state and behavior in the form of variables and methods
from its superclass. The subclass can use just the items inherited from its superclass as is,
or the subclass can modify or override it. So, as you drop down in the hierarchy, the
classes become more and more specialized:

Definition: A subclass is a class that derives from another class. A subclass


inherits state and behavior from all of its ancestors. The term superclass refers to a class's
direct ancestor as well as all of its ascendant classes.

Creating Subclasses

To create a subclass of another class use the extends clause in your class
declaration. As a subclass, your class inherits member variables and methods from its
superclass. Your class can choose to hide variables or override methods inherited from its
superclass.

You declare that a class is the subclass of another class within The Class

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Declaration. For example, suppose that you wanted to create a subclass named SubClass
of another class named SuperClass. You would write:

class SubClass extends SuperClass {


...
}

This declares that SubClass is the subclass of the Superclass class. It also
implicitly declares that SuperClass is the superclass of SubClass. A subclass also
inherits variables and methods from its superclass's superclass, and so on up the
inheritance tree.

Page 63
Java Programming

A Java class can have only one direct superclass. Java does not support multiple
inheritance.

Creating a subclass can be as simple as including the extends clause in your class
declaration. However, usually we have to make other provisions in our code when
subclassing a class, such as overriding methods or providing implementation for abstract
methods.

What Member Variables Does a Subclass Inherit?

A subclass inherits all of the member variables within its superclass that are
accessible to that subclass (unless the member variable is hidden by the subclass).

The following list itemizes the member variables that are inherited by a subclass:

 Subclasses inherit those member variables declared as public or


protected.
 Subclasses inherit those member variables declared with no access
specifier as long as the subclass is in the same package as the superclass.
 Subclasses don't inherit a superclass's member variable if the subclass
declares a member variable using the same name. The subclass's member variable is said
to hide the member variable in the superclass.
 Subclasses don't inherit the superclass's private member variables.

Hiding Member Variables

As mentioned earlier, member variables defined in the subclass hide member


variables of the same name in the superclass.

While this feature of the Java language is powerful and convenient, it can be a
fruitful source of errors: hiding a member variable can be done deliberately or by
accident. So, when naming your member variables be careful to only hide those member
variables that you actually wish to hide.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
One interesting feature of Java member variables is that a class can access a
hidden member variable through its superclass. Consider this superclass and subclass
pair:
class Super {
Number aNumber;
}
class Sub extends Super {
Float aNumber;
}
The aNumber variable in Sub hides aNumber in Super. But you can access
aNumber from the superclass with:

Page 64
Java Programming

super.aNumber

super is a Java language keyword that allows a method to refer to hidden


variables and overriden methods of the superclass.

What Methods Does a Subclass Inherit?

The rule that specifies which methods get inherited by a subclass is similar to that
for member variables.

A subclass inherits all of the methods within its superclass that are accessible to
that subclass (unless the method is overriden by the subclass).

The following list itemizes the methods that are inherited by a subclass:
 Subclasses inherit those methods declared as public or protected.
 Subclasses inherit those superclass methods declared with no access
specifier as long as the subclass is in the same package as the superclass.
 Subclasses don't inherit a superclass's method if the subclass declares a
method using the same name. The method in the subclass is said to override the one in
the superclass.
 Subclasses don't inherit the superclass's private methods.

A subclass can either completely override the implementation for an inherited


method, or the subclass can enhance the method by adding functionality to it.

Overriding Methods

The ability of a subclass to override a method in its superclass allows a class to


inherit from a superclass whose behavior is "close enough" and then supplement or
modify the behavior of that superclass.

A subclass can either completely override the implementation for an inherited


method or the subclass can enhance the method by adding functionality to it.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Replacing a Superclass's Method Implementation

Sometimes, you want a subclass to entirely replace its superclass's


implementation of a method. Indeed, many superclasses provide an empty method
implementation with the expectation that most, if not all, subclasses will completely
replace the superclass's implementation of the method.

One example of this is the run method in the Thread class( will be discussed in
Multithreading topic later on). The Thread class provides an empty implementation (the
method does nothing) of the run method because, by definition, the run method is
dependent on the subclass implementation of the method. The Thread class can't possibly

Page 65
Java Programming

provide a reasonable default implementation for the run method. However, the run
method cannot be abstract because it also does not make sense for the Thread class to be
abstract (programmers should be able to instantiate a generic Thread without building a
subclass). Thus, the implementation of run is empty.

To completely replace a superclass's method implementation, simply name your


method the same as the superclass method and provide the overriding method with the
same signature as the overridden method:

class BackgroundThread extends Thread {


void run() {
...
}
}

The BackgroundThread class overrides the run method from its superclass
Thread and completely replaces Thread's implementation of it.

Adding to a Superclass's Method Implementation

At other times a subclass will want to keep its superclass's implementation of a


method but enhance it further with behavior specific to the subclass. For example,
constructor methods within a subclass typically do this--the subclass wants to preserve
the initialization done by the superclass, but provide additional initialization specific to
the subclass.

Suppose that you wanted to create a subclass of the Window class in the java.awt
package. The Window class has one constructor that requires a Frame argument which is
the parent of the window:

public Window(Frame parent)

This constructor performs some initialization on the window such that it will work
within the window system. To make sure your new subclass of Window also works within
the window system, you too must provide a constructor for your Window subclass that
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
performs the same initialization. Rather than attempt to figure out and recreate the
initialization process that occurs within the Window constructor, you would much rather
just use what the Window class already does. You can leverage the code in the Window
constructor simply by calling it from within your Window subclass constructor:

class MyWindow extends Window {


public MyWindow(Frame parent) {
super (parent);
...
// MyWindow-specific initialization here
...

Page 66
Java Programming

}
}

The MyWindow constructor calls the superclass's constructor first, before it does
anything else. Typically, this is the desired behavior in constructors--the superclass
should get the opportunity to perform all its initialization before the subclass. Other types
of methods may wish to call the superclass's implementation of the method at the end of
the subclass's method or in the middle of it. If the positioning of the call to the
superclass's method is critical to the successful operation of the subclass's method, it's
important to note that in a comment.

Methods a Subclass Cannot Override

 A subclass cannot override methods that are declared final in the


superclass (by definition, final methods cannot be overriden). If you attempt to override a
final method, the compiler will display an error message similar to this one and refuse to
compile the program:

 FinalTest.java:7: Final methods can't be overriden. Method void iamfinal is


final in class ClassWithFinalMethod.
 void iamfinal() {
 ^
 1 error

 Also, a subclass cannot override methods that are declared static in the
superclass. In other words, a subclass cannot override a class method.

Methods a Subclass Must Override

Subclass must override methods that are declared abstract in the superclass, or
the subclass itself must be abstract.

Writing Final Classes and Methods

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Sometimes, for security or design reasons, you want to prevent your class from
being subclassed. Or, you may just wish to prevent certain methods within your class
from being overriden. In Java, you can achieve either of these goals by marking the class
or the method as final.

Final Classes

You can declare that your class is final; that is, that your class cannot be
subclassed. There are (at least) two reasons why you might want to do this: security
reasons and design reasons.

Page 67
Java Programming

Security:

One mechanism that hackers use to subvert systems is to create subclasses of a


class and then substitute their class for the original. The subclass looks and feels like the
original class but does vastly different things possibly causing damage or getting into
private information. To prevent this kind of subversion, you can declare your class to be
final and prevent any subclasses from being created. The String class in the java.lang
package is a final class for just this reason. The String class is so vital to the operation
of the compiler and the interpreter that the Java system must guarantee that whenever a
method or object uses a String they get exactly a java.lang.String and not some
other string. This ensures that all strings have no strange, inconsistent, undesirable, or
unpredictable properties.

If you try to compile a subclass of a final class, the compiler will print an error
message and refuse to compile your program. In addition, the bytecode verifier ensures
that the subversion is not taking place at the bytecode level by checking to make sure that
a class is not a subclass of a final class.

Design:

Another reason you may wish to declare a class as final is for object-oriented
design reasons. You may think that your class is "perfect" or that, conceptually, your
class should have no subclasses.

To specify that your class is a final class, use the keyword final before the class
keyword in the class declaration. For example, if you wanted to declare a (perfect)
ChessAlgorithm class as final, its declaration would look like this:

final class ChessAlgorithm {


...
}

Any subsequent attempts to subclass ChessAlgorithm will result in a compiler


error such as the following:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Chess.java:6: Can't subclass final classes: class ChessAlgorithm
class BetterChessAlgorithm extends ChessAlgorithm {
^
1 error

Final Methods

If creating a final class seems heavy handed for your needs, and you really just
want to protect some of your class's methods from being overriden, you can use the
final keyword in a method declaration to indicate to the compiler that the method
cannot be overridden by subclasses.

Page 68
Java Programming

You might wish to make a method final if the method has an implementation that
should not be changed and is critical to the consistent state of the object. For example,
instead of making your ChessAlgorithm class final, you might just want to make the
nextMove method final:

class ChessAlgorithm {
...
final void nextMove(ChessPiece pieceMoved, BoardLocation newLocation) {
}
...
}

Writing Abstract Classes and Methods

On the other hand, some classes are written for the sole purpose of being
subclassed (and are not intended to ever be instantiated). These classes are called abstract
classes and often contain abstract methods.

Abstract Classes

Sometimes, a class that you define represents an abstract concept and as such,
should not be instantiated. Take, for example, food in the real world. Have you ever seen
an instance of food? No. What you see instead are instances of carrot, apple, and
chocolate. Food represents the abstract concept of things that we can eat. It doesn't make
sense for an instance of food to exist.

Similarly in object-oriented programming, you may want to model abstract


concepts but you don't want to be able to create an instance of it. For example, the
Number class in the java.lang package represents the abstract concept of numbers. It
makes sense to model numbers in a program, but it doesn't make sense to create a generic
number object. Instead, the Number class makes sense only as a superclass to classes like
Integer and Float which implement specific kinds of numbers. Classes such as Number,
which implement abstract concepts and should not be instantiated, are called abstract
classes. An abstract class is a class that can only be subclassed--it cannot be

ANNAMALAI
ANNAMALAI UNIVERSITY
instantiated.
UNIVERSITY
To declare that the class is an abstract class, use the keyword abstract before the
class keyword in the class declaration:
abstract class Number {
...
}

If you attempt to instantiate an abstract class, the compiler will display an error
similar to the following and refuse to compile your program:

Page 69
Java Programming

AbstractTest.java:6: class AbstractTest is an abstract class. It can't be instantiated.


new AbstractTest();
^
1 error

Abstract Methods

An abstract class may contain abstract methods, that is, methods with no
implementation. In this way, an abstract class can define a complete programming
interface, thereby providing its subclasses with the method declarations for all of the
methods necessary to implement that programming interface. However, the abstract class
can leave some or all of the implementation details of those methods up to its subclasses.

Let's look at an example of when you might want to create an abstract class with
an abstract method in it. In an object-oriented drawing application, you can draw circles,
rectangles, lines, curves, and so on. Each of these graphic objects share certain states
(position, bounding box) and behavior (move, resize, draw). You can take advantage of
these similarities and declare them all to inherit from the same parent object--
GraphicObject.

However, the graphic objects are also substantially different in many ways:
drawing a circle is quite different from drawing a rectangle. The graphics objects cannot
share these types of states or behavior. On the other hand, all GraphicObjects must
know how to draw themselves; they just differ in how they are drawn. This is a perfect
situation for an abstract super class.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
First you would declare an abstract class, GraphicObject, to provide member
variables and methods that were wholly shared by all subclasses, such as the current
position and the moveTo method. GraphicObject also declares abstract methods for
methods, such as draw, that need to be implemented by all subclasses, but are
implemented in entirely different ways (no default implementation in the superclass
makes sense). The GraphicObject class would look something like this:

abstract class GraphicObject {


int x, y;
...
void moveTo(int newX, int newY) {

Page 70
Java Programming

...
}
abstract void draw();
}

Each non-abstract subclass of GraphicObject, such as Circle and Rectangle,


would have to provide an implementation for the draw method.

class Circle extends GraphicObject {


void draw() {
...
}
}

class Rectangle extends GraphicObject {


void draw() {
...
}
}

An abstract class is not required to have an abstract method in it. But any class
that has an abstract method in it or that does not provide an implementation for any
abstract methods declared in its super classes must be declared as an abstract class.

The Object Class

All objects in the Java environment inherit either directly or indirectly from the
Object class. This section talks about the interesting methods in Object--methods that
you may wish to invoke or override.

The Object api class sits at the top of the class hierarchy tree in the Java
development environment. Every class in the Java system is a descendent (direct or
indirect) of the Object class. The Object class defines the basic state and behavior that
all objects must have, such as the ability to compare oneself to another object, to convert
to a string, to wait on a condition variable, to notify other objects that a condition variable

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
has changed, and to return the object's class.

The equals Method

Use the equals to compare two objects for equality. This method returns true if
the objects are equal, false otherwise. Note that equality does not mean that the objects
are the same object. Consider this code that tests two Integers, one and anotherOne, for
equality:

Integer one = new Integer(1), anotherOne = new Integer(1);

Page 71
Java Programming

if (one.equals(anotherOne))
System.out.println("objects are equal");

This code will display objects are equal even though one and anotherOne
reference two different, distinct objects. They are considered equal because they contain
the same integer value.

Your classes should override this method to provide an appropriate equality test.
Your equals method should compare the contents of the objects to see if they are
functionally equal and return true if they are.

The getClass Method

The getClass method is a final method (cannot be overridden) that returns a


runtime representation of the class of this object. This method returns a Class object.
You can query the Class object for a variety of information about the class, such as its
name, its superclass, and the names of the interfaces that it implements. The following
method gets and displays the class name of an object:

void PrintClassName(Object obj) {


System.out.println("The Object's class is” + obj.getClass().getName());
}

One handy use of the getClass method is to create a new instance of a class
without knowing what the class is at compile time. This sample method creates a new
instance of the same class as obj which can be any class that inherits from Object
(which means that it could be any class):

Object createNewInstanceOf(Object obj) {


return obj.getClass().newInstance();
}

The toString Method

Object's toString method returns a String representation of the object. You

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
can use toString to display an object. For example, you could display a String
representation of the current Thread like this:

System.out.println(Thread.currentThread().toString());

The String representation for an object is entirely dependent on the object. The
String representation of an Integer object is the integer value displayed as text. The
String representation of a Thread object contains various attributes about the thread,
such as its name and priority. For example, the previous of code above display the
following:

Page 72
Java Programming

Thread[main,5,main]

The toString method is very useful for debugging and it would behoove you to
override this method in all your classes.

The Object class provides a method, finalize that cleans up an object before its
garbage collected.

The Object class also provides five methods that are critical when writing
multithreaded Java programs:

 notify
 notifyAll
 wait (three versions)

These methods help you ensure that your threads are synchronized. (and are
covered later)

1.2.10 Packages

Creating and Using Packages

Typically, to make objects easier to find and use, and to avoid naming conflicts,
groups of related objects can be bundled into class libraries. In Java, a class library is
called a package. Packages can also contain interface definitions.

Creating Own Packages

Own Packages can be created easily and any number of class and interface
definitions can be included in them.

Packages are groups of related classes and interfaces which provides a convenient
mechanism for managing a large set of classes and interfaces, to avoid naming conflicts.
In addition to the Java packages, own packages can be created and using Java’s package
statement any number of classes and interface definitions can be put in it.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Suppose a group of classes that represent a collection of graphic objects such as
circles, rectangles, lines, and points are need to be implemented and in addition to these
classes say also there is an interface Draggable that these classes need to implement and
say they can be dragged with the mouse by the user and to make these classes available
to other programmers, then all these classes and interfaces can be bundled into a package
called, graphics and give the package to the user (along with some reference
documentation as to what the classes and interfaces do and what their public
programming interfaces are).

Page 73
Java Programming

In this way, the programmers can easily determine what for the group of classes
are, how to use them and how they relate to one another and to other classes and
packages. Also, the names of the classes won't conflict with class names in other
packages because the classes and interfaces within a package are referenced in terms of
their package (technically a package creates a new name space.)

Package using the package statement:


package graphics;

interface Draggable {
. . .
}

class Circle {
. . .
}

class Rectangle {
. . .
}

The first line in the preceding code sample creates a package called graphics. All
the classes and interfaces defined in the file containing this statement in it are members of
the graphics package. So, Draggable, Circle, and Rectangle are all members of the new
graphics package.

The .class files, generated by the compiler when compiled, contains the source
for Draggable, Circle, and Rectangle. It must be placed in a directory named graphics
somewhere in the CLASSPATH. The CLASSPATH is a list of directories that indicate where
on the file system the various compiled Java classes and interfaces are installed. When
looking for a class, the Java interpreter searches the CLASSPATH for a directory whose
name matches the package name of which the class is a member. The .class files for all
classes and interfaces defined in the package must be in that package directory.

The package names can have multiple components (separated by periods). In fact,
the Java package names have multiple components: java.util, java.lang, and so on.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Each component of the package name represents a diretory on the file system. So, the
.class files for java.util are in a directory named util in a directory named java
somewhere in the CLASSPATH.

CLASSPATH

To run a stand-alone Java application, we specify the name of the Java application
that we wish to execute to the Java interpreter. To run an applet, we specify the applet's
name with an <APPLET> tag within an HTML file. The browser that the applet is running
in passes the applet's name to the Java interpreter. In either case, the application or applet
that we are running could be anywhere on our system or on the network. Also, the
Page 74
Java Programming

application or applet might use other classes or objects that are in the same or different
location.

Because the classes could be anywhere, the Java interpreter must be informed
where it can find the classes that the user is trying to run. This is done with the
CLASSPATH environment variable. The CLASSPATH environment variable is
comprised of a list of directory names that contain compiled Java classes. The actual
construct of CLASSPATH depends on the system that is run.

When the interpreter gets a classname, either from the command line, from a
browser, or from an application or applet, the interpreter searches each directory in the
CLASSPATH until it finds the class it's looking for.

The top-level directory that contains the Java classes must be put in the
CLASSPATH. By convention, many people have a classes directory in their home
directory where they put all of the Java code. If such a directory is available then, it
should be put in the CLASSPATH. However, when working with applets, it's convenient
to put the applet in a classes directory underneath the directory where the HTML file is
that contains the applet. For this and other reasons, it's often convenient to put the current
directory in the CLASSPATH as well.

The classes included with the Java development environment are automatically
available, because the interpreter automatically appends the correct directory to the
CLASSPATH when it starts up.

The order is very important. When the Java interpreter is looking for a class, it
searches the directories indicated by the CLASSPATH in order, until it finds a class with
the correct name. The Java interpreter runs the first class with the correct name that it
encounters and does not search the remaining directories. Normally, it's best to give the
classes unique names, but if it can't be avoided, make sure that the CLASSPATH
searches the classes in the proper order. This has to be kept in mind when setting up the
CLASSPATH and the source code hierarchy.

All classes and interfaces belong to a package even if one is not specified with the
package statement. If a package is not specified explicitly using package, then all the

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
classes and interfaces become members of the default package, which has no name and
which is always imported.

Using the Classes and Interfaces from a Package

To use the classes and interfaces defined in one package from within another
package, the package is need to be import. Also, the classes and interfaces must be
declared public.

To import a specific class or interface into the current file (like the Circle class
from the graphics package created in the previous section) use the import statement:

Page 75
Java Programming

import graphics.Circle;

The import statement must be at the beginning of a file before any class or
interface definitions and makes the class or interface available for use by the classes and
interfaces defined in that file.

The import statement with the asterisk “*” wildcard character must be used to
import all the classes and interfaces from a package.(for instance, say the entire
graphicspackage)

import graphics.*;

Trying to use a class or interface from a package that has not been imported, the
compiler will issue a fatal error:
testing.java:4: Class Date not found in type declaration.
Date date;
^

Only the classes and interfaces that are declared to be public can be used by
classes outside of the package that they are defined in.

The default package (a package with no name) is always imported. The runtime
system automatically imports the java.lang package as well.

If by some chance the name of a class in one package is the same as the name of a
class in another package, the names must be differentiated by prepending the package
name to the beginning of the class. For example, previously a class named Rectangle was
defined in the graphics package. The java.awt package also contains a Rectangle class.
If both graphics and java.awt have been imported then the following line of code (and
others that attempt to use the Rectangle class) is ambiguous:
Rectangle rect;

In such a situation which Rectangle class is used must be said more specifically.
graphics.Rectangle rect;

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This is done by prepending the package name to the beginning of the class name
and separating the two with a period.

The Java Packages

Eight packages comprise the standard Java development environment.

The Java Language Package

The Java language package, also known as java.lang, contains classes that are
core to the Java language. The classes in this package are grouped as follow:
Page 76
Java Programming

Object

The grand-daddy of all classes--the class from which all others inherit.
.
Data Type Wrappers

A collection of classes used to wrap variables of a primitive data type: Boolean,


Character, Double, Float, Integer and Long. Each of these classes are subclasses of the
abstract class Number.

Strings

Two classes that implement character data. The String and StringBuffer Classes is
a thorough lesson on the use of both types of strings.

System and Runtime

These two classes allows the users to use system resources. System provides a
system-independent programming interface to system resources and Runtime gives we
direct system-specific access to the runtime environment.

Threads

The Thread, ThreadDeath and ThreadGroup classes implement the multi-


threading capabilities so important to the Java language. The java.lang package also
defines the Runnable interface. Runnable makes it convenient for Java class to be active
without subclassing the Thread class.

Classes

The Class class provides a runtime description of a class and the ClassLoader
class allows to load classes into the program during runtime.

Math

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A library of math routines and values such as pi.

Exceptions, Errors and Throwable

When an error occurs in a Java program, the program throws an object which
indicates what the problem was and the state of the interpreter when the error occurred.
Only objects that derive from the Throwable class can be thrown. There are two main
subclasses of Throwable: Exception and Error. Exceptions are a form of Throwable that
"normal" programs may try to catch. Errors are used for more catastophic errors--normal
programs should not catch errors. The java.lang package contains the Throwable,

Page 77
Java Programming

Exception and Error classes, and numerous subclasses of Exception and Error that
represent specific problems.

Processes

Process objects represent the system process that is created when Runtime is used
to execute system commands. The java.lang packages defines and implements the generic
Process class.

The compiler automatically imports this package. No other packages are


automatically imported.

The Java I/O Package

The Java I/O Package (java.io) provides a set of input and output streams used
to read and write data to files or other input and output sources.

The Java Utility Package

This Java package, java.util, contains a collection of utility classes. Among


them are several generic data structures (Dictionary, Stack, Vector, Hashtable) a useful
object for tokenizing a string and another for manipulating calendar dates. The
java.util package also contains the Observer interface and Observable class which
allow objects to notify one another when they change.

The Java Networking Package

The java.net package contains classes and interface definitions that implement
various networking capabilities. The classes in this package include a class that
implement a URL, a connection to a URL, a socket connection, and a datagram packet.
These classes are used to implement client-server applications and other networking
communication applications.

The Applet Package

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This package contains the Applet class -- the class that is to be subclassed while
writing an applet. Included in this package is the AudioClip interface which provides a
very high level abstraction of audio.

The Abstract Window Toolkit Packages

Three packages comprise the Abstract Window Toolkit: java.awt,


java.awt.image, and java.awt.peer.

Page 78
Java Programming

AWT Package

The java.awt package provides GUI elements used to get input from and display
information to the user such as windows, buttons, scrollbars, and text items.

AWT Image Package

The java.awt.image package contains classes and interfaces for managing


image data, such as setting the color model, cropping, color filtering, setting pixel values,
and grabbing snapshots of the screen.

1.2.11 Interfaces

The Java language supports interfaces to define a protocol of behavior that can be
implemented by any class anywhere in the class hierarchy.

In general, in English, an interface is a device or system that unrelated entities use


to interact. According to this definition, a remote control is an interface between you and
a television set, the English language is an interface between two people, and the protocol
of behavior enforced in the military is the interface between people of different ranks.

Similarly, a Java interface is a device that unrelated objects use to interact with
one another. Java interfaces are probably most analogous to protocols (an agreed-upon
behavior). In fact, other object-oriented languages have the functionality of Java's
interfaces, but they call their interfaces protocols.

A Java interface defines a set of methods but does not implement them. A class
that implements the interface agrees to implement all of the methods defined in the
interface, thereby agreeing to certain behavior.

Definition: An interface is a collection of method definitions (without


implementations) and constant values. It is used to define a protocol of behavior that can
be implemented by any class anywhere in the class hierarchy.

In short, interface is a template of behavior that other classes need to implement.


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This means that the body of the method is empty.

public interfce myinterface


{
public void addition(int a, int b);
public void subtraction(int x, int y);
}

Interfaces cannot extend classes but can extend other interfaces. If an interface
that extends an interface is implemented, then it becomes necessary to override methods

Page 79
Java Programming

in the new interface as well as in the old interface. In the above example, the methods
have just been declared and not defined. These methods have to be defined in the class
that implements this interface. ie the behavior of the method has to be specified. All
methods in the interfaces have to be of type public. It is illegal to use any other standard
modifiers such as protected, private etc., when declaring the methods in an interface.

import java.io.*;

class IntExample implements myinterface


{
public void addition(int a, int b)
{
System.out.println(“ “ + (a+b));
}
public void subtraction(int x, int y)
{
System.out.println(“ “ + (x-y));
}

public static void main(String args[])


{
IntExample d = new IntExample();
d.addition(10,20);
d.subtraction(10,5);
}
}

Interfaces can also be used to define a set of constants that can be used by the
classes.

public interface myconstants


{
public static final double price=1450.00;
public static final int counter =10;
}

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Often interfaces are touted as an alternative to multiple class inheritance. While
interfaces may solve similar problems, interface and multiple class inheritance are quite
different animals, in particular:

A class inherits only constants from an interface.

A class cannot inherit method implementations from an interface.

The interface hierarchy is independent of the class hierarchy. Classes that


implement the same interface may or may not be related through the class hierarchy. This

Page 80
Java Programming

is not true for multiple inheritance. Yet, Java does allow multiple interface inheritance.
That is, an interface can have multiple super interfaces. Interface is used to define a
protocol of behavior that can be implemented by any class anywhere in the class
hierarchy. Interfaces are useful for the following:

1. Capturing similarities between unrelated classes without artificially


forcing a class relationship.
2. Declaring methods that one or more classes are expected to implement.
3. Revealing an object's programming interface without revealing its class.
(Objects such as these are called anonymous objects and can be useful
when shipping a package of classes to other developers.)

1.3 Revision Points

Java
Java is an object oriented programming language, simple, distributed, interpreted, robust,
secure, architecture-neutral, portable, high performance, multithreaded and dynamic
language.

Variable
A variable is an entity that can change values during the program execution. Variables
are the nouns of any programming language. A variable's scope is the block of code
within which the variable is accessible and determines when the variable is created and
destroyed.

Encapsulation
Encapsulation is the process of packaging an object's data together with its methods. A
powerful benefit of encapsulation is the hiding of implementation details from other
objects. This means that the internal portion of an object has more limited visibility than
the external portion. This arrangement results in the safeguarding of the internal portion
against unwanted external access.

Array
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
An array is a construct that provides for the storage of a list of items of the same type.
Array items can have either a simple or composite data type. Arrays also can be
multidimensional.

Class
A class is usually described as the blueprint or template from which, the object is actually
made. It attributes and methods represent a class.

Page 81
Java Programming

Object
An object is an instance of the class. A software object maintains its states in variables
and implements its behavior with methods.

Inheritance
Inheritance is the process of creating a new class with the characteristics of an existing
class, along with additional characteristics to the new class.

Package
A package is a collection of related classes and interfaces that provides access protection
and namespace management.

Interface
An interface is a prototype for a class and is useful from a logical design perspective. The
benefits of using interfaces are much the same as the benefits of using abstract classes.
Interfaces provide a means to define the protocols for a class without worrying about the
implementation details.

1.4 Intext Questions

1. What is Unicode?
2. What is inheritance?
3. What is a Package? Give an example
4. What are the different types of inheritance java supports?
5. What is super keyword stands for?
6. What is an abstract class?

1.5 Summary
 Java is a programming language developed by Sun Microsystems
 Java is simple, object oriented, distributed, compiled and interpreted, robust,
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
architecture neutral and portable, secure, multithreaded, high performance,
dynamic language.
 Applications, Applets, Servlets and packages are different types of java programs.
 Applications are the programs that can be executed from the command prompt.
 Applets are programs that run on web page and a browser is needed.
 The variables in java can be assigned constants.
 A variable must not be a keyword in java. It must not begin with a digit.

Page 82
Java Programming

 The order of argument and the name of the overriding method should be identical
to those of the super class method.

1.6 Terminal Exercises

1. Write down the various features of Java.


2. Write a short notes on data types in java
3. Write a program to explain switch case statement
4. Explain about the life cycle of an object
5. What is multithreading? Explain the various methods in Object class.
6. Write an example to demonstrate Multithreading.
7. What is interface? Discuss multiple inheritance in java.

1.7 Supplementary Materials

1. Herbert Schildt, “Java 2: The Complete reference”, TMH, Fourth Edition,


2001.
2. E.Balagurusamy, “Programming with JAVA”, TMG, 1999.

1.8 Assignments

1. Java is called the “interactive web language”. Why it is interactive?


2. Write a program using if else ladder statement to find whether a given number
is odd or even.
3. Write a program to display the following output using For loop
1 *****
ANNAMALAI
ANNAMALAI UNIVERSITY
12UNIVERSITY ****
123 ***
1234 **
12345 *

4. Write a program to find the second largest and second smallest element in an
array.

Page 83
Java Programming

1.9 Suggested Reading/Reference Books/Set Books

1. Deital and Deital, “Java How to Programme”, Pearson Education, New Delhi,
2001.
2. http://www.sun.com/java
3. http://java.sun.com
4. http://www.sun.com/java/list.html
5. http://www.yahoo.com/Computers_and_Internet/Programming
languages/Java

1.10 Learning Activities

1. Collect Information on Object Oriented Programming concepts.


2. Collect Information on Packages (not covered in this lesson) from the Internet.

1.11 Keywords

Java Object
Class Applet
Inheritance Package
Constructor Main
Public Static
Void Encapsulation
Operands Operator
Decision Making Branching
Control Conditional Branching
ANNAMALAI
ANNAMALAI UNIVERSITY
Ladder UNIVERSITY Switch

Page 84
Java Programming

UNIT – II

Snapshot

 Exception Handling
 Multithreading
 Input/Output Streams
 Applets
 AWT
 Layout Manager
 Event Handling
 Socket Programming

2.0 Introduction
Exceptions can be used as a means of indicating other situations as well.
Exceptions provide notification of errors and a way to handle them. This control structure
allows you to specify exactly where to handle specific types of errors. Multithreading
involves multiple threads of control within a single program. Not only is the operating
system running multiple programs, each program can run multiple threads of control
think of threads as subprograms within the program. A thread is a single sequence of
execution within a program. The Java I/O package provides an extensive set of classes
that handle input and output to and from many different devices. The Abstract
Windowing Toolkit (AWT) package in the JDK is a library of Java classes you can use to
create graphical user interfaces (GUIs). These interfaces allow users to interact with the
Java application or applet in the same way they are accustomed to interacting with other
applications on their native platforms. A socket is nothing more than a convenient
abstraction. It represents a connection point into a TCP/IP network. When two computers
want to converse, each uses a socket. One computer is termed the server it opens a socket
and listens for connections. The other computer is termed the client it calls the server
socket to start the connection. To establish a connection, all that's needed is a server's
destination address and port number.

2.1 Objective
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The objective of this lesson is to understand the fundamentals of Java, which
include a wide range of topics from fundamentals of Exception handling to Socket
Programming. The fundamental concepts include threads, I/O streams, Applets, AWT,
Layout Manager and Event Handling.

2.2 Content

2.2.1 Exception Handling


An exception is the condition that occurs, when a program gets into a state that is
not quite normal. Exceptions trapping are sometimes referred to as error trapping. A

Page 85
Java Programming

typical example of an exception is that when a program attempts to open a file that does
not exists or trying to refer to an element of an array that does not exist. The Java
language uses exceptions to provide error-handling capabilities for its programs.

Definition: An exception is an event that occurs during the execution of a


program that disrupts the normal flow of instructions.
Java exceptions are built in part of the language. For example while performing
I/O one must put it in exception handling.
Many kinds of errors can cause exceptions ie., problems ranging from serious
hardware errors - such as a hard disk crash, to simple programming errors - such as trying
to access an out-of-bounds array element. When such an error occurs within a Java
method, the method creates an exception object and hands it to the runtime system. The
exception object contains information about the exception, including its type and the state
of the program when the error occurred. The runtime system is then responsible for
finding some code to handle the error. In Java terminology, creating an exception object
and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system leaps into action to find
someone to handle the exception. The set of possible "someones" to handle the exception
is the set of methods in the call stack of the method where the error occurred. The
runtime system searches backwards through the call stack, beginning with the method in
which the error occurred, until it finds a method that contains an appropriate exception
handler.
An exception handler is considered appropriate if the type of the exception thrown
is the same as the type of exception handled by the handler. Thus the exception bubbles
up through the call stack until an appropriate handler is found and one of the calling
methods handles the exception. The exception handler chosen is said to catch the
exception.
If the runtime system exhaustively searches all of the methods on the call stack
without finding an appropriate exception handler, the runtime system (and consequently
the Java program) terminates.
All exceptions in Java are subclasses of java.lang.Throwable that individually go
to describe the particular exceptional condition associated with them. java.lang.Error
and java.lang.Exception are "major" subclasses of Throwable –

There is a slight difference between an exception and an error; basically an


exception can be handled whilst an error cannot. Handling an exception basically means
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
dealing with it so that the program can continue as if nothing had happened. Exceptions
can occur for many reasons; the typically cited example is attempting to divide a number
by zero. But there are many others, such as trying to access an array element, which
doesn't exist.
If an exception occurs in a Java program and is left unhandled the program will
stop executing and the user will see a runtime error. The following code generates such a
runtime error by attempting to access an array element which doesn't exist.

class genExc
{

Page 86
Java Programming

public static void main (String args[])


{
int array [] = new int[9];
int index = 10;

array [index] = 3; // illegal


}
}

Handling the Exception


Java has a mechanism for handling exceptions so that the program can continue to
run as if nothing had happened. This mechanism is based around two statements: try and
catch.

try and catch

This statement is placed before a block of code which the programmer suspects
and might generate an exception. The catch statement comes straight after the try block
and specifies what type of exception is being caught, a block of instructions after the
catch statement are executed if the exception generated matches the one in the catch.
There can be multiple catch statements after a try block all with the different exceptions.
For example, the following program has two classes, the constructor for two Exc
takes two int parameters divides the first by the second and accesses an array using the
result as the index.

Example 1

class testExc
{
public static void main (String args[])
{
twoExc first = new twoExc(10, 0);
twoExc second = new twoExc(110, 10);
}

ANNAMALAI
ANNAMALAI UNIVERSITY
}
UNIVERSITY
class twoExc
{
int array[] = new int[10];
int index;

twoExc (int a, int b)


{
try
{

Page 87
Java Programming

index = a/b; // possible divide by 0


array [index] = 0; // possible array out of bounds
}
catch (ArithmeticException e)
{
System.out.println ("Divide by 0");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println ("Array Index Out of Bounds");
}
}
}

If an exception occurs in a Java program and is left unhandled the program will
stop executing and the user will see a runtime error. The following code generates such a
runtime error by attempting to access an array element which doesn't exist.

class genExc
{
public static void main (String args[])
{
int array [] = new int[9];
int index = 10;

array [index] = 3; // illegal, array only has 10 elements


// do not forget that array index starts from 0
}
}

Example 2

class testExc
{
public static void main (String args[])
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
twoExc first = new twoExc (10, 0);
twoExc second = new twoExc (110, 10);
}
}

When an exception occurs in Java an Object is created which is of the Exception


type, this is then thrown until it is caught.

The call-stack

Page 88
Java Programming

It is possible to allow an exception to move backwards through the call-stack until


a catch clause is found which is the same type as the exception. Imagine the situation
where the main method calls another method (called, for example, print) and print in turn
calls another called display. If an exception occurs in display then a check will be made
to see if there is a catch for the exception, if not then the next method in the call-stack
(print) will be made, then the next (main), if the exception is not handled by the last
method on the call-stack then a runtime error occurs and the program stops running.

throws

Before allowing an exception to check the next method in the call-stack first it
must be stated that the current method generates an exception that it does not handle
itself, this is achieved by adding the word throws, after the method parameter list, and a
comma separated list of exceptions. This tells the compiler that these exceptions can be
generated by the method but are dealt with elsewhere.
In the following example the method cause does not deal with the exception it
generates (divide by 0), it tells the compiler that it cannot (with throws) and the error is
caught by the catch statement in main, which follows the try block in which the call to the
cause method is found.

Example 3

class csTest
{
public static void main (String args[])
{
try
{
csTest.cause();
}
catch (ArithmeticException e)
{
System.out.println ("Divide by 0 error: caught in main");
}
}
static void cause () throws ArithmeticException
ANNAMALAI
ANNAMALAI UNIVERSITY
{ UNIVERSITY
int a = 0;
int b;
b = 10 / a; // exception
}
}
If a method is capable of raising an exception that it does not handle, it must
specify that the exception has to be handled by the calling method. This is done using the
throws statement, as given in the above example.

Page 89
Java Programming

The output of Example 3 is given below.

throw

It is possible to actually throw an exception from within the program code, using
the keyword throw. This is useful if an exception is caught in method and the calling
method also needs to be informed of the exception.

Example 4

class tesThrow
{
static void called_method()
{
int a = 0;
int b;
try
{
b = 10/a; // exception
}
catch (ArithmeticException e) // e is the exception object
{
System.out.println ("divide by 0: in called_method");

throw e; // throw the exception

ANNAMALAI
ANNAMALAI UNIVERSITY
}
}
UNIVERSITY
public static void main (String args[])
{
try
{
called_method ();
}
catch (ArithmeticException e)
{
System.out.println ("divide by zero: main");

Page 90
Java Programming

}
}}

User-defined Exceptions

It is possible to create ones own exceptions simply by creating a sub-class of the


Exception class. This allows custom exceptions to be generated (using throw) and caught
in the same way as normal exceptions. The following example creates an exception
(illegalValue), this is tested for in the method print, if one of the values is found to be
illegal the exception is thrown, it is caught by the main method.

Example 5

class illVal extends Exception


{
// The class simply has to exist to be an exception
}

class userExc
{
int value1;
int value2;

userExc(int a, int b)
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
value1 = a;
value2 = b;
}

void print() throws illVal // causes it, but does not catch it
{
if ((value1 < 0) || (value2 > 0))
throw new illVal();

System.out.println ("Value 1 = " + value1);


System.out.println ("Value 2 = " + value2);

Page 91
Java Programming

}
}

class runCX
{
public static void main(String args[])
{
userExc vals = new userExc(-1, 20); // values will generate an exception in print
try
{
vals.print();
}
catch(illVal e) // the custom exception
{
System.out.println ("Illegal Values: caught in main");
}
}
}
The output of Example 5 is given below.

finally

Usually when an exception is thrown the code immediately stops executing and
goes looking for a catch block to match the exception. However, this is not always
desirable, it is sometimes useful to have a piece of code which runs no matter what
exceptions have been generated and handled. This is known as the finally block. In the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
following example the finally block is demonstrated.

Example 6
class finTest
{
public static void main (String args[])
{
int a = 0;
try
{
System.out.println (1 / a); // causes an exception

Page 92
Java Programming

}
catch (ArithmeticException e)
{
System.out.println ("Divide by 0");
}
finally
{
System.out.println ("Finally block");
}}}

2.2.2 Multithreading

The programs so far discussed have run sequentially, that is they have completed
one task before they have moved on to the next. There are many advantages of being able
to run more than one task at once. For example, if one is waiting for some event to occur
without any reason, he or she could do some other calculation instead of waiting for an
event that does not use much of the CPU's time. This kind of concurrent programming is
supported in Java in the guise of threads.
A thread is a real thing with a beginning, a sequence of operations that it will
execute and an end. So far all the programs looked at, have just had a single thread, the
beginning was the start of the program, the sequence the whole program and the end
when the program terminated. Threads in Java are also known as lightweight processes
and execution contexts. They are similar to processes in the UNIX operating system
(which are known as heavyweight processes) except that threads run within the address
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
space of the program to which they belong.

Thread control

The control of threads in Java is achieved by the Thread class. It is important not
to confuse the objects, which are of type Thread with the actual thread itself. The thread
is the so-called lightweight process with a beginning, sequence and an end. The Thread
object, on the other hand, is simply the mechanism by which the thread is controlled,
rather like a control panel.
Some of the methods which control threads are called an instances of the Thread
object, others are static and are called on the classname (Thread). Typically the static

Page 93
Java Programming

methods refer to the current thread while those called on an object obviously refer to the
thread connected with that object.

currentThread

currentThread is a static method which returns a Thread object referring to the


currently running thread.

Thread cur = Thread.currentThread();

cur would now be an object of type Thread referring to the current thread and thus
allows to manipulate it.

setName

Threads have a name associated with them to help debugging, this can be set with
the setName method which is called on the Thread object referring to the thread that is
wished to be renamed. The only parameter passed to it is a string. For example,
cur.setName ("Current Thread");

getName
This method is the partner of setName, again it is called on the Thread object.
getName takes no parameters but returns a String object, which can be printed or
assigned to a String reference, containing the thread name. For example,
system.out.println (cur.getName); // will print the threads name
sleep

This is a very useful static method which simply sends the current thread to sleep
for a length of time which is specified as an input parameter, in milliseconds. This is
useful for pauses in execution, to allow other threads to take control for a period of time.
The only slight complication with sleep is that it can cause an exception if it is
interrupted. Any program with sleep will not compile if the exception is not caught. sleep
can be used as follows:

try
{
ANNAMALAI
ANNAMALAI UNIVERSITY
}
UNIVERSITY
Thread.sleep(1000); // sleep for 1 second

catch
{
System.out.println ("Thread interrupted");
}

An example of how simple Thread methods at work

class simpleThread

Page 94
Java Programming

{
public static void main (String args[]) throws Exception
{
Thread cur = Thread.currentThread();

cur.setName("Current Thread"); // set name


System.out.println(cur.getName()); // print name

for (int cnt = 0; cnt < 10; cnt ++)


{
System.out.println(cnt);
Thread.sleep(1000); // sleep for 1 second
}
}
}

The above example shows how a reference to the current thread can be got and
used to change and print the name. The second half shows the effect of sleep when
printing the numbers one to ten.

Note that whenever one wants to refer to the current thread there is no need to
create a reference to it. It is possible to use the static method currentMethod anywhere
one would normally use a reference since currentMethod returns a reference. For
example, the following two fragments of code achieve the same end:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Thread cur = Thread.currentThread();
System.out.println (cur.getName());

Has the same effect as :

System.out.println (Thread.currentThread().getName());

It is really up to the individual programmer when to use which version.

Page 95
Java Programming

Using Multiple Threads

Creating a new thread

To create a new thread all that needs to be done is to create a new instance of the
Thread class using the new operator. There are several versions of the constructor for this
class, the simplest takes no parameters. For example :

Thread newOne = new Thread ();

Controlling Threads

The whole concept of controlling multiple threads can appear complicated at first.
Java expects the control of threads to appear in the form of the following methods:
run()
start()
stop()
suspend()
resume()

The run method should contain the sequence part of the thread (i.e. what it has to
do), the other methods are called on the Thread object in order to affect the running of the
thread, for example start starts the execution of the thread (i.e. begins executing
statements in run).

run

run is the key to any thread, it is here that the sequence of the thread is described.
There are two ways that run can be implemented in Java. Firstly the Thread class can be
extended and the run method overridden in the new class. A rather more elegant way of
achieving, effectively, the same result is to have your class implement the Runnable
interface.

start

This method is called on a Thread object and simply starts the thread running.

stop
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
This method is called on a Thread object and halts a thread.

suspend and resume

This method is identical to the stop method except that a thread stopped with
suspend can be restarted, at the point it was stopped with the resume method.

Page 96
Java Programming

Running Multiple Threads

The execution of the program begins, as ever, in the main method. Main creates a
new instance of testMulti which in turn calls its constructor. The constructor contains the
code to create the two Thread objects. The original thread is already running whilst the
second is created by the call to start. The current thread continues to run the code in the
constructor whilst the new one moves into the run method and executes the code there.
Although this appears to happen simultaneously it cannot, even as the first thread is
asleep the second runs and vice-versa, this is why the parent thread can count down from
10 because the child is asleep for twice as much time.

class testMulti implements Runnable


{
testMulti()
{
Thread cur = Thread.currentThread();
Thread t = new Thread (this, "New thread");
t.start();

try
{
for (int cnt = 10; cnt > 0; cnt --)
{
System.out.println ("Parent Thread : "+cnt);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println ("Interrupted");
}
System.out.println ("exiting main thread");
}

public void run ()


{
ANNAMALAI
ANNAMALAI UNIVERSITY
try
{
UNIVERSITY
for (int i = 5; i > 0; i--)
{
System.out.println ("Child Thread : " + i);
Thread.sleep(2000);
}
}
catch (InterruptedException e)
{

Page 97
Java Programming

System.out.println ("child interrupted");


}

System.out.println ("exiting child thread");

public static void main (String args[])


{
new testMulti();
}
}

Thread Priorities

It is sometimes useful to have threads which take precedence over each other,
these threads are said to have a higher priority. The priority of a thread is an integer
between 1 and 10, the higher the number the higher the priority. If, for example, two
threads were started at the same time the thread with the higher priority would execute
first. Similarly if threads were running and another, with a higher priority, woke up the
thread with the higher priority would immediately take over and start executing.

Changing Thread Priorities

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
When a thread is created it is automatically given a priority of 5. This can later be
increased or decreased using the method setPriority. There is also a partner method called
getPriority which allows the priority of a thread to be returned as an int.
In addition to priorities being referred to as numbers the Thread class also
provides static final variables (effectively constants). These are as follows:

MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10

The setPriority method

Page 98
Java Programming

This method is called on a Thread object with an int between 1 and 10 as the only
input parameter. This parameter can be one of the three static final variables defined in
the Thread class.

The getPriority method

This method is also called on a Thread object but takes no input parameters and
returns the priority of the thread, referenced by the Thread object, as an int.
This example show threads work. It's probably best to run the example before
trying to figure it out.

class testPri implements Runnable


{
testPri()
{
Thread cur = Thread.currentThread();
Thread t = new Thread (this, "New thread");
cur.setPriority (Thread.NORM_PRIORITY + 1);
System.out.println ("parent priority is : " + cur.getPriority());
System.out.println ("child priority is : " + t.getPriority());

t.start();
for (int cnt = 0; cnt < 100; cnt ++)
{
System.out.println ("Parent Thread : "+ cnt);
if (cnt == 20)
{
try
{
Thread.sleep (1500);
}
catch (InterruptedException e)
{
System.out.println ("interrupted");
}
ANNAMALAI
ANNAMALAI UNIVERSITY
}
UNIVERSITY
}

t.resume();
System.out.println ("exiting main thread");
}

public void run ()


{
for (int i = 100; i > 0; i--)
{

Page 99
Java Programming

System.out.println ("Child Thread : " + i);


if (i == 30)
Thread.currentThread().suspend();
}

System.out.println ("exiting child thread");


}

public static void main (String args[])


{
new testPri();
}
}

The code itself is very similar to the previous example, except that the parent
thread counts up and the child down, the Thread objects are created in the constructor of
a class, in this case testPri. After the Thread objects have been created the parent thread's
priority is increased and the priorities of the two threads displayed. Then the second
thread is started, however, since the parent thread is has the higher priority it continues to
execute. Them:
When the parent thread gets to 20 it puts itself to sleep for 1500 ms (1.5
seconds).Because the parent is asleep the child takes over executing, however, when it
gets to 30 is suspends itself.
For a short time there is no thread executing since the child is suspended and the
parent is asleep.
After its 1500 ms sleep the parent wakes up and continues counting, when the
loop is exited (when 99 is reached) the parent thread allows the child to resume. The
parent then informs the user it has finished.
The child takes over execution again until it completes. It then informs the user
that it too has finished.

Threads and Synchronization

Synchronization

When a program is split into more than one thread there is an inherent problem
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
with shared resources. Take the example of a Stack, if threads are processing data and
placing it onto the stack obviously timing is very important. Such a situation is very
unpredictable since you are unable to tell what is on top of the stack at any one time. The
idea of synchronization is that the programmer can exercise more control over the threads
access to shared resources.

Synchronized Methods

In order to make the interaction of threads and shared resources more predictable
methods can be made synchronized. Synchronized methods differ from normal methods

Page 100
Java Programming

in that only one thread can call a synchronized method on a particular object, any other
thread trying to access a synchronized method on the same object must wait until the first
thread has finished. Synchronized methods can be thought of as a car park with reserved
spaces, one for each object. If one thread is already parked in the space reserved for the
object the method was called on the thread must drive round and round until the other
thread leaves and the space is free. This obviously means that the interaction of threads
and shared resources can become much more predictable.
The following example highlights the usefulness the synchronized method. This
example has two threads, the current one and a newly created one. The current thread
adds four objects to a Stack, but with a sleep before adding the final one. The new thread
(in run) prints out the string which is on top, i.e. the last item pushed onto the Stack.

wait, notify and notifyAll

These three methods exist in all Java objects and allow communication between
threads via a synchronized method.

wait

wait orders the current thread, in a synchronized method, to go to sleep and wait
until notified to awaken. Note that the wait method can generate a InterruptedException
and therefore must either throw it or deal with it.

notify

notify is called in a synchronized method and wakes the first thread which is
wait(ing).

notifyAll

notifyAll works in the same way as notify except that all wait(ing) threads are
awakened in order of their priority.

An example of wait and notify

This example shows wait and notify at work. The constructor of the waitTest class
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
creates and starts a new thread. However, since the current thread and the newly created
one have the same priority the current one continues to run, until control is explicitly
yielded to the other thread. This thread then enters the run method (which is
synchronized) where it is told to wait. Since waiting causes the thread to sleep the
original thread regains control and calls the notify() method which notifies the waiting
thread, this thread then takes control and informs the user that it has been notified.

class waitTest implements Runnable


{
waitTest ()

Page 101
Java Programming

{
Thread thr = new Thread (this);
thr.start();
}

synchronized void notifyIt()


{
System.out.println ("Notifying the waiting thread");
this.notify();
}

synchronized public void run()


{
try
{
this.wait();
}
catch(InterruptedException e)
{}
System.out.println ("Thread notified");
}
}

class runWtest
{
public static void main(String args[])
{
waitTest wt = new waitTest();
Thread.yield ();
wt.notifyIt();
}
}

The Output is given below:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 102
Java Programming

2.2.3 Input/Output Streams

Concept of Streams
Streams are pipelines for sending and receiving information in Java programs.
When a stream of data is sent and received, it is said writing and reading a stream. When
a stream is read or written, the other threads are blocked. While reading or writing a
stream if an error occurs, an IOException is thrown. Hence the stream statements must
consist of a try-catch clause.
Generally programs need to read data from some input source or write data to
some output source. The Java development environment includes a package, java.io, that
contains a set of input and output streams that the programs can use to read and write
data. Probably one would have first encountered I/O streams in Java through the use of
the standard output, standard error, and standard input streams managed by the System
class.

First Encounter with I/O in Java

One would have probably used System.out.println() to display information to


the user, and used System.in.read() to read in characters entered by the user. If these
methods have been used, then perhaps unknowingly one has been using input and output
streams from the java.io package. These streams are created and managed by the System
API class and implement the standard streams.
The concept of standard input and output streams, is a C library concept that has
been assimilated into the Java environment. There are three standard streams all of which
are managed by the java.lang.System class:

standard output--referenced by System.out


used for program output, typically displays information to the user.

standard input--referenced by System.in


used for program input, typically reads input entered by the user.

standard error--referenced by System.err


used to display error messages to the user.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Standard Output and Standard Error
Probably the most often used items from the System class are the streams used for
writing program output-the standard output and standard error streams. Both the standard
output and standard error streams are System class variables; it can be referenced with
System.out and System.err, respectively.
Both the standard output and standard error streams are instances of the
PrintStream API class from the java.io package. The PrintStream class implements an
output stream that is easy to use. Simply one of the print(), println(), or write()
methods can be called to write various types of data to the stream.

Page 103
Java Programming

Standard Input
In addition to the two output streams for writing data, the System class provides a
stream for reading data--the standard input stream--referenced with System.in.
InputStream is an abstract base class from which all input streams in the java.io package
derived. InputStream defines a programming interface for input streams that includes
methods for reading from the stream, marking a location within the stream, skipping to a
mark, and closing the stream.

Overview of java.io's Input and Output Streams


The java.io package contains two classes, InputStream and OutputStream, from
which most of the other classes in the package derive.
The InputStream class is an abstract base class that provides a minimal
programming interface and a partial implementation of input streams in Java. The
InputStream class defines a methods for reading bytes or arrays of bytes, marking
locations in the stream, skipping bytes of input, finding out the number of bytes that are
available for reading, and resetting the current position within the stream. An input
stream is automatically opened when it is created. A stream can be explicitly closed with
the close() method, or let it be closed implicitly when the object is garbage collected.
The OutputStream class is an abstract base class that provides a minimal
programming interface and a partial implementation of output streams in Java.
OutputStream defines methods for writing bytes or arrays of bytes to the stream and
flushing the stream. An output stream is automatically opened when it is created. It can
be explicitly closed with the close() method, or let it be closed implicitly when the
object is garbage collected.
The java.io package contains several subclasses of InputStream and OutputStream
that implement a specific input or output function. For example, FileInputStream and
FileOutputStream are input and output streams that operate on a file on the native file
system.
The first of the following two diagrams shows the class hierarchy for the input
stream classes comprising the java.io package. InputStream inherits from the Object
class; six classes inherit directly from InputStream. One of OutputStream's descendents,
FilterInputStream, is itself an abstract class with four children.
The second of the diagram shows the class hierarchy for the output stream classes
contained in the java.io package. OutputStream inherits from the Object class; four
classes inherit directly from OutputStream. One of OutputStream's descendents,

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
FilterOutputStream, is itself an abstract class with three descendents.

Page 104
Java Programming

Simple Input and Output Streams


1. ByteArrayInputStream and ByteArrayOutputStream
Reads data from or writes data to a byte array in memory.
Methods Description

ByteArrayInputStream(byte[] bytes) – Creates an input stream of the array of


bytes
int size() - Returns the total number of bytes written to the stream

Example

import java.io.*;

public class ByteExam


{
public static void main(String args[]) throws IOException
{
ByteArrayOutputStream os = new ByteArrayOutputStream();

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
String s = "Welcome to byte array input output classes";
for(int i=0; i< s.length(); i++)
os.write(s.charAt(i));
System.out.println("Output Stream is " + os);
System.out.println("Size is " + os.size());
ByteArrayInputStream in = new ByteArrayInputStream(os.toByteArray());
int ib = in.available();
System.out.println("Input Stream has " + ib + "available bytes");
byte ibuf[] = new byte[ib];
int byrd = in.read(ibuf,0,ib);
System.out.println(byrd + "Bytes were read");

Page 105
Java Programming

System.out.println("They are " + new String(ibuf));


}
}

output:

FileInputStream and FileOutputStream


Used to read data from or write data to a file on the native file system.

BufferedInputStream and BufferedOutputStream

This is an efficient stream that buffers data while reading or writing.


SequenceInputStream
Concatenates multiple input streams into one input stream.

Example:

import java.io.*;
public class BuffExam
{
public static void main(String args[]) throws IOException
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
SequenceInputStream a3;
FileInputStream a1 = new FileInputStream("File1.txt");
FileInputStream a2 = new FileInputStream("File2.txt");
a3 = new SequenceInputStream(a1,a2);
BufferedInputStream inst = new BufferedInputStream(a3);
BufferedOutputStream oust = new BufferedOutputStream(System.out);
boolean eof = false;
int bytcnt =0;
while(!eof)
{
int I =inst.read();

Page 106
Java Programming

if(I==-1)
eof = true;
else
{
oust.write((char)I);
bytcnt++;
}
}
String bytrd = String.valueOf(bytcnt);
bytrd = bytrd + "Bytes were read";
oust.write(bytrd.getBytes(),0,bytrd.length());
inst.close();
oust.close();
a2.close();
}
}

Output:

PipedInputStream and PipedOutputStream


Implements the input and output components of a pipe. Pipes are used to channel
the output from one program (or thread or code block) into the input of another. A
PipedInputStream must be connected to a PipedOutputStream and vice versa.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
StringBufferInputStream
Allows programs to read from a StringBuffer as if it were an input stream.

Filtered Streams
FilterInputStream and FilterOutputStream are subclasses of InputStream and
OutputStream, respectively, and are both themselves abstract classes These classes
defines the interface for filtered streams. Filtered streams process the data as its being
read or written. For example, the BufferedInputStream and BufferedOutputStream
classes buffer the data while reading and writing to speed it up.

Page 107
Java Programming

DataInputStream and DataOutputStream


Reads or writes primitive Java data types in a machine independent format.

LineNumberInputStream
An input stream that keeps track of line numbers while reading.

PushbackInputStream
An input stream with a one-byte pushback buffer.

PrintStream
An output stream with convenient printing methods. In addition to the streams
classes, java.io contains these other classes:

File
Represents a file on the native file system. It is used to access file and directory
objects. It uses the file-naming conventions of the host operating system. The class has
constructors that are used for creating files and directories. The methods of this class
allows to delete and rename files. Using the directory methods, directories can be created,
deleted, renamed and listed.

Constructors

File(String pathname) -Creates a new instance of the File class by


converting the given pathname string into an abstract pathname.
File(String parent, String child) - Creates a new instance of the File class from a
parent pathname and a child pathname string.
File(File parent, String child) - creates a new File instance from a parent File
object and a child pathname.

Example

import java.io.*;
public class FileClass
{
public static void main(String args[]) throws IOException
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
File fileobj = new File("c:\\javabook\\file1.txt");
System.out.println("\n The size of the file is \t\t " + fileobj.length());
System.out.println("\n The Exist status of th file is \t\t " + fileobj.exists());
System.out.println("\n The File or directory \t\t " + fileobj.isFile());
System.out.println("\n The File or directory \t\t " + fileobj.isDirectory());
System.out.println("\n Path \t\t " + fileobj.getAbsolutePath());
System.out.println("\n Can Read \t\t " + fileobj.canRead());
System.out.println("\n Can Write \t\t " + fileobj.canWrite());
System.out.println("\n Name of the file is \t\t " + fileobj.getName());
System.out.println("\n Path \t\t " + fileobj.getPath());

Page 108
Java Programming

}
}
Output

Example: To display list of files in a directory

import java.io.*;

public class ListDir


{
public static void main(String args[])
{
File obj = new File("c:\\corbaboa");

String files[] = obj.list();


for(int i=0; i<files.length; i++)
{
System.out.println("\n (" + i + ") \t" + files[i]);
}
}
}

Output
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 109
Java Programming

RandomAccessFile
Represents a random access file.

StreamTokenizer
Breaks the contents of a stream into tokens.

DataInput and DataOutput


These two interfaces describe streams that can read and write primitive Java types
in machine independent format.

Using Piped Streams


The java.io package contains two classes, PipedInputStream and
PipedOutputStream, that implements the input and output components of a pipe. Pipes
are used to channel the output from one program (or thread or code block) into the input
of another. A PipedOutputStream must be connected to a PipedInputStream and vice
versa.
Piped input and output streams are convenient for methods that produce output to
be used as input by someone else. For example, suppose while writing a class that
implements various text utilities such as sorting, extracting unique lines, and reversing
text. It would be nice if the output of one of these methods could be used as the input for
another. Thus a series of these methods could be stringed together to perform some
ANNAMALAI
ANNAMALAI UNIVERSITY
function.
UNIVERSITY
Using Streams to Read and Write Files
File streams are perhaps the easiest streams to understand. Simply put,
FileInputStream represent an input and FileOutputStream represent an output stream on a
file that lives on the native file system. A file stream can be created from the filename, a
File object or a FileDescriptor object. Use these streams to read data from or write data to
files on the file system.

This small example uses the file streams to copy the contents of one file into
another.

Page 110
Java Programming

import java.io.*;

public class FileStreamsTest


{
public static void main(String args[])
{
try {
FileInputStream fis = new FileInputStream("TestIn.txt");
FileOutputStream fos = new FileOutputStream("TestOut.txt");
int c;

while((c=fis.read())!=-1)
{
fos.write(c);
}

fis.close();
fos.close();
}
catch (FileNotFoundException e)
{
System.err.println("FileStreamsTest: " + e);
}
catch (IOException e)
{
System.err.println("FileStreamsTest: " + e);
}
}
}

Using Streams to Read and Write Memory Locations

Use ByteArrayInputStream and ByteArrayOutputStream to read and write 8-bit


data. These streams can be created on an existing byte array and then use the read() and
write() methods to read from or write data to the array in memory. Other streams
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
operate on Unicode data.
StringBufferInputStream is used to read data from a StringBuffer. stream can be
created from on an existing StringBuffer object and then use the read() methods to read
from StringBuffer as it lives in memory. This stream is similar to the
ByteArrayInputStream which reads 8-bit data from a byte array in memory.
StringBufferInputStream reads 16-bit Unicode data from a string buffer in memory.

Using Streams to Concatenate Files


The SequenceInputStream creates a single input stream on multiple input sources.

Page 111
Java Programming

Working with Filtered Streams


Filtered streams process data as its being written to or read from the stream. The
java.io package implements these filtered streams:

DataInputStream and DataOutputStream


BufferedInputStream and BufferedOutputStream
LineNumberInputStream
PushbackInputStream
PrintStream (this is an output stream)

This section shows you how to use filtered streams through an example that uses a
DataInputStream and a DataOutputStream. In addition, this section shows you how to
write your own filtered streams.

Using Filtered Streams


To use a filtered input (output) stream, attach the filtered stream to another input
(output) stream. For example, a DataInputStream can be attached to the standard input
stream like this:

DataInputStream dis = new DataInputStream(System.in.read());


String input;

while ((input = dis.readLine()) != null) {


. . . // do something interesting here
}

This might be done, so that the more convenient readXXX() methods can be used,
such as readLine(), implemented by DataInputStream.

Using DataInputStream and DataOutputStream

Working with Random Access Files


The input and streams that have been used so far used sequential access streams--
streams whose contents must be read or written sequentially. Sequential access files are
leftovers from the days of magnetic tape and other naturally sequential medium. Random
access files, on the other hand, permit non-sequential, or random, access to the contents
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
of a file. Random access files are useful for many different applications. One specific
example of a good use of random access files are zip files. Zip files contain many other
files and are compressed to conserve space. Zip files contain a directory at the end that
indicates where the various contained files begin:

An efficient way to extract a particular file from within a zip file is with a random
access file:
open the file
find and read the directory locating the entry for the desired file
seek to the position of the desired file

Page 112
Java Programming

read it

With a sequential access file, on average, half the zip file must be read, before
finding the file that wanted. With a random access file, only the directory and the file that
needed is read. The RandomAccessFile class in the java.io package implements a random
access file.

2.2.4 Applets
Java code can also be executed under the control of a web browser. Code written
to execute under the control of a browser is called an applet. Applets have access to a
subset of the normal Java network and file I/O access. Applets can be used to provide
dynamic user-interfaces, and a variety of graphical effects for web pages.
To create an applet, we extend the java.applet.Applet class. By overriding the
methods of java.awt.Applet, new functionality can be provided that can create useful
programs, which can be placed into web pages.

First applet

Let us write the first applet “Hello World”

The java.applet package is the smallest package in the Java API. The Applet class
is the only class in the package. An apple is automatically loaded and executed when a
web page that contains it is opened. The Applet class has more than 20 methods that are
used to display images, play audio files etc.,
The environment of the applet is known as the context of the applet. It can be
retrieved by using the getAppletContext() method. The life of an applet is implemented
using the methods init(), start(), stop() and destroy(). Applets are compiled using javac
compiler and it can be executed either by using an appletviewer or by embedding the
class file in the HTML file.
Life cylce of an applet
The init() method is invoked when an applet is loaded for the first time into the
memory of a computer. In this method, variables can be initialized, various components
can be added.

Called when user open the web page for the first time
ANNAMALAI
ANNAMALAI UNIVERSITY
init
UNIVERSITY
start After init when the applet receives the focus

stop
Called when the applet loses focus

destroy
It is called when the user moves to another page

Life cycle of an applet

Page 113
Java Programming

The next is the start() method that is called immediately after init(). It is called
everytime when an applet receives focus.

The stop() method is called every time when an applet loses focus. It can be used
to reset variables and stop the threads that are running.
The destroy() method is called by the browser, when the user moves to the
another page. This method can be used to perform clean-up operations like closing a file.
It is not mandatory to use all the methods of the applet. They are called by the
Java environment and must be declared public.We start by extending java.applet.Applet,
and importing the applet and awt package. The AWT package represents the Abstract
Windowing Toolkit, a library of classes that give applets and stand-alone applications
graphical capability.
To display the greeting, we must override the paint method of java.awt.Applet.
The paint method deals with the display of graphics on our applet - we'll override it to
show our message. We set the colour to blue, and then draw a string on the applet
window.

// HelloWorldApplet.java

import java.awt.Graphics;
import java.awt.Color;
import java.applet.*;

public class HelloWorldApplet extends Applet


{

// Overridden paint method


public void paint(Graphics g)
{
g.drawString("Hello world! ",20,20);
}
}

The update() method takes a Graphics class object as a parameter. When the
applet area needs to be redrawn, the Windows system starts the painting process. The
update() method is called to clear the screen and calls the paint() method. The screen is
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
then refreshed by the system.The paint() method is called automatically first time when
the applet is displayed on the screen and every time when the applet receives the focus.
The paint() method can be invoked by calling the repaint() method.

The repaint() method is called when the applet area to be redrawn. The update()
method is called by the repaint() , to signal that the applet has to be updated. The default
action of the update() method is to clear the applet area and call the paint() method. The
update() method can be overridden if there is any requirement for the applet area to be
cleared. In the paint method, we draw a string on the applet. After compiling the
HelloWorldApplet class, insert it into a web page for testing. This is done with the applet
tag.

Page 114
Java Programming

Applets and HTML

<APPLET
CODE=”name of the class file that extends java.applet.Applet”
CODEBASE=”path of the class file”
HEIGHT=maximum height of the applet, in pixels
WIDTH=maximum width of the applet, in pixels
VSPACE=vertical space between the applet and the rest of the HTML, in pixels
HSPACE=horizontal space between the applet and the rest of the HTML, in pixels
ALIGN
ALT
>
<PARAM NAME=”parameter_name” VALUE=”value_of_parameter”>
<PARAM NAME=”parameter_name” VALUE=”value_of_parameter”>
…..
</APPLET>

The applet tag is used to embed an applet in an HTML document. The applet tag
takes zero or more parameters. The most commonly use attributes of the applet tag are
CODE, WIDTH, HEIGHT,CODEBASE and ALT.

<applet CODE= "HelloWorldApplet" HEIGHT=150 WIDTH=200>

This tag loads the applet HelloWorldApplet.class, giving it a width of one


hundred and fifty pixels, and a height of thirty. When the class is copied to the same
directory as the HTML document it is to be inserted into, the applet will load whenever a
Java enabled browser views the page. The following output will be seen in the browser.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Passing Parameters

HTML tag is the place where the parameters can be sent. Parameters are an easy way to
configure Java applets without actually changing the source file.

<param> tag is used to with <applet> to send the parameters to the applet classes.

Page 115
Java Programming

Eg.

<applet code=HelloWorldApplet width=300 height=200>


<param name=”colour” value =”green”>
</applet>

The getParameter() method is used to retrieve the parameter value inside the program.
The value returned by the parameter will be of String type. Thus, for numeric data types,
it must be converted into their internal formats. If no parameters are sent, the
getParameter() method returns a null value.The HTML file passes the two values,
‘principal’ and ‘NoofYears’ to the Java class. The java code uses these values and
calculates the simple interest and print the same along with the passed values.

Example

import java.awt.Graphics;
import java.awt.Color;
import java.applet.*;

/*
<applet code = "PassingParam" width=300 height=200>
<param name = fontName value=Courier >
<param name = fontSize value=14 >
<param name = leading value= 2>
</applet>
*/

public class PassingParam extends Applet


{
String fontName;
int fontSize;
float leading;

public void start()


{
String param;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
fontName = getParameter("fontName");

if(fontName == null)
fontName = "Not found";
param = getParameter("fontSize");

try
{
if(param != null)
fontSize = Integer.parseInt(param);

Page 116
Java Programming

else
fontSize=0;
}catch(NumberFormatException e)
{
fontSize = -1;
}

param = getParameter("leading");

try
{
if(param != null)
leading =Float.valueOf(param).floatValue();
else
leading=0;
}
catch(NumberFormatException e)
{
leading = -1;
}

}
public void paint(Graphics g)
{
g.drawString("Font Name " + fontName,0,10);
g.drawString("Font Size " + fontSize,0,26);
g.drawString("Leading " + leading,0,42);
}
}

Output

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 117
Java Programming

2.2.5 AWT

Graphical User Interface Components

Introduction
With the help of Graphical User Interface (GUI), a pictorial interface with the
user can be created. This helps to develop more efficient programs that are easy to work
with. The user can interact with the application without any problem. This is achieved by
creating

GUI components.
It is a visual object and the user interacts with this object via a mouse or a
keyboard. Components included, can be actually seen on the screen, such as, buttons,
labels etc.. Any operation that is common to all the GUI components are found in class
Component. In order to create these GUI components, we need to use the classes that are
available in the package java.awt. AWT stands for Abstract Windowing Toolkit.The
AWT package consists of classes, interfaces and other packages. The figure below
explains a portion of the AWT class hierarchy.
Anything that inherits from class container is in itself a container; A container is
an area, where all components can be placed. Applet is a container as it derives from
panel, which is in turn derived from class container.
Object

CheckboxGrou MenuCompone BorderLayout


p nt
Component FlowLayout GridLayout

TextFie
TextComp ld
onent TextAr
Button ea
C
o Label
ANNAMALAI
ANNAMALAI UNIVERSITY
m
p
UNIVERSITY CheckBox
o List
n
e Choice Panel
n Panel
t Container Frame
Windo
Canvas w Dialog

Scrollbar

Page 118
Java Programming

Abstract Windowing Toolkit

java.awt.Label

This class is used to display the String, which cannot be modified. It is read only
string. The following example draws a label on an applet.

import java.awt.*;
import java.applet.*;

public class Mylabel extends Applet


{
String msg;
Label label1, label2;

public void init()


{
setBackground(Color.cyan);
setForeground(Color.black);
setFont(new Font("SansSerif", Font.BOLD, 16));

label1 = new Label("You cannot edit me :");


label2 = new Label("Iam just a LABEL :");

add(label1);
add(label2);
}
public void paint(Graphics g)
{
msg="An example for the Label Class";
showStatus(msg);
}
}

This statement declares two Label objects - Label label1 , label2;

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
label 1 = new Label("Enter your Name:");
label2 = new LabeI("This is just a LABEL : ");

Instantiates the Label objects

add(labell);
add(label2);

The label will be visible only if they are added to the container. Here, applet is the
cantainer to which component label is added.

Page 119
Java Programming

The output of the program is as follows:

Description of Label Class:


Fields
public static final int CENTER
public static final int LEFT
public static final int RIGHT

These are the constants that specify the alignment of the text. By default, the text
of all the Label objects is left aligned.
Constructors
public Label()
creates an empty Label

public Label( String str)


creates a Label that displays the text specified in str.

public Label( String str , int alignment)


creates a Label that displays the text specified in str along with the specified
alignment.
ANNAMALAI
ANNAMALAI UNIVERSITY
java.awt.List
UNIVERSITY
List, as the name suggests, is a collection of items from which the user may select
one or more than one item. The use of this package is illustrated in the following
program:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Mylist extends Applet implements ItemListener

Page 120
Java Programming

{
Label label1 , label2;
List courseList;
String str[] = {" Introduction to C",
" Introduction to C++",
" Introduction to Java",
" Introduction to Beans",
};
String msg1 ,msg2;

public void init()


{
setFont(new Font("Arial", Font.BOLD,16));
setBackground(Color.cyan);
setForeground(Color.black);
courseList = new List(2, false);
for(int i=0 ; i<str.length ; i++)
courseList.add(str[i]);
courseList.addItemListener(this);
add(courseList);
}

public void itemStateChanged(ItemEvent e)


{
msg1="You selected :" + courseList.getSelectedItem();
msg2="Index is : "+ courseList.getSelectedIndex();
}
public void paint(Graphics g)
{
g.drawString(msg1,20,150);
g.drawString(msg2,20,170);
}
}
This program allows the user to select an item from the list and display the item
selected. This is done in combination with the class methods and the event handling
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
methods and interface. Henceforth, we will be working with handling of events
simultaneously, along with different components. Now let us go into the details of the
List class.
courseList = new List(2 , false);
The constructor is invoked with two arguments. The int value decides on the
number of lines visible and the boolean value decides on single selection or multiple
selection. In this case, false indicates that only one item can be selected. The scrollbar
automatically appears because the number of items are more that what is visible.
for(int i=0;i<str.length; i++)

Page 121
Java Programming

courseList.add(str[i]);

Adds items to the list courseList.

msgl="You selected : " +courseList.getSelectedItem() ;

msg2="Index is : "+courseList.getSelectedIndexQ;
Clicking on the item once triggers an item event and invokes the method
itemStateChanged(). getSelectedItem( ). returns the item selected by the user and
getSelected!ndex() returns the index of that selected item.
Description of the List Class :

public void ddd(String)


Adds the string to the end of the list.
public void add(String Ustltem, int index)
Adds the string at the specified index.
public void remove(String Ustltem)
Removes the item from the list specified by string
public void removeftnf index)
Removes the item from the list at the specified index.
public void removeAll()
Removes all the items from the list
public String getltem(int index)
Returns the item from the list aat the specified index
public int getItemCount()
Returns the number of items present in the list.
public String [ ] getltems()
Returns an array containing all the items from the list.
public String getSelected!tem()
Returns the selected item,
public String getSelected!ndex()
Returns the index of the selected item.
public String [ ] getSelectedItems( )
Returns an array containing all the selected items
public int getSelectedIndexes( )
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Returns an array containing the indexes of the selected items.

The output is as
follows:

Page 122
Java Programming

Handling Events
Graphical User Interface (GUI) systems handle all the user interactions with the
help of an event-driven model. The user performs an action, such as, moving the mouse,
pressing a key, releasing the key and so on. All these operations generate an event of
some kind. Everything is an event in Java.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 123
Java Programming

Object

java.util.EventObject

java.awt.AWTEvent

ActionEvent AdjustmentEvent ComponentEvent ItemEvent

ContainerEvent InputEvent FocusEvent WindowEvent

KeyEvent MouseEvent

ActionListener
E
AdjustmentListener
v
e
ContainerListener
n
t
FocusListener
L
i
ItemListener
s
t KeyListener
e
n MouseListener
e
ANNAMALAI
ANNAMALAI UNIVERSITY
r UNIVERSITY MouseMotionListener

TextListener

WindowListener

Figure: Hierarchy of the Event Listeners interfaces

Page 124
Java Programming

The way these events are handled depends on the type of application. Some
events are handled by the Abstract Windowing Toolkit (AWT) or by the environment in
which these applications are executed, such as, a Browser. There are certain events which
need to be explicitly handled by the programmer. The programmer has to write the event
handler. Here the application needs to register an event handler with an object, and this
handler will be called whenever the appropriate event takes place for the right object.
JDK1.2 follows this event processing model. This is a process whereby, the application
allows to register handlers called listeners, with the objects. These handlers are
automatically called when a suitable event takes place. An Event Listener listens to a
particular event generated by an object. This in turn calls the methods that handle the
event, called event handler. Each event listener provides methods that handle these
events. The class that implements the listener, needs to define these methods.We will
now learn to handle an event with the help of different components that we create.

The below figures displays a list of listeners for the specified component.

ActionListener
Button

List

MenuItem

TextField

ItemListener
Choice

Checkbox

List

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Below is the listeners for the Component class

Component
ComponentListener

FocusListener

KeyListener

MouseListener

MouseMotionListener

Page 125
Java Programming

WindowListener
Dialog

java.awt.Button Frame

Push buttons are the components that are used to trigger a specific action when
clicked. The text that describes the button is called button label. Each button should be
unique and perform a particular task.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class MyButton extends Applet implements ActionListener


{
private Button b1,b2;
String msg;

public void init()


{
setFont(new Font("Arial", Font.BOLD,16));
setBackground(Color.cyan);
setForeground(Color.black);

b1= new Button("Demo Button 1");


b2= new Button("Demo Button 2");
b1.addActionListener(this);
b2.addActionListener(this);

add(b1);
add(b2);
ANNAMALAI
ANNAMALAI UNIVERSITY
} UNIVERSITY
public void actionPerformed(ActionEvent e)
{
msg = "You have selected : "+e.getActionCommand();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,20,150);

Page 126
Java Programming

}
}
Buttons generate action .events. This action event is processed by the
ActionListener which in turn invokes the actionPerformed() method, all you need to do is
register an ActionListener for each button that you create.

The output of the code is as follows:

Description of Button Class :

public void addActionListener(ActionListener)


Listens to the event and is notified when the button is clicked.

public String getActionCommand()


returns the action command associated with the button object-

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public String getLabelf)
returns the label of the button

public void setLabel(String str)


Sets the label associated with the button.

java.awtCheckbox

Checkbox class is used to create two types of components. Checkboxes and


Radiobuttons These buttons have the values true or false. The difference between the two

Page 127
Java Programming

is , checkboxes can be used for multiple selections, whereas, radio button is a single
choice button.

The following program shows the working of the checkbox.

import java.awt. *;
import java.awt.event. *;
import java.applet. *;
import java.util.*;

public class Mycheckbox extends Applet implements ItemListener


{
String msg = "Checkbox options";
Checkbox cb1,cb2;
private Button b1,b2;

public void init()


{
setFont(new Font("TimesRoman",Font.PLAIN,14));
setBackground(Color.cyan);
b1 = new Button("Test Button 1");
b2 = new Button("Test Button 2");
cb1 = new Checkbox("BOLD");
cb2 = new Checkbox("ITALICS");
cb1.addItemListener(this);
cb2. addItemListener(this);
add(b1);
add(b2);
add(cb1);
add(cb2);
}
public void itemStateChanged(ItemEvent e)
{
int b=0, i=0;
b = (cb1.getState() ? Font.BOLD : Font.PLAIN);
i = (cb2.getState() ? Font.ITALIC : Font.PLAIN);
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
start();
b1.setFont(new Font("TimesRoman", b+i,14));
b2.setFont(new Font("TimesRoman", b+i,14));
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,10,150);
}
}

Page 128
Java Programming

The output is as follows :

The statements

int b = cbl.getState() ? Font-BOLD, 14);


int i = cb2.getState() ? Font.ITALIC , 14);

use ternary operator to determine the state of the checkboxes. The getState( ) method,
returns a boolean, depending upon the state. Once this state is determined, the sum of and
is used to set the state of the font style used in the buttons.

Description of Checkbox Class:

public boolean getState()


returns the current state of the checkbox

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public void setLabel(String sir)
sets the label displayed along with the checkbox

public void setState(boolean)


sets the current state of the checkbox

public String getLabelf)


returns the label displayed with the checkbox

java.awt-CheckboxGroup

Page 129
Java Programming

This class is used to create Radio Buttons. The following programs demostrates
the change in the Fontstyle of the label displayed, depending on the choice made.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;

public class Mycheckboxgroup extends Applet implements ItemListener


{
String msg = "CheckboxGroup options";
Checkbox cb1,cb2,cb3;
CheckboxGroup cbg;
private Label lbl;

public void init()


{
setFont(new Font("TimesRoman", Font.PLAIN,14));
setBackground(Color.cyan);
setForeground(Color.black);

lbl = new Label("This demonstrates Radio Buttons :");

cbg = new CheckboxGroup();

cb1 = new Checkbox("BOLD", cbg , false);


cb2 = new Checkbox("ITALICS", cbg , false);
cb3 = new Checkbox("PLAIN", cbg , true);

cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);

add(lbl);
add(cb1);
add(cb2);
ANNAMALAI
ANNAMALAI UNIVERSITY
}
UNIVERSITY
add(cb3);

public void itemStateChanged(ItemEvent e)


{
if(e.getSource()==cb1)
lbl.setFont(new Font("TimesRoman", Font.BOLD,14));
else if(e.getSource()==cb2)
lbl.setFont(new Font("TimesRoman", Font.ITALIC, 14));
if(e.getSource()==cb3)
lbl.setFont(new Font("TimesRoman", Font.PLAIN,14));

Page 130
Java Programming

repaint();
}

public void paint(Graphics g)


{
g.drawString(msg, 10,150);
}

The output is as follows :

The checkboxgroup object created, helps to create radio buttons. Every checkbox
object now includes the checkboxgroup object cbg which indicates that cbl is a radio
button.

cbl=new CheckboxfWLD", cbg , false);

The third argument - false, indicates that this option by default is not selected,

ANNAMALAI
ANNAMALAI UNIVERSITY
when displayed.
UNIVERSITY
Description of Checkbox Class :

public Checkbox getSelectedCheckbox()


returns the currently selected checkbox
public voidsetSelecledCheckbox(Checkbox cb)
sets the currently selected checkbox
public String toString( )
returns a string representing this object

Page 131
Java Programming

java.awtChoice

The choice object provides a list of items from which the user can select an item.
It is also called dropdown list. The following program uses the Choice class to select a
component.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class MyChoice extends Applet implements ItemListener


{
private Label lbl;
String msg = " The component selected is :";
String str;
Choice ch;

public void init()


{
setFont(new Font("TimesRoman", Font.PLAIN,14));
setBackground(Color.cyan);
setForeground(Color.black);

lbl = new Label("Select a component");

ch = new Choice();
ch.add("Push Buttons");
ch.add("Lists");
ch.add("Choice");
ch.add("Radio Buttons");
ch.add("Check Boxes");
ch.add("Labels");
ch.addItemListener(this);

add(lbl);
add(ch);
ANNAMALAI
ANNAMALAI UNIVERSITY
} UNIVERSITY
public void itemStateChanged(ItemEvent e)
{
str = ch.getSelectedItem();
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg + str, 10,150);

Page 132
Java Programming

}
}

The output of the program is as follows :

java.awt.TextField
TextField is a single line area, in which text can be displayed or can be entered by
the user. After the text is entered and the entcrkey is pressed, an event is generated. This
class extends TextComponent class. The following program uses two text field objects
where the text .selected from the first text field is displayed in the second text field.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Mytextfield extends Applet implements ActionListener


{
private Label lbl;
TextField tf1,tf2;
String msg;

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public void init()
{
setFont(new Font("TimesRoman", Font.PLAIN,14));
setBackground(Color.cyan);
setForeground(Color.black);

lbl = new Label("Enter a string and select the text:");


tf1 = new TextField(22);
tf2 = new TextField(22);
tf1.addActionListener(this);

Page 133
Java Programming

tf2.setEditable(false);
msg = "This demonstrates TextField ";

add(lbl);
add(tf1);
add(tf2);

}
public void actionPerformed(ActionEvent e)
{
String str = tf1.getSelectedText();
tf2.setText(str);
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg, 10,150);
}
}

The statements

String str = tfl.getSelectedTextQ;


ti2.setText(str);
gets the selected text from tfl with the help of getSelectedText( ) method, and sets
the text to tf2 with sctText(str).

The output is as follows :

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 134
Java Programming

Description of TextField class

public String getText()


returns the contents of the Text component
public void setText(String str )
sets the contents ofstr to the Text component
public void setEditable(boolean true)
when set to true, allows the text to be modified
public boolean isEditable()
returns true if the component is editable
public int getColumns()
returns the number of columns that are visible
public Dimension getMinimumSize()
returns the minimum size that the component can take up
public Dimension getMinimumSize(inl n )
returns the minimum size for the component with number of visible columns
specified by n
public void setColumnsfinf cols )
sets the number of visible columns specified by cols.

iava.awtTextArea

This class provides an area where multiple text lines are visible and can be
manipulated. The following program demonstrates Text areas. One text area component,
displays the text and the user can select the text. The selected text, then appears on the
second text component which is not editable.

Example

import java.awt.*;
import java.awt.event. *;
import java.applet.*;

public class Mytextarea extends Applet implements ActionListener


{
private Button b1;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
TextArea ta1,ta2;

String str;
String msg = "This class is created \n"
+ " for testing the \n"
+ "TextArea usage \n "
+ "This class extends applet \n"
+ "and implements the \n"
+ "ActionListener interface.\n" ;

Page 135
Java Programming

public void init()


{
setFont(new Font("TimesRoman",Font.PLAIN,14));
setBackground(Color.cyan);
setForeground(Color.black);

b1 = new Button("COPY");
ta1 = new TextArea(msg,5,15);
ta2 = new TextArea(5,15);
ta2. setEditable(false);
b1.addActionListener(this);

add(ta1);
add(b1);
add(ta2);
}
public void actionPerformed(ActionEvent e)
{
str = ta1.getSelectedText()+"\n";
ta2.setText(str);
}
}

The output of the program is as follows :

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
ta2.setEditable(false);

This statement sets the second text area to a non editable state. It means that you
cannot write or modify the contents of this text area.

2.2.6 Layout Managers

A Layout Manager controls the size and position of Components in a Container.


In the case of some other programming environments, absolute positioning is used. This
should be avoided in Java for several reasons:

Page 136
Java Programming

 Java is a cross-platform language and the GUI components may have


different sizes depending on the platform.
 If an application may ever be converted to support different national
languages (e.g., French, German), then it is important to have the labels and other
components resize themselves to fit the length of the words.
 Even running on the same platform and the same national language,
different screen resolutions may require automatic positioning.
 Every container has a default Layout Manager. In the case of a Panel, the
default Layout Manager is the Flow Layout. In the case of a Window, (e.g., Frame or
Dialog), the default Layout Manager is the Border Layout. In order to take advantage of
the default Layout Manager, no additional work is required. In order to change to a
different Layout Manager, use the following method of the Container:

setLayout(new LayoutManager());

where "LayoutManager" will be replaced by the one which is to be used


e.g., "CardLayout".

Whether one is using the default Layout Manager or a different one, the
components are placed in the Container by using the add method of the Container. This
method will have slightly different forms depending on the Layout Manager.

The Flow Layout Manager

The Flow Layout Manager is the default Layout Manager for the Panel. This
Layout Manager adds components in their natural size in a horizontal line. If there are too
many components to fit in one row, then the Flow Layout will use multiple rows. By
default, components within each row are centered.

The following constructors apply to the Flow Layout:

 FlowLayout(int align, int hgap, int vgap)


 FlowLayout(int align)
 FlowLayout()

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The align parameter used in the first two
constructors controls where the components will be added.
The possible values are FlowLayout.LEFT,
FlowLayout.RIGHT or FlowLayout.CENTER (default).
The hgap is the horizontal gap between components and
defaults to 5 pixels. The vgap is the vertical gap between
components and also defaults to 5 pixels.

The Flow Layout uses the simplest form of the add


method which requires only a reference to a component.

Page 137
Java Programming

Here is some sample code which illustrates the use of a


Flow Layout:

setLayout(new FLowLayout());
add(new Button("Button 1"));
add(new Button("2"));
add(new Button("Button 3"));
add(new Button("Long-Named Button 4")):
add(new Button("Button 5"));

Example
import java.awt.*;
import java.awt.event.*;

class FlowDemo extends Frame


{
Button b1=new Button("one");
Button b2=new Button("two");
public FlowDemo(String s)
{
super(s);
setSize(400,400);
setLayout(new FlowLayout(FlowLayout.LEFT));
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
add(b1);
add(b2);
}
public static void main(String arg[])
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Frame f=new Frame();
f.show();

}
}

The Border Layout Manager

The Border Layout Manager is the default Layout Manager for the Window (e.g.,
Frame or Dialog). This layout has the following five areas -- North, South, East, West

Page 138
Java Programming

and Center. When the Container managed by the Border Layout is enlarged, then the
Center area grabs as much of the newly available space as possible. The other areas
expand only as much as needed to keep all available space filled.
The Border Layout is good for maintaining a row of buttons in one of the areas
near the edges; e.g, South or West. The Center area can be used for drawing by adding a
Canvas or for holding other components by adding a Panel. The following constructors
apply to the Border Layout:

 BorderLayout(int hgap, int vgap)


 BorderLayout()

The hgap is the horizontal gap between components and defaults to 0 pixels.
The vgap is the vertical gap between components and also defaults to 0
pixels.

The Border Layout uses the following special form of the add method:

add(String name, Component comp)

where "name" is either "North", "South", "East", "West" or "Center".

The following sample code adds five buttons to a Border Layout:

setLayout(new BorderLayout());
add("North", new Button("North"));
add("South", new Button("South"));
add("East", new Button("East"));
add("West", new Button("West"));
add("Center", new Button("Center"));

Example

//Border layout example


import java.awt.*;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
import java.applet.*;
import java.util.*;

/* <applet code= "BorderDemo" width=400 height=400>


</applet>
*/
public class BorderDemo extends Applet
{
public void init()
{

Page 139
Java Programming

setLayout(new BorderLayout());

add(new Button("This across the top"),BorderLayout.NORTH);


add(new Button("The Footer message might go here"),BorderLayout.SOUTH);
add(new Button("Right"),BorderLayout.EAST);
add(new Button("Left"),BorderLayout.WEST);

String msg="This is border layout";


add(new TextArea(msg),BorderLayout.CENTER);
add(new Button("new"),BorderLayout.CENTER);
}
}

Output is given below

The Card Layout Manager

The Card Layout Manager helps to manage multiple components which share the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
same display space. It is called a Card Layout because the components are managed like
a deck of cards. Only the top card is visible at any time and one can choose which card to
display next. The Card Layout Manager is useful for creating notebook style controls.

The following methods apply to the Card Layout Manager:

 CardLayout() - This is the constructor which creates the object.


 first(Container parent) - This displays the first card added.
 next(Container parent) - This displays the card added after the one which is
currently displayed.

Page 140
Java Programming

 previous(Container parent) - This displays the card which was added before
the one currently displayed.
 last(Container parent) - This displays the last card added.
 show(Container parent, String name) - This method shows the component
identified by the specified "name".

In all of the above methods, parent is the Container which


holds the cards.

The Card Layout uses the following special form of the add
method:

add(String name, Component comp)

where "name" is any unique string which can be used to identify the
component. This same "name" is used by the "show" method.

The following sample code illustrates the use of the Card Layout:

Panel cards = new Panel();


CardLayout cardLayout = new CardLayout();
cards.setLayout(cardLayout);

cards.add("Ace", new Button("Ace of Hearts"));


cards.add("Deuce", new Button("Two of Hearts"));
cards.add("Three", new Button("Three of Hearts"));

The Grid Layout Manager

The Grid Layout Managers assigns components to a grid of cells. Each cell in the
grid is the same size and the components grow to fill the available area. This Layout
Manager is good for laying out containers that look like grids; e.g., a calculator, a
calendar page or a battleship game.

The following constructors apply to the Grid Layout:

ANNAMALAI
ANNAMALAI UNIVERSITY


UNIVERSITY
GridLayout(int rows, int cols, int hgap, int vgap)
GridLayout(int rows, int cols)

The rows is the number of rows in the grid and the


cols is the number of columns. At least one of these must be
non-zero. A zero means as many rows or columns as
necessary. The hgap is the horizontal gap between
components and defaults to 0 pixels. The vgap is the vertical
gap between components and also defaults to 0 pixels.

Page 141
Java Programming

The Grid Layout uses the simplest form of the add


method which requires only a reference to a component.
Here is some sample code which illustrates the use of a Grid
Layout:

setLayout(new GridLayout(0, 1));


add(new Button("Button 1"));
add(new Button("2"));
add(new Button("Button 3"));
add(new Button("Long-Named Button 4")):
add(new Button("Button 5"));

Creating a Custom Layout Manager

One may create his own Layout Manager by implementing the LayoutManager
Interface. This interface has the following 5 methods:

 addLayoutComponent(String name, Component comp)

Called by the Container "add(String name, Component comp) method. If the


layout does not require components to have names, then do nothing here.

 removeLayoutComponent(Component comp)

Called by the Container "remove()" and "removeAll()" methods. This method is


also a "do-nothing" method unless the components have names that requires one to
maintain his own internal list. Otherwise, the Container "getComponents()" method can
be used for list retrieval.

 preferredLayoutSize(Container parent)

Called by the Container "preferredSize()" method. This method returns a


Dimension object which is the preferred size of the Container taking into account the
preferred size of each component and the Container insets (internal padding).

 minimumLayoutSize(Container parent)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Called by the Container "minimumSize()" method. This method returns a
Dimension object which is the minimum size of the Container taking into account the
minimum size of each component and the Container insets (internal padding).

 layoutContainer(Container parent)

Called when the container is first displayed and each time that its size is changed.
In this method it is necessay to calculate the correct position of each component taking

Page 142
Java Programming

into account its size and the Container insets. Then the "reshape()" method (or the 1.1
equivalent) is actually used to position the component.

2.2.7 Event Handling

AWT Event Classes

Events

When the user interacts with a GUI application, an event is generated. Examples
of user events are clicking a button, selecting an item or closing a window. Events are
represented as Objects in Java. The super class of all event classes is
java.util.EventObject. Some of the important classes and their hierarchy is shown below.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Methods related to Events are

Object getSource()

This method is defined in the Event Object class. It returns the object that
originated the event. So if the user has clicked a Push button, the method getSource
returns the object corresponding to the Push button that is generated.

int getID()

Page 143
Java Programming

This method returns the integer value corresponding to the type of event. For
example if the user has clicked on the mouse, the method getID returns the integer
defined as MouseEvent.MOUSE_CLICKED.

AWT event classes

The subclasses of ATW Event can be categorized into two groups - Semantic
events and low-level events. Semantic events directly correspond to high level user
interactions with a GUI component. Clicking of a button is an example of a semantic
event.

Following event classes are semantic classes.

ActionEvent
AdjustmentEvent
ItemEvent
TextEvent

Multiple low-level events may get generated for each high level user event.

Following event classes are low level event classes.

ComponentEvent
ContainerEvent
FocusEvent
KeyEvent
MouseEvent
PaintEvent
WindowEvent

Event classes for GUI controls

GUI component - is meant for objects like Button, ListBox etc. For each Java
GUI component, a set of events of above type are generated. It is important to understand
which events are generated for each component. This is explained below.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The GUI component that generate ActionEvent are

Button : When the user clicks on a PushButton.


List : When an item in list box is double clicked.
MenuItem : When a MenuItem is selected.
TextField : When the user clicks the Enter key in a text box.

AdjustmentEvent is generated when the user adjusts the position of a scrollbar.


Scrollbar is the only GUI control that receives the

Page 144
Java Programming

AdjustmentEvent.

ItemEvent is generated when an item is selected or deselected. Following


components generate ItemEvents.
CheckBox : When the state of the CheckBox is changed.
CheckBoxMenuItem : When the state of a MenuItem is changed.
Choice : When the state of a ChoiceBox is changed.
List : When an item in list is selected or deselected.

TextEvent is generated when the contents of text component are changed.


The components that generate TextEvent are
TextArea
TextField

The GUI components corresponding to low level event classes are :

FocusEvent : This event is generated when a component gains or looses focus.


Focus may be gained by bringing the mouse over a component (or by using the tab key).
The component that has the focus receives all user keyboard events. Focus events are
generated by objects of Component class and all its subclasses.

KeyEvent and MouseEvent are subclasses of abstract InputEvent class. Both


these events are generated by objects of type Component class and its subclasses. The
KeyEvent is generated when the user presses or releases a key on the keyboard. The
MouseEvent is generated when the user presses the mouse or moves the mouse.

WindowEvent are generated for the Window class and its subclasses. These
events are generated if an operation is performed on a window. The operation could be
closing of window, opening of window, activating a window etc.

PaintEvent is generated when a component needs to be repainted (for example


when an application which is in front is closed and the component needs to be redrawn.)
PaintEvents are internally handled by AWT, and cannot (and should not) be handled in
the application.

ComponentEvent are also generated by objects of type Component class and its
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
subclasses. This event is generated when a component is hidden, shown, moved or
resized.

ContainerEvents are generated when a component is added or removed from a


container. ComponentEvent and ContainerEvent are handled by AWT and are not
normally handled by the user.

Event Listeners

Page 145
Java Programming

These are objects that define methods to handle certain type of events. An event
source (for example a PushButton) can generate one or more type of events, and maintain
a list of event listeners for each type of event. An event source can register listeners by
calling addXListener type of methods. For example a Button may register an object for
handling ActionEvent by calling addActionListener. This object would then need to
implement the listener interface corresponding to ActionEvent, which is ActionListener.

So to set up the processing of events the following tasks must be done.

1. For the GUI component (like pushbutton) associate a listener object class with the
component by calling a method of type addXListener (See table below for list of
methods).
2. Define this listener object. It must implement the corresponding interface. The name
of interface is of type EventListener. Table below gives list of event listeners.
3. The object must define all the methods defined in the interface it is implementing.
See table for the list of Event Listener methods defined in each Event Listener
interface.

Table Event types and corresponding EventSource & EventListener

Event Type Event Source Event Listener interface

ActionEvent Button, List, MenuItem,


TextField ActionListener

AdjustmentEvent Scrollbar AdjustmentListener

ItemEvent Choice, Checkbox,


CheckboxMenuItem, List ItemListener

TextEvent TextArea, TextField TextListener

ComponentEvent Component ComponentListener

ContainerEvent Container ContainerListener

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
FocusEvent Component FocusListener

KeyEvent Component KeyListener

MouseEvent Component MouseListener,


MouseMotionListener

WindowEvent Window WindowListener

Page 146
Java Programming

Table Event Listener Interfaces and corresponding methods which it defines

Event Listener interface Event Listener Methods

ActionListener actionPerformed(ActionEvent evt)


AdjustmentListener adjustmentValueChanged(AjustmentEvent evt)
ItemListener itemStateChanged(ItemEvent evt)

TextListener textValueChanged(TextEvent evt)

ComponentListener componentHidden(ComponentEvent evt),


componentMoved(ComponentEvent evt),
componentResized(ComponentEvent evt),
componentShown(ComponentEvent evt)

ContainerListener componentAdded(ContainerEvent evt),


componentRemoved(ContainerEvent evt)

FocusListener- focusGained(FocusEvent evt),

focusLost(FocusEvent evt)

KeyListener keyPressed(KeyEvent evt),


keyReleased(KeyEvent evt),
keyTyped(KeyEvent evt)

MouseListener mouseClicked(MouseEvent evt),


mouseEntered(MouseEvent evt),
mouseExited(MouseEvent evt),
mousePressed(MouseEvent evt),
mouseReleased(MouseEvent evt)

MouseMotionListener mouseDragged(MouseEvent evt),


mouseMoved(MouseEvent evt)
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
WindowListener windowActivated(WindowEvent evt),
windowClosed(WindowEvent evt),
windowClosing(WindowEvent evt),
windowDeactivated(WindowEvent evt),
windowDeiconified(WindowEvent evt),
windowIconified(WindowEvent evt),
windowOpened(WindowEvent evt)

Adapter classes

Page 147
Java Programming

Event adapters facilitate implementing listener interfaces. Many event listener


interfaces have more than one event listener methods. For such interfaces, Java defines
adapter classes. These have empty implementation (stubs) of all the event listener
methods defined in the interface they implement. A listener can subclass the adapter and
override only stub methods for handling events of interest. The table below lists the low
level event listener interfaces and their adapters.

Table Event Listener Interfaces and their corresponding adapter classes.

Event Listener interface Event Listener Adapter

ComponentListener ComponentAdapter
ContainerListener ContainerAdapter
FocusListener FocusAdapter
KeyListener KeyAdapter
MouseListener MouseAdapter
MouseMotionListener MouseMotionAdapter
WindowListener WindowAdapter

2.2.8 Socket Programming

The Internet is composed of millions of computers, located all across the


globe, communicating and transmitting information over a variety of
computing systems, platforms, and networking equipment. Each of these
computers (unless they are connecting via an intranet) will have a unique IP
address.

IP addresses are 32-bit numbers, containing four octets (8 bit numbers)


separated by a full stop. Each computer with a direct internet connection will
have a unique IP address, (e.g. 207.68.156.61). Some computers have
temporary addresses, such as when you connect to your ISP through a
modem. Others have permanent addresses, and some even have their own
unique domain names (e.g. www.microsoft.com).

An IP address allows us to uniquely identify a device or system connected to


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the Internet. If we wanted to connect to a specific IP address, and send a
message, we could do so. Without an IP address, any message would have
no way of reaching its destination - a bit like leaving the address off a letter
or parcel.

Often, computers connected to the Internet provide services. Here it is


provided by a web server, for example. Because computers are capable of
providing more than one type of service, we need a way to uniquely identify
each service. Like an IP address, we use a number. We call this number a
port. Common services (such as HTTP, FTP, Telnet, SMTP) have well

Page 148
Java Programming

known port numbers. For example, most web servers use port 80. Of course,
we can use any port we like - there's no rule that says you must use 80.

Fig. Ports help computers identify which service data is for.

When we talk to our friend over phone or in person, we follow some


rules (or protocols). For example, both of us will not talk simultaneously
without a pause. Neither of us would will understand what the other person
is talking. So, When somebody talks the other one listens and vice versa.
Moreover we talk common language and at a pace that both can understand.

Similarly when computers communicate, they need to follow certain


rules too. Data is sent from one machine to another in the form of packets.
Rules govern packaging of the data into packets, speed of transmission and
recreation of data to its original form. These rules are called network
protocols. Network protocols are a set of rules and conventions followed by
systems that communicate over network. Networking software usually
implements multiple levels of protocols layered one on top of another.
Some examples of network protocols are TCP/IP, UDP, Apple Talk and
NetBEUI.

There are several communications mechanisms to provide network


services. TCP is the one which is mostly chosen as it makes life much
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
easier. TCP guarantees that messages will arrive at their destination. UDP is
unreliable, and the application isn't notified if the message is lost in transit.
Also, many protocols (such as HTTP, SMTP, POP & FTP) use TCP.

Sockets follow TCP/IP, Datagram packets follow UDP

TCP establishes link between the source port’s IP address and


destination port’s IP address. These ports are bound via this link till the
connection is terminated or broken. A simple example is that of a telephone
conversation. When the connection is established, the conversation takes
place and then the connection is terminated. It implements the connection as

Page 149
Java Programming

a stream of bytes from source to the destination. This is supported by the


java.io.stream classes.
UDP is a connectionless protocol. It does not establish a link for the
connection. A simple example is that of a postal mail. While mailing
something, we write the message and to whom to mail in other words the
destination address and put it in the mailbox.

Internet Addressing with Java

Handling internet addresses (domain names, and IP addresses) is made easy


with Java. Internet addresses are represented in Java by the InetAddress
class. InetAddress provides simple methods to convert between domain
names, and numbered addresses.

We start by importing the java.net package, which contains a set of pre-


written networking routines (including InetAddress).

import java.net.*;

Next, we declare a new variable of type InetAddress, which we assign the


value of the local host machine (for machines not connected to a network,
this should represent 127.0.0.1). Due to the fact that InetAddresses can
generate exceptions, we must place this code between a try .. catch
UnknownHostException block.

Example program illustrating the working of the InetAddress class

// Obtain the InetAddress of the computer on which this program is


// running

InetAddress localaddr = InetAddress.getLocalHost();

The InetAddress class has methods that return the IP


address as an array of bytes (which can be easily converted
into a string), as well as a string representation of its domain
name (e.g. mydomain.org ). We can print out the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
InternetAddress, as well as the domain name of the local
address.

System.out.println ("Local IP Address : " + localaddr );


System.out.println ("Local hostname : " + localaddr.getHostName());

public class MyFirstInternetAddress


{
public static void main(String args[])
{

Page 150
Java Programming

try
{
InetAddress localaddr = InetAddress.getLocalHost();
System.out.println ("Local IP Address : " + localaddr );
System.out.println ("Local hostname : " + localaddr.getHostName());
}
catch (UnknownHostException e)
{
System.err.println ("Can't detect localhost : " + e);
}
}
}

The above program provides the following output

Writing network applications in Java is extremely easy. Java takes away much of the
implementation details which are operating system specific. There's no need to worry
about hostname lookups, size of IP address structures, or pointers. The java.net package
provides all this functionality for you, and provides a simple way to write networking
clients. However, when writing Java applets (as opposed to applications), remember that

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
the browser may impose security restrictions - many applets can only communicate with
the host from which they were downloaded from.

GetLocalHost() – it is a static method. It represents the address of the local host


computer.

GetHostNmae() – It is a static method, gets the machine’s domain name.

GetHostAddress() – It is also a static method, displays the IP address of the host which is
numeric. The address is displayed in the dotted decimal string.

Page 151
Java Programming

Socket

The Socket class helps in establishing client connections. It has eight constructors that
create sockets. They in turn connect to the destination host and port. The I/O streams are
accessed using the access methods provided by the socket class. The port number of the
machine to which the socket is connected is obtained by the getPort() method. The local
port number is obtained using the getLocalPort() method.

The local IP address is obtained using the getLocalAddress(). The input and output
streams are accessed using the getInputStream() and getOutputStream() methods.

The socket is closed using the close() method.


The String representation of the object is written using the toString() method.
Example

TCP ServerSocket

TCP ServerSocket is implemented using the ServerSocket class.There are three


constructors specifying the port to which the server socket is to listen for incoming
connection requests.

DatagramSocket Class

This class is used to implement the client and server sockets using the User Datagram
Protocol (UDP) protocol. Datagrams are nothing but chunks of data. This class provides
three constructors.

o The default constructor creates a datagram socket. It is used by client applications.


In this case no port number is specified.
o The second constructor creates a datagram socket using a specified port. This is
generally with the server applications.
o The third constructor allows an Internet Address to be specified in addition to the
port.

The datagrams are sent and received using the send() and receive() methods respectively.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The getLocalPort() and getLocalAddress() methods are used to get the local port and
Internet address of the socket respectively.

The socket is closed using the close() method.

DatagramPacket class

The datagrams that are sent and received are encapsulated using the objects of class
DatagramSocket. There are two constructors, one for datagrams that are received from

Page 152
Java Programming

the datagram socket and the other for creating datagrams that are sent over the datagram
socket.
For reading the destination IP address and port of the datagram, getAddress() and
getPort() are used respectively.

For getting the number of bytes of data in the datagram and reading the data into a byte
array buffer, getLength() and getData() methods are used.
To allow the datagram’s IP address, port, length and data values to be set – setAddress(),
setPort(), setLength() and setData are used respectively.

URL class

The class java.net.URL encapsulats the object on the web. It consists of URL class that
supplies us with everything that is required to read files and resources from the internet.
It consists of the following methods
openConnection() - this method establishes a connection and returns a stream
getContent() - this method makes a connection and reads addressed contents
getFile() - This method returns the filename part of the URL.
getHost() - This method returns only the host name part from the URL.
getPort() - This method returns the port number part from the URL.
getProtocol() - This method returns the name of the protocol of the URL.
getRef() - This method returns the anchor reference part from the URL.
equals(Object) - This method compares whether two URL objects represent the same
resouce.
openStream() - This method establishes a connection and returns a stream for reading it.

2.3 Revision Points

Exception
Exceptions provide notification of errors and a way to handle them. Exceptions can be
used as a means of indicating other situations as well.

Multithreading
Multithreading is an extension of the multitasking paradigm. But rather than multiple
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
programs, multithreading involves multiple threads of control within a single program.
Not only is the operating system running multiple programs, each program can run
multiple threads of control within the program.

Thread
A thread is a single sequence of execution within a program. Java threads allow you to
write programs that do many things at once. Each thread represents an independently
executing sequence of control.

Page 153
Java Programming

AWT
AWT is a package that provides an integrated set of classes to manage user interface
components like windows, dialog boxes, buttons, check boxes, lists, menus, scrollbars
and text fields.

I/O Package
The Java I/O package, also known as java.io, provides classes with support for reading
and writing data to and from different input and output devices-including files. The I/O
package includes classes for inputting streams of data, outputting streams of data,
working with files, and tokenizing streams of data.

Interface
An interface is a prototype for a class and is useful from a logical design perspective.

2.4 Intext Questions

1. What is Exception?
2. What are the keywords used in Exception handling?
3. What are the different types of Layouts in AWT?
4. What is the difference between UDP and TCP/IP
5. What is the use of repaint() method

2.5 Summary
 An exception is an abnormal event that occurs during program execution and
disrupts the normal flow of instructions. An application must be capable of
handling exceptions.
 When an exception is raised, the java runtime system searches for an exception
handler in the current method, and then in the calling method.
 The try and catch blocks can be nested.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 A thread is a sequential flow of control within a program. Every program has at
least one thread that is called the primary thread.
 The currentThread() method retrieves the reference of the current method.
 The Thread class is used to create and manipulate threads in a program.
 The start() method of the Thread class is used to start the thread.
 The run() method contains the code which the thread executes.
 A thread can be put to sleep using the sleep() method.

Page 154
Java Programming

 The stop() method is used to stop the thread.

 The synchronized keyword is used to ensure that no two threads access the same
object simultaneously.
 A stream is a sequence of bytes traveling from a source to a destination over a
communication path.
 The InputStream and OutputStream are superclasses used for reading from and
writing to byte streams.

 The Applet class is the only class for the java.applet package.
 AWT is a package that provides an integrated set of classes to manage user
interface components like windows, dialog boxes, buttons, check boxes, lists,
menus, scrollbars and text fields.

 Panels are used for organizing components.

 Labels are used to display Strings.

 Buttons are used to trigger events in a GUI environment.

 The Component class is the super class for all graphical interface elements.

 Network protocols are a set of rules and conventions followed by systems that
communicate over a network.
 Two tools available in java for communication are UDP and TCP/IP.

2.6 Terminal Exercises


1. Write a program to read and write from file?
2. Discuss life cycle of an applet.
3. Explain the various AWT components.

2.7 Supplementary Materials

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1. Herbert Schildt, “Java 2: The Complete reference”, TMH, Fourth Edition,
2001.
2. E.Balagurusamy, “Programming with JAVA”, TMG, 1999.

2.8 Assignments
 Write an Exception to handle illegal multiplication of matrices. Two matrices can
be multiplied only if no of columns of first matrix is same as no of rows of second
matrix. The exception should be thrown if we try to multiply two matrices with
illegal rows and columns.

Page 155
Java Programming

2.9 Suggested Reading/Reference Books/Set Books

1. Deital and Deital, “Java How to Programme”, Pearson Education, New Delhi,
2001.
2. http://www.sun.com/java
3. http://java.sun.com

2.10 Learning Activities

1. Collect information on Multithreading from internet.


2. Collect information on Exception handling.

2.11 Keywords

Interface Implementation
Multiple Inheritance Thread
Multithread Errors
Exception Exception Handling
Try catch
Throw finally
Input Stream Output Stream

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 156
Java Programming

UNIT – III

Snapshot

 Database Foundation
 Concepts of hierarchical, network and relational DBMS’s
 Usage of Database
 Evolution of Database Management System
 Characteristics of Database
 Important models in Database Management Systems
 Introduction - OODBMS and ORDBMS
 The next generation of DBMS
 Abbreviations
 Strategies for developing the databases
 Data Modeling
 Relationships
 Normalization
 Denormalization
 Components of Database
 Database Engine
 Comparing Procedural and Declarative Languages
 The Human Roles in a DBMS
 When to Use SQL
 Brief History of SQL
 Features of SQL
 Oracle Data Types
 Creating table
 Constraints
 Insertion, Updation, Deletion and Execution of queries

3.0 Introduction
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The purpose of this chapter is to help us understand the basic concepts of
Database Management System (DBMS). Further this chapter includes RDBMS,
OODBMS, Normalization and Structured Query Language and so on.

3.1 Objective
At the end of this chapter you will have an understanding of
 DBMS
 RDBMS
 OODBMS
 Normalization

Page 157
Java Programming

 Structured Query Language (SQL)

3.2 Content

3.2.1 Database Foundation

Data
Data is collection of records.

Database

A database is a collection of data that represents important objects in a user's


business.

In 1979 a small company Ashon-Tate launched a microcomputer product called


dBase II and called it a relational DBMS. Company distributed 100,000 copies of its
product free of cost and soon dBase II was a massive hit in the industry. Thus dBase II
was a pioneer and one of the most genuine Relational database products of its time. And
soon companies like Oracle, Focus and Ingress also came up with their own RDBMS
products.

As history shows, conceptually different DBMSs have been developed, and these
DBMSs have different capabilities, both regarding organization of data, modelling of
data and access to data.

3.2.2 Concepts of hierarchical, network and relational DBMSs.

Hierarchical

Hierarchical DBMSs became commercial available in the late 1960s with IBMs
IMS and the DL/1-language. The hierarchical DBMSs organise and model their data in a
hierarchical fashion as a collection of trees. All data elements have an owner or root (one
and only one) - the hierarchical mother of the data-instance, and accordingly all other
records have a unique parent record. Finally, the access to data in a hierarchical database
is done by using low-level calls which the programmer writes into his/hers programs for
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
access purposes using a navigational language, navigating from the root records to the
actual record of interest (Silberschatz et al. 1991). To be able to do this, the programmer
must know the physical representation of the database.

This approach is well suited for large systems containing a lot of data where the
data can be organized in a hierarchical way without compromising the information.
Hierarchical databases support two types of information, the record type which is a
record containing data, and parent-child relations (PCR) which defines a 1:N relationship
between one parent record and N child-records. Hierarchical databases are still used in
many systems and IMS is still the leading hierarchical DBMS. On the other hand, this
approach has several major limitations due to its representation of data. It is not trivial to

Page 158
Java Programming

represent a non-hierarchical structure of information in such a database (Elmasri &


Navathe 1994).
Network

C.W. Bachman developed the first commercial network DBMS database


(Bachman 1965). The system - IDS - was available in 1964. The modelling paradigm of
the network database is somewhat different than its hierarchical counterpart. The network
databases arrange its data as a directed graph and have a standard navigational language
(DBTG 1971). This paradigm made it possible to move directly from one specific entry
point in a data set to another record in another data set (Silberschatz et al.1991).

The network databases offer an efficient access-path to its data and are capable to
represent almost any informational structure containing simple types (e.g. integers, floats,
strings and characters). This is accomplished using different kinds of mapping
mechanisms called sets. A set is a container of pointers identifying which sets of data can
be reached from the current record. Three sets are defined by the CODASYL standard -
singular/system sets, multimember sets and recursive sets. Using these sets, the database
designer and programmer may represent and navigate on 1:1, 1:N and N:M relationships
(Elmasri & Navathe 1994). To be able to do this, the programmer has to know the
physical representation of the database and access the database using a low-level
navigational language (Bachman 1973). This approach to DBMS is more flexible than
the hierarchical approach, but still the programmer has to know the physical
representation of data to be able to access it, and accordingly applications using a
network database have to be changed every time the structure of the database changes.

Relational

Edgar F. Codd first represented the relational data-model in (Codd 1970) and later
in a series of papers up to 1972 (Codd 1971a, Codd 1971b, Codd 1971c, and Codd 1972).
The model offers a conceptually different approach to data storage. In the relational
database, all data is represented as simple tabular data structures (relations), which may
be accessed using a high-level non-procedural language. This language is used to gain
access to the relations and the desired set of data and the programmer does not have to
write algorithms for navigation. By using this approach the physical implementation of
the database is hidden, thus the programmer does not have to know the physical
implementation to be able to access the data. In 1974 Chamberlain and others at IBM
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
proposed such a high-level non-procedural language - SEQUEL, which later, due to legal
problems, was renamed into SQL (Date 1990). In 1986 the ANSI X3H2 committee
accepted SQL as an ANSI standard, and soon SQLs biggest competitor, QUEL, vanished.

The relational approach separates the program from the physical implementation
of the database, making the program less sensitive to changes of the physical
representation of the data by unifying data and metadata in the database. This makes the
development of programs more effective and less dependent on changes in the physical
representation of data (Gray 97). SQL and RDBMS’s have become widely used due to
the separation of the physical and logical representation (and marketing of course). It is

Page 159
Java Programming

much easier to understand tables and records than pointers and pointers to records. Most
significantly, research showed that a high-level relational query language could give
performance comparable to the best record-oriented databases (Gray 97).

Object-relational

The object-relational DBMS (ORDBMS) is the newest commercial breed of


DBMSs which embraces some object-oriented features and encapsulates these features
into an RDBMS, creating an ORDBMS. ORDBMSs are mainly based upon the criteria
defined by Stonebraker et al.(1990). This manifesto is built as an opposing manifesto to
Atkinson et al. (1989). Stonebraker et al. suggests extending the capabilities of an
RDBMS to include support for richer object structures and rules and still be open to other
systems. This is done by thirteen propositions of requirements to ORDBMSs as
extensions to RDBMS.

The first tenet in (Stonebraker et al. 1990) is concerned with richer objects and
rules. This includes inheritance, advanced data type (ADT), and a number of different
constructors, e.g. sets, lists and bags, needed to operate on objects or collections of
objects. Stonebraker et al. (1990) suggest that all functions which involve data should be
written in a high-level, non-procedural access language (HLL) to avoid programming
towards low-level interfaces being dependent on physical implementation of the
database.

The second tenet is concerned with the increasing DBMS functions, how the
functions should be written and how they should access data. Stonebraker et al. (1990)
state that essentially all programmatic access to DBMS should be using the HLL while
ensuring data independence. This should be accomplished by including updateable views,
enumeration of members in collections combined with the HLLs capabilities to specify
membership, and by avoiding all kinds of low-level access dependent on the physical
implementation. The ORDBMS should also, according to Stonebraker et al. (1990), keep
a backward compatibility to RDBMS, making porting from RDBMS to ORDBMS easy.

The third tenet concerns openness and the ORDBMSs application-programming


interface (API). Stonebraket et al. (1990) put forward the idea that ORDBMSs should be
accessible from multiple HLLs, and that all of these HLLs should be based upon SQL.
Persistent programming languages should be supported on top of a single DBMS by
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
compiler extensions to the programming language, and a runtime-system.

The ORDBMS camp is however split. Darwen & Date (1995) have written an
opposing manifesto to Stonebraker et al. (1990) and Atkinson et al. (1989) suggesting a
completely different set of guidelines to the future DBMSs. First of all, Darwen & Date,
state that SQL is not suited as the base language for the future DBMSs (they feel strongly
that "any attempt to move forward, if it is to stand time, must reject SQL unequivocally").
They claim that the foundation of the DBMSs must be firmly rooted in the relational
model of data, that the relational model is capable to include object-oriented features and
that a new HLL has to be developed (and SQL omitted).

Page 160
Java Programming

Darwen & Date and Stonebraker et al. agree on several important issues (e.g. use
of the relational model and development of a new HLL), but disagree on other (e.g. SQL
and multiple inheritance). In 1992 the ANSI X3H2 committee started its work on a new
object-relational standard SQL3 (SQL3 is the ORDBMS standard), which was scheduled
to be finished in 1995. The committee is still working on it and the expected timeframe
for completion is currently 1999 (JCC 1998).
Since no standard currently exists, no vendors can truthfully claim to be SQL3
compliant, but some vendors have done major changes to their RDBMS to include
object-relational features (e.g. ORACLE, IBMs DB2, and Informix). The ORDBMS
models its data based upon the extensions to the relational model and relational calculus.
ORDBMS is capable of storing ADTs or basal types in records; lists, bags etc. and can
access the data using an extended version of SQL. The result - some kind of hybrid
DBMS, half relational, half object-oriented. Whether or not this is a good idea, is not the
subject for this essay.

Object-oriented
The conceptual paradigm of the object-oriented DBMS (OODBMS) is quite
different from the other approaches presented. OODBMSs offer persistence to objects,
including the objects associations and methods. Atkinson et al. (1989) gave a guideline
on the requirements to an OODBMS, and this manifesto is still a very good guideline on
OODBMS. In 1993 ODMG put forward its ODMG-93, and later in 1997 ODMG 2.0
standard which today is the de facto standard for OODBMSs (Cattell 1994 and Cattell et
al. 1997). Before I look deeper into the concepts of the OODBMS, orthogonal persistence
has to be defined and understood.

Usage of Database

Types of Users

Single User
Consider a case of Service Engineer who is working in a Chennai Area and gets
repair calls from on average 5-10 houses each day for servicing work. He also has
contract with many companies, houses and shops for monthly inspection of their
computers to check that all woks are in order. He definitely want that each time his client
gives him a call for repair work he does not need to ask him his address, driving
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
directions and other associated issues. Therefore he needs to keep a track of the data
about all his clients. And this he designs himself or get it design from a database
specialist in requirement to his needs. Single user data are usually straightforward and
simple and usually less the 10 MB in size.

Multiple Users
Consider a case of one large DVD renting store. It has many counters in the store
where people can ask for availability of a particular DVD and if available can rent a DVD
for limited period. Now the salesman at all these counters needs to access the database to
check that they have a copy of particular DVD which a customer has asked for. For this a

Page 161
Java Programming

Local Area network is set up in the store connecting several computers to the rental
database. This particular database reflects the stock of particular DVD and DVD count is
added when returned and subtracted when issued. Also the Store Manager can use this
database to check which DVDs are in more demand and so can order for more DVDs
from the distributor. Thus this is a case of multiple user databases. Multiple users’
database is moderate in size and complexity and usually between 50-100 MB.

Very Large Application: Consider a case of State Licensing office, which has
number of offices in all states and all over India. The personnel in these offices access a
database to perform their jobs. Before issuing a Driving License to anyone Licensing
official has to check for the traffic violations or criminal offences of that person. The data
is critical to determine if license can be issued or renewed for the person. No surprisingly
such database is accessed by large number of people and is complex in nature. Usually
database of large Organizations is of this nature. Very large application databases are
usually very complex in nature and may run into several GBs

Client Server Database Application

In 1980s the concept of Local Area Network (LAN) emerged to share computer
peripherals like Printer, Plotters etc. But soon people felt the need to share databases too
and this led to development of the multi user database applications on LAN. Eventually
this led to the new style of multi user database processing called the client server
architecture. A client server application can be defined as one that has two parts: One part
runs on the server, and the other part runs on workstations. The server side of the
application provides security, fault tolerance, performance, concurrency, and reliable
backups. The client side provides the user interface and can contain empty reports,
queries, and forms. In client/server computing, when a query is run, the server searches
the database and sends only the rows that are a match to the client.

Database server

It's a specialized process that manages the database itself. The applications are
clients to the database server and they never manipulate the database directly, but only
make requests for the server to perform these operations. Access is a relational database
but it is not a database server. MS SQL, SQL Anywhere, DB2, Oracle, is both relational
databases and database servers.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Database used by Internet Application

These days large database oriented web sites are very common to see. Take the
case of Book site like Amazon.com or job site like Monster.com or Online shopping site
like bestbuy.com, all these sites use very complex database for selling their products or
services online. These database applications are different from standard database
application as they can be accessed by any when anywhere using a browser like Internet
Explorer. The other factor is that standardized web oriented technology is used to transfer
the data between the browser and web server. Depending on the services and products

Page 162
Java Programming

being sold by the Internet Company, there may be thousands of concurrent users and
database size may run into hundreds of MBs and even GBs

Evolution of Database Management System

File-Processing System

In early processing systems, an organization's information was stored as groups of


records in separate files. These file processing systems consisted of a few data files and
many application programs. Each file, called a flat file, contained and processed
information for one specific function, such as accounting or inventory. Programmers used
programming languages such as COBOL to write applications that directly accessed flat
files to perform data management services and provide information for users.

Although File processing system is a great improvement over manual record keeping
systems, they suffer from these limitations

Separated and Isolated Data


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
To make a decision, a user might need data from two separate files. First, analysts
and programmers to determine the specific data required from each file and the
relationships between the data evaluated the files. Then applications could be written in
some language like COBOL to process and extract the needed data.

Data Duplication
Often, the same information was stored in more than one file. In addition to
taking up more file space on the system, this replication of data caused loss of data
integrity. For instance, if a customer's address were stored in four different files, an
address change would have to be updated in each file separately. If a user were not
consistent in updating all files, no one would know which information was correct
Page 163
Java Programming

Application Program Dependency


In File processing system application program depended on the file formats. In
file processing system the physical formats of the files and records are part of the
application code. So any change in the records requires change of the application code
and thus made things very complex.

Incompatible Files
File formats depend on the language of the product used to generate them. So if
one file is processed using C and other using VB, they cannot be combined and
processed. For getting information combined from them we need to convert both files to
a common structure

Information providing as per users perspectives: In file processing system it is


difficult to represent data in Users perspective because it is difficult to readily join the
information between various files. So it was difficult to answer ad-hoc queries of
database users.

Database Management system


Database Management system was able to take care of most of the limitations of
File Processing System

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Separated and Isolated Data issue
In DBMS all the data is stored in a single facility called the database. It's very
easy and simple to combine the data in DBMS. Programmer just needs to tell DBMS that
how the data to be combined and the DBMS are performs the necessary action. Thus the
Programmer does not need to write the program to consolidate the files.

Reduce Data Duplication


Since all the data is integrated the information need to be stored at just one place
and unlike File Processing system it does not need to be kept at more then one place.

Page 164
Java Programming

Program/ Data Dependence


Database reduces the dependency of programs on file formats. All record formats
are stored in the database itself by the DBMS and not by application Programs so there is
no need for database application program to include file format and records the process.

Allows for representation of data from the user's view


Relationships between data objects in a user's environment are stored in the
DBMS. Data elements from any number of files can be combined to create useful forms,
reports, and other applications

Characteristics of Database

It is self-describing: In addition to the users source data, a data dictionary or


metadata contain information about the database structure. In this sense database is
similar to Library. This characteristic is important as it promoted program- data
independence. So looking at the database itself can assess database structure and we do
not need any documentation etc to know data structure. Also changes to database are easy
to be made. It is a collection of integrated records: In addition to Meta data and user data
database contains Indexes, which represent relationship between among the data and also
improve the performance of database applications. Database also contains data about the
application, which uses the data and is known as application metadata. Database also
contains Business rules or logics.

Thus a database contains 4 types of data:

 Users Data
 Meta Data
 Indexes
 Application Metadata
 Also Business Rules or Logics are stored in database.

A Database is Model of Model

Its representation of the user’s world or user’s model. Thus database is a model
of users' model of their business activities. Therefore based on the characteristics of the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Database we can formulate the definition as: A database is self-describing collection of
integrated records.

Characteristics of Database Management System

 It is collection of databases
 It is a computerized record-keeping system
 It contains facilities that allow the user to
 Add and delete files to the system
 Insert, retrieve, update, and delete data in existing files

Page 165
Java Programming

A DBMS may contain many databases that can be used for separate purposes or
combined to provide useful information. Therefore based on this we can define Database
Management System as:

A database management system (DBMS) is a program that allows users to define,


manipulate, and process the data in a database in order to produce meaningful
information.

Functions of a DBMS

o To organize data
o To store data
o To control access to data
o To protect data
o Uses of a DBMS
o To provide decision support: Managers and analysts retrieve information
generated by the DBMS for inquiry, analysis, and decision-making.
o To provide transaction processing: Users input, update, and process data
with transactions that generate information needed by managers and other
users or by other departments.

The History of Database Processing


Database processing has come a long way as its initial use was limited to just for
large Organizations but slowly migrated to micro level and started being used for
personal database and Internet applications. Initially Organizations faced problems in
using DBMS in the following counts: Slow speed of Database Management Systems-
This problem was tackled effectively with coming up of the powerful hardware and
software solutions. Other was that if a database fails, all its dependent application too
crashed which was not in the case of file processing system as if one file failed, only
application associated with that file crashed. But this problem was also taken care of in
due time with the effective and easy Backup & Restore methodologies.

Important models in Database Management Systems

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The Relational Model: E.F.Codd gave the concept of relational database in 1970
in a paper where he used concepts of relational algebra to the problem of storing large
data. Its Codds paper, which led to great improvement in the way database, is stored.

Relational Database

Short for relational database management system and pronounced as separate


letters, a type of database management system (DBMS) that stores data in the form of
related tables. Relational databases are powerful because they require few assumptions
about how data is related or how it will be extracted from the database. As a result, the
same database can be viewed in many different ways.

Page 166
Java Programming

Definition of Relational Database

Relational databases are databases in which data is organized into tables.


Tables are organized by grouping data about the same subject together. The tables are
related back to each other by the database engine when requested.

An important feature of relational systems is that a single database can be spread


across several tables. This differs from flat-file databases, in which each database is self-
contained in a single table.

E.F.Codd formulated rules for Relational Database Management Systems which


can be tabulated as below:

Information
All data must be represented logically in tables
Representation
Guaranteed logical All data is accessible logically using a combination of
accessibility table name, key name, key value and column
NULL support A Null value represents missing information and are not
to be confused with empty, blank or zero filled data.
They also are not necessarily equal
Dynamic online The definition of data is represented in the same manner
catalog as data so that it can be relationally accessed. Example
every database has catalog tables
Comprehensive data A unique language which is supported along with
sub-language (HLL several other programming languages to achieve data
Like SQL ) definition, view and manipulation
Updateable views All views that can theoretically exists can be updated
Both base and derived relations can be handled as
High level insert,
singular requests and apply to retrieval, insert, update
updates and delete
and deletion of data
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Physical data
Program and terminal activities are preserved when
changes are made in storage representation or access
independence
methods
Logical data Program and terminal activities are preserved when
independence changes are made to base tables
Integrity Integrity constraints must be definable in the unique
independence sub-language and stored in the catalog
Distribution The unique sub-language must support database

Page 167
Java Programming

independence e distribution while preserving program and terminal


activities
Nonsubersion A relational system which perform low-level processing
of records cannot supplant the integrity rules in effect in
high level, record processing by a relational language
Relational Table Defined as a rectangular array of columns and rows
database where columns are homogenous, non-grouped, uniquely
named data items( attributes ) and rows are not
duplicated. It is also important to impose the property
that column and row order within the array is immaterial

Almost all full-scale database systems are RDBMS's. Small database systems, however,
use other designs that provide less flexibility in posing queries.

3.2.3 Introduction - OODBMS and ORDBMS

Computer science has evolved a lot since its early beginning in the late 1940s.
The first non-proprietary programming language was Cobol and with Cobol, and later
Fortran, programming became the foundation of creating enterprise computer systems.
The systems developed, needed to store its data somewhere and the programmers
designed more or less proprietary and specialized solutions for this purpose. In 1964 the
first commercial database management system (DBMS) was born; IDS - Integrated Data
Store, developed at General Electric, based upon an early network data model developed
by C.W.Bachman (Bachman 1965). In the late 1960s, IBM and North American Aviation
(later Rockwell International) developed IMS - Information Management System, and its
DL/1-language. This was the first commercial hierarchical DBMS. Both kinds of DBMSs
(hierarchical and network) were accessible from the programming language (usually
Cobol) using a low-level interface. This made the task of creating an application,
maintaining the database as well as tuning and development controllable, but still
complex and time-consuming.

In 1970 Edgar F. Codd published an article, which offered a fundamentally


different approach (Codd 1970). Codd suggested that all data in a database could be

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
represented as a tabular structure (tables with columns and rows, which he called
relations) and that these relations could be accessed using a high-level non-procedural (or
declarative) language. Instead of writing algorithms to access data, this approach only
needed a predicate that identified the desired records or combination of records. This
would lead to higher programmer productivity and in the beginning of the 1980s several
Relational DBMS (RDBMS) products emerged (e.g. Oracle, Informix, Ingress and DB2).

As the DBMSs evolved, so did the programming languages. In 1967 Simula, the
first object-oriented programming language was born. Simula was developed to make a
foundation to develop simulation programs, and contained the now familiar class-
concept. Several other programming languages adopted the class-concept from Simula

Page 168
Java Programming

(e.g. C++, Java, Eiffel, and Smalltalk) and continued to evolve more or less
independently of the DBMSs.

In the early 1980s research started on another kind of database. This research was
among other things, motivated by the need of a database system capable of handling
complex objects and structures like those used in CAD systems, CASE and OIS systems
(Zdonik. 1994). To accomplish these tasks the database had to be able to store classes and
objects and the objects associations and methods, and the object-oriented DBMS
(OODBMS) emerged. In the late 1980s several vendors had developed OODBMSs (e.g.
ObjectDesign, Versant, O2 and Objectivity).

OODBMSs were no threat in the late 1980s to the now big commercial vendors
developing and selling hierarchical, network or relational databases. In 1991 ODMG
(Object Database Management Group) was founded, mainly thanks to Rick Cattell of
JavaSoft, and in 1993 several vendors of OODBMSs agreed upon an OODBMS standard
called ODMG-93. The relational databases already had its standard - SQL-92, defined by
its ANSI committee and ISO. And so did the network database vendors as well;
CODASYL (defined in 1986 by the ANSI X3H2 committee).

The founding of ODMG and the fact that object-oriented programming languages
became more and more used may well have been the major driving forces when the
ANSI X3H2 committee started its work on SQL3 in 1992. This proposal put another type
of DBMS on the arena - the object relational DBMS (ORDBMS).

While all this was happening, more and more programmers converted from C and
other languages to C++. C++ was becoming the most used object-oriented language, but
C++ application was not always that easy to develop and maintain. Such applications
often had memory-leaks, erroneous pointers and other trivial problems attached to them.

In 1991 Sun's Green Team started the development of a new programming


language which was loosely based on C++. The language was named Oak after the trees
outside the office window of the language designer - James Gosling. In 1992 Sun turned
Green Team into a fully owned company, called First Person Inc. National Center for
Supercomputing introduced Mosaic in 1993, a WWW browser, and the Internet began to
bustle with traffic. Soon other WWW browser followed. In 1994 First Person built an
Oak-ready browser called WebRunner and Sun backed the decision to give the language
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
(Oak) away for free, but first Oak was renamed to Java and WebRunner to HotJava. Java
became available to millions of people due to Netscapes bundling of Java, and soon
others followed (Bank 1995).
Since the late 1970s M.P. Atkinson had been working on research into databases,
persistence and their applications, and he was one of the major contributors to the first
orthogonally persistent language, PS-algol (Atkinson et al. 1983). The term and concept,
"Orthogonal persistence", will be explained later. Atkinson has continued his work and is
currently working on the PJama-project at University of Glasgow. PJama is an
orthogonally persistent version of Java. Today many regard Java as the "hottest"
language, and OODBMSs are by many the "hottest" DBMSs as well.
Page 169
Java Programming

OODBMS Concepts
Currently there is no consensus on an object-oriented data modell (OODM), but
several proposals exists (e.g. Cattell et al. 1997, TM-Language 1996, and Sarkar & Reiss
1992). All of these models represent actual objects and their associations as data-models,
and should not be confused with analysis- and design-methods like OMT by Rumbaugh
et al. (1991), OOA/OOD by Coad & Yourdon (1991a, 1991b), the Booch-method by
Grady Booch (1994), OOram by Reenskaug et al. (1995), etc. The OODMs differ on
several issues, e.g. multiple versus single inheritance, and whether the
operations/methods or only the definition should be stored. The sources of these
differences are, among other things, caused by the different capabilities of OO-languages
(or combination of languages), which should use the OODB. E.g. C++ supports multiple
inheritances, so all OODBMSs that support object-persistence and C++ as the
programming language must support multiple inheritances in the OODBMS. If the
OODBMS supports different programming languages, it probably should store the
interface of the methods rather than the methods itself. With this kind of problems, it is
very difficult to reach an agreement on all parts of the modelling perspective.

The lack of a commonly agreed data-model and definition language is by some


argued to be one of the biggest problems associated with OODM (Darwen & Date 1995),
and it is a problem, but it is not a conceptual problem - it is an implementation problem.
Currently ODMG 2.0 is the de facto standard among OODBMSs, and it supports
a common object-model with database functionality, an object query language (an SQL
look-alike, only including SELECT-statements) - OQL, an object definition language -
ODL, and finally a set of bindings to some programming-languages - C++, Java and
Smalltalk (Cattell et al. 1997).

The next generation of DBMS

Since no time machine currently exists, we must rely on the past and the current
works to predict the future. The languages have evolved from coding binary sequences to
procedural languages (e.g. Cobol, Fortran and Pascal), functional programming
languages (e.g. APE and ML), object-oriented languages (e.g. Simula, Smalltalk, C++,
and Java), commercial 4GLs (Open Ingress, Informix 4GL and PowerHouse 4GL), and

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
other breeds as well, all offering some degree of user-level abstraction. The need of
persistent data has evolved from sequential files to structured files, network databases,
hierarchical databases, RDBMS, and recently into ORDBMS and OODBMS offering
more controlled and flexible storage, interface, and transactional capabilities on complex
objects and structures (Wade 1996a).

Programming in general.

As these tools (programming languages, databases, program development


environments, standards, etc.) mature, users will begin to appreciate their value and more
and more off-the-shelf objects (components) will become available. Today program and

Page 170
Java Programming

database development requires knowledge about translating a problem in an universe of


discourse (UoD) to some computer language and/or database. Tomorrow it would
probably be a question about choosing the combination of components and integrating
them to solve the problem in the UoD. This would eventually result in fewer professional
programmers building core-objects, and more people working on the actual problem
domain of the UoD using pre-built re-usable objects.

The components will range from simple components (graphical user interface -
GUI and database components) to complex components for solving some kind of UoD-
specific need.

Information and databases.

Today information and databases are often centralized in some way, though
distributed systems do occur. Tomorrow this will probably change drastically. Databases
will be distributed and accessed using some kind of intelligent agents that hides
implementation issues for the users. The database(s) will be spread on several sites,
accessible over Internet (or an Intranet or maybe even a combination of these). The
databases will conform to some kind of standard (ODMG or SQL3 presumably), but the
standard will be hidden for the user, which probably will access these information
resources using intelligent agents.

Application architecture.

The first applications to be written used a one-layer architecture. As the databases


evolved, so did the application architecture resulting in the now-famous two-layer and
three-layer architectures. The three-layer architecture requires a knowledge and
understanding of a programming language, the UoD, application design and database
implementation. I believe that these layers will disappear (layers will probably be hidden
by intelligent agents, reusable components and persistent languages) for the common
programmer, resulting in an easier implementation that will be hiding the impedance
mismatch if such exists.

Databases and standards.

When databases first became commercially available no standards existed, but in


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1971 the CODASYL-standard (sometimes called DBTG-standard) emerged (DBTG
1971). However, the network database community had to wait until 1986 for a formal
standard (ANSI X3H2 defined the CODASYL-standard in 1986). In 1986 SQL became a
standard for RDBMSs, and in 1993 ODMG put forward its ODMG-93 standard for
OODBMSs. The work on the SQL3-standard for ORDBMS started in 1992 and is
expected to be completed in 1999.

The hierarchical databases and network databases are still used, but more and
more legacy systems are being converted or reprogrammed into using some newer
DBMS, usually an RDBMS. The RDBMS has shown its strength, but it will also

Page 171
Java Programming

eventually disappear, and the two new DBMS-concepts will become more and more
used. The vendors claiming support of SQL3 has become big commercial enterprises and
stick to the relational data model and to SQL as DML/DDL. The relational calculus and
tuple calculus is the mathematical foundation of the relational data model, and SQL is not
as close as it should be to either. The additions in SQL3 makes the differences even
bigger, and in the future SQL will, unless another language takes it place, become a
problem for the ORDBMS society (Darwen & Date 1995).

OODBMS on the other hand will continue to grab chunks of the market, and as
component based development, information hiding and intelligent agents become more
and more used, distributed database systems based on OODBMS will grow rapidly and
sooner or later the centralised database as it is known today is likely to disappear.
Eventually some kind of hybrid database that tries to capture the better of two worlds will
be enforced. This has already happened to some degree with the emerging SQL3 standard
(a hybrid of relational and object-oriented database systems), and will continue to
happen. Another scenario would be that the OODBMS and ORDBMS communities
concentrate on different application areas. This is not likely to happen because
applications and the need to store complex data structures will increase and both the
ORDBMS-vendors and the OODBMS-vendors want a part of it.

The database management systems have evolved a lot from IMS and up to
ORDBMSs, OODBMSs, The size of the impedance mismatch is decreasing, the level of
abstraction is getting higher and the architecture of DBMS-applications is changing.

Abbreviations

4GL 4th Generation Language


ACM Association of Computing Machinery
ADT Advanced Data Type
API Application Programming Interface
ANSI American National Standard Institute
BLOB Binary Large Object
CAD Computer Aided Design
CASE Computer Aided Software Engineering
CODASYL Conference on Data Systems Languages
DB Database
DBMS
DDL
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Database Management System
Data Definition Language
DML Data Manipulation Language
HLL High-Level Language
GUI Graphical User Interface
IBM International Business Machines
IDL Interface Definition Language
ISO International Standard Organization
OIS Office Information System
ODL Object Definition Language

Page 172
Java Programming

ODMG Object Database Management Group


OMG Object Management Group
OODBMS Object-Oriented Database Management System
OODM Object-Oriented Data Model
OQL Object Query Language
ORDBMS Object-Relational Database Management System
QUEL Query Language
PCR Parent Child Relationship
RDBMS Relational Database Management System
SQL Structured Query Language
UoD Universe of Discourse

Strategies for developing the databases:


Top-Down development:

This proceed from general to specific

Step 1:Study strategic goals of the organization


Step 2:Means to accomplish the goals
Step 3:Information required to accomplish the goals
Step 4:System required to accomplish the goals
Using step 1-4 an abstract model is made and the development team progressively work
downward toward more and more detailed descriptions, details and models. So this
approach is Process-oriented Systems are modeled based on the flow of business
processes.

Bottom up Development Approach:


It operates in reverse order of abstraction, by beginning with the need to develop a
specific system. In it a particular system is developed and then with further studies and
analysis keep on adding to the system and eventually end up designing up whole system.
So this approach is Data-oriented as Systems are modeled based on the business
application's data, regardless of data usage or data access needs

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
3.2.4 Data Modeling
A data model is a conceptual representation of the data structures that are required
by a database. The data structures include the data objects, the associations between data
objects, and the rules, which govern operations on the objects. As the name implies, the
data model focuses on what data is required and how it should be organized rather than
what operations will be performed on the data. To use a common analogy, the data model
is equivalent to an architect's building plans.

A data model is independent of hardware or software constraints. Rather than try


to represent the data, as a database would see it, the data model focuses on representing
the data as the user sees it in the "real world". It serves as a bridge between the concepts
Page 173
Java Programming

that make up real-world events and processes and the physical representation of those
concepts in a database.

There are two major methodologies used to create a data model: the Entity-
Relationship (ER) approach and the Object Model. This document uses the Entity-
Relationship approach.

The Entity Relationship Model (E-R Model)


Peter Chen introduced entity Relationship Model in 1976. Its important to note
that Peter Chen set out the foundation of this model and over the period of time, this
model has undergone a comprehensive change. Various people who worked on this
model for all along this period have brought the change. The E-R Model has been made
part of various CASE Tools.

CASE Tools
Known as Computer Aided Software Engineering (CASE) tools. These tools are
primarily used for design documentation and code generation. In simple layman terms,
CASE is a tool, which aids a software engineer to maintain and develop software, much
like a mechanic who uses the aid of his/her tools to maintain and develop vehicles, but
obviously using respective techniques. It is believed that CASE tools reduces cost as well
as development time, and assures superior design consistency. Popular CASE tools are
IEW, IEF, Visio, ER-Win etc.

E-R Model is primarily used to represents the overall logical structure of the
Database.
Two Important observations which need to be understood before probing E-R
Model in deep are:

There is no single generally accepted standard E-R Model. Rather there are a set
of common constructs from which most of the E-R variants are derived.

In addition symbols used to represent E-R Model differ widely in IT Industry.


Also the symbols used here are one of the popular and widely used symbols

The most important elements of E-R Model are:


ANNAMALAI
ANNAMALAI UNIVERSITY
Entities
UNIVERSITY
Entities are the principal data object about which information is to be collected.
Entity is something that can be identified in the users environment. It's something that the
user wants to track. An entity is an object that exists and is distinguishable from other
objects. Entities are usually recognizable concepts, either concrete or abstract, such as
person, places, things, or events, which have relevance to the database. Some specific
examples of entities are Students, Instructors. An entity is analogous to a table in the
relational model.

Page 174
Java Programming

Examples: Student entity

STUDENT

StudentID
StudentName
Address
City
State
Zip
TelephoneNumber

Entities of a given type are clubbed into Entity class. Example All students
studying in an Institute attending various different classes. Thus the Students Entity class
is the collection of all student entities. Thus an Entity class is a collection of entities and
is described by the structure of the Entities in that class.

Whereas an Entity instance is representation of a particular Entity in the entity


class such as Student Joe. There are usually many instances of an Entity in an Entity
Class. Entity instance is analogous to a row in the relational table.

Instance of STUDENT

01
Adam
100 Gateway Drive
Seattle
WA
98101
206-334-9876
ANNAMALAI
ANNAMALAI UNIVERSITY
Attributes
UNIVERSITY
Entities have Attributes. Attributes are also known as Entity properties or
Domain. Attributes describe the entity of which they are associated. Examples of
Attributes are Student Name, Student ID, Class ID etc. Attributes are analogous to a
column in the relational table. It's an important assumption of an E-R Model that all
instances of a given class have the same attributes.

Page 175
Java Programming

Composite Attribute: Composite Attribute is one, which consists of group of attributes.


Example of Composite Attribute is Address, which consists of group of attributes [Street,
City, State, Zip]

Multi Value Attributes: When a particular Entity has more then one values. Example
can be anyone's E-mail ID as person may have more then one E-Mail ID.

There can be also multi value composite attribute like a student can give his more
then one phone number as a contact number. Now phone number is composite in the
sense that it contains Area Code and Telephone Number and multi value in the sense that
Student may provide more then one number as his or her Telephone number.

Identifiers Entity instances have identifiers, which are attributes that name or
identify entity class. Like in student entity class student instance can be identified by
student name or student id. Also Faculty name or FacultyID can identify faculty entity
class instance.

The identifier usually contains one or more of the entities attributes. An identifier
may either be unique or non unique. StudentID or FacultyID is most probably unique
identifier but Student name or faculty name usually may not be a unique identifier as in
an entity class more then one student or faculty have same name. Identifiers having more
then one attributes are called composite identifiers.

3.2.5 Relationships
A Relationship represents an association between two or more entities. An
example of a relationship would be:

 Students are assigned to projects


 Projects have subtasks
 Class manage one or more projects
 Relationships are classified in terms of degree, connectivity, cardinality,
and existence

E-R Model take care of both Entity class relationships and Entity instance
relationship. Like how STUDENT entity class related to INSTRUCTOR entity class and
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
how a student Joe related to Instructor Tim or fellow student Smith.

Degree of a Relationship
The degree of a relationship is the number of entities associated with the
relationship. Example in a Student-Teacher relationship degree is two as each instance of
the relationship involves two entity instances: Student and Teacher. The n-ary
relationship is the general form for degree n. Special cases are the binary, and ternary,
where the degree is 2, and 3, respectively.

Page 176
Java Programming

Binary relationships, the association between two entities are the most common
type in the real world. Binary relationships are relationships of degree two. A recursive
binary relationship occurs when an entity is related to itself. An example might be "some
employees are married to other employees".Example of Binary relationship is:
Husband – Wife
A ternary relationship involves three entities and is used when a binary
relationship is inadequate. Many modeling approaches recognize only binary
relationships. Ternary relationships are decomposed into two or more binary
relationships. Example of Ternary relationship is: Mother-Father-Child

Connectivity and Cardinality


The connectivity of a relationship describes the mapping of associated entity
instances in the relationship. The values of connectivity are "one" or "many". The
cardinality of a relationship is the actual number of related occurrences for each of the
two entities. The basic types of connectivity for relations are: one-to-one, one-to-many,
and many-to-many.
A one-to-one (1:1) relationship is when at most one instance of an entity A is
associated with one instance of entity B. For example, "employees in the company are
each assigned their own cube. For each employee there exists a unique cube and for each
cube there exists a unique employee.
Example: Student and Book (Hash on student side and oval on book side
A one-to-many (1:N) relationships is when for one instance of entity A, there
are zero, one, or many instances of entity B, but for one instance of entity B, there is only
one instance of entity A. An example of 1:N relationships is a department has many
employees and each employee is assigned to one department.

Example: Student-Instructor: Each Instructor has many students to teach but all
students have only one Instructor to learn from.

Example: Employee-Project
Example: Dormitory-Student relationship

A many-to-many (M: N) relationship, sometimes called non-specific, is when


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
for one instance of entity A, there are zero, one, or many instances of entity B and for one
instance of entity B there are zero, one, or many instances of entity A.

Example: Student can be assigned to no more than two projects at the same time or
projects must be assigned to at least three students.

A single employee can be assigned to many projects; conversely, a single project


can have assigned to it many employees. Here the cardinality for the relationship between
employees and projects is two and the cardinality between project and employee is three.
Many-to-many relationships cannot be directly translated to relational tables but instead

Page 177
Java Programming

must be transformed into two or more one-to-many relationships using associative


entities.

Entity Relationship Diagrams

E-R Diagrams are standardized, but only loosely. According to standard used above

 Entity classes are shown by rectangles


 Relationships are shown by diamonds
 Maximum cardinality of the relationship is inside the diamond
 The name of the relationship is shown near the diamond

To show Minimum cardinality one can place a hash mark (|) across the
relationship line to indicate that the entity must exist in the relationship and place an oval
across the relationship line to indicate that there may or may not be an entity in the
relationship

Weak Entities

There is special type of entities called weak entities and are those that cannot exist
in the database unless another type of entity also exist in the database. Weak entities are
represented by rounding the corners of the entity rectangle. Also the relationship on
which the weak entity depends for its existence is signified in a diamond with a rounded
corner. Also in some E-R Diagrams weak entities are represented with double line for the
boundary of a weak entity rectangle and double diamonds for the relationship on which
the entity depends. Example of weak entity can be apartment and building case.

The identifier for building is Building name and the identifier for apartment is
composite of both building name and apartment number. Since the identifier of the
apartment depends on the building identifier we can say that apartment is id dependent on
building. Seeing logically and physically also apartment also cannot exist without a
building. To identify the weak entity criterion used is that weak entity should depend
logically on another entity.

Generalization Hierarchy or Subtype Entities

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A generalization hierarchy is a form of abstraction that specifies that two or more
entities that share common attributes can be generalized into a higher-level entity type
called a supertype or generic entity. The lower level of entities becomes the subtype, or
categories, to the supertype. Subtypes are dependent entities. To understand we can take
an example of Store Membership, now this Membership can be an individual
membership or a corporate membership. An individual membership contains:
 Address, Social Security Number Corporate Membership contains:
 Address, Tax identification number

Page 178
Java Programming

In order to implement such scenes we define two subtypes entities of entity


membership. The e next to the relationship line indicates that the Individual Member and
Corporate Member are subtypes of entity Membership. Subtypes can be either mutually
exclusive (disjoint) or overlapping (inclusive). A mutually exclusive category is when an
entity instance can be in only one category. The above example is a mutually exclusive
category as member can be either corporate member or an individual member.

To represent such a relationships we put 1 in front of the curved line to indicate


that the supertype entity must belong to one and only one subtype. These structures of
subtype and supertype are referred as generalized hierarchies because Member is
generalization of two subtypes. This relationship is also called IS-A relationship as
individual member is a Member, just as Corporate member is a member

3.2.6 Normalization
Normalization is a process for converting a relation that has certain problems to
two or more relations that do not have problem. We can say that Normalization is used to
check the desirability and correctness of relations. In Relational Model Tables are termed
as relations. The relational model was formally introduced by Dr. E. F. Codd in 1970 and
has evolved since then, through a series of writings. The model provides a simple, yet
rigorously defined, concept of how users perceive data.

The relational model represents data in the form of two-dimension tables

 Each table represents some real-world person, place, thing, or event about which
information is collected
 A relational database is a collection of two-dimensional tables
 The organization of data into relational tables is known as the logical view of the
database. That is, the form in which a relational database presents data to the user
and the programmer · The way the database software physically stores the data on
a computer disk system is called the internal view. The internal view differs from
product to product

A basic understanding of the relational model is necessary to effectively use


relational database software such as Oracle, Microsoft SQL Server, or even personal
database systems such as Access or FoxPro, which are based on the relational model.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Normalization is used to check the desirability and correctness of relations. So in nutshell
we conclude that, Normalization is a design technique that is widely used as a GUIDE in
designing relational databases. The goal of normalization is to create a set of relational
tables that are free of redundant data and that can be consistently and correctly modified.

A relation is a 2-D table with each row holding data that pertain to some thing or a
portion of some thing. Each column has a data regarding an attribute. The term relational
comes from the mathematical field of relational algebra. So, Relational models are
composed of relations, or two-dimensional tables, which follow the operations described
in relational algebra. Rows are called tuples and columns attributes.
For a table to be in a relation, it must follow these rules
Page 179
Java Programming

 Cells of the table must be of single value


 All entries of the column must be of same type
 Each column/attribute need to have a unique name
 No two rows in a table may be identical
 Also order of the rows and columns in a relationship is insignificant

Functional Dependency

It's a relationship between or among attributes. Means if we know value of 1


attribute we can obtain the value of another attribute. Like if we know StudentId we can
know his admission date. And we can say that admission dates are functionally dependent
on the StudentId. Or in general attribute Y is dependent on attribute X. One can
comprehend that the storage and retrieval of functional dependencies is the only reason
for having a database.

Functional dependencies are written using the following notions:

StudentId admissiondate (Read as StudentId determines admissiondate) Or


another example:

CourseId CourseFee

Attributes on the left side of an arrow are called determinants.

As many number of students can have same admission date but each particular
student have a specific admission date. Consequently we can say that Relationship of
StudentId and admission date is Many to One or N: 1

Functional dependencies can involve group of attributes too. Like we can take a
case of Relation Grades. Table has an attributes like (SID, Subject, Grade). The
combination of SID and a subject determine a grade, a functional dependency written:
(SID, Subject) Grade

Here above both SID and subject determines a grade

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
So in more a broad sense we conclude that the concept of functional dependencies
is the basis for the first three normal forms. A column, Y, of the relational table R is said
to be functionally dependent upon column X of R if and only if each value of X in R is
associated with precisely one value of Y at any given time. X and Y may be composite.
Saying that column Y is functionally dependent upon X is the same as saying the values
of column X identify the values of column Y. If column X is a primary key, then all
columns in the relational table R must be functionally dependent upon X.

A shorthand notation for describing a functional dependency is:

R.x ; R.y

Page 180
Java Programming

which can be read as in the relational table named R, column x functionally


determines (identifies) column y.

Key: It is a group of one or more than one attributes that uniquely identifies a row

StudentId CourseName Fee


100 IT203 2220
101 1T161 1000
102 IT107 2000
103 IT121 1000
104 IT331 200
Relation: Courses

Now here above we assume that a student can enroll in only one course at a time.
In that case StudentId uniquely identifies the each row.

Since keys can be composed of group of attributes. Like if we assume that anyone
can enroll in >1 courses at a time, then same StudentId would have appear in > 1 Rows in
a table.

StudentId CourseName Fee


100 IT203 2220
101 1T161 1000
102 IT107 2000
103 IT121 1000
101 IT107 2000
103 IT 203 2220
104 IT331 200
Relation: Courses1

On careful analysis we find that StudentId would not have uniquely identified
each row. But combination of StudentId and CourseName would have
Modification Anomalies

Consider a case we delete a row for student 104 from Table A or Table B, in such
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
case we do not just loose information that Student 331 is enrolled for course IT 206 but
also the fact that IT 331 costs $220. This is called deletion anomaly.

Similarly if we want to add another course say IT 176, we cannot unless some student
enrolls for this particular course. This is called an insertion anomaly. We cannot insert a
fact about one entity until we have an additional fact about another entity.

So to overcome this problem we divide Table B into 2 tables:

Page 181
Java Programming

StudentId CourseName
100 IT203
101 1T161
102 IT107
103 IT121
101 IT107
103 IT 203
104 IT331

Relation: Student-Course

CourseName Fee
IT203 2220
1T161 1000
IT107 2000
IT121 1000
IT107 2000
IT 203 2220
IT331 200

Relation: Courses-Fee

So above scenario take care of both addition and deletion anomaly.

This we can compare with General English where one paragraph contain a single
theme, in a relational tables too one table can have one theme only. So whenever we find
a relation with modification anomalies we split the relation to more than one relation with
each counting a single theme and this itself is the essence of Normalization.

In early 70s each time anomaly was found in a relation, relation theorists worked
on same and thought of the way to prevent same. This way Relations were classified
based on anomalies. These classes of Relations and the techniques for preventing
anomalies are called Normal Forms. This way 1st, 2nd and 3rd Normal Forms were
defined. It was followed by Boyce-Codd Normal form, then 4th and 5th Normal form.
All these Normal forms are nested means for a relation by 5NF it need to be 4NF, 3NF,
2NF, and 1NF.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
But still these NF were not able to eliminate all the anomalies. This was however
changed when a new Normal Form called domain/key normal form (DK/NF) was
introduced by R.Fagin in 1981. Fagin proved DK/NF as free of all the anomalies.

Normal Forms- First to Third

First Normal Form


Any table of data that meets the definition of a relation is said to be in First Normal
Form. For a table to be in a relation, it must

Page 182
Java Programming

 Cells of the table must be of single value (No arrays or repeating groups are
allowed as value)
 All entries in any column must be of same type
 Each column/attribute need to have a unique name
 No two rows in a table may be identical
 Also order of the rows and columns in a relationship is insignificant

StudentId CourseName Fee


100 IT203 2220
101 1T161 1000
102 IT107 2000
103 IT121 1000
104 IT331 200
Relation: Courses
So Relation Courses is an example of 1NF But careful examination of this
relation show that it have modification anomalies. Like consider the case when say record
of studentid=103 is deleted or when we have to add a new course IT100 which no student
has yet joined , so in that case knowing course fee will be a difficult proposition.
Second Normal Form

Consider once again Relation Course1, now this relation also suffers from
modification anomalies as discussed before. In this relation one student can register for
one or more courses. That means that StudentId itself only cannot be key. So we consider
(StudentId, CourseName), (StudentId, Fee) and (CourseName, Fee). But since two
courses can have same fee we can not have (CourseName, Fee) and also (StudentId, Fee)
can not determine uniqueness in row as student 100, for example, could engage in two
different activities both having same fee. Thus only (StudentId, CourseName) can
uniquely determine each row.

StudentId CourseName Fee


100 IT203 2220
101 1T161 1000
102 IT107 2000
103 IT121 1000
101 IT107 2000
103 IT 203 2220
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
104
100
IT331
IT161
200
1000
Relation: Courses1

The problem here is that it has dependency involving only one part of the key.
The key is combination of (StudentId, CourseName), but relation has a dependency like
this:

CourseName Fee

Page 183
Java Programming

Thus determinant of this dependency is only one part of the key. So in this case
we can say that Fee is partially dependent on the key of the table. There would be no
modification anomalies (In above case deletion anomaly for StudentId 104) if Fee were
dependent on the entire key. To eliminate the anomaly we divide into two relations

So we define that a relation is said to be in second Normal Form if all its non-key
attributes are dependent on the entire key and not part of it. Therefore we also conclude
that if a relation has a single attribute as a key then it's automatically in 2NF. Thus 2NF
concerns only those, which have composite keys

So Courses1 can be split into two relations Student-Course and Course-fee

Third Normal Form

Relations in 2NF too can have anomalies. Consider HOUSING Relation below:

StudentId BldgName Rent


100 CityHall 1200
101 CityWoods 1000
102 CityHall 1200
103 CalmPlace 1500
104 UrbaneColony 1200

CityHall 1200
105
106 CityWoodsl 1000
Relation: HOUSING

In above relation StudentId is a key, and the functional dependencies are:

StudentId BldgName

and BldgName Rent

These dependencies occur because each student lives in one building and each
building has a predefined Rent. Since StudentId determines BldgName and BldgName
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
determine rent, we can say that indirectly StudentId determines Rent. An arrangement of
functional dependencies like this is called Transitive Dependency

Now analyzing further key to HOUSING is StudentId, which is a single attribute,


and hence the relationship is in 2NF.Despite being 2NF it suffers from Modification
anomalies, consider case of deletion of StudentId 103 and consider case when we want to
add rent for another building say named PoshColony, we cant until student decide to
move in this building

Page 184
Java Programming

So to eliminate anomalies from 2nd NF we need to remove transitive


dependencies. So we conclude that A relation is in third Normal Form if it is in second
normal form and has no transitive dependencies

So we can divide HOUSING into two separate relations to make it in 3rd NF.

StudentId BldgName
100 CityHall
101 CityWoods
102 CityHall
103 CalmPlace
104 UrbaneColony
105 CityHall
106 CityWoodsl
Relation: STUDENT-BLDG

BldgName Rent
CityHall 1200
CityWoods 1000
CityHall 1200
CalmPlace 1500
UrbaneColony 1200
CityHall 1200
CityWoodsl 1000
Relation: BLDG-RENT

Boyce-Codd Normal Form (BCNF)

 A relation is in BCNF if every determinant is a candidate key.


 Key: One or more attributes that uniquely identify a tuple (row) in a relation
 Those determinants that are keys we initially call candidate keys. Eventually, we
select a single candidate key to be the primary key for the relation
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Consider the following example

 Funds consist of one or more Investment Types.


 Funds are managed by one or more Managers
 Investment Types can have one more Managers
 Managers only manage one type of investment

FundID InvestmentType Manager


99 Common Stock Smith
99 Municipal Bonds Jones

Page 185
Java Programming

33 Common Stock Green


22 Growth Stocks Brown
11 Common Stock Smith

 FundID, InvestmentType -> Manager


 FundID, Manager -> InvestmentType
 Manager -> InvestmentType

 In this case, the combination FundID and InvestmentType form a candidate key
because we can use FundID, InvestmentType to uniquely identify a tuple in the
relation.
 Similarly, the combination FundID and Manager also form a candidate key
because we can use FundID, Manager to uniquely identify a tuple.
 Manager by itself is not a candidate key because we cannot use Manager alone to
uniquely identify a tuple in the relation.

Checking this relation R(FundID, InvestmentType, Manager) if its in 1NF, 2NF


or 3NF

Assuming we pick FundID, InvestmentType as the Primary Key

 1NF for sure as relation is as per definition of 1NF


 2NF because all of the non-key attributes (Manager) is dependant on all of the key
 3NF because there are no transitive dependencies

Presence of anomaly

Consider what happens if we delete the tuple with FundID 22. We loose the fact that
Brown manages the InvestmentType "Growth Stocks." The following are steps to
normalize a relation into BCNF:

 List all of the determinants




ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
See if each determinant can act as a key (candidate keys)
For any determinant that is not a candidate key, create a new relation from the
functional dependency. Retain the determinant in the original relation

For our example:

Rorig (FundID, InvestmentType, Manager)


The determinants are:

 FundID, InvestmentType

Page 186
Java Programming

 FundID, Manager
 Manager

Which determinants can act as keys ?

 FundID, InvestmentType YES


 FundID, Manager YES
 Manager NO

Create a new relation from the functional dependency:

 Rnew (Manager, InvestmentType) : Key - Manager


 Rorig (FundID, Manager) : Key - FundID, Manager

In this last step, we have retained the determinant "Manager" in the original relation
Rorig.

Fourth Normal Form

Id Major Minor
10 Physics Geography
10 Math Geography
10 Physics Computers
10 Math Computers
10 Geology Economics

 Id -> -> Major


 Id -> ->Minor
 Since student can have many Majors there is no functional dependency as one
value of Id can have several Majors.
 Also for single value of Id one can have many Minors.

This attribute dependency is called multi-value dependency.

In above Relation:


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Student can enroll in several different majors and several different minors
 Major and Minor are independent of each other
 Only possible key is (id, major, minor)

Above relation is:

 1NF for sure


 2NF because there is no non-key attributes
 3NF because there are no transitive dependencies
 BCNF as it does not have any functional dependency, so this relation is in BCNF
Page 187
Java Programming

Above relation also suffers from anomalies as:

 If we want to signup student 10 for minor Chemistry, then we can add row (10,
Physics, Chemistry) but this will mean that student can take minor Chemistry
with Major Physics only and not with Math, which is wrong. So we will have to
add row (10, Math, Chemistry) too. This is an update anomaly as too much
information needs to be updated for simple change in the data
 Also if a student drops a major, all the entries associated with major need to be
dropped, this causes deletion anomaly

To make this relation 4NF we need to:

Create 2 relations each storing data only for one multi multi-value attribute.

 (SID, Major) : Key(SID, Major)


 (SID, Minor) : Key (SID, Minor)

So dividing the single relation into two relations we have eliminated multi valued
Dependencies and above-discusses updation and deletion anomaly.

Multi-valued dependencies exist only when:

There must be at least 3 attributes in the relation, call them A, B, and C, for example.

 Given A, one can determine multiple values of B


 Given A, one can determine multiple values of C
 B and C are independent of one another

So, A relation meets the requirements of 4NF only if it is in 3NF (or BCNF) and
has no multi-valued dependencies.

3.2.7 Denormalization

Denormalization is a technique to move from higher to lower normal forms of


database modeling in order to speed up database access. One may apply Denormalization

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
in the process of deriving a physical data model from a logical form. Sometimes
deviating from good normalization practices seems logical or practical. Well-normalized
databases are complex to program against.

Application programmers who are charged with creating user front ends usually
have to use multi-table joins, sub queries, or views as data sources. This method can
make the application run so slowly as to be unusable. Also, a well-normalized database is
so complex and so fragmented into data groups that data readers often get confused and
disoriented while trying to find information.

Page 188
Java Programming

Under certain circumstances, one can denormalize ones database. Keeping in


mind that every time one does so, one pays a price. The cost might be in lost flexibility,
in future scalability, in performance, or in data integrity.

One might find that by denormalizing, one have much more data redundancy in
the database; when modifying data, one'll have to manage this redundancy through
program code, either at the user interface (UI) or by using triggers. Only one valid reason
exists for denormalizing a relational design - to enhance performance.

Current relational packages

Under our loose definition, several software packages now available qualify as
relational, e.g.

dBase (PC DOS/Windows), one of the earliest; now quite old-fashioned.


Access (PC Windows), currently very popular, the software used in this
Course.
Paradox (PC Windows), currently very popular.
Ingress and Oracle (multiple platforms), two systems often preferred for very large
database applications.
4th Dimension (Mac).

3.2.8 Components of Database

The database is processed by the DBMS, which is used both by developers and
users, who can manipulate the DBMS either directly or indirectly through application
Program.

Four Important Components of Database

User Data
User data is stored in tables consisting of Rows and Columns. Columns contain field
attributes and Rows contain records of Particular entity in the business environment.
Good Database design is associated primarily with the good Table designs. Consider an
example:

ANNAMALAI
ANNAMALAI UNIVERSITY
Table StudentInsUNIVERSITY
StudentID Student Name Student Phone InstructorName InstructorPhone

100 Adam 111-222-0987 Gary 111-222-3333

101 John 111-221-3457 Gary 111-222-3333

Page 189
Java Programming

102 Jenny 111-220-9822 Tim 111-219-3267


103 Smantha 111-220-7644 Tim 111-219-3267
104 Stacy 111-222-3478 Gary 111-222-3333

Table Student

StudentID Student Name StudentPhone InstructorName


100 Adam 111-222-0987 Gary
101 John 111-221-3457 Gary
102 Jenny 111-220-9822 Tim
103 Smantha 111-220-7644 Tim
104 Stacy 111-222-3478 Gary

Table Instructor

InstructorName InstructorPhone
Gary 111-222-3333
Tim 111-219-3267

In case of Table StudentIns if we need to change Instructor Jims Phone we will


have to change at three places but when Table StudentIns is split into Table Student and
Table B2, we just need to change it at a single place. Table Student and Instructor can be
joined together using the principles of Database Managements.

Metadata
As described database is self-describing, which means that it contain description
of structure as part of itself. This description about own self is called Metadata. All
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
present day products keeps Meta data in the form of Tables. The table containing
information about data structure is called Systems Tables.

Table Name Number of Columns Primary Key


Student 3 StudentName
Instructor 2 InstructorName
Course 4 Courseid
Registration 4 {Reg_No, zip}

Page 190
Java Programming

Hypothetical Systems Table

Storing Metadata makes thing easy and convenient for both DBMS and user.
Accessing Metadata employs same techniques as for accessing user tables.

Indexes

Indexes are the third type of database data, which improve the performance, and
accessibility of the data. This data known as overhead data lead to better sorting of data
and quick access to data. Indexes are most useful in searching the data. But keeping
Indexes involves overheads, as each time database is updated Indexes too need to be
updated and thus consume system resources.

Student Name Index

StudentName StudentID
Adam 100
Smith 101
Chris 102
Nancy 103
Andrew 104

Application Metadata

Application metadata stores the structure and format of user forms, reports,
queries and other application components. Usually application metadata is accessed by
using DBMS tools.

3.2.9 Database Engine

The part of the DBMS that works with the data. An engine typically has code that

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
can search, read, write, index and otherwise execute the actual interaction with the
information. A database engine performs the largest share of work in most databases and
thus it is the subject of an intense optimization effort by the DBMS creators. Some of the
most advanced DBMS have engines which can self-optimize after monitoring the actual
conditions after deployment. A DBMS will have additional features that are not part of
the data engine, including query analyzing, replication and back-up tools, user
management, security tools and performance monitoring.

Page 191
Java Programming

Results: The term "Result" frequently confuses folks learning SQL because the
term can be used in three ways:

First, and most common, we mean a set of data that is returned after a front end
sends a SQL statement to a DBMS. You ask for "The first and last names of all the
employees that started after 1995" and you get back a block of characters (a recordset)
containing those names.

But what if the SQL statement instructs the DBMS to modify data rather than just
read it?

The second case is when the "result" refers to a change in the data. We do not
necessarily receive any characters back from the DBMS although we may get a status
message noting that the operation was successful.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Third, we may make changes to the data and have the DBMS report back to us on
the changes. Frequently this is a notice of how many records were changed or what errors
arose or a True/False that the SQL statement was executed successfully. In this case we
get a result back, but it is not actual data; it is a message or code indicating the number of
records changed, an error or success.
"SQL" and "SQL Server": SQL is the name of an open-standard language for
communicating with databases. Microsoft SQL Server and Sybase SQL Server are
proprietary DBMS products that can handle SQL statements. Microsoft SQL Server is
popular, but it is only one of many DBMS that can handle your data and your SQL
statements.

Page 192
Java Programming

Comparing Procedural and Declarative Languages

Procedural (Basic, C++, Cobol, Declarative (SQL)


etc.)
Most work done by interpreter of Most work done by Data Engine
the languages within the DBMS
Many lines of code to perform a One SQL statement to perform
task task
Programmer must be skilled in Programmer must be skilled in
translating the objective into lines clearly stating the objective as a
of procedural code SQL statement
Requires minimum of management Relies on sophisticated, SQL-
around the actual data enabled DBMS to hold the data
and execute the SQL statement
against the data
Programmer understands and has Programmer has no interaction
access to each step of the code with the execution of the SQL
statement
Data exposed to programmer Programmer receives data at end
during execution of the code as an entire set
More susceptible to failure due to More resistant to changes in the
changes in the data structure data structure
Traditionally faster, but that is Originally slower, but now setting
changing speed records
Code of procedure tightly linked to Same SQL statements will work
front end with most front ends
Code loosely linked to front end.
Code tightly integrated with Code loosely linked to structure of
structure of the datastore data; DBMS handles structural
issues

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Programmer works with a pointer Programmer not concerned with
or cursor positioning
Knowledge of coding tricks Knowledge of SQL tricks applies
applies only to one language to any language using SQL

To summarize this table, declarative languages are quite different from the
procedural languages you may be using now. Procedural languages like C++ place an
emphasis on the programmer writing many lines of code to describe the exact steps of
obtaining a result. Declarative languages like SQL place an emphasis on the programmer
writing an exact description of the desired result. The DBMS then handles the task of
obtaining the result. A good SQL programmer becomes very skilled at carefully
Page 193
Java Programming

describing the result but remains blissfully ignorant of the internal code of the DBMS that
executes the result.

Oracle

Oracle offers one of the world's most widely deployed DBMS, currently named
Oracle9i. The Oracle product has proven itself in many of the largest data stores
supporting entire corporations. Oracle has established itself as a leader for web sites with
very high traffic. The explosion of data access requests from the web has pushed Oracle
to further increase speed, capacity and reliability.

The Human Roles in a DBMS

With the increasing size and complexity of computing tasks, IT departments


frequently grow to have several specialists contributing to the database solutions of the
company. If you are coming from a background in desktop databases you may not have a
clear idea of the titles and roles of the players. Obviously, in a small company one person
may have more than one of these roles – as a SQL programmer you may even be
expected to cover responsibilities beyond just programming.

The Database Administrator (DBA) specializes in installing and maintaining the


DBMS, including the physical devices, backups and recoveries. Frequently the DBA is
the person responsible for maintaining the security scheme as well as troubleshooting the
DBMS. Note that the DBA is not usually specifically responsible for any given database.
Rather, the DBA keeps the DBMS running as a service for all the users that have
databases on that DBMS. Each DBMS vendor has training and certification programs for
its particular systems.

The Systems Administrator (sometimes called the System Operator or "SysOp")


specializes in the Operating System (OS) and connectivity of the servers, both data
servers and others. "SysAdmins" perform back-ups of the OS and monitor the traffic load
between servers. "SysAdmins" are likely also to be involved in the security settings of
servers needed by SQL programmers.

A newer position is the Security Administrator. Valuable corporate data is now


exposed through the web to a degree that would horrify the last generation of IT
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
professionals. As hackers improve their sophistication and means of collaboration, IT
shops have responded by hiring individuals with specific training in establishing
hardware and software safeguards and in monitoring the servers for signs of intrusion.
SQL programmers may have to work closely with a Security Administrator to develop
ways of using data that minimize risk.

A Database Designer creates the overall scheme of the datastore, generally using
specialized database design tools. The designer will not only understand the principles of

Page 194
Java Programming

databases but also the client's business model. The result from the designer's desk will be
a layout of tables, relationships and queries needed to satisfy the client's needs.

The Database Programmer writes code and interfaces to implement the design.
The programmer may be less familiar with the business rules and more familiar with how
to write SQL statements and front ends to implement the design. Whereas Database
Designers are more involved at the start of a project, programmers are involved for as
long as the database is in use and changes and amendments need to be performed. Many
programmers joining a team will have no contact with the designer who left after the
database deployment. On legacy systems it may even be difficult to find any manuals
regarding how the system was designed.

When to Use SQL

My students frequently ask, "When should I be using SQL?" They may have
created a database in a lower level desktop system and are considering switching to a
DBMS that will require SQL. SQL is a language, not a software product, so the real
question is best phrased as "When do I need to use a heavy-duty DBMS, which would
then require me to start communicating in SQL?" There are several factors to consider
which we'll look at in turn in this section.

Scaling

Many small sites or applications start in desk top systems such as Access. As they
grow, a number of problems become apparent with the Access JET database engine. The
primary problem is that it was never designed to support many users at once. Database
software designed for the desktop generally fails when more than a few people try to use
the data at the same time. Microsoft Access will perform well if five users are on a LAN.
When you get to ten or twenty concurrent users, problems begin. Obviously a desktop
database cannot handle the problems introduced by large numbers of concurrent hits from
a web site.

Second, the Access file-based system becomes fragile when the amount of data
starts to climb into the gigabyte range. Lower scale systems like Access also lack the
security that more powerful systems offer. Access databases, for example, are quite easy
to copy and walk away with. The individual installations can also be readily accessed.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
So for these reasons companies move from Access type desk top systems to a
more robust DBMS. Almost all of these heavy duty DBMS rely on SQL as the main form
of communication. In summary, although there is nothing about SQL itself that concerns
scaling; there is a need to use SQL in order to communicate with DBMS that scale well.

Speed

Page 195
Java Programming

When SQL-enabled DBMS first appeared they were slower than previous DBMS.
However, as they have taken over the market during the last ten years, SQL data engines
have been the focus of an intense effort to improve performance. There are heated
contests between the major vendors for bragging rights to the fastest machine with the
lowest transaction price. But the intense competition drives the vendors to produce faster,
more robust DBMS that work at lower and lower costs per transaction.

When you consider your quest for improved speed, consider that pure speed
problems will be evident at all times, not just at peak usage. They are usually the result of
more complex queries, particularly with the advanced techniques we study later like
multiple joins on data that cannot be indexed. Although SQL itself does not cure speed
problems, the implementation of faster DBMS does, and those faster DBMS will
probably require communications in SQL.

Price
It is more expensive to run a server-centric DBMS (that only speaks SQL) than it
is to use a desktop system such as Paradox or Access (for which you do not necessarily
need to use SQL). First, the software is more expensive. Second, in most cases you have
to run more expensive operating systems in order to support the DBMS. Third, you have
to tune the OS differently to optimize for a DBMS than for other applications, so you
generally need a server dedicated to the DBMS. Last, you will need personnel with more
expensive qualifications.

However, the price of hardware and software is frequently the smallest item in an
IT budget. As your data center grows, at some point the reliability, performance and
standardization benefits of a DBMS that uses SQL will outweigh the cost.

A note on price – you can get started on a SQL-centric DBMS for almost nothing.
In fact, we have included the 120-day trial version of Microsoft SQL Server 2000 with
this book. You can download other trial versions such as Oracle Personal Edition. But
remember, that these are trial versions; when you are ready to build your business on a
SQL-centric DBMS you will be paying a considerable amount more than you did for
Access.

Universality

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
An alternative to using SQL statements is to write code in a procedural language
like C++. The problem with this approach is that you are then closely tied to the
procedural language, the metadata and the specific DBMS. If there is a change in the
structure of the tables the code must change. If a new DBMS is installed, most of the
code must be revised to mesh with the new DBMS system of pointers, recordset
definitions, etc. But by using SQL statements almost all changes are handled by the
DBMS, behind the scenes from the programmer.

Analytic Capabilities

Page 196
Java Programming

An advanced feature of SQL (which is beyond the scope of this book) is the
emergence of analytical tools that allow managers to extract business knowledge from
large amounts of data. These tasks frequently require the constructions of multi-
dimensional aggregates of data. These tools are referred to by the generic names of
Online Analytical Processing (OLAP), Decision Support Systems (DSS) and Executive
Information Systems (EIS). Each vendor then has proprietary trademarks for their
version. All of these tools are only available in full-scale DBMS that require SQL for
their means of communication.

3.2.10 SQL

SQL (Structured Query Language) was born as consequence of the enormous


relational databases diffusion. Through SQL language it is possible to list, edit and delete
data in relational databases. A long standardization work, managed by international
organization like ANSI and OSI, contributed to the diffusion of an unique SQL syntax.
The result is that nowadays about all DBMS, relational implements an SQL parser.

SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is


used to communicate with a database. According to ANSI (American National Standards
Institute), it is the standard language for relational database management systems. SQL
statements are used to perform tasks such as update data on a database, or retrieve data
from a database. Some common relational database management systems that use SQL
are: Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc. Although most database
systems use SQL, most of them also have their own additional proprietary extensions that
are usually only used on their system. However, the standard SQL commands such as
"Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used to accomplish
almost everything that one needs to do with a database. This tutorial will provide you
with the instruction on the basics of each of these commands as well as allow you to put
them to practice using the SQL Interpreter.

Data Types

The data to be held within each field of a given record will possess certain
characteristics in terms of size (length measured in characters or digits) and type
(numeric, alphabetic, dates, etc). Each field of a record is allocated a particular data type
which describes the allowed characteristics of the data to be held by the field and further
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
indicates the range of operations which can be carried out on the field; for example,
arithmetic operations would be valid on fields containing numeric data but not on fields
containing an address or a narrative description.

Keys

A key is a field or combination of fields used to identify a record. When a key


uniquely identifies a record it is referred to as the primary key.

Page 197
Java Programming

SQL was developed by IBM Corporation Inc. in mid 1970. Oracle corporation
introduced the first commercially available implementation of SQL.

ANSI (American National Standard Institute) adopted SQL as a standard


language for RDBMS, in Oct. 1986.

Features of SQL

 Non-procedural language
 Unified language
 Common language for all relational databases.

SQL is made up of three sub languages such as:

DDL
Data Definition language (DDL) - Allows one to define database objects at the
conceptual level. It consists of commands to create objects and alter the structure of
objects, such as tables, views, indexes etc. Commonly used DDL statements are Create,
Drop etc. If we have to create table Student then use the following syntax:

Create Table Student


(Student_id Integer Primary Key,
Student_nm Varchar (30),
Course_id Varchar (15),
Phone Varchar (10),
Address Varchar (50))
Consists of commands to create, alter, drop the objects, such as tables, views,
indexes etc.,

Data Manipulation Language (DML)


Data Manipulation language (DML) - Allows one to retrieve or update data within
a database. It is used for query, insertion, and deletion and updating of information stored
in databases. E.g.: Select, Insert, Update, Delete.
E.g.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
1.Select * From Student where Student_nm = 'Dave'
2.Delete Student where Student_nm = 'James'
3.Update Student Set Address = '146, Fauntleroy Way Sw, Seattle- 98116' where
Student_nm = 'Jim'
Used for query, insertion, updation and deletion of information stored in database.

Data Control Language (DCL)


Data control language (DCL) -In RDBMS one of the main advantage is the
security for the data in the database. You can allow some user to do a specific operation

Page 198
Java Programming

or all operations on certain objects. Examples for DCL statements are Grant, Revoke
statements. Used for controlling data and access to the database through Granting and
Revoking privileges on objects. SQL statements are generally called as query. Through a
query it is possible, according to the keyword used, to add, edit, delete fields (and
more...). SQL*plus is a software product from Oracle Corporation that allows users to
interactively use the sql commands to access Oracle database.

3.2.11 Oracle Data types

The different datatypes are:

CHAR (Size) To store character type of data. Default and minimum size is 1 and
Maximum size is 2000.

VARCHAR2 (Size) Similar to CHAR but can store variable number of characters
Minimum size is 1 and maximum size is 4000.

NUMBER (p,s) Stores fixed and floating numbers. Maximum precision (p) and /or
scale(s) is 38.

DATE Stores point-in-time values (i.e. dates and times) in table. Date data
is stores in fixed-length fields of seven bytes each. Default format
is DD-MON-YY.

LONG Can store up to 2GB of characters.

RAW (Size) Used to store binary data such as graphics, sound etc. Maximum
size is 2000 bytes.

LONGRAW Contains raw binary data otherwise the same as a LONG column.
The values entered must be in hex notation. Maximum size is 2
GB.

CLOB A character large objects containing single byte characters.


Maximum size is 4 GB.

NCLOB ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A character large objects containing fixed-width multi-byte
characters. Maximum size is 4GB.

BLOB Binary Large Objects. Maximum size is 4 GB.

BFILE Binary File. Contains a locator to a large binary file stored outside
the database. Enables byte stream I/O access to external LOBs
residing on the database server, Maximum size is 4 GB.

Page 199
Java Programming

Connection to SQL

Creating tables

Tables are created using Create table command

Syntax:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Create Table <table-name> (<column-name1> <datatype(size)> <constraint
specification>, …);

Example: create table employee (eno number(4) not null, ename char(20), job
varchar2(9), manager number(4), hiredate date, salary number(7,2), comm Number(7,2),
deptno number(2));

Once the command is executed, a message “Table created” will be shown as given below.

Page 200
Java Programming

Creating table from another table

Tables can be created from an already existing tables with all the columns or
specific columns and also with or without records

Syntax:

Create table <target table name> as select * from <source table name>

Example:

Create table NewEmp as select * from employee;

Constraints:

Constraints are a part of the table definition that limits the values entered to its
columns.

Different types of constraints are :

Primary key
Foreign key / References
Check
Unique
Not null
Null
ANNAMALAI
ANNAMALAI UNIVERSITY
Default UNIVERSITY
While creating a table, constraints can be specified to the column(s). SQL will reject any
value that violates the criteria that were defined.

Primary key

It is a column in a table, which must contain a unique value, which can be used to
identify each and every row of a table uniquely. The column will maintain the UNIQUE
Page 201
Java Programming

value and will not accept the NULL value for any single record. In a table one primary
key is allowed.

Reference / Foreign key constraints:

A foreign key is a combination of columns with values based on the primary key
values from another table. A foreign key constraint, also known the Referential Integrity
constraint, specifies that the values of the foreign key correspond to actual values of the
primary key in another table.

Check Constraint

SQL provides the CHECK constraint, which allows the user to define the range of
values to the column(s).

Unique Constraint

This constraint ensures that the value entered into a column are unique.

Not Null Constriant

This constraint will expect some value to be entered in the specified columns.
Any attempt to pull NULL value in that column will be rejected. Columns without NOT
NULL constraint will allow NULL values.

Default constraint

While inserting a row into a table without having value for a column, SQL will
insert a default value to the specified column.

Check Constraint

Checks for a particular condition on a column.

Insertion:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 Insert command is used to insert rows in the table.

 Values can be inserted for all the columns or for all the columns or for the selected
columns.

 In the insert into command, values can also be given through query, however the
columns of the table being inserted must match the columns output by the subquery.

 To insert multiple values, we can use substitution parameter “&” with Insert
command.

Page 202
Java Programming

Example 1 for insertion : As shown below

Example 2 for insertion :

To view the structure of the table the following comman is used.

sql>desc tablename;

sql>desc employee;

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 203
Java Programming

Alter/Modify table

Through Data Definition Language (DDL) we can alter/modify the tables,


sequences etc.,

Alter/Modify the tables involve:


1. changing datatype of the column(s)
2. Increasing/Decreasing width of the datatypes
3. Adding columns to the table
4. Dropping/Removing a column(s) from the table

Example:

The following example adds primary key constraint to the already created
employee table.

sql> alter table employee add constraint con_c1 primary key(eno);

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Viewing & Updation

To view the records from a database the following query is used.


To view all records from the table, the wild character ‘*’ is used.

Syntax:

Page 204
Java Programming

Select * from <tablename>;

Example :

Select * from emp;

To view selected columns the syntax is given below.

Syntax:

Select <columnname1>, <columnname2>, … from <tablename> where <condition>;

Updation:

 Update command is used to update the columns in a table.


 Values of a single column or a group of columns can be updated.
 Update statement can affect a single row or a set of rows depending on the WHERE
clause in the update statement.

Syntax:

Update <tablename> set <columnname> = <newvalue> <where condition>;

Example:

Sql> update emloyee set salary=5000 where eno=302;


The output is shown below:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Note: The identical rows in the above output can be deleted as said below:

Deletion:

Delete command is used to delete a row(s) from the table.

Page 205
Java Programming

All the rows will be deleted with a single DELETE command, if the where clause is not
specified.
DELETE command is used to delete a single row or a set of rows from the table , is
subject to the WHERE clause.

Syntax:
Delete <table-name> <where condition>;
Example

Delete employee where eno=201; or Delete from employee where eno=201;

Output is shown below:

3.3 Revision Points

DBMS
A DBMS is a software program that typically operates on a database server or mainframe
system to manage data, accept queries from users, and respond to those queries.

SQL
SQL is viewed as an interface to access data on many different types of database systems,
including mainframes, midrange systems, UNIX systems, and network servers.

RDBMS
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
An RDBMS is a system that stores data in multiple databases called tables. The tables
can be related and combined in a number of ways to correlate and view data.

OODBMS
An object database is designed to handle a variety of different data types, including
documents, images, audio, and video. It also stores methods, which include properties
and procedures that are associated directly with objects in the database. In addition, new
object types can be created as necessary to define any type of information.

Page 206
Java Programming

ODBC
ODBC is a database connectivity architecture that provides a way for clients to access a
variety of heterogeneous databases.

JDBC
The Java Database Connectivity (JDBC) API includes classes that can handle most
database access needs. From simple select statements to processing the results of a
complex stored procedure to accessing more than one database at a time, the JDBC
provides the functionality most applications need.

3.4 Intext Questions

1. What are the various steps in creating a DSN?


2. What are the different types of SQL statements?
3. What is ODBC?
4. What are the different types of JDBC drivers?
5. State the difference between DBMS, RDBMS and ORDBMS

3.5 Summary

 Data is collection of records.


 The hierarchical DBMS’s organized and model their data in a hierarchical
fashion as a collection of trees.
 The network databases arrange its data as a directed graph and have a standard
navigational language.
 In the relational database, all data is represented as simple tabular data
structures (relations), which may be accessed using a high-level non-
procedural language.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 The object-relational DBMS (ORDBMS) is the newest commercial breed of
DBMS’s which embraces some object-oriented features and encapsulates
these features into an RDBMS, creating an ORDBMS.
 A database contain 4 types of data:
 Users Data
 Meta Data
 Indexes
 Application Metadata
 Also Business Rules or Logics are stored in database.

Page 207
Java Programming

 A DBMS may contain many databases that can be used for separate purposes
or combined to provide useful information
 Relational databases are databases in which data is organized into tables.
Tables are organized by grouping data about the same subject together. The
tables are related back to each other by the database engine when requested.
 E.F.Codd formulated rules for Relational Database Management Systems

3.6 Terminal Exercises

1. Write down the Evolution of RDBMS.


2. Write a short note on SQL.
3. Write a program to create a table of your own structure.
4. Try to insert and update a record using JDBC.

3.7 Supplementary Materials

1. Herbert Schildt, “Java 2: The Complete reference”, TMH, Fourth Edition,


2001.
2. E.Balagurusamy, “Programming with JAVA”, TMG, 1999.
3. R.Krishnamoorthy & S.Prabu, “Internet and Java Programming”, New Age
International, 2002.
3.8 Assignments
Create an address book described as following:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The personal information includes:

name varchar(15)
age int
address varchar(15)
phone varchar(15)
email varchar(20)
Birthday date

Page 208
Java Programming

The program should do the following:

1. Show all the records in the table.

2. insert a record and display it again

3. delete a record and display the records

4. Update a person’s address and displays the records.

5. Implement the above programs with Java Application.

3.9 Suggested Reading/Reference Books/Set Books

1. http://www.oracle.com
2. http://www.jcc.com/sql_stnd.html
3. http://www.sun.com/java/list.html

3.10 Learning Activities

1. Collect Information on Normalization (not covered in this lesson) from the


Internet.
2. Collect Information on SQL.
3.11 Keywords

DBMS RDBMS
OODBMS SQL
Normalization ODBC

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 209
Java Programming

UNIT – IV

Snapshot

 Client/Server Software Architectures-An Overview


 Remote Database Access
 ODBC and JDBC drivers
 Architecture Model
 Types of JDBC technology drivers
 Connecting to an ODBC DATA SOURCE
 Developing JDBC based application
 Examples for Creating, Inserting, Updating, Deleting rows
 Examples for Writing procedure, Calling procedure
 Examples for Passing parameter in query

4.0 Introduction
This unit provides a detailed description about the Remote Database Access and
associated interface. It includes ODBC, JDBC drivers and types of JDBC drivers. At the
end of the lesson you learn about how the end user machines exchange data from one
system to another system.

4.1 Objective
At the end of this unit you will have an understanding of
 Client/Server Software Architectures
 ODBC
 JDBC
 JDBC drivers
4.2 Content

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4.2.1 Client/Server Software Architectures-An Overview
The term client/server was first used in the 1980s in reference to personal
computers (PCs) on a network. The actual client/server model started gaining acceptance
in the late 1980s. The Client/server software architecture is a versatile, message-based
and modular infrastructure that is intended to improve usability, flexibility,
interoperability and scalability as compared to centralized, mainframe, time sharing
computing. A client is defined as a requester of services and a server is defined as the
provider of services. A single machine can be both a client and a server depending on the
software configuration.

Page 210
Java Programming

Mainframe architecture
With mainframe software architectures all intelligence is within the central host
computer. Users interact with the host through a terminal that captures keystrokes and
sends that information to the host. Mainframe software architectures are not tied to a
hardware platform. User interaction can be done using PCs and UNIX workstations. A
limitation of mainframe software architectures is that they do not easily support graphical
user interfaces. In the last few years, mainframes have found a new use as a server in
distributed client/server architectures.

File sharing architecture


The original PC networks were based on file sharing architectures, where the
server downloads files from the shared location to the desktop environment. The
requested user job is then run (including logic and data) in the desktop environment. File
sharing architectures work if shared usage is low, update contention is low, and the
volume of data to be transferred is low. In the 1990s, PC LAN (local area network)
computing changed because the capacity of the file sharing was strained as the number of
online user grew (it can only satisfy about 12 users simultaneously) and graphical user
interfaces (GUIs) became popular (making mainframe and terminal displays appear out
of date). PCs are now being used in client/server architectures.

Client/server architecture
As a result of the limitations of file sharing architectures, the client/server
architecture emerged. This approach introduced a database server to replace the file
server. Using a relational database management system (DBMS), user queries could be
answered directly. The client/server architecture reduced network traffic by providing a
query response rather than total file transfer. It improves multi-user updating through a
GUI front end to a shared database. In client/server architectures, Remote Procedure
Calls (RPC’s) or standard query language (SQL) statements are typically used to
communicate between the client and server.

Two tier architectures


With two tier client/server architectures, the user system interface is usually
located in the user's desktop environment and the database management services are
usually in a server that is a more powerful machine that services many clients. Processing

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
management is split between the user system interface environment and the database
management server environment.

The database management server provides stored procedures and triggers. There
are a number of software vendors that provide tools to simplify development of
applications for the two-tier client/server architecture.

The two-tier client/server architecture is a good solution for distributed computing


when work groups are defined as a dozen to 100 people interacting on a LAN
simultaneously. It does have a number of limitations. When the number of users exceeds
100, performance begins to deteriorate. This limitation is a result of the server

Page 211
Java Programming

maintaining a connection via "keep-alive" messages with each client, even when no work
is being done.

A second limitation of the two tier architecture is that implementation of


processing management services using vendor proprietary database procedures restricts
flexibility and choice of DBMS for applications. Finally, current implementations of the
two-tier architecture provide limited flexibility in moving (repartitioning) program
functionality from one server to another without manually regenerating procedural code.

Client Server

Figure of Two-Tier Architecture

Three tier architectures


The three-tier architecture (also referred to as the multi-tier architecture) emerged
to overcome the limitations of the two-tier architecture. In the three-tier architecture, a
middle tier was added between the user system interface client environment and the
database management server environment. There are a variety of ways of implementing
this middle tier, such as transaction processing monitors, message servers, or application
servers. The middle tier can perform queuing, application execution, and database
staging.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Client Middle-Tier Server Database Server

Figure: Three-Tier Architecture

Page 212
Java Programming

Distributed/collaborative enterprise architecture


The distributed/collaborative enterprise architecture emerged in 1993. This
software architecture is based on Object Request Broker (ORB) technology, but goes
further than the Common Object Request Broker Architecture (CORBA) by using
shared, reusable business models (not just objects) on an enterprise-wide scale.
The benefit of this architectural approach is that standardized business object
models and distributed object computing are combined to give an organization flexibility
to improve effectiveness organizationally, operationally, and technologically. An
enterprise is defined here, as a system comprised of multiple business systems or
subsystems. Distributed/collaborative enterprise architectures are limited by a lack of
commercially available object orientation analysis and design method tools that focus on
applications
Remote Database Access
In Remote Database Access, a database client communicates to the database
server on behalf of the user. It provides the user the required information.
Figure below shows a client accessing a remote database

Client Database
Database Server
Program Program Database

4.2.2 ODBC and JDBC drivers


Database drivers are used by the Database clients to send SQL statements to
database servers and to receive result set and other responses from the servers. JDBC
drivers are used by Java application and applets to communicate with database servers.

Microsoft’s ODBC

Database
ODBC Server 1
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY Driver

ODBC
Database Driver
ODBC API Database
Client
Server 2

ODBC Database
Driver
Server 3

Page 213
Java Programming

Microsoft established a common standard for communicating with databases,


called Open Database Connectivity (ODBC). Here the client communicates with the
ODBC API and which in turn allows accessing the required respective database servers.
Figure below shows that a client can access many database servers via ODBC drivers.

ODBC
Open Database Connectivity (ODBC) is an API (Application Program Interface)
module written in C. It allows data exchanging between different kinds of databases
which implement SQL query language. At the beginning ODBC was introduced by
Microsoft (1992) to connect its DBMS to the ones produced by different software
companies. ODBC soon became a standard gaining a great diffusion all over the world. It
is build up by an ODBC Manager and a Driver Manager distributed in 16 and 32 bit
versions. Windows's ODBC Manager allows users to manage, through a user friendly
interface, connections to one or more databases.

Driver Manager's task is loading drivers, checking for errors, managing multiple
database connections and updating ODBC.INI file. Database to which we want to
connect to, can be on the local file system or on remote servers. ODBC connectivity
functions will work in both these cases.

ODBC security

Given that all shared data pass through the ODBC driver, it is important to
underline it plays a leading role in the systems' security. At the moment, on the other
hand, the current ODBC version doesn't implement any data protection function. This
means there are no modules that takes care of encoding information passing thorough the
stream that connects the ODBC driver to the datasource. This problem gets more serious
when we haven't the datasource and the application program on the same (physical)
system, but we are working in a client server environment. This is the case in which an
encoding function, perhaps like secret key algorithms as DES, RC2, RC4, already used in
many commercial and internet applications, could be useful to solve the problem.

JDBC

JDBC means Java Database Connectivity. It provides a standard API for


accessing virtually any data sources, from relational databases to spreadsheets and flat
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
files. JDBC establishes a connection with a database or access any tabular data source,
send SQL statements and process the results.

JDBC (Java Database Connectivity) is an interface defined by Javasoft in 1996 (in


march version 0.5 was released, in august version 1.01 was ready). JDBC allows Java
applications and applets to communicate with JDBC enabled DBMS. JDBC is made up
of many classes and interfaces built to perform connections and to communicate with
datasources. According to the way JDBC has been developed, a datasource is not
necessary a database.

Page 214
Java Programming

JDBC based Java applications use JDBC's Connection object to connect to a


database. The right driver has to be loaded before connecting. Then a new object in
instantiated to hold the SQL statement is used to request the execution. This object is first
sent to the driver, and then the driver translates it and passes the query to the DBMS. The
DBMS executes the query and sends back to the driver the result. This result reaches the
application through the JDBC driver.

Javasoft has developed a JDBC-ODBC driver, called JDBC-ODBC Bridge. It is


able to convert JDBC methods in ODBC calls. JDBC-ODBC Bridge allows Java
applications to communicate with all ODBC enabled DBMS. This means Java developers
can benefit of the great ODBC diffusion using a large number of different DBMS
products without change their applications' code. JDBC drivers do not directly
communicate with as many databases using ODBC. JDBC provides a common database
programming API for java programs.

4.2.3 Architecture Model

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4.2.4 Types of JDBC technology drivers

JDBC technology drivers fit into one of four categories:

1. A JDBC-ODBC Bridge provides JDBC API access via one or more ODBC
drivers. Note that some ODBC native code and in many cases native database client code
must be loaded on each client machine that uses this type of driver. Hence, this kind of
driver is generally most appropriate when automatic installation and downloading of a

Page 215
Java Programming

Java technology application is not important. Figure below shows: A database client can
talk to many Database servers via JDBC ODBC drivers.

Type 1 Driver

Database
ODBC Driver Server 1

ODBC Driver
Java
JDBC ODBC Database
Database
Bridge Server 2
Client

ODBC Driver
Database
Server 3

2. A native-API partly Java technology-enabled driver converts JDBC calls into


calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like
the bridge driver, this style of driver requires that some binary code be loaded on each
client machine. Figure below shows Type 2 JDBC driver uses a vendor specific protocol
and must be installed on each client.

Java Database Type 2 JDBC Database Server


Client driver
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY Vendor Specific
Protocol
3. A net-protocol fully Java technology-enabled driver translates JDBC API calls
into a DBMS-independent net protocol which is then translated to a DBMS protocol by a
server. This net server middleware is able to connect all of its Java technology-based
clients to many different databases. The specific protocol used depends on the vendor. In
general, this is the most flexible JDBC API alternative. It is likely that all vendors of this
solution will provide products suitable for Intranet use. In order for these products to also
support Internet access they must handle the additional requirements for security, access

Page 216
Java Programming

through firewalls, etc., that the Web imposes. Several vendors are adding JDBC
technology-based drivers to their existing database middleware products.
This is the JDBC-Net pure Java driver, which consists of Java drivers that speak a
standard network protocol such as HTTP to a database access server. The database access
server then translates the network protocol into a vendor specific database protocol.
Figure below shows Type 3: A database client that can talk to many database access
servers via JDBC drivers.

Type 3 Driver

Database
Server 1

Java Database
Database
Database Server 2
Access Server
Client

Database
Server 3

4. A native-protocol fully Java technology-enabled driver converts JDBC


technology calls into the network protocol used by DBMSs directly. This allows a direct
call from the client machine to the DBMS server and is a practical solution for Intranet
access. Since many of these protocols are proprietary the database vendors themselves
will be the primary source for this style of driver. Several database vendors have these in
progress. Figure below show Type 4 JDBC driver.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Type 4 Driver

Java Database Type 4 JDBC Database Server


Client driver

Vendor Specific
Protocol

Page 217
Java Programming

A type 3 driver uses a separate database access server. Type 4 driver


communicates with the database server using a vendor specific protocol. Type 3 and
Type 4 is pure Java drivers.

4.2.5 Connecting to an ODBC DATA SOURCE

A database can be created and managed through Java applications. Java


application that uses a JDBC-ODBC bridge to connect to a database file either a dbase,
Excel, FoxPro, Access, SQL Server, Oracle or any other. Open the ODBC Data source
from the control panel. A database can be created and managed through Java
applications.

Connecting to an ODBC Data source

Select Control Panel

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 218
Java Programming

Select “Data Sources (ODBC)” icon

Select the Ms-ODBC for oracle or any other driver that felt is required.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Once clicking the finish button, the following window appears asking for Data source
name, description etc.,

Page 219
Java Programming

Provide “Data Source Name”, “Desription”, “UserName” and “Server” name. The
username and Server name can be obtained from the Administrator. Click on the ok
button.

“MyDSN” that has been created as DSN, can be seen in the figure below.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The DSN is now ready and the Java code can be written to access the database's
tables.

4.2.6 Developing JDBC based application

JDBC is implemented as the java.sql package. This package contains all the
JDBC classes and methods as shown below.

Page 220
Java Programming

Type Class

Driver java.sql.Driver
java.sql.DriverManager
java.sql.DriverPropertyInfo

Connection java.sql.Connection

Statements java.sql.Statement
java.sql.PreparedStatement
java.sql.CallableStatement

ResultSet java.sql.ResultSet

Errors/Warnings java.sql.SQLException
java.sql.SQLWarning

Metadata java.sql.DatabaseMetaData

Date/Time java.sql.Date
java.sql.Time
java.sql.Timestamp

Miscellaneous java.sql.Types
java.sql.DataTruncation

JDBC URL

JDBC identifies a database with an URL. The URL is of the form:

Jdbc:<subprotocol>:<subname related to the DBMS/protocol>

Example of how an URL looks is given below:

jdbc:odbc:<ODBC DSN>; User=<username>;PW=<password>

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Driver, DriverManager and related methods (below table)

Return Type Method Name Parameter


java.sql.Driver
Connection connect (String url,
java.util.Properties info)

Boolean AcceptsURL (String url)

Page 221
Java Programming

DriverPropertyInfo[] GetPropertyInfo (String url,


java.util.Properties info)

Int GetMajorVersion ()
Int getMinorVersion ()
Boolean jdbcCompliant ()
java.sql.DriverManager
Connection getConnection (String url,
java.util.Properties info)

Connection getConnection (String url. String user.


String password)

Connection getConnection (String url)


Driver getDriver (String url)
void registerDriver (java.sql-Driver driver)

void deregisterDriver (Driver driver)


java.util.Enumeration getDrivers ()

void setLoginTimeout (int seconds)

int getLoginTimeout

void setLogStream (java.io.PrintStream out)

java.io.PrintStream getLogStream ()

Void println (String message)

Class Initialization Routine

Void ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY Initialize ()

The Connection class is one of the major classes in JDBC. It packs a lot of
functionality, ranging from transaction processing to creating statements, in one class as
seen in Table below.

Page 222
Java Programming

Return Type Method Name Parameter


Statement-Related Methods
Statement create Statement ()
PreparedStatement prepareStatement (String sql)
CallableStatement prepareCall (String sql)
String nativeSQL (String sql)
void close ()
Boolean isClosed ()
Metadata-Related Methods
DatabaseMetaData getMetaData ()
void SetReadOnly (boolean readonly)
Boolean IsReadOnly ()
void setCatalog (String catalog)
String getCatalog ()

SQLWarning getWarnings ()
void clearWarnings ()
Transaction-Related Methods
void setAutoCommit (booleanautoCommit)
Boolean getAutoCommit ()
void commit ()

Void rollback ()
void SetTransactionIsolation (int level)
Int GetTransactionIsolation ()
java. sql.Connection Methods and Constants

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A ResultSet provides access to a table of data. Executing a statement usually
generates a ResultSet object. The ResultSet object is actually a tabular data set; that is, it
consists of rows of data organized in uniform columns.

Table below shows java.sql.ResultSet methods

RESULTSET PROCESSING

ResultSet columns within each row should be read in left-to-right order and each
column should be read only once.

Page 223
Java Programming

The JDBC driver attempts to convert the underlying data to the specified Java
type and returns a suitable Java value through the getXXX methods. See the JDBC
specification for allowable mappings from SQL types to Java types with the
ResultSet.getXXX methods.

Column names used as input to getXXX methods are case insensitive. When
performing a getXXX using a column name, if several columns have the same name, then
the value of the first matching column will be returned. The column name option is
designed to be used when column names are used in the SQL query. For columns that are
NOT explicitly named in the query, it is best to use column numbers. If column names
are used, there is no way for the programmer to guarantee that they actually refer to the
intended columns.
A ResultSet is automatically closed by the Statement that generated it when that
Statement is closed, re-executed, or used to retrieve the next result from a sequence of
multiple results.

Return Type Method Name Parameter


Boolean next ()
void close ()
Boolean wasNull ()
Get Data By Column Position
java.io.InputStream getAsciiStream (int columnlndex)

java.io.InputStream getBinary Stream (int columnIndex)

boolean getBooIean (int columnIndex)

byte getByte (int columnIndex)

byte[] getBytes (int columnIndex)

java.sql.Date getDate (int columnlndex)

double getDouble (int columnlndex)

float
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY getFloat (int columnlndex)

int getInt (int columnlndex)

long getLong (int columnlndex)

java.lang.Bignum getBignum (int columnlndex, int


scale)

Object getObject (int


columnlndex)
Page 224
Java Programming

short getShort (int columnlndex)

String getString (int columnlndex)

java.sql.Time getTime (int columnlndex)

java.sql.Timestamp getTimestamp (int


columnlndex)
java.io.InputStream getUnicodeStream (int columnlndex)

Get Data By Column Name


java.io.InputStream getAsciiStream (String
coiumnName)
java.io-InputStream getBinary Stream (String
coiumnName)
boolean getBoolean (String
coiumnName)
byte getByte (String
coiumnName)
byte[] getBytes (String
coiumnName)
java.sql.Date getDate (String
ColumnName)
double getDouble

float getFtoat (String


columnName)
int getint (String
columnName)
long getLong (String
columnName)
java.lang.Bignum getBignum (String
columnName, int
scale)
Object getObject (String

short
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
getShort
columnName)
(String
columnName)
String getString (String
columnName)
java.sql.Time getTime (String
columnName)
java.sql.Timestamp getTimestamp (String
columnName)
java.io.InputStream getUnicode Stream (String
columnName)
Page 225
Java Programming

int findColumn (String


columnName)
SQLWarning getWamings ()

void clearWarnings ()

String getCursorName ()
ResultSetMetaData getMetaData ()

java.sql-ResultSet Methods

The ResultSet methods even though there are many are very simple. The major
ones are the getXXXQ methods. The getMetaDataQ method returns the meta data
information about a ResultSet- The DatabaseMetaData also returns the results in the
ResultSet form. The ResultSet also has methods for the silent SQLWarnings, It is a good
practice to check any warnings using the getWarningQ method that returns a null if there
are no warnings.

Other Jdbc Classes

java.sqLDate

This package gives a Java program the capability to handle SQL DATE
information with only year, month, and day values.

Return Type Method Name Parameter


Date Date (int year, int month, int
day)
Date Date (long date)

Date valueOf (String s)

String toString ()
int getHours ()
ANNAMALAI
ANNAMALAI UNIVERSITY
int UNIVERSITY getMinutes ()

int getSeconds ()

void setHours (int Hr)


void setMinutes (int Min)
void setSeconds (int Sec)

void setTime (long date)

Page 226
Java Programming

java.sql.Date Method

java.sql.Time

As seen in Table below, the java.sql.Time adds the Time object to the
java.util.Date package to handle only hours, minutes, and seconds. java.sql.Time is also
used to represent SQL TIME information.

Return Type Method Name Parameter

Time Time (int hour, int minute, int


second)
Time Time (long time)
Time Time valueOf(String s)
String toString ()
Int getDate ()
int getDay ()
int getMonth ()
int getYear ()
void setDate (int date)
void setMonth (int month)
void setTime (int time)
void SetYear (int year)
java.sql.Time Methods

java. sql Timestamp

The java.sql.Timestamp package adds the TimeStamp class to the java.util.Date


package.(Table given below). It adds the capability of handling nanoseconds. But the
granularity of the subsecond timestamp depends on the database field as well as the
operating system.

ANNAMALAI
ANNAMALAI UNIVERSITY
Return Type UNIVERSITY Method Name Parameter
TimeStamp TimeStamp (int year, int month, int date, int
hour, int minute, int second, int
nano)
TimeStamp TimeStamp (long time)

TimeStamp valueOf (Strings)

String toString ()

Page 227
Java Programming

int getNanos ()
OS
void setNanos (int n)
OS
boolean after (TimeStamp ts)

boolean before (TimeStamp ts)


boolean equals (TimeStamp ts)
java.sql.Timestamp Methods

JDBC Calls

Opening a Connection

Four parameters are required to open a JDBC connection:

url Database URL


driverName JDBC Driver
userName User Name
password Password

A connection is opened with the following steps:

Load JDBC driver

Class drvClass = Class.forName(m_driverName);


DriverManager.registerDriver((Driver) drvClass.newInstance());

Open a connection

Connection m_con = DriverManager.getConnection(m_url, m_userName, m_password);


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
After all the works have been done, the Connection should be closed with the following
code:

m_con.close();

Sending SQL Statements

Once a connection is established, it is used to pass SQL statements to its


underlying database. JDBC provides three classes for sending SQL statements to the

Page 228
Java Programming

database, where PreparedStatement extends from Statement, and CallableStatement


extends from PreparedStatement:

Statement For simple SQL statements (no parameters).


For SQL statements with one or more IN parameters, or
PreparedStatement
simple SQL statements that are executed frequently.
CallableStatement For executing SQL stored procedures.

The Statement interface provides three different methods for executing SQL statements:

executeQuery For statements that produce a single result set.


For executing INSERT, UPDATE, or DELETE statements and also SQL
executeUpdate
DDL (Data Definition Language) statements.
For executing statements that return more than one result set, more than
execute
one update count, or a combination of the two.

A Statement object is used with the following steps:

Create a statement

Statement stmt = m_con.createStatement();


Statement Statement stmt = m_con.createStatement(int
resultSetType, int resultSetConcurrency);

PreparedStatement pstmt =
m_con.prepareStatement(String sql);

PreparedStatement pstmt =
m_con.prepareStatement(String sql, int resultSetType,
int resultSetConcurrency);
PreparedStatement
The sql parameter could contain one or more '?' s in it.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Before a PreparedStatement object is executed, the
value of each '?' parameter must be set by calling a
setXXX method, where XXX is the appropriate type for
the parameter. For example, if the parameter has a Java
type of String, the method to use is setString.

CallableStatement cstmt =
m_con.prepareCall(String sql);
CallableStatement CallableStatement cstmt =
m_con.prepareCall(String sql, int resultSetType,
int resultSetConcurrency);

Page 229
Java Programming

The sql parameter is in the form of "{call


<stored_procedure_name>[(arg1, arg2, ...)]}" or "{? =
call <stored_procedure_name>[(arg1, arg2, ...)]}".
It could contain one or more '?'s in it, which indicate IN,
OUT, or INOUT parameters. The value of each IN
parameter is set by calling a setXXX method, while
Each OUT parameter should be registered by calling a
registerOutParameter method.

Execute the statement

ResultSet res = stmt.executeQuery(String sql);


Statement int rowCount = stmt.executeUpdate(String sql);
boolean result = stmt.execute(String sql);
ResultSet res = pstmt.executeQuery();
PreparedStatement int rowCount = pstmt.executeUpdate();
boolean result = pstmt.execute();
CallableStatement Same as PreparedStatement.
Close the statement
After all the works have
been done, the Statement
stmt.close();
should be closed with the
following code:
Statement
PreparedStatement Same as Statement.
CallableStatement Same as Statement.

Processing the Results

A ResultSet contains all of the rows which satisfied the conditions in an SQL
statement, and it provides access to the data in those rows through a set of getXXX
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
methods that allow access to the various columns of the current row.
The ResultSet.next() method is used to move to the next row of the ResultSet,
making the next row become the current row. ResultSet.next() returns true if the new
current row is valid, false if there are no more rows. After all the works have been done,
the ResultSet should be closed with ResultSet.close() method.
Because of limitations imposed by some DBMSs, it is recommended that for
maximum portability, all of the results generated by the execution of a CallableStatement
object should be retrieved before OUT parameters are retrieved using
CallableStatement.getXXX methods.

Page 230
Java Programming

4.2.7 Examples
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("SELECT a, b, c FROM table");
while (res.next())
{
// print the values for the current row.
int i = res.getInt("a");
String s = res.getString("b");
float f = res.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f);
}
res.close();
stmt.close();

JDBC Programs

Example for creating a table

// Create Table

import java.sql.*;

public class CreateTab


{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =
DriverManager.getConnection("jdbc:odbc:Mydata","scott","tiger");

Statement stat = con.createStatement();


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
String str = "Create table Do1(Itemno number(2),Itemname
varchar2(20))";
stat.executeUpdate(str);
System.out.println("Table created successfully");
}
catch(SQLException e1)
{
System.out.println("Errors" + e1);
}
catch(ClassNotFoundException e2)
{
Page 231
Java Programming

System.out.println("Errors" + e2);
}
}
}

import java.sql.*;

The statement below imports all classes that belong to the package java.sql.*; All
the JDBC code will be delimited in the try block to avoid any exceptional handling.

Connection con =
DriverManager.getConnection("jdbc:odbc:Mydata","scott","tiger");

Specifies the type of driver as JdbcOdbcDriver


Example for inserting records into a table

// Insert into table

import java.sql.*;

public class InsertTab


{
public static void main(String args[])
{
ResultSet result;

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:Mydata","scott","tiger");

Statement stat = con.createStatement();

stat.executeUpdate("Insert into Do1 values(20,'Rexona')");


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
stat.executeUpdate("Insert into Do1 values(21, 'Lux')");
stat.executeUpdate("Insert into Do1 values(22,'Hamam')");
stat.executeUpdate("Insert into Do1 values(23,'Mysore san')");

System.out.println("Rows Inserted successfully");

result = stat.executeQuery("Select * from Do1");


while(result.next())
{

Page 232
Java Programming

System.out.println(result.getInt(1) + result.getString(2));
}
}
catch(Exception e)
{
System.out.println("Errors" + e);
}
}
}

Example for viewing rows from a table

// Viewing from emp table

import java.sql.*;

public class SelectEmp


{

public static void main(String args[])


{
String url = "jdbc:odbc:Mydata";
Connection con;
String s = "select ename from emp1";
Statement stmt;

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}

catch(java.lang.ClassNotFoundException e)
{
System.err.println("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
ANNAMALAI
ANNAMALAI UNIVERSITY
try
UNIVERSITY
{
con = DriverManager.getConnection(url,"scott","tiger");
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(s);
while(rs.next())
{
String s1 = rs.getString("ename");
System.out.println("Employee's name: " + s1);

Page 233
Java Programming

}
stmt.close();
con.close();
}
catch(SQLException ex)
{
System.err.println("SQLException:" + ex.getMessage());
}
}
}

Example for creating procedure

// Creating procedure

import java.sql.*;
class Call{
public static void main(String[] args)
{
Connection c = null;
Statement s = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch(ClassNotFoundException e)
{
System.err.println(e.getMessage());
}
try{
c = DriverManager.getConnection("jdbc:odbc:Myora","scott","tiger");
s = c.createStatement();

// code for creating a procedure

String str = "create or replace procedure p1(a in number,b out number) is "+
" begin "+
" b := a + 100;" +
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
"end;";
s.executeUpdate(str);
System.out.println("Procedure created");
s.close();
c.close();
} catch(SQLException e)
{
System.err.println(e.getMessage());
}

Page 234
Java Programming

}
}

Example for calling a procedure

// Calling procedure

import java.sql.*;

class Proc{
public static void main(String[] args)
{
Connection c = null;
CallableStatement cs = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch(ClassNotFoundException e)
{
System.err.println(e.getMessage());
}
try{
c = DriverManager.getConnection("jdbc:odbc:Myora","scott","tiger");
cs = c.prepareCall("{call p1(?,?)}");
cs.setInt(1,10);
cs.registerOutParameter(2,Types.NUMERIC);
cs.executeUpdate();
System.out.println(cs.getInt(2));
cs.close();
c.close();
}catch(SQLException e)
{
System.err.println(e.getMessage());
}
}
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Example for passing parameters in a query

// Passing parameters

import java.sql.*;
import java.util.*;

public class Callb


{

Page 235
Java Programming

public static void main(String args[])


{
ResultSet result;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:test","scott","tiger");
System.out.println("Connection established");

Statement stat = con.createStatement();

String s = "Select dname from dept where deptno=?";

PreparedStatement ps = con.prepareStatement(s);
ps.clearParameters();
int i = 10;
ps.setInt(1,i);

String str=" ";


result = ps.executeQuery();

while(result.next())
{
System.out.println("Printing");
str += result.getString(1) + "\n";
System.out.println(str);
}
}
catch(SQLException e1)
{
}
catch(Exception e)
{
System.out.println("Errors" + e);
}

}
} ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Example for updating a column in a table

// update

import java.sql.*;
import java.io.*;

Page 236
Java Programming

class UpdateDemo
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:mani","scott","tiger");
Statement st = con.createStatement();
st.executeUpdate("update mani set salary = 10000 where eno =2");
System.out.println("1 row updated");
st.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Example for deleting a record in a table


// Delete
import java.sql.*;
import java.io.*;
class DeleteDemo
{
public static void main(String args[])
{ try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:mani","scott","tiger");
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Statement st = con.createStatement();
st.executeUpdate("delete from mani where eno = 5");
System.out.println("1 row deleted");
con.commit();
st.close();
con.close();
}
catch(Exception e)
{ e.printStackTrace();
}
}
Page 237
Java Programming

Example for dropping a table


// Drop
import java.sql.*;
import java.io.*;

class DropDemo
{
public static void main(String args[])
{ try
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:mani","scott","tiger");
Statement st = con.createStatement();
st.executeUpdate("drop table dog");
System.out.println("Table Dropped");
st.close();
con.close();
}
catch(Exception e) { e.printStackTrace();
}
}
}

4.3 Revision Points


Client/Server
It is a relationship between two different applications running on two different machines
across a network.

Two Tier Architecture


In two tier client/server architectures, the user system interface is usually located in the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
user's desktop environment and the database management services are usually in a server
that is a more powerful machine that services many clients.

Three Tier Architecture


The three-tier architecture (also referred to as the multi-tier architecture) emerged to
overcome the limitations of the two-tier architecture. In the three-tier architecture, a
middle tier was added between the user system interface client environment and the
database management server environment.

Page 238
Java Programming

ODBC
ODBC is a database connectivity architecture that provides a way for clients to access a
variety of heterogeneous databases. In the multitiered client/server model of the Web and
intranets, the middle-tier server connects with back-end databases and the client has less
functionality. This means that the middle-tier server is responsible for running the
different ODBC drivers that connect with back-end databases.

JDBC
JDBC means Java Database Connectivity. It provides a standard API for accessing
virtually any data sources, from relational databases to spreadsheets and flat files. JDBC
establishes a connection with a database or access any tabular data source, send SQL
statements and process the results.

4.4 Intext Questions

1. What is Client/Server?
2. Define RPC.
3. Compare and contrast two tier and three tier architecture.
4. What are the four types of JDBC drivers in Java?
5. What are the statements available in Java.sql?

4.5 Summary

 Database Management Systems are repositories of information used by


applications
 ODBC API is a set of library routines that enable the program to access a variety
of databases
 JDBC provides a database programming API for java programs
 The different types of JDBC drivers are

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
 JDBC-ODBC bridge + ODBC driver
 Native API, partly Java driver
 JDBC-Net pure Java driver
 Native protocol, pure Java driver

Page 239
Java Programming

 The java.sql package contains classes that help in connecting to database, sending
embedded SQL statements to the database.
 The Connection object represents a connection to a database.
 The PreparedStatement object allows executing parameterized queries.
 The ResultSet object provides with methods to access data from a table.

4.6 Terminal Exercises

1. Write a short note on Callable Statement.


2. Explain the steps involved in Data Source Name creation.
3. Define Mainframe client/server architecture.
4. Write a short note on the following
i. ResultSetMetaData
ii. Connection
4.7 Supplementary Materials

1. Herbert Schildt, “Java 2: The Complete reference”, TMH, Fourth Edition,


2001.
2. E.Balagurusamy, “Programming with JAVA”, TMG, 1999.
3. R.Krishnamoorthy & S.Prabu, “Internet and Java Programming”, New Age
International, 2002.

4.8 Assignments

1. Write a brief note on JDBC.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
2. Create a table called emp with the following structure empno number(5),
empname varchar2(15), deptno number(3), salary number(5). Insert ten
records to above table. Display all the records in the table using JDBC-ODBC
bridge.

4.9 Suggested Reading/Reference Books/Set Books

1. http://www.oracle.com

Page 240
Java Programming

2. http://www.jcc.com/sql_stnd.html
3. http://www.sun.com/java/list.html

4.10 Learning Activities

1. Collect Information on Client/Server (not covered in this lesson) from the


Internet.
2. Collect Information on ODBC.

4.11 Keywords

Client
Server
Two Tier Architecture
Three Tier Architecture
Mainframe Architecture
Structured Query Language (SQL)
Common Object Request Broker Architecture (CORBA)
Remote Procedure Call (RPC)
Open Database Connectivity (ODBC)
Java Database Connectivity (JDBC)

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 241
Java Programming

UNIT - V

Snapshot

 Introduction to JavaScript
 Client side and server side JavaScript
 Incorporating JavaScript into HTML
 Data Types in JavaScript
 Declaring variables
 Operators
 Statements
 Core Objects
 JavaScript Objects
 Form Objects
 Event Handling
 What JavaScript is not?
 Introduction to VBscript
 Introduction to Servlets
 Use of Servlets
 Servlet Architecture Overview
 Servlet Lifecycle
 Writing the Servlet
 Lifecycle methods
 Servlet Chaining
 Servlet Features
 Introduction to JSP
 Servlet and JDBC

5.0 Introduction

JavaScript is what is known as a scripting language, which means that it is easier


to learn than a full-blown programming language such as C++ or Java. Any special tools,
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
programs, or compilers are not required to write JavaScript; whatever currently that is
used for writing HTML should work just fine. JavaScript can be used to make the Web
pages interactive and dynamic. A static HTML page without any JavaScript just sits
there, if a visitor returns to a particular site next week, it'll look exactly the same as it
was. With JavaScript, different images can be displayed, give feedback on forms, control
the user's browser and manage framed sites. Overall, JavaScript is used to give the user
feedback.

With JavaScript and forms, the information has been entered correctly or not can
be validated, crosscheck fields against each other, and use one field to set another. With
JavaScript and frames, the site can be forced, either into or out of a frame set, as well as
Page 242
Java Programming

to use information in one frame to change the display of another. The page can be
changed based on the date, time, browser, available plug-ins, and/or platform of a
particular site's visitors.
With JavaScript, applications that can run over the Internet can be created.
Dynamic HTML pages that process user input and maintain persistent data using special
objects, files, and relational databases can also be created. Applications ranging from
internal corporate information management and intranet publishing to mass-market
electronic transactions and commerce can be build. Through JavaScript's LiveConnect
functionality, the applications can access Java and CORBA distributed object
applications.

5.1 Objective
At the end of this unit you will have an understanding of
 JavaScript
 VBscript
 Servlets
 JSP
 JDBC
5.2 Content
5.2.1 Client side and server side JavaScript
Both share the same core language. This core language corresponds to ECMA-
262, the scripting language standardized by the European standards body, with some
additions. The core language contains a set of core objects, such as the Array and Date
objects. It also defines other language features such as its expressions, statements, and
operators. Although server-side and client-side JavaScript use the same core
functionality, in some cases they use them differently. Client-side JavaScript (or
Navigator JavaScript) encompasses the core language plus extras such as the predefined
objects, only relevant to running JavaScript in a browser. Server-side JavaScript
encompasses the same core language plus extras such as the predefined objects and
functions, only relevant to running JavaScript on a server. Client-side JavaScript is
embedded directly in HTML pages and is interpreted by the browser completely at
runtime. Because production applications frequently have greater performance demands
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
upon them, JavaScript applications that take advantage of its server-side capabilities are
compiled before they are deployed. The components of JavaScript are illustrated in the
figure below.

Page 243
Java Programming

JavaScript language.
Client-Side JavaScript

Web browsers such as Netscape Navigator 2.0 and later versions can interpret
client-side JavaScript statements embedded in an HTML page. When the browser or
client requests such a page, the server sends the full content of the document, including
HTML and JavaScript statements, over the network to the client. The client reads the
page from top to bottom, displaying the results of the HTML and executing JavaScript
statements as it goes.

Client-side JavaScript statements embedded in an HTML page can respond to


user events such as mouse clicks, form input, and page navigation. For example, a
JavaScript function can be written to verify the information entered by the user into a
form requesting a telephone number or zip code. Without any network transmission, the
embedded JavaScript on the HTML page, it can check the entered data and display a
dialog box to the user who enters an invalid data.

Server-Side JavaScript

On the server, JavaScript is also embedded in HTML pages. The server-side


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
statements can connect to relational databases from different vendors, share information
across users of an application, access the file system on the server, or communicate with
other applications through LiveConnect and Java. A compiled JavaScript application can
also include client-side JavaScript in addition to server-side JavaScript.

In contrast to pure client-side JavaScript scripts, JavaScript applications that use


server-side JavaScript are compiled into byte code executable files. These application
executables are run in concert with a web server that contains the JavaScript runtime
engine. For this reason, creating JavaScript applications is a two-stage process.

Page 244
Java Programming

In the first stage, the developer creates HTML pages (which can contain both
client-side and server-side JavaScript statements) and JavaScript files. Then compile all
of those files into a single executable. The runtime engine uses the application executable
to look up the source page and dynamically generate the HTML page to return. It runs
any server-side JavaScript statements found on the page. The result of those statements
might add new HTML or client-side JavaScript statements to the HTML page. It then
sends the resulting page over the network to the client, which displays the results. In
contrast to standard Common Gateway Interface (CGI) programs, all JavaScript is
integrated directly into HTML pages, facilitating rapid development and easy
maintenance.

5.2.1.1 Incorporating JavaScript into HTML:

The SCRIPT Tag:


<SCRIPT>
JavaScript Program
</SCRIPT>

The SCRIPT tag takes two optional attributes

Attributes Description

SRC URL for a file containing the JavaScript source code- The
file should have the extension .js. This attribute is not
implemented in the final release of Navigator 2.0 but is expected
to make it into the next version of Navigator.

LANGUAGE Indicates the language used in the script. In the current


version of Navigator 2.0 this attribute can take only two values:
JavaScript and LiveScript. LiveScript is provided for backward
compatibility with early scripts developed when the language was
called LiveScript. We should use JavaScript in the scripts.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Hiding Scripts from Other Browsers:

Browser's that don't support JavaScript will happily attempt to display or parse the
content of the script. In order to avoid this, Netscape recommends the following approach
using HTML comments:

<SCRIPT LANGUAGES JavaScript" >


<! - - HIDE THE SCRIPT FROM OTHER BROWSERS
JavaScript Program
//STOP HIDING FROM OTHER BROWSERS - ->
</SCRIPT>

Page 245
Java Programming

Navigator 3 has introduced the NOSCRIPT, which provides a way for alternate
text to be specified for non-JavaScript browsers.

<SCRIPT LANGUAGE^ JavaScript'' >


<! - - HIDE THE SCRIPT FROM OTHER BROWSERS
JavaScript Program
//STOP HIDING FROM OTHER BROWSERS - -> </SCRIPT>

<NOSCRIPT>
JavaScript Script appears here<BR> Download Netscape Navigator 2.0 to use it.
</NOSCRIPT>

Where to INSERT the JavaScript Code:

JavaScript scripts and programs can be included anywhere in the header or the
body of an HTML file. Make it a habit to include the script container in the header of the
file, and this is the preferred format.

Using External Files for JavaScript Programs:

To make development and maintenance of HTML files and JavaScript scripts


easier, the JavaScript specification includes the option of keeping the JavaScript scripts in
separate files and using the SRC attribute of the SCRIPT tag to include the JavaScript
program in an HTML file.

<SCR1PT LANGUAGE=”Javascript”
SRC=" http://www.you.com/ JavaScript.js"
</SCRIPT>

One of the benefits of this approach is that the scripts are automatically hidden
from other browsers that don't support JavaScript. This technique requires an additional
server request and server access, which may be problematic on a slow server or across a
slow connection to the Internet.

Example:

<HTML>
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
<HEAD>
<TITLE> JavaScript<TITLE>
</HEAD>
<BODY> HERE'S THE RESULT:
<SCRIPT LANGUAGE=" JavaScript" >
<! - - HIDE THE SCRIPT FROM OTHER BROWSERS

//OUTPUT " IT WORKS!" document.writeln (" IT WORKS! <BR>“);

Page 246
Java Programming

//STOP HIDING FROM OTHER BROWSERS - ->


</SCRIPT>
</BODY>
</HTML>

The result will be:

HERE'S THE RESULT: IT WORKS!

Example:

<HTML>
<HEAD>
<TITLE> JavaScript<TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=" JavaScript" >
<! - - HIDE THE SCRIPT FROM OTHER BROWSERS
document.write (‘<IMG SRC=” welcome.gif” >’);
document.write (" <BR><H1>WELCOME TO NETSCAPE NAVIGATOR 2!
</Hl>" ) ;
//STOP HIDING FROM OTHER BROWSERS - -> </SCRIPT>
</BODY>
</HTML>

JavaScript provides the ability for the programmers to generate output in small
dialog boxes - the alert() method.

alert(" Click ok to continue" );

The alert () method is used exactly - to warn the user or alert him or her to
something. Examples of this type of use include:

 Incorrect information in a form


 An invalid result for a calculation
 A warning that a service is not available on a given date.
ANNAMALAI
ANNAMALAI UNIVERSITY
Example:
UNIVERSITY
<HTML>
<HEAD>
<TITLE> JavaScript<TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=" JavaScript" >
<! - - HIDE THE SCRIPT FROM OTHER BROWSERS

Page 247
Java Programming

alert(" WELCOME TO NETSCAPE NAVIGATOR 2!" ) ;


document.write (‘<IMG SRC=" welcome.gif" >');
//STOP HIDING FROM OTHER BROWSERS - ->
</SCRIPT>
</BODY.>
</HTML>

Interacting With the User:

The simplest way to interact with the user is with the prompt () method. Prompt()
creates a dialog box with the specified message, but it also provides a single entry field
with a default entry.

Example:

<HTML>
<HEAD>
<TITLE> JavaScr.ipt<TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=" JavaScript" > <! - - HIDE THE SCRIPT FROM
OTHER BROWSERS
document.write(" <Hl>GREETINGS, ");
document.write (prompt (" ENTER YOUR NAME:" , " NAME" ));
document.write (" WELCOME TO NETSCAPE NAVIGATOR !</H1>");
//STOP HIDING FROM OTHER BROWSERS - -> </SCRIPT>
</BODY>
</HTML>

document.write(string) – is used to display the string given within quotes the


page.
5.2.1.2 Data Types in JavaScript

JavaScript uses four data types - numbers, strings, Boolean values and a null value

Type Example
ANNAMALAI
ANNAMALAI UNIVERSITY
Numbers
UNIVERSITY Any number, such as 17,21.5 or 54e7
Strings " Greetings!" or " Fun)'
Boolean Either true or false
Null A special keyword for exactly that - the
null value (that is, nothing)

Page 248
Java Programming

Integers:

Integers are numbers without any portion following the decimal point; that is,
they are whole numbers - no fractions. Integers can be either positive or negative
numbers. The maximum integer size is dependent on the platform running the JavaScript
application.

Floating Point Values

Floating point values can include a fractional component. A floating point literal
includes a decimal integer plus either a decimal point or a fraction expressed as another
decimal number or an exponent indicator.

Examples:

7.2945
-34/2
2E3

Strings:

A string literal contains zero or more character enclosed in single or double


quotes:
" HELLO!"
'245'
““
Strings are different from other data types in JavaScript. Strings are actually
objects.

Boolean:

A Boolean literal can take two values: true or false. This type of literal comes in
handy when comparing data and making decisions.

The null Value:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The null value is special value in JavaScript. The null value represents just that -
nothing. A null value is distinct from a value of zero or an empty string where this is an
actual value.

5.2.1.3 Declaring Variables:

In order to use a variable, it is good programming style to declare it. A variable


can be declared using a var command:

Var example;

Page 249
Java Programming

The equal sign (=) is used in assigning a value to a variable is known as an


assignment operator.

Example:

<HTML>
<HEAD>
<TITLE> JavaScript<TITLE>
<SCRIPT LANGUAGE=" JavaScript" >
<! - - HIDE THE SCRIPT FROM OTHER BROWSERS
var name=prompt(" ENTER YOUR NAME:" , " NAME" );
//STOP HIDING FROM OTHER BROWSERS - ->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE=" JavaScript" >
<\ - - HIDE THE SCRIPT FROM OTHER BROWSERS
document.write ('<IMG SRC=" welcome.gif >');
document, write (" <H1>GREETINGS, " + NAME + " . WELCOME TO
NETSCAPE NEVIGATOR!</H1>" );
//STOP HIDING FROM OTHER BROWSERS - ->
</SCRIPT>
</BODY>
</HTML>

5.2.1.4 Operators
JavaScript has assignment, comparison, arithmetic, bit wise, logical, string, and
special operators..

Table below summarizes all of the JavaScript operators.

Table JavaScript operators.


Operator O Description
ANNAMALAI
ANNAMALAI UNIVERSITY
Category
UNIVERSITY
perator
+
Arithmetic (Addition) Adds 2 numbers.
Operators
+ (Increment) Adds one to a variable representing a
+ number (returning either the new or old value of the
variable)
- (Unary negation, subtraction) As a unary operator,
negates the value of its argument. As a binary operator,
subtracts 2 numbers.

Page 250
Java Programming

- (Decrement) Subtracts one from a variable


- representing a number (returning either the new or old value
of the variable)
* (Multiplication) Multiplies 2 numbers.
/ (Division) Divides 2 numbers.
% (Modulus) Computes the integer remainder of
dividing 2 numbers.

String + (String addition) Concatenates 2 strings.


Operators
+ Concatenates 2 strings and assigns the result to the
= first operand.

Logical & (Logical AND) Returns true if both logical operands


Operators & are true. Otherwise, returns false.

|| (Logical OR) Returns true if either logical expression


is true. If both are false, returns false.

! (Logical negation) If its single operand is true,


returns false; otherwise, returns true.

Bitwise & (Bitwise AND) Returns a one in each bit position if


Operators bits of both operands are ones.
^ (Bitwise XOR) Returns a one in a bit position if bits
of one but not both operands are one.
| (Bitwise OR) Returns a one in a bit if bits of either
operand is one.
~ (Bitwise NOT) Flips the bits of its operand.
< (Left shift) Shifts its first operand in binary
< representation the number of bits to the left specified in the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
>
second operand, shifting in zeros from the right.

(Sign-propagating right shift) Shifts the first operand


> in binary representation the number of bits to the right
specified in the second operand, discarding bits shifted off.
> (Zero-fill right shift) Shifts the first operand in
>> binary representation the number of bits to the right
specified in the second operand, discarding bits shifted off,
and shifting in zeros from the left.

Page 251
Java Programming

Assignment = Assigns the value of the second operand to the first


Operators operand.
+ Adds 2 numbers and assigns the result to the first.
=

- Subtracts 2 numbers and assigns the result to the


= first.
* Multiplies 2 numbers and assigns the result to the
= first.
/ Divides 2 numbers and assigns the result to the first.
=

% Computes the modulus of 2 numbers and assigns the


= result to the first.
& Performs a bitwise AND and assigns the result to the
= first operand.
^ Performs a bitwise XOR and assigns the result to the
= first operand.
| Performs a bitwise OR and assigns the result to the
= first operand.
< Performs a left shift and assigns the result to the first
<= operand.
> Performs a sign-propagating right shift and assigns
>= the result to the first operand.
> Performs a zero-fill right shift and assigns the result
>>= to the first operand.

=
Comparison = Returns true if the operands are equal.
Operators
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
!= Returns true if the operands are not equal.

> Returns true if left operand is greater than right


operand.

> Returns true if left operand is greater than or equal to


= right operand.

< Returns true if left operand is less than right operand.

Page 252
Java Programming

< Returns true if left operand is less than or equal to


= right operand.

Special ? Allows to perform a simple "if...then...else"


Operators :

, Evaluates two expressions and returns the result of


the second expression.
d Allows deleting an object property or an element at a
elete specified index in an array.
n Allows creating an instance of a user-defined object
ew type or of one of the built-in object types.
t Keyword that is used to refer to the current object.
his

t Returns a string indicating the type of the


ypeof unevaluated operand.
v The void operator specifies an expression to be
oid evaluated without returning a value.

Assignment Operators
An assignment operator assigns a value to its left operand based on the value of
its right operand. The basic assignment operator is equal (=), which assigns the value of
its right operand to its left operand. That is, x = y assigns the value of y to x. The other
assignment operators are shorthand for standard operations, as shown in Table below

Table Assignment operators

Shorthand Mean
operator ing
x += y x = x
+ y
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY x -= y
– y
x = x

x *= y x = x
* y

x /= y x = x
/ y

x %= y x = x
% y

Page 253
Java Programming

x <<= y x = x
<< y

x >>= y x = x
>> y

x >>>= y x = x
>>> y

x &= y x = x
& y

x ^= y x = x
^ y

x |= y x = x
| y

Comparison Operators

A comparison operator compares its operands and returns a logical value based on
whether the comparison is true or not. The operands can be numerical or string values.
When used on string values, the comparisons are based on the standard lexicographical
ordering.

They are described in Table below In the examples in this table, assume var1 has
been assigned the value 3 and var2 had been assigned the value 4.

Table - Comparison operators


Operator Description Examples
returning true

Equal (==) Returns true if the operands are equal. 3 == var1

Not equal (!=) Returns true if the operands are not equal. var1 != 4

Greater than (>) Returns true if left operand is greater than var2 > var1
right operand.
ANNAMALAI
ANNAMALAI UNIVERSITY
Greater than UNIVERSITY
or Returns true if left operand is greater than or var2 >= var1
var1 >= 3
equal (>=) equal to right operand.

Less than (<) Returns true if left operand is less than right var1 < var2
operand.

Less than or equal Returns true if left operand is less than or var1 <= var2
equal to right operand. var2 <= 5
(<=)

Page 254
Java Programming

Arithmetic Operators

Arithmetic operators take numerical values (either literals or variables) as their


operands and return a single numerical value. The standard arithmetic operators are
addition (+), subtraction (-), multiplication (*), and division (/). These operators work as
they do in other programming languages.

% (Modulus)

The modulus operator is used as follows:


var1 % var2

The modulus operator returns the first operand modulo the second operand, that
is, var1 modulo var2, in the preceding statement, where var1 and var2 are variables.
The modulo function is the integer remainder of dividing var1 by var2. For example, 12
% 5 returns 2.

++ (Increment)

The increment operator is used as follows:

var++ or ++var

This operator increments (adds one to) its operand and returns a value. If used
postfix, with operator after operand (for example, x++), then it returns the value before
incrementing. If used prefix with operator before operand (for example, ++x), then it
returns the value after incrementing.

For example, if x is three, then the statement y = x++ sets y to 3 and increments
x to 4. If x is 3, then the statement y = ++x increments x to 4 and sets y to 4.

-- (Decrement)

The decrement operator is used as follows:

ANNAMALAI
ANNAMALAI UNIVERSITY
var--
UNIVERSITY
or --var

This operator decrements (subtracts one from) its operand and returns a value. If
used postfix (for example, x--), then it returns the value before decrementing. If used
prefix (for example, --x), then it returns the value after decrementing.

For example, if x is three, then the statement y = x-- sets y to 3 and decrements
x to 2. If x is 3, then the statement y = --x decrements x to 2 and sets y to 2.

- (Unary Negation)
Page 255
Java Programming

The unary negation operator precedes its operand and negates it. For example,
y = -x negates the value of x and assigns that to y; that is, if x were 3, y would get the
value -3 and x would retain the value 3.

Bitwise Operators

Bitwise operators treat their operands as a set of bits (zeros and ones), rather than
as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a
binary representation of 1001. Bitwise operators perform their operations on such binary
representations, but they return standard JavaScript numerical values.
Table below summarizes JavaScript's bitwise operators

Table - Bitwise operators

Operator U Description
sage

Bitwise AND a & b Returns a one in each bit position if bits of both operands
are ones.

Bitwise OR a | b Returns a one in a bit if bits of either operand is one.

Bitwise XOR a ^ b Returns a one in a bit position if bits of one but not both
operands are one.

Bitwise NOT ~a Flips the bits of its operand.

Left shift a << Shifts a in binary representation b bits to left, shifting in


b
zeros from the right.

Sign-propagating a >> Shifts a in binary representation b bits to right, discarding


right shift b
bits shifted off.

Zero-fill right shift a >>> Shifts a in binary representation b bits to the right,
b
discarding bits shifted off, and shifting in zeros from the
left.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Bitwise Logical Operators

Conceptually, the bitwise logical operators work as follows:


 The operands are converted to thirty-two-bit integers and
expressed by a series of bits (zeros and ones).
 Each bit in the first operand is paired with the corresponding bit in
the second operand: first bit to first bit, second bit to second bit, and so on.
 The operator is applied to each pair of bits, and the result is
constructed bitwise.
Page 256
Java Programming

For example, the binary representation of nine is 1001, and the binary
representation of fifteen is 1111. So, when the bitwise operators are applied to these
values, the results are as follows:
 15 & 9 yields 9 (1111 & 1001 = 1001)
 15 | 9 yields 15 (1111 | 1001 = 1111)
 15 ^ 9 yields 6 (1111 ^ 1001 = 0110)

Bitwise Shift Operators


The bitwise shift operators take two operands: the first is a quantity to be shifted,
and the second specifies the number of bit positions by which the first operand is to be
shifted. The direction of the shift operation is controlled by the operator used.
Shift operators convert their operands to thirty-two-bit integers and return a result
of the same type as the left operator.

<< (Left Shift)


This operator shifts the first operand the specified number of bits to the left.
Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right.
For example, 9<<2 yields thirty-six, because 1001 shifted two bits to the left
becomes 100100, which is thirty-six.
>> (Sign-Propagating Right Shift)
This operator shifts the first operand the specified number of bits to the right.
Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in
from the left.
For example, 9>>2 yields two, because 1001 shifted two bits to the right becomes
10, which is two. Likewise, -9>>2 yields -3, because the sign is preserved.
>>> (Zero-Fill Right Shift)
This operator shifts the first operand the specified number of bits to the right.
Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
For example, 19>>>2 yields four, because 10011 shifted two bits to the right
becomes 100, which is four. For non-negative numbers, zero-fill right shift and sign-
propagating right shift yield the same result.
Logical Operators
Logical operators take Boolean (logical) values as operands and return a Boolean
value.
They are described in Table below
Table - Logical operators
Page 257
Java Programming

Operator Usage Description

and (&&) expr1 && Returns expr1 if it converts to false. Otherwise, returns
expr2
expr2.

or (||) expr1 || Returns expr1 if it converts to true. Otherwise, returns


expr2
expr2.

not (!) !expr If expr is true, returns false; if expr is false, returns true.

Examples
Consider the following script:
<html>
<script language="JavaScript1.2">
v1 = "Cat";
v2 = "Dog";
v3 = "false";
document.writeln("t && t returns " + (v1 && v2));
document.writeln("f && t returns " + (v3 && v1));
document.writeln("t && f returns " + (v1 && v3));
document.writeln("f && f returns " + (v3 && (3 == 4)));
document.writeln("t || t returns " + (v1 || v2));
document.writeln("f || t returns " + (v3 || v1));
document.writeln("t || f returns " + (v1 || v3));
document.writeln("f || f returns " + (v3 || (3 == 4)));
document.writeln("!t returns " + (!v1));
document.writeln("!f returns " + (!v3));
</script>
</html>

This script displays the following:


t && t returns Dog
f && t returns Cat
t && f returns false
f && f returns false
t || t returns Cat
f || t returns false
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
t || f returns Cat
f || f returns false
!t returns false
!f returns false

Short-Circuit Evaluation
As logical expressions are evaluated left to right, they are tested for possible
"short-circuit" evaluation using the following rules:
 false && anything is short-circuit evaluated to false.
 true || anything is short-circuit evaluated to true.

Page 258
Java Programming

The rules of logic guarantee that these evaluations are always correct. Note that
the anything part of the above expressions is not evaluated, so any side effects of doing
so do not take effect.
String Operators
In addition to the comparison operators, which can be used on string values, the
concatenation operator (+) concatenates two string values together, returning another
string that is the union of the two operand strings. For example, "my " + "string"
returns the string "my string".
The shorthand assignment operator += can also be used to concatenate strings.
For example, if the variable mystring has the value "alpha," then the expression
mystring += "bet" evaluates to "alphabet" and assigns this value to mystring.

Special Operators
?: (Conditional operator)
The conditional operator is the only JavaScript operator that takes three operands.
This operator is frequently used as a shortcut for the if statement.

Syntax
condition ? expr1 : expr2

Parameters
condit an expression that evaluates to true
ion
or false
expr1, expressions with values of any type.
expr2
Description

If condition is true, the operator returns the value of expr1; otherwise, it


returns the value of expr2. For example, to display a different message based on the
value of the isMember variable, this could be used.
document.write ("The fee is " + (isMember ? "$2.00" : "$10.00"))

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
, (Comma operator)
The comma operator is very simple. It evaluates both of its operands and returns
the value of the second operand.
Syntax
expr1, expr2
Parameters
expr1, Any
expr2 expressions

Description

Page 259
Java Programming

The comma operator can be used when multiple expressions need to be included
in a location that requires a single expression. The most common usage of this operator is
to supply multiple parameters in a for loop.
For example, if a is a 2-dimensional array with 10 elements on a side, the
following code uses the comma operator to increment two variables at once. The code
prints the values of the diagonal elements in the array:
for (var i=0, j=10; i <= 10; i++, j--)
document.writeln("a["+i+","+j+"]= " + a[i,j])

new
An operator that lets to create an instance of a user-defined object type or of one
of the built-in object types that has a constructor function.
Syntax
objectName = new objectType (param1 [,param2] ...[,paramN])
Arguments

objectName Name of the new object instance.


objectType Object type. It must be a function that defines an object
type.
param1...para Property values for the object. These properties are
mN
parameters defined for the objectType function.
Description
Creating a user-defined object type requires two steps:
1. Define the object type by writing a function.
2. Create an instance of the object with new.
To define an object type, create a function for the object type that specifies its
name, properties, and methods. An object can have a property that is itself another object.
A property can be always added to a previously defined object. For example, the
statement car1.color = "black" adds a property color to car1, and assigns it a value
of "black". However, this does not affect any other objects. To add the new property to
all objects of the same type, add the property to the definition of the car object type.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A property can be added to a previously defined object type by using the
Function.prototype property. This defines a property that is shared by all objects
created with that function, rather than by just one instance of the object type. The
following code adds a color property to all objects of type car, and then assigns a value
to the color property of the object car1.
Car.prototype.color=null
car1.color="black"
birthday.description="The day you were born"

Examples

Page 260
Java Programming

Example 1: object type and object instance. To create an object type for cars. If this
type of object to be called car, and to have properties like make, model, and year, write a
function as given below.
function car(make, model, year) {
this.make = make
this.model = model
this.year = year
}
Now an object called mycar can be created as follows:
mycar = new car("Eagle", "Talon TSi", 1993)

This statement creates mycar and assigns it the specified values for its properties.
Then the value of mycar.make is the string "Eagle", mycar.year is the integer 1993,
and so on.
Any number of car objects can be created by using new. For example,
kenscar = new car("Nissan", "300ZX", 1992)

Example 2: object property that is itself another object. An object called person is
defined as follows:

function person(name, age, sex) {


this.name = name
this.age = age
this.sex = sex
}
And then instantiate two new person objects as follows:
rand = new person("Rand McNally", 33, "M")
ken = new person("Ken Jones", 39, "M")

Then the definition of car can be rewritten, to include an owner property that
takes a person object, as follows:
function car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
To instantiate the new objects, use the following:
car1 = new car("Eagle", "Talon TSi", 1993, rand);
car2 = new car("Nissan", "300ZX", 1992, ken)

Instead of passing a literal string or integer value when creating the new objects,
the above statements pass the objects rand and ken as the parameters for the owners. To
find out the name of the owner of car2, access the following property as given below.
car2.owner.name

this

Page 261
Java Programming

A keyword that is used to refer to the current object. In general, in a method this
refers to the calling object.
Syntax
this[.propertyName]

Examples
Suppose a function called validate validates an object's value property, given
the object and the high and low values:
function validate(obj, lowval, hival) {
if ((obj.value < lowval) || (obj.value > hival))
alert("Invalid Value!")
}
validate could be called in each form element's onChange event handler, using
this to pass it the form element, as in the following example:
<B>Enter a number between 18 and 99:</B>
<INPUT TYPE = "text" NAME = "age" SIZE = 3
onChange="validate(this, 18, 99)">

typeof

The typeof operator is used in either of the following ways:

1. typeof operand
2. typeof (operand)

The typeof operator returns a string indicating the type of the unevaluated
operand. operand is the string, variable, keyword, or object for which the type is to be
returned. The parentheses are optional.
After defining the following variables as follows:
var myFun = new Function("5+2")
var shape="round"
var size=1
var today=new Date()

The typeof operator returns the following results for these variables:
ANNAMALAI
ANNAMALAI UNIVERSITY
typeof
typeof
UNIVERSITY
myFun is object
shape is string
typeof size is number
typeof today is object
typeof dontExist is undefined

For the keywords true and null, the typeof operator returns the following
results:
typeof true is boolean
typeof null is object

Page 262
Java Programming

For a number or string, the typeof operator returns the following results:
typeof 62 is number
typeof 'Hello world' is string

For property values, the typeof operator returns the type of value the property
contains:
typeof document.lastModified is string
typeof window.length is number
typeof Math.LN2 is number

For methods and functions, the typeof operator returns results as follows:

typeof blur is function


typeof eval is function
typeof parseInt is function
typeof shape.split is function

For predefined objects, the typeof operator returns results as follows:

typeof Date is function


typeof Function is function
typeof Math is function
typeof Option is function
typeof String is function

void
The void operator is used in either of the following ways:

1. javascript:void (expression)
2. javascript:void expression

The void operator specifies an expression to be evaluated without returning a


value. expression is a JavaScript expression to evaluate. The parentheses surrounding
the expression are optional, but it is good style to use them.

The void operator is used to specify an expression as a hypertext link. The


expression is evaluated but is not loaded in place of the current document.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The following code creates a hypertext link that does nothing when the user clicks
it. When the user clicks the link, void(0) evaluates to 0, but that has no effect in
JavaScript.
<A HREF="javascript:void(0)">Click here to do nothing</A>

The following code creates a hypertext link that submits a form when the user
clicks it.

<A HREF="javascript:void(document.form.submit())">
Click here to submit</A>

Page 263
Java Programming

5.2.1.5 Statements
The JavaScript statements consist of keywords used with the appropriate syntax.
A single statement may span multiple lines. Multiple statements may occur on a single
line if each statement is separated by a semicolon. Syntax conventions: All keywords in
syntax statements are in bold. Words in italics represent user-defined names or
statements. Any portions enclosed in square brackets, [ ], are optional. {Statements}
indicates a block of statements, which can consist of a single statement or multiple
statements delimited by a curly braces { }.

Following are the list of statements available in JavaScript.

Table JavaScript statements.

brea Statement that terminates the current while or for loop and transfers
k program control to the statement following the terminated loop.
comm Notations by the author to explain what a script does. Comments are
ent ignored by the interpreter.
cont Statement that terminates execution of the block of statements in a
inue while or for loop, and continues execution of the loop with the next
iteration.
dele Deletes an object's property or an element of an array.
te

do.. Executes its statements until the test condition evaluates to false.
.while Statement is executed at least once.
expo Allows a signed script to provide properties, functions, and objects
rt to other signed or unsigned scripts.
for Statement that creates a loop that consists of three optional
expressions, enclosed in parentheses and separated by semicolons,
followed by a block of statements executed in the loop.

..in
ANNAMALAI
ANNAMALAI UNIVERSITY
for.
UNIVERSITY
Statement that iterates a specified variable over all the properties of
an object. For each distinct property, JavaScript executes the specified
statements.
func Statement that declares a JavaScript function name with the
tion specified parameters. Acceptable parameters include strings, numbers, and
objects.
if.. Statement that executes a set of statements if a specified condition
.else is true. If the condition is false, another set of statements can be executed.

Page 264
Java Programming

impo Allows a script to import properties, functions, and objects from a


rt signed script, which has exported the information.
labe Provides an identifier that can be used with break or continue to
led indicate where the program should continue execution.
retu Statement that specifies the value to be returned by a function.
rn

swit Allows a program to evaluate an expression and attempt to match


ch the expression's value to a case label.
var Statement that declares a variable, optionally initializing it to a
value.
whil Statement that creates a loop that evaluates an expression, and if it
e is true, executes a block of statements.
with Statement that establishes the default object for a set of statements.

delete
Deletes an object's property or an element at a specified index in an array.
Syntax
delete objectName.property
delete objectName[index]
delete property
Arguments

objectName An object from which to delete the specified property or value.


property The property to delete.
index An integer index into an array.

Description
If the delete operator succeeds, it sets the property of element to undefined; the
operator always returns undefined.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The delete operator can only be used to delete object properties and array
entries. This operator cannot be used to delete objects or variables. Consequently, only
the third form can be used within a with statement, to delete a property from the object.

do...while

Executes its statements until the test condition evaluates to false. Statement is
executed at least once.

Page 265
Java Programming

Syntax
do
statement
while (condition);

Arguments

sta Block of statements that is executed at least once and is re-executed


tement each time the condition evaluates to true.
con Evaluated after each pass through the loop. If condition evaluates to
dition
true, the statements in the preceding block are re-executed. When condition
evaluates to false, control passes to the statement following do while.

Example

In the following example, the do loop iterates at least once and reiterates until i is
no longer less than 5.

do {
i+=1
document.write(i);
while (i<5);

for

Creates a loop that consists of three optional expressions, enclosed in parentheses


and separated by semicolons, followed by a block of statements executed in the loop.

Syntax
for ([initial-expression;] [condition;] [increment-expression]) {
statements
}

Arguments

initial- Statement or variable declaration. Typically used to initialize a counter


expression variable. This expression may optionally declare new variables with the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
var keyword.
condition Evaluated on each pass through the loop. If this condition evaluates to
true, the statements in statements are performed. This conditional test
is optional. If omitted, the condition always evaluates to true.
increment- Generally used to update or increment the counter variable.
expression
statements Block of statements that are executed as long as condition evaluates to
true. This can be a single statement or multiple statements. Although not
required, it is good practice to indent these statements from the
beginning of the for statement.

Page 266
Java Programming

Examples
The following for statement starts by declaring the variable i and initializing it to
0. It checks that i is less than nine, performs the two succeeding statements, and
increments i by 1 after each pass through the loop.

for (var i = 0; i < 9; i++)


{ n += i
myfunc(n)
}
for...in
Iterates a specified variable over all the properties of an object. For each distinct
property, JavaScript executes the specified statements.

Syntax
for (variable in object) {
statements}

Arguments
vari Variable to iterate over every property.
able
obje Object for which the properties are iterated.
ct
stat Specifies the statements to execute for each
ements property.

Examples

The following function takes as its argument an object and the object's name. It
then iterates over all the object's properties and returns a string that lists the property
names and their values.

function dump_props (obj, objName) {


var result = ""
for (var i in obj) {
result += objName + "." + i + " = " + obj[i] + "<BR>"
}
result += "<HR>"

}
ANNAMALAI
ANNAMALAI UNIVERSITY
return result UNIVERSITY
function

Declares a JavaScript function with the specified parameters. Acceptable


parameters include strings, numbers, and objects.

Syntax
function name([param] [, param] [..., param]) {
statements}

Page 267
Java Programming

Arguments
n The function name.
ame
p The name of an argument to be passed to the function. A function can have
aram up to 255 arguments.

Description

To return a value, the function must have a return statement that specifies the
value to return. A function statement cannot be nested in another statement or in itself.

All parameters are passed to functions, by value. In other words, the value is
passed to the function, but if the function changes the value of the parameter, this change
is not reflected globally or in the calling function.

In addition to defining functions as described here, Function objects can also be


defined.

Examples

//This function returns the total dollar amount of sales, when


//given the number of units sold of products a, b, and c.

function calc_sales(units_a, units_b, units_c)


{
return units_a*79 + units_b*129 + units_c*699
}

labeled

Provides an identifier that can be used with break or continue to indicate where
the program should continue execution.

In a labeled statement, break or continue must be followed with a label, and the
label must be the identifier of the labeled statement containing break or continue.

Syntax
ANNAMALAI
ANNAMALAI UNIVERSITY
label : UNIVERSITY
statement

Arguments
statement Block of statements. break can be used with any labeled statement, and
continue can be used with looping labeled statements.
Return
Specifies the value to be returned by a function.
Syntax

Page 268
Java Programming

return expression

Examples
The following function returns the square of its argument, x, where x is a number.
function square(x) {
return x * x
}

switch
Allows a program to evaluate an expression and attempt to match the expression's
value to a case label.
Syntax
switch (expression){
case label :
statement;
break;
case label :
statement;
break;
...
default : statement;
}

Arguments

expr Value matched against label.


ession
labe Identifier used to match against
l expression.
stat Any statement.
ement

Description
If a match is found, the program executes the associated statement.
The program first looks for a label matching the value of expression and then
executes the associated statement. If no matching label is found, the program looks for
the optional default statement, and if found, executes the associated statement. If no
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
default statement is found, the program continues execution at the statement following
the end of switch.

The optional break statement associated with each case label ensures that the
program breaks out of switch once the matched statement is executed and continues
execution at the statement following switch. If break is omitted, the program continues
execution at the next statement in the switch statement.

Example

Page 269
Java Programming

In the following example, if expression evaluates to "Bananas," the program


matches the value with case "Bananas" and executes the associated statement. When
break is encountered, the program breaks out of switch and executes the statement
following switch. If break were omitted, the statement for case "Cherries" would also
be executed.
switch (i) {
case "Oranges" :
document.write("Oranges are $0.59 a pound.<BR>");
break;
case "Apples" :
document.write("Apples are $0.32 a pound.<BR>");
break;
case "Bananas" :
document.write("Bananas are $0.48 a pound.<BR>");
break;
case "Cherries" :
document.write("Cherries are $3.00 a pound.<BR>");
break;
default :
document.write("Sorry, we are out of " + i + ".<BR>");
}
document.write("Is there anything else you'd like?<BR>");

var
Declares a variable, optionally initializing it to a value.
Syntax
var varname [= value] [..., varname [= value] ]

Arguments
v Variable name. It can be any legal identifier.
arname
v Initial value of the variable and can be any legal
alue expression.

Description
The scope of a variable is the current function or, for variables declared outside a
function, the current application.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Using var outside a function is optional; you can declare a variable by simply
assigning it a value. However, it is good style to use var, and it is necessary in functions
if a global variable of the same name exists.

Examples

var num_hits = 0, cust_no = 0


while
Creates a loop that evaluates an expression, and if it is true, executes a block of
statements. The loop then repeats, as long as the specified condition is true.

Page 270
Java Programming

Implem Navigator 2.0,


ented in LiveWire 1.0

Syntax
while (condition) {
statements
}

Arguments
cond Evaluated before each pass through the loop. If this condition
ition evaluates to true, the statements in the succeeding block are performed.
When condition evaluates to false, execution continues with the statement
following statements.
stat Block of statements that are executed as long as the condition
ements evaluates to true. Although not required, it is good practice to indent these
statements from the beginning of the statement.

Examples
The following while loop iterates as long as n is less than three.
n = 0
x = 0
while(n < 3) {
n ++
x += n
}
Each iteration, the loop increments n and adds it to x. Therefore, x and n take on
the following values:
 After the first pass: n = 1 and x = 1
 After the second pass: n = 2 and x = 3
 After the third pass: n = 3 and x = 6

After completing the third pass, the condition n < 3 is no longer true, so the loop
terminates.

with
Establishes the default object for a set of statements. Within the set of statements,
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
any property references that do not specify an object are assumed to be for the default
object.

Syntax
with (object){
statements
}

Arguments
obje Specifies the default object to use for the statements. The
ct parentheses around object are required.

Page 271
Java Programming

stat Any block of statements.


ements

Examples

The following with statement specifies that the Math object is the default object.
The statements following the with statement refer to the PI property and the cos and sin
methods, without specifying an object. JavaScript assumes the Math object for these
references.
var a, x, y
var r=10
with (Math) {
a = PI * r * r
x = r * cos(PI)
y = r * sin(PI/2)
}

5.2.1.6 Core Objects

JavaScript core objects are Array, Boolean, Date, Function, Math, Number,
Object, and String. These objects are used in both client-side and server-side JavaScript.

Table below summarizes the objects

Object Description

Array Represents an array.


Boolean Represents a Boolean value.
Date Represents a date.
Function Specifies a string of JavaScript code to be compiled as a
function.
Math Provides basic math constants and functions; for example, its PI
property contains the value of pi.
Number Represents primitive numeric values.
Object Contains the base functionality shared by all JavaScript objects.
RegExp Represents a regular expression; also contains static properties that
are shared among all regular expression objects.
String ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Represents a JavaScript string.

5.2.1.7 JavaScript Objects


JavaScript has predefined objects for the core language, as well as additions for
client-side and server-side JavaScript.

Object Description

Frame A window that can display multiple, independently scrollable frames on a


single screen, each with its own distinct URL.

Page 272
Java Programming

History Contains an array of information on the URLs that the client has visited
within a window.
Location Contains information on the current URL.
screen Contains properties describing the display screen and colors.
Window Represents a browser window or frame. This is the top-level object for
each document, Location, and History object group.

Figure Containment relationships among client-side objects

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Window

Represents a browser window or frame. This is the top-level object for each
document, Location, and History object group.

The JavaScript runtime engine creates a Window object for each BODY or
FRAMESET tag. It also creates a Window object to represent each frame defined in a
FRAME tag. In addition, other windows can be created by calling the Window.open
method.

Page 273
Java Programming

The Window object is the top-level object in the JavaScript client hierarchy. A
Window object can represent either a top-level window or a frame inside a frameset. As a
matter of convenience, a Frame object can be thought of as a Window object that is not a
top-level window. However, there is not really a separate Frame class; these objects
really are Window objects, with a very few minor differences:

For a top-level window, the parent and top properties are references to the
window itself. For a frame, the top refers to the topmost browser window, and parent
refers to the parent window of the current window.

For a top-level window, setting the defaultStatus or status property sets the text
appearing in the browser status line. For a frame, setting these properties only sets the
status line text when the cursor is over the frame.

The close method is not useful for windows that are frames.

If a FRAME tag contains SRC and NAME attributes, that frame can be
referred from a sibling frame by using parent.frameName or parent.frames[index]. For
example, if the fourth frame in a set has NAME="homeFrame", sibling frames can refer
to that frame using parent.homeFrame or parent.frames[3].

For all windows, the self and window properties of a Window object are
synonyms for the current window, and optionally it can be used to refer to the current
window. For example, the current window can be closed by calling the close method of
either window or self. These properties can be used to make the code more readable or to
disambiguate the property reference selfstatus from a form called status.

Because the existence of the current window is assumed, there is no need to refer
to the name of the window when its methods are called and its properties are assigned.
For example, status="Jump to a new location" is a valid property assignment, and close()
is a valid method call.

However, when a window is opened or closed within an event handler,


window.open() or window.close() must be specified, instead of simply using open() or
close(). Due to the scoping of static objects in JavaScript, a call to close() without
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
specifying an object name is equivalent to document.close().

For the same reason, when the location object is referred within an event handler,
window.location must be specified, instead of simply using location. A call to location
without specifying an object name is equivalent to document.location, which is a
synonym for document.URL.

A window's Frame objects can be referred in the code by using the frames array.
In a window with a FRAMESET tag, the frames array contains an entry for each frame.

Page 274
Java Programming

A windows lacks event handlers until HTML that contains a BODY or


FRAMESET tag is loaded into it.

Properties

closed Specifies whether a window has been closed.


defaultStatus Reflects the default message displayed in the window's status bar.
document Contains information on the current document, and provides methods
for displaying HTML output to the user.
frames An array reflecting all the frames in a window.
history Contains information on the URLs that the client has visited within a
window.
innerHeight Specifies the vertical dimension, in pixels, of the window's content
area.
innerWidth Specifies the horizontal dimension, in pixels, of the window's content
area.
length The number of frames in the window.
location Contains information on the current URL.
locationbar Represents the browser window's location bar.
menubar Represents the browser window's menu bar.
Name A unique name used to refer to this window.
opener Specifies the window name of the calling document when a window is
opened using the open method
outerHeight Specifies the vertical dimension, in pixels, of the window's outside
boundary.
outerWidth Specifies the horizontal dimension, in pixels, of the window's outside
boundary.
pageXOffset Provides the current x-position, in pixels, of a window's viewed page.
pageYOffset Provides the current y-position, in pixels, of a window's viewed page.
parent A synonym for a window or frame whose frameset contains the current
frame.
personalbar Represents the browser window's personal bar (also called the
directories bar).
scrollbars Represents the browser window's scroll bars.
self A synonym for the current window.
status Specifies a priority or transient message in the window's status bar.
ANNAMALAI
ANNAMALAI UNIVERSITY
statusbar
toolbar
UNIVERSITY
Represents the browser window's status bar.
Represents the browser window's tool bar.
top A synonym for the topmost browser window.
window A synonym for the current window.

Frame
A window can display multiple, independently scrollable frames on a single
screen, each with its own distinct URL. These frames are created using the FRAME tag
inside a FRAMESET tag. Frames can point to different URLs and be targeted by other
URLs, all within the same screen. A series of frames makes up a page. The Frame object

Page 275
Java Programming

is a convenience for thinking about the objects that constitute these frames. However,
JavaScript actually represents a frame using a Window object. Every Frame object is a
Window object, and has all the methods and properties of a Window object. There are a
small number of minor differences between a window that is a frame and a top-level
window.

History
Contains an array of information on the URLs that the client has visited within a
window. This information is stored in a history list and is accessible through the
browser's Go menu.
History objects are predefined JavaScript objects that you access through the
history property of a Window object. To change a window's current URL without
generating a history entry, the Location.replace method can be used. This replaces the
current page with a new one without generating a history entry. See Location.replace.

The history entries can be referred by using the Window.history array. This array
contains an entry for each history entry in source order. Each array entry is a string
containing a URL. For example, if the history list contains three named entries, these
entries are reflected as history[0], history[1], and history[2].
If the history array is accessed without specifying an array element, the browser
returns a string of HTML which displays a table of URLs, each of which is a link.

Properties

current Specifies the URL of the current history entry.


length Reflects the number of entries in the history list.
next Specifies the URL of the next history entry.
previous Specifies the URL of the previous history entry.

Methods

back Loads the previous URL in the history list.


forward Loads the next URL in the history list.
go Loads a URL from the history list.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Example 1: The following example goes to the URL the user visited three clicks ago in
the current window.
history.go(-3)

Example 2: The history object can be used with a specific window or frame. The
following example causes window2 to go back one item in its window (or session)
history:
window2.history.back()

Location

Page 276
Java Programming

Contains information on the current URL.


Location objects are predefined JavaScript objects that you access through the
location property of a Window object: The location object represents the complete URL
associated with a given Window object. Each property of the location object represents a
different portion of the URL.
In general, a URL has this form:
protocol//host:port/pathname#hash?search

These parts serve the following purposes:


o protocol represents the beginning of the URL, up to and including the first
colon.
o host represents the host and domain name, or IP address, of a network
host.
o port represents the communications port that the server uses for
communications.

o pathname represents the URL-path portion of the URL.


o hash represents an anchor name fragment in the URL, including the hash
mark (#). This property applies to HTTP URLs only.
o search represents any query information in the URL, including the
question mark (?). This property applies to HTTP URLs only. The search
string contains variable and value pairs; each pair is separated by an
ampersand (&).
A Location object has a property for each of these parts of the URL. See the
individual properties for more information. A Location object has two other properties
not shown here:
href represents a complete URL.
hostname represents the concatenation host:port.
The location object is contained by the window object and is within its scope. If
you refer to a location object without specifying a window, the location object represents
the current location. If you refer to a location object and specify a window name, as in
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
windowReference.location, the location object represents the location of the specified
window.
In JavaScript, a call to location without specifying an object name is equivalent to
document.location, which is a synonym for document.URL.
Location is not a property of the document object; its equivalent is the
document.URL property. The document.location property, which is a synonym for
document.URL, will be removed in a future release.
Screen

Page 277
Java Programming

Contains properties describing the display screen and colors.


The JavaScript runtime engine creates the screen object. Its properties can be
accessed automatically.
This object contains read-only properties that allows to get information about the
user's display.

Properties

availHeight Specifies the height of the screen, in pixels, minus permanent or


semipermanent user interface features displayed by the operating
system, such as the Taskbar on Windows.
availWidth Specifies the width of the screen, in pixels, minus permanent or
semipermanent user interface features displayed by the operating
system, such as the Taskbar on Windows.
colorDepth The bit depth of the color palette, if one is in use; otherwise, the value
is derived from screen.pixelDepth.
height Display screen height.
pixelDepth Display screen color resolution (bits per pixel).
width Display screen width.

5.2.1.8 Form Objects

Lets users input text and make choices from Form elements such as checkboxes,
radio buttons, and selection lists. A form can also be used to post data to a server.

The HTML FORM tag. The JavaScript runtime engine creates a Form object for
each FORM tag in the document. FORM objects are accessed through the
document.forms property and through named properties of that object.

To define a form, use standard HTML syntax with the addition of JavaScript
event handlers. If a value for the NAME attribute is supplied , that value can be used to
index into the forms array. In addition, the associated document object has a named
property for each named form.

ANNAMALAI
ANNAMALAI UNIVERSITY
Event handlers UNIVERSITY
onReset
onSubmit

Each form in a document is a distinct object. A form's elements can be referred in


the code by using the element's name (from the NAME attribute) or the Form.elements
array. The elements array contains an entry for each element (such as a Checkbox, Radio,
or Text object) in a form.

Page 278
Java Programming

If multiple objects on the same form have the same NAME attribute, an array of
the given name is created automatically. Each element in the array represents an
individual Form object. Elements are indexed in source order starting at 0. For example,
if two Text elements and a Textarea element on the same form have their NAME
attribute set to "myField", an array with the elements myField[0], myField[1], and
myField[2] is created. One need to be aware of this situation in the code and know
whether myField refers to a single element or to an array of elements.

Property Summary

action Reflects the ACTION attribute.


elements An array reflecting all the elements in a form.
encoding Reflects the ENCTYPE attribute.
length Reflects the number of elements on a form.
method Reflects the METHOD attribute.
name Reflects the NAME attribute.
target Reflects the TARGET attribute.

Method Summary

handleEvent Invokes the handler for the specified event.


reset Simulates a mouse click on a reset button for the calling form.
submit Submits a form.

Table -Form objects

Object Description

Button A push button on an HTML form.


Checkbox A checkbox on an HTML form.
FileUpload A file upload element on an HTML form.
Form Lets users input text and make choices from Form elements such as
checkboxes, radio buttons, and selection lists.
Hidden A Text object that is suppressed from form display on an HTML form.

ANNAMALAI
ANNAMALAI UNIVERSITY
Option
Password UNIVERSITY
A Select object option.
A text field on an HTML form that conceals its value by displaying
asterisks (*).
Radio A set of radio buttons on an HTML form.
Reset A reset button on an HTML form.
Select A selection list on an HTML form.
Submit A submit button on an HTML form.
Text A text input field on an HTML form.
Textarea A multiline input field on an HTML form.

Page 279
Java Programming

Button

A push button on an HTML form.

The HTML INPUT tag, with "button" as the value of the TYPE attribute. For a
given form, the JavaScript runtime engine creates appropriate Button objects and puts
these objects in the elements array of the corresponding Form object. A Button object is
accessed by indexing this array. The array can be indexed either by number or, if
supplied, by using the value of the NAME attribute.

A Button object is a form element and must be defined within a FORM tag.

The Button object is a custom button that is used to perform an action that is
defined by the user. The button executes the script specified by its onClick event handler.

Properties

form Specifies the form containing the Button object.


name Reflects the NAME attribute.
type Reflects the TYPE attribute.
value Reflects the VALUE attribute.

Checkbox

A checkbox on an HTML form. A checkbox is a toggle switch that lets the user
set a value on or off.

The HTML INPUT tag, with "checkbox" as the value of the TYPE attribute. For a
given form, the JavaScript runtime engine creates appropriate Checkbox objects and puts
these objects in the elements array of the corresponding Form object. You access a
Checkbox object by indexing this array. You can index the array either by number or, if
supplied, by using the value of the NAME attribute.

A Checkbox object is a form element and must be defined within a FORM tag.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Use the checked property to specify whether the checkbox is currently checked.
Use the defaultChecked property to specify whether the checkbox is checked when the
form is loaded or reset.

Property

checked Boolean property that reflects the current state of the checkbox.
defaultChecked Boolean property that reflects the CHECKED attribute.
form Specifies the form containing the Checkbox object.
name Reflects the NAME attribute.

Page 280
Java Programming

type Reflects the TYPE attribute.


value Reflects the TYPE attribute.

FileUpload

A file upload element on an HTML form. A file upload element lets the user
supply a file as input.

The HTML INPUT tag, with "file" as the value of the TYPE attribute. For a given
form, the JavaScript runtime engine creates appropriate FileUpload objects and puts these
objects in the elements array of the corresponding Form object. A FileUpload object by
indexing this array. The array can be indexed either by number or, if supplied, by using
the value of the NAME attribute.

A FileUpload object is a form element and must be defined within a FORM tag.

Property

form Specifies the form containing the FileUpload object.


name Reflects the NAME attribute.
type Reflects the TYPE attribute.
value Reflects the current value of the file upload element's field; this corresponds
to the name of the file to upload.
select Selects the input area of the file upload field.

Hidden

A Text object that is suppressed from form display on an HTML form. A Hidden
object is used for passing name/value pairs hen a form submits.

The HTML INPUT tag, with "hidden" as the value of the TYPE attribute. For a
given form, the JavaScript runtime engine creates appropriate Hidden objects and puts
these objects in the elements array of the corresponding Form object. A Hidden object is
accessed by indexing this array. The array can be indexed either by number or, if
supplied, by using the value of he NAME attribute.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A Hidden object is a form element and must be defined within a FORM tag.

A Hidden object cannot be seen or modified by an end user, but you can
programmatically change the value of the object by hanging its value property. The
Hidden objects are used for client/server communication.

Property

form Specifies the form containing the Hidden object.


name Reflects the NAME attribute.

Page 281
Java Programming

type Reflects the TYPE attribute.


value Reflects the current value of the Hidden object.

Option

An option in a selection list.

The Option constructor or the HTML OPTION tag. To create an Option object
with its constructor:

new Option(text, value, defaultSelected, selected)

Once an Option object is created, it can be added to a selection list using the
Select.options array.

Parameters

text (Optional) Specifies the text to display in the select list.


value (Optional) Specifies a value that is returned to the server when the
option is selected and the form is submitted.
defaultSelected (Optional) Specifies whether the option is initially selected (true or
false).
selected (Optional) Specifies the current selection state of the option (true or
false).

Property

defaultSelected Specifies the initial selection state of the option


selected Specifies the current selection state of the option
text Specifies the text for the option
value Specifies the value that is returned to the server when the option is
selected and the form is submitted

Usually we work with Option objects in the context of a selection list (a Select
object). When JavaScript creates a Select object for each SELECT tag in the document, it
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
creates Option objects for the OPTION tags inside the SELECT tag and puts those
objects in the options array of the Select object.

In addition, new options can be created using the Option constructor and add
those to a selection list. After the creating the option and adding it to the Select object,
the document must be refreshed by using history.go(0). This statement must be last.
When the document reloads, variables are lost if not saved in cookies or form element
values.

Page 282
Java Programming

The Option.selected and Select.selectedIndex properties can be used to change the


selection state of an option.

The Select.selectedIndex property is an integer specifying the index of the


selected option. This is most useful for Select objects that are created without the
MULTIPLE attributes. The following statement sets a Select object's

selectedIndex property: document.myForm.musicTypes.selectedIndex = i

The Option.selected property is a Boolean value specifying the current


selection state of the option in a Select object. If an option is selected, its selected
property is true; otherwise it is false. This is more useful for Select objects that are
created with the MULTIPLE attributes. The following statement sets an option's selected
property to true:

document.myForm.musicTypes.options[i].selected = true

To change an option's text, use is Option.text property. For example, suppose a


form has the following Select object:

<SELECT name="userChoice">
<OPTION>Choice 1
<OPTION>Choice 2
<OPTION>Choice 3
</SELECT>

The text of the item in the selection can be set based on text entered in a text field
named whatsNew as follows:

myform.userChoice.options[i].text = myform.whatsNew.value

No need to reload or refresh after changing an option's text.

Password

A text field on an HTML form that conceals its value by displaying asterisks (*).
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
When the user enters text into the field, asterisks (*) hide entries from view.

The HTML INPUT tag, with "password" as the value of the TYPE attribute. For a
given form, the JavaScript runtime engine creates appropriate Password objects and puts
these objects in the elements array of the corresponding Form object. The Password
object can be accessed by indexing this array. The array can be indexed either by number
or, if supplied, by using the value of the NAME attribute.

A Password object is a form element and must be defined within a FORM tag.

Page 283
Java Programming

Properties

defaultValue Reflects the VALUE attribute.


form Specifies the form containing the Password object.
name Reflects the NAME attribute.
type Reflects the TYPE attribute.
value Reflects the current value of the Password object's field.

Radio

An individual radio button in a set of radio buttons on an HTML form. The user
can use a set of radio buttons to choose one item from a list.

The HTML INPUT tag, with "radio" as the value of the TYPE attribute. All the
radio buttons in a single group must have the same value for the NAME attribute. This
allows them to be accessed as a single group.

For a given form, the JavaScript runtime engine creates an individual Radio
object for each radio button in that form. It puts in a single array all the Radio objects that
have the same value for the NAME attribute. It puts that array in the elements array of the
corresponding Form object. If a single form has multiple sets of radio buttons, the
elements array has multiple Radio objects.

You access a set of buttons by accessing the Form.elements array (either by


number or by using the value of the NAME attribute). To access the individual radio
buttons in that set, you use the returned object array. For example, if your document has a
form called emp with a set of radio buttons whose NAME attribute is "dept", you would
access the individual buttons as document.emp.dept[0], document.emp.dept[1], and so
on. A Radio object is a form element and must be defined within a FORM tag.

Properties

checked Lets to programmatically select a radio button (property of the


individual button).
defaultChecked Reflects the CHECKED attribute (property of the individual
button).
form ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Specifies the form containing the Radio object (property of the array
of buttons).
name Reflects the NAME attribute (property of the array of buttons).
type Reflects the TYPE attribute (property of the array of buttons).
value Reflects the VALUE attribute (property of the array of buttons).

Reset
A reset button on an HTML form. A reset button resets all elements in a form to
their defaults.

Page 284
Java Programming

Select
A selection list on an HTML form. The user can choose one or more items from a
selection list, depending on how the list was created.

The HTML SELECT tag. For a given form, the JavaScript runtime engine creates
appropriate Select objects for each selection list and puts these objects in the elements
array of the corresponding Form object. A Select object can be accessed by indexing this
array. The array can be indexed either by number or, if supplied, by using the value of the
NAME attribute.

The runtime engine also creates Option objects for each OPTION tag inside the
SELECT tag.

A Select object is a form element and must be defined within a FORM tag.

Properties

form Specifies the form containing the selection list.


length Reflects the number of options in the selection list.
name Reflects the NAME attribute.
options Reflects the OPTION tags.
selectedIndex Reflects the index of the selected option (or the first selected
option, if multiple options are selected).
type Specifies that the object is represents a selection list and
whether it can have one or more selected options.

Submit

A submit button on an HTML form. A submit button causes a form to be


submitted.

The HTML INPUT tag, with "submit" as the value of the TYPE attribute. For a
given form, the JavaScript runtime engine creates an appropriate Submit object and puts
it in the elements array of the corresponding Form object. A Submit object can be
accessed by indexing this array. The array can be indexed either by number or, if
supplied, by using the value of the NAME attribute.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A Submit object is a form element and must be defined within a FORM tag.

Clicking a submit button submits a form to the URL specified by the form's action
property. This action always loads a new page into the client; it may be the same as the
current page, if the action so specifies or is not specified.

The submit button's onClick event handler cannot prevent a form from being
submitted; instead, use the form's onSubmit event handler or use the submit method
instead of a Submit object. See the examples for the Form object.

Page 285
Java Programming

Properties

form Specifies the form containing the Submit object.


name Reflects the NAME attribute.
type Reflects the TYPE attribute.
value Reflects the VALUE attribute.
Text

A text input field on an HTML form. The user can enter a word, phrase, or series
of numbers in a text field.

The HTML INPUT tag, with "text" as the value of the TYPE attribute. For a
given form, the JavaScript runtime engine creates appropriate Text objects and puts these
objects in the elements array of the corresponding Form object. You access a Text object
by indexing this array. You can index the array either by number or, if supplied, by using
the value of the NAME attribute.

To define a Text object, use standard HTML syntax with the addition of
JavaScript event handlers.

A Text object is a form element and must be defined within a FORM tag.

Text objects can be updated (redrawn) dynamically by setting the value property
(this.value).

Properties

defaultValue Reflects the VALUE attribute.


form Specifies the form containing the Text object.
name Reflects the NAME attribute.
type Reflects the TYPE attribute.
value Reflects the current value of the Text object's field.

Textarea

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A multiline input field on an HTML form. The user can use a textarea field to
enter words, phrases, or numbers.

The HTML TEXTAREA tag. For a given form, the JavaScript runtime engine
creates appropriate Textarea objects and puts these objects in the elements array of the
corresponding Form object. A Textarea object can be accessed by indexing this array.
The array can be indexed either by number or, if supplied, by using the value of the
NAME attribute.

Page 286
Java Programming

To define a text area, use standard HTML syntax with the addition of JavaScript
event handlers.

A Textarea object is a form element and must be defined within a FORM tag.

Textarea objects can be updated (redrawn) dynamically by setting the value


property (this.value).

To begin a new line in a Textarea object, you can use a newline character.
Although this character varies from platform to platform (Unix is \n, Windows is \r, and
Macintosh is \n), JavaScript checks for all newline characters before setting a string-
valued property and translates them as needed for the user's platform. A new value could
also be entered programmatically--one way is to test the navigator.appVersion property to
determine the current platform, then set the newline character accordingly.

Properties

defaultValue Reflects the VALUE attribute.


form Specifies the form containing the Textarea object.
name Reflects the NAME attribute.
type Specifies that the object is a Textarea object.
value Reflects the current value of the Textarea object.

5.2.1.9 Event Handling

What are Events?

Events are signals generated when specific actions occur.

Event-Description

Abort Occurs when the user cancels loading of an image-


Blur Occurs when input focus is removed from a form element (when the
use clicks outside a field) or focus is removed from a window.
Click Occurs when the user clicks on a link or form element.
Change
Error
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Occurs when the value of a form field is changed by the user.
Occurs when an error happens during loading of a document or image.
Focus Occurs when input focus is given to a form element or a window.
Load Occurs when a page is loaded into Navigator.
Mouseout Occurs when the user moves the pointer off of a link or clickable area
of an imagemap.
Mouseover Occurs when the user moves the pointer over a hypertext link.
Reset Occurs when the user clears a form using the reset button.
Select Occurs when the user selects a form element's field.
Submit Occurs when a form is submitted (i.e. , when the user clicks on a
submit button)

Page 287
Java Programming

Unload Occurs when the user leaves a page.

What are Event Handlers?

Event handlers are scripts, in the form of attributes of specific HTML tags, which
you as the programmer can write

Object Event-Handlers-Available

Selection list OnBlur,onChange,onFocus


Text element OnBlur,onChange,onFocus, onSelect
Textarea element OnBlur,onChange,onFocus, onSelect
Button element OnClick
Checkbox OnClick
Radio button OnClick.
Hypertext link OnCiick, onMouseOver, OnMouseOut
Clickable imagemap area OnMouseOver, OnMouseOut
Reset button OnClick
Submit button OnClick
Document OnLoad, onUnLoad, onError
Window OnUnLoad, onError, OnBlur, onFocus
Frame sets OnBlur, onFocus
Form OnSubmit, onReset
Image OnLoad, onError, onAbort

The onLoad and onDnLoad Event Handlers

The Load event is generated when a page has completed loading. Likewise, the
UnLoad event occurs when the user exits a page.

Example:

<HTML>
<HEAD> <TITLE> JavaScript<TITLE>
<SCRIPT LANGUAGE^ JavaScript" > <! - - HIDE THE SCRIPT FROM
ANNAMALAI
ANNAMALAI UNIVERSITY
OTHER BROWSERS UNIVERSITY
var name = " " ;

//STOP HIDING FROM OTHER BROWSERS- ->


</SCRIPT>
</HEAD>

<BODY onLoad =" name == prompt ('Enter Your Name: ' , 'Name') ;
alert ('Greetings * + name + ', welcome to my page'');" onUnLoad = "
alert {'Goodbye ' + name •»- ', sorry to see you go!'»;->

Page 288
Java Programming

<IMG SRC = " title.gif >


</BODY>
</HTML>

Likewise you can use functions for this script to make it easier to read:
<HTML>
<HEAD> <TITLE> JavaScript<TITLE>
<SCRIPT LANGUAGE=" JavaScript" > <! - - HIDE THE SCRIPT FROM
OTHER BROWSERS
//DEFINE GLOBAL VARIABLE

var name = " " ;


function hello()
{
name = prompt('Enter Your Name:','Name') ;
alert('Greetings ' + name + ', welcome to my page!');
}
function goodbye()
{
alert('Goodbye ' + name + ', sorry to see you go!');
)
//STOP HIDING FROM OTHER BROWSERS - ->
</SCRIPT>
</HEAD>
<BODY onLoad == - hello();" onUnLoad = " goodbye();" >
<IMG SRC = " title.gif" > </BODY>
</HTML>

Commands and Extensions Review:

Extension Type Description

Blur() JavaScript method Removes focus from a specified object.


Click() JavaScript method Emulates a mouse click on an obj ect.
Focus() JavaScript method Emulates the user focusing on a
particular form field
ANNAMALAI
ANNAMALAI UNIVERSITY
Reset () UNIVERSITY
JavaScript method Emulates the user clicking on the Reset
button of a form.
Submit() JavaScript method Emulates a click on the submit button of
a form.
Select () JavaScript method Selects the input area of a
particular form field.
OnAbort Event Handler Specifies the JavaScript code to execute
when the users cancel the loading of an
image
OnLoad Event Handler Specifies the JavaScript code to execute
Page 289
Java Programming

when a page finishes loading.


OnUnLoad Event Handler Specifies the JavaScript code to execute
when the user opens a new URL.
Math.random() JavaScript method Generates a random number between 0
and 1.
Math.sqrtO JavaScript method Calculates the square root of a number.
Window.open() JavaScript method Opens a URL in a named window or
frame.
Math.round() JavaScript method Rounds a floating-point value to the
closest integer.
OnFocus Event Handler Specifies the JavaScript code to execute
when the use gives focus to a form field
or a window.
OnBlur Event Handler Specifies the JavaScript code to execute
when the user moves the mouse off a link or
clickable area of an image map.
OnMouseOut Event Handler Specifies the JavaScripfc code to execute
when the user moves the mouse off a
link or clickable area o£ an image map
OnMouseOver Event Handler Specifies the .JavaScript code to
execute when the user moves the mouse
over a link or clickable area of an image
map
OnError Event Handler Specifies the JavaScript code to execute
when the loading of a document or image
generates an error.
OnChange Event Handler Specifies the JavaScript code to execute
when the user changes the value of a
form field.

Example 1

The first example demonstrates that it is possible to create functions in JavaScript


that automate certain HTML tasks. By using custom-designed functions you can shorten
or simplify HTML documents that contain repetitive elements. The following code
demonstrates these sorts of functions:
ANNAMALAI
ANNAMALAI UNIVERSITY
<HTML>
UNIVERSITY
<HEAD>
<TITLE>HTML document for the World Wide Web</TITLE>
<SCRIPT>
<!--- hide script from old browsers
function outputH(text, level)
{
document.write("<H" + level + ">" + text + "</H" + level + ">")
}

Page 290
Java Programming

function outputP(text)
{
document.write("<P>" + text)
}
// end hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT>
<!--- hide script from old browsers
outputH("This is big", 3)
outputH("This is bigger", 2)
outputH("This is biggest", 1)
outputP("This isn't big")
// end hiding from old browsers -->
</SCRIPT>
</BODY>
</HTML>

There are several important things to notice in this simple script:


In the <head> section there is a <script> tag that contains two functions named
outputP and outputH. These functions are not intended to be useful - they simply
demonstrate the process.

The <body> section also contains a <script> tag that calls the two functions.

Note that both pieces of script code are held within comments. These comments
protect the code so that it is not displayed in pre-JavaScript browsers, but do not affect
the JavaScript interpreter.

Note that the functions have parameters but you do not have to worry about
parameter types. In general, JavaScript will make all typing and type conversion
decisions for you and you do not have to worry about them.

In the body, you can see calls to the functions.


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
JavaScript contains objects (document is an object, for example), but does not
allow you to create new ones. The objects have methods that you call like functions. In
this case, the write method of the document object is called to send HTML output into the
document. HTML code is sequential, like output from a teletype, and whenever you write
something to the document it is appended to what is already there and interpreted
immediately.

Example 2

Page 291
Java Programming

The second example demonstrates how you can call a function in response to an
event in a control.

<HTML>
<HEAD>
<TITLE> JavaScript Test </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide this script tag's contents from old browsers
function myFunction(form)
{
if (form.data.value == "")
alert ("You typed nothing");
else
alert ("You typed: " + form.data.value);
}
<!-- done hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<P>
Enter text in the field, remove focus and watch it appear in a mesage box.
<FORM method=POST >
<TEXTAREA NAME="data" ROWS=5 COLS=50
onChange=myFunction(this.form)>
Enter your data here.
</TEXTAREA>
</FORM>
</BODY>
</HTML>

This script demonstrates that you can call functions in response to events. In this
case, when the text area generates an onChange event, the function gets called. It in turn
produces a dialog box. The contents of the dialog depends on the contents of the text area
(be sure the text area contains absolutely nothing to see the "nothing" dialog). Note that
the onChange function is not triggered until you remove focus from the text area. Since
there is only one control in this document, you must click somewhere else in the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
document to change the focus.

Example 3

The third example demonstrates that you can create simple applications in
JavaScript. Here the program creates an extremely simple application able to multiply
two numbers together, but you can easily imagine more complicated scripts:

<HTML>
<HEAD>
<TITLE> The JavaScript Interest Calculator</TITLE>
Page 292
Java Programming

<SCRIPT LANGUAGE="JavaScript">
<!-- hide this script tag's contents from old browsers

function computeProduct(form)
{
if ((form.one.value == "") || (form.two.value == ""))
{
return;
}
form.product.value = form.one.value * form. two.value;
}

function clearForm(form)
{
form.one.value = "1";
form.two.value = "2";
form.product.value = "Product";
}

<!-- done hiding from old browsers -->


</SCRIPT>
</HEAD>

<BODY>
Enter two numbers to find their product.
<FORM method=POST>
<INPUT NAME=one VALUE=1 onChange=computeProduct(this.form)> *
<INPUT NAME=two VALUE=2 onChange=computeProduct(this.form)> =
<INPUT NAME=product VALUE=Product
onChange=computeProduct(this.form)>
<BR>
<INPUT NAME=clear VALUE=Reset TYPE=BUTTON
onClick=clearForm(this.form)>
<INPUT NAME=calc VALUE=Calculate
TYPE=BUTTON onClick=computeProduct(this.form)>
</FORM>
ANNAMALAI
ANNAMALAI UNIVERSITY
</BODY>
</HTML>
UNIVERSITY
In this program, three editable areas and two buttons create the "application". The
two buttons each call functions that perform obvious tasks. The edit controls also call
functions when they change.

Example 4

Page 293
Java Programming

The following example demonstrates how to use the setTimeout feature and the
status method of the window class to create a scrolling banner on the status line.

<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript Applet -------------------

function scroller(distance)
{
var msg = "Welcome to the On-Line Training Center! Please
sign our guest book if you have a minute...";
var out = " ";
var cmd = "";
var i = 0;
if (distance < 0)
{
distance = 300;
cmd="scroller(" + distance + ")";
window.setTimeout(cmd,100);
}
else if (distance > msg.length)
{
out = "";
for (i=0 ; i < distance - msg.length; i++)
{
out += " ";
}
out += msg;
distance--;
cmd="scroller(" + distance + ")";
window.status=out;
window.setTimeout(cmd,100);
}
else
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
out = msg.substring(msg.length-distance, msg.length);
distance--;
cmd="scroller(" + distance + ")";
window.status=out;
window.setTimeout(cmd,100);
}
}
// -- End of JavaScript code -------------- -->
</SCRIPT>
</head>

Page 294
Java Programming

<BODY onLoad="window.setTimeout('scroller(300)',500);" >


<h1>This is a test</h1>
</body>
</html>

The code creates a function called scroller. This function is first called by body's
the onLoad event when the page loads. The scroller function simply creates a string and
sends it to window.status (the status line for the browser window). The message initially
consists of a long line of spaces, which are reduced each time the function loops.
Eventually the actual message scrolls into view and moves across the status area.

The line of spaces in this code has to be long enough to cover the " widest
possible window". In the code that width is set in the onLoad event and in the first if
statement. You could change the code to display the whole message left justified for a
second or two, and then scroll it off to the left or right. That would get you out of the
business of having to guess the widest possible window.

5.2.1.10 What JavaScript Isn't

There are a number of common misconceptions about JavaScript. I'll just clear
them up now.

JavaScript Is not Java At one time, Netscape added a little scripting language to
Navigator 2, which they called LiveScript. They had high hopes for this language, but
hardly anyone paid attention to it -- most of the mind share was being given to a new
language called Java, which had been recently released by Sun Microsystems.

The marketing department at Netscape decided that it was better to switch than
fight, and (with permission from Sun) changed the name of LiveScript to JavaScript.
After that, getting attention became much easier. Unfortunately, this led to the common
side effect that many people think that they're the same language, or that JavaScript is a
"light" version of Java, or that Sun invented JavaScript. None of these stories are true,
and the only thing that the two have in common are the first four letters.
JavaScript Is not a Security Risk This myth started due to a number of horror
stories that tried to convince everyone that they should turn JavaScript off because

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
otherwise, bad, bad things could happen. The stories just aren't true. There are no verified
reports of anyone, ever, using JavaScript by itself in a way that creates a security hole on
a live site. And in every case where someone has written an exploit using JavaScript
combined with a server-side program, the hack could have been done just as well without
JavaScript.
JavaScript Can't Do Everything While one wishes that JavaScript could do
everything, but it can't. JavaScript can't read from or write to ones hard drive, and
JavaScript can't send e-mail. JavaScript also can't get rid of the need for server-side
programs; for instance, it can't keep track of visit counters or store form info in a
database.

Page 295
Java Programming

5.2.2 Introduction to VBScript

Adding VBScript to Web Pages

Scripting languages, like JavaScript and VBScript, are designed as an extension to


HTML. It is a product of Microsoft. The web browser receives scripts along with the rest
of the web document. It is the browser's responsibility to parse and process the scripts.
HTML was extended to include a tag that is used to incorporate scripts into HTML - the
<SCRIPT> tag.

The <SCRIPT> Tag

Scripts are added into the web pages within a pair of <SCRIPT> tags. The
<SCRIPT> tag signifies the start of the script section, while </SCRIPT> marks the end.
An example of this is shown below:

<HTML>
<HEAD>
<TITLE>Working With VBScript</TITLE>
<SCRIPT LANGUAGE="VBScript">
MsgBox "Welcome to my Web page!"
</SCRIPT>

The beginning <SCRIPT> tag includes a LANGUAGE argument that indicates


the scripting language that will be used. The LANGUAGE argument is required because
there is more than one scripting language. Without the LANGUAGE argument, a web
browser would not know if the text between the tags was JavaScript, VBScript or another
scripting language.

While technically scripts can be places throughout an HTML document using


pairs of <SCRIPT> tags, typically scripts are often found at either the top or bottom of a
Web document. This provides for easy reference and maintenance.

Handling Non-Supporting Browsers

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Not all browsers support scripting languages. Some only support JavaScript. Only
Microsoft's Internet Explorer supports VBScript. One might be wondering what happens
to his/her scripts when non-supporting browsers encounter them. Usually browsers will
do what they do most frequently with text, they will display the scripts as part of the web
page. Obviously, this isn't the result one had hoped for. One simple way to address this
problem is to encase the scripts in comment tags (<!-- and -->). Below is an example
script as it appears with the addition of the comment tags:

<HTML>
<HEAD>

Page 296
Java Programming

<TITLE>Working With VBScript</TITLE>


<SCRIPT LANGUAGE="VBScript">
<!--
MsgBox "Welcome to my Web page!"
-->
</SCRIPT>
</HEAD>
</HTML>

Now, when a browser that does not support VBScript processes this page, it will
view the script as a comment and simply ignore it.

Variables

Let's look at a simple VBScript example to clarify the use of variables.

Sub cmdVariables_OnClick
Dim Name
Name = InputBox("Enter your name: ")
MsgBox "The name you entered was " & Name
End Sub

The first line of this example defines a sub procedure associated with the click
event of a command button named cmdVariables.

On the second line a variable named Name is declared. This variable is used to
store the name of the user when it is entered. The third line uses the InputBox function to
first prompt for, and then return, the user's name. The name it returns is stored in the
Name variable.

The fourth line uses the MsgBox function to display the user's name. Finally, the
sub procedure completes on line five.

Exactly how, and where, variables are stored is not important. What for it is used
and how it is used is important.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Declaring Variables

There are two methods for declaring variables in VBScript, explicitly and
implicitly. Variables are usually and explicitly declared with the Dim statement:

Dim Name

This statement declares the variable Name. Multiple variables can also be
declared on one line as shown below, although it is preferable to declare each variable
separately:

Page 297
Java Programming

Dim Name, Address, City, State

Variables can be declared implicitly by simply using the variable name within the
script. This practice is not recommended. It leads to code that is prone to errors and more
difficult to debug.

VBScript can be forced to require all variables to be explicitly declared by


including the statement Option Explicit at the start of every script. Any variable that is
not explicitly declared will then generate an error.

Variable Naming Rules

When naming variables the following rules apply:

They must begin with an alphabetic character


They cannot contain embedded periods
They must be unique within the same scope.

Variants and Subtypes

VBScript has a single data type called a variant. Variants have the ability to store
different types of data. The types of data that a variant can store are referred to as
subtypes. The table below describes the subtypes supported by VBScript.

S
Description of Uses for Each Subtype
ubtype
B
Integer numbers between 0 to 255
yte
B
True and False
oolean
C
Monetary values
urrency
D
ate
ANNAMALAI
ANNAMALAI UNIVERSITY
D
UNIVERSITY
Date and time

Extremely large numbers with decimal points


ouble
E
The value that a variant holds before being used
mpty
E
An error number
rror
I
Large integers between -32,768 and 32,767
nteger

Page 298
Java Programming

L Extremely large integers (-2,147,483,648 and


ong 2,147,483,647)
O
Objects
bject
N
No valid data
ull
S
Large numbers with decimal points
ingle
S
Character strings
tring

Assigning Values

A value can be assigned to a variable by using the following format:

Variable_name = value

The following examples demonstrate assigning values to variables:

Name = "Larry Roof"


HoursWorked = 50
Overtime = True

Scope of Variables

The scope of a variable dictates where it can be used in the script. A variable's
scope is determined by where it is declared. If it is declared within a procedure, it is
referred to as a procedure-level variable and can only be used within that procedure. If it
is declared outside of any procedure, it is a script-level variable and can be used
throughout the script.

The example below demonstrates both script-level and procedure-level variables.


<SCRIPT>
Dim counter
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Sub cmdButton_onClick
Dim temp
End Sub
</SCRIPT>

The variable counter is a script-level variable and can be utilized throughout the
script. The variable temp exists only within the cmdButton_onClick sub-procedure.

Constants

Page 299
Java Programming

VBScript does not provide support for constants, such as one finds in other
programming languages. One can work around this by assigning values to variables that
he has defined as shown in the example below. Here, TAX_RATE is a constant.

<SCRIPT>
Dim TAX_RATE
TAX_RATE = .06
Function CalculateTaxes
CalculateTaxes = CostOfGoods * TAX_RATE
End Function
</SCRIPT>

Arrays

The VBScript language provides support for arrays. An array can be declared
using the Dim statement, just as done with variables:

Dim States(50)

The statement above creates an array with 51 elements. Why 51? Because
VBScript arrays are zero-based, meaning that the first array element is indexed 0 and the
last is the number specified when declaring the array.

Values can be assigned to the elements of an array just as we would a variable,


but with an additional reference (the index) to the element in which it will be stored:

States(5) = "California"
States(6) = "New York"

Arrays can have multiple dimensions-VBScript supports up to 60. Declaring a


two dimensional array for storing 51 states and their capitals could be done as follows:

Dim StateInfo(50,1)

To store values into this array we would then reference both dimensions.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
StateInfo(18,0) = "Michigan"
StateInfo(18,1) = "Lansing"

VBScript also provides support for arrays whose size may need to change as the
script is executing. These arrays are referred to as dynamic arrays. A dynamic array is
declared without specifying the number of elements it will contain:

Dim Customers()

Page 300
Java Programming

The ReDim statement is then used to change the size of the array from within the
script:

ReDim Customers(100)

There is no limit to the number of times an array can be re-dimensioned during


the execution of a script. To preserve the contents of an array when we are re-
dimensioning, use the Preserve keyword:

ReDim Preserve Customers(100)

VBScript has a full range of operators, including arithmetic operators, comparison


operators, concatenation operators, and logical operators.

Operator Precedence

When several operations occur in an expression, each part is evaluated and


resolved in a predetermined order called operator precedence. Parentheses is used to
override the order of precedence and force some parts of an expression to be evaluated
before others. Operations within parentheses are always performed before those outside.
Within parentheses, however, standard operator precedence is maintained.

When expressions contain operators from more than one category, arithmetic
operators are evaluated first, comparison operators are evaluated next, and logical
operators are evaluated last. Comparison operators all have equal precedence; that is, they
are evaluated in the left-to-right order in which they appear. Arithmetic and logical
operators are evaluated in the following order of precedence.

Arithmetic Comparison Logical


Description Symbol Description Description Symbol
Symbol
Exponentiation ^ Equality = Logical negation Not
Unary negation - Inequality <> Logical conjunction And
MultiplicationANNAMALAI
ANNAMALAI UNIVERSITY
* UNIVERSITY
Less than < Logical disjunction Or
Division / Greater than > Logical exclusion Xor
Integer division \ Less than or equal to <= Logical equivalence Eqv
Modulus Mod Greater than or equal >= Logical implication Imp
arithmetic to
Addition + Object equivalence Is
Subtraction -

Page 301
Java Programming

String &
concatenation

When multiplication and division occur together in an expression, each operation


is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur
together in an expression, each operation is evaluated in order of appearance from left to
right.

The string concatenation (&) operator is not an arithmetic operator, but in


precedence it does fall after all arithmetic operators and before all comparison operators.
The Is operator is an object reference comparison operator. It does not compare objects or
their values; it checks only to determine if two object references refer to the same object.

Controlling the VBScript Routines

VBScript allows to control how the scripts process data through the use of
conditional and looping statements. By using conditional statements one can develop
scripts that evaluate data and use criteria to determine what tasks to perform. Looping
statements allows to repetitively execute lines of a script. Each offers benefits to the
script developer in the process of creating more complex and functional web pages.

Conditional Statements

VBScript provides two forms of conditional statements:

If..Then..Else

Select..Case

If..Then..Else

The If..Then..Else statement is used, first to evaluate a condition to see if it is true


or false and second, depending upon the condition, to execute a statement or set of
statements.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The simplest version of an If statement is one that contains only a condition and a
single statement:

If AmountPurchased > 10000 Then


DiscountAmount = AmountPurchased * .10

In this example statement the condition is:


If AmountPurchased > 10000

Page 302
Java Programming

which simply checks to see if the contents of the variable AmountPurchased is


greater than ten thousand. If it is, the condition is true. In this simple version of the If
statement when the condition is true the following statement is executed:

DiscountAmount = AmountPurchased * .10

Next we will look at a more complicated version of the If statement. In this


version we will perform a series of statements when the condition is true:

If AmountPurchased > 10000 Then


DiscountAmount = AmountPurchased * .10
Subtotal = AmountPurchased - DiscountAmount
End If

In this form of the If statement, one or more statements can be executed when the
condition is true, by placing them between the If statement on top and the End If
statement on the bottom.

The next form of the If statement uses the If..Then..Else format.

If AmountPurchased > 10000 Then


DiscountAmount = AmountPurchased * .10
Subtotal = AmountPurchased - DiscountAmount
Else
HandlingFee = AmountPurchased *.03
Subtotal = AmountPurchased + HandlingFee
End If

In this example when the condition is true, that is the customer's order is over
$10,000, they receive a 10% discount. When the order is under $10,000, they are charged
a 3% handling fee.

The final version of the If statement is the If..Then..Else If. In this form the If
statement checks each of the conditions until it either finds one that is true or an Else
statement:

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
If AmountPurchased > 10000 Then
DiscountAmount = AmountPurchased * .10
Subtotal = AmountPurchased - DiscountAmount
Else If AmountPurchased > 5000 Then
DiscountAmount = AmountPurchased * .05
Subtotal = AmountPurchased - DiscountAmount
Else
HandlingFee = AmountPurchased *.03
Subtotal = AmountPurchased + HandlingFee
End If

Page 303
Java Programming

In this example the customer receives a 10%discount for orders over $10000, a
5% discount for orders over $5000 and a handling fee of 3% for orders under $5000.

Select Case

The Select Case statement provides an alternative to the If..Then..Else statement,


providing additional control and readability when evaluating complex conditions. It is
well suited for situations where there are a number of possible conditions for the value
being checked. Like the If statement the Select Case structure checks a condition, and
based upon that condition being true, executes a series of statements.

The syntax of the Select Case statement is:

Select Case condition


Case value
Case value
...
Case Else
End Select

For example, the following Select statement assigns different shipping fees based
upon the State where the order is being sent:

Select Case Document.frmOrder.txtState.Value


Case "California"
ShippingFee= .04
Case "Florida"
ShippingFee = .03
Case Else
ShippingFee = .02
End Select

The Select Case statement checks each of the Case statements until it finds one
that will result in the condition being true. If none are found to be true, it executes the
statements within the Case Else.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Looping Statements

VBScript provides four forms of looping statements:

For..Next
For Each..Next
Do..Loop
While..Wend

Page 304
Java Programming

These four statements can be divided into two groups. The For statements are best
used when one wants to perform a loop a specific number of times. The Do..While and
While..Wend statements are best used to perform a loop an undetermined number of
times.

For..Next

The For..Next structure is used if we want to perform a loop a specific number of


times. It uses a counter variable, which is incremented or decremented with each
repetition of the loop. The following example demonstrates a simple For loop:

For counter = 1 To 12
result = 5 * counter
MsgBox counter & " times 5 is " & result
Next counter

The variable counter is the numeric value being incremented or decremented. The
number 1, defines the start of the loop, 12 the end of the loop. When this loop executes it
will display twelve dialog box messages, each containing the product of multiplying five
times the counter as it runs from 1 to 12.
In this example, the variable counter is incremented by 1 with each loop.
Optionally, we could control how we wanted the counter to be modified through the
addition of the Step argument:

For counter = 1 To 12 Step 2


result = 5 * counter
MsgBox counter & " times 5 is " & result
Next counter

This slight modification to the loop results in only the products of the odd
numbers between 1 and 12 being displayed. If you want to create a countdown loop,
where the number is decremented with each loop simply use a negative value with the
Step argument as shown in the following example:

For counter = 12 To 1 Step -1


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
result = 5 * counter
MsgBox counter & " times 5 is " & result
Next counter

Note that in a decrementing loop the starting number is greater than the ending
number.

For Each..Next

Page 305
Java Programming

The For Each..Next is similar to the For..Next loop but instead of repeating a loop
for a certain number of times, it repeats the loop for each member of a specified
collection.

Do..Loop

The Do..Loop structure repeats a block of statements until a specified condition is


met. Normally, when using a Do..Loop, the condition being checked is the result of some
operation being performed within the structure of the loop. Two versions of this structure
are provided the Do..While and the Do..Until.

Do..While

A Do loop that contains the While keyword will be performed as long as the
condition being tested is true. There is an option of checking the condition at the start of
the loop, as in the form:

Do While condition
statement
statement
...
Loop

Or at the end of the loop as shown in the following example:

Do
statement
statement
...
Loop While condition

The difference between these two formats is that the first example may never
perform the statements included within its structure while the second example will
always perform its statements at least once.

Do..Until
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A Do loop that contains the Until keyword will continue to loop as long as the
condition being tested is false. As with the Do..While structure, there is an option of
checking the condition at the start of the loop as in the form:

Do Until condition
statement
statement
...
Loop

Page 306
Java Programming

Or at the end of the loop as shown in the following example:


Do
statement
statement
...

Loop Until condition

One use for a Do..Loop is shown in the example below:

password = InputBox("Enter your password:")

Do Until password = "letmein"


Msgbox "Invalid password - please try again."
password = InputBox("Enter you password:")
Loop

In this example we ask the user to enter a password before performing the
conditional part of the Do..Loop the first time. The result is that, if they enter the correct
password the first time, the statements within the loop's structure will never be
performed. If the user were to enter an invalid password then the statements within the
Do..Loop structure would be performed, a message would be displayed and the user
would be prompted to re-enter their password.

While..Wend

The While..Wend structure loops as long as the condition being checked is true. If
the condition is true, the While..Wend statement operates similar to the Do..Loop
structure but without its flexibility.

The structure for the While..Wend statement is:

While condition
statement
statement
...
ANNAMALAI
ANNAMALAI UNIVERSITY
Wend UNIVERSITY
First VBScript

The easiest way to learn any language is to work with it.

Exercise 1: Adding VBScript to a Web page


.
In this exercise, we will create an HTML document and add a simple script to
respond to a click event generated by a command button.

Page 307
Java Programming

Creating the HTML Document

Open up a text editor application and insert the following HTML code:

<HTML>
<HEAD>
<TITLE>Working With VBScript: Exercise 1</TITLE>
</HEAD>
<BODY>
<H1>Your First VBScript Exercise</H1>
<P> By utilizing VBScript you can give your web pages actions.
Click on the button below to see what we mean. </P>
<FORM NAME="frmExercise1">
<INPUT TYPE="Button" NAME="cmdClickMe" VALUE="Click Me">
</FORM>
</BODY>
</HTML>

Save the file and test it by loading it into Internet Explorer.

Try out and click “Click Me button” and see what happens.

5.2.3 Servlets
A servlet is a server extension. It should be a small, self-contained, portion of
code that is executed at the web server in response to an HTTP request. Servlets are
written in Java and once inside a servlet, a developer has access to all the resources
available on the Java 2 Platform. Servlets are gateways from the web tier into the
enterprise using key middleware solutions such as RMI, CORBA, JMS, MQ, JNDI and
so on.
Servlets are a powerful mechanism for a Java programmer to gain access an
object-oriented abstraction of HTTP. Servlets are portable across web servers, simple to
design and implement, have tight integration with the web server, service requests in an
efficient manner and run within the secure and reliable scope of a Java Virtual Machine
(JVM).ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Java Servlet API (Application Program Interface) assures programmers that they
can write totally portable software according to the Java principle "Write Once Run
Anywhere". Servlets are to servers what applets are to browsers. When a server has
client's data to compute a CGI program, usually written in C-like or Perl languages, is
executed. A CGI receives parameters, executes one or more computations, gets a result,
send it back to the client and exits. This means that at each client's request the same CGI
program has to be loaded, executed and terminated. This procedure is actually the most
popular in the client-server environment, but it often overloads servers.

Page 308
Java Programming

Servlets are an effective substitute for CGI scripts, they provide a way to
generate dynamic documents that is both easier to write and faster to run. They also
address the problem of doing server-side programming with platform-specific APIs.
Servlets are developed with the Java Servlet API, a standard Java extension. While it is
not part of the core Java framework, which must always be part of all products bearing
the Java brand, it will be made available with such products by their vendors as an add-on
package. Many popular web servers already support it.

The API tells about how a servlet is loaded, the server environment in which the
servlet runs, or the protocol used to transmit data to and from the user. This allows
servlets to be embedded in many different web servers. A servlet engine provides the
runtime environment in which a servlet executes. The servlet engine manages the life-
cycle of servlets from when they are first created through to their imminent destruction.
The servlet engine exposes an API based on the version of the servlet specification that it
implements. It is this Servlet API that developers write their servlets against. The result,
servlet portability between servlet engines that adhere to the specification.

How portable are servlet engines across proprietary web servers? Not really. This
is a question for the vendors, implementors of servlet engines. Some have implemented
them natively for the major web servers such as IIS/ISAPI and Netcape/NSAPI whilst
others have written them in pure Java (eg. Jigsaw, Tomcat).

Relationship between web server, servlet Engine and servlets


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Servlet engines come in two flavors: standalone and add-on. A standalone servlet
engine is a fully functioning web server with support for servlets, for example,
WebSphere, Java Web Server, IPlanet and W3's Jigsaw.

An add-on servlet engine is a plug-in that can be added to a web server to give it
the servlet support it was probably never designed to have. Examples of add-on servlet
engines are ServletExec and Tomcat, the former being very easy to configure so that even
IIS can comfortably support Java Servlets!. Moreover Java application development is
easier than C or Perl, so it is easier to create a Java error free application. All these
advantages are obtained to the detriment of a longer execution time. Therefore the

Page 309
Java Programming

developers decided to have servlet loaded and initialized just once in all their life cycle.
According to this strategy, a servlet is loaded at the first execution and then it is ready to
run again without reloading. A servlet life cycle ends only when a particular method is
invoked.

5.2.3.1 Use of Servlets

A few of the many applications to include servlets are, Processing data POSTed
over HTTPS using an HTML form, including purchase order or credit card data. A
servlet like this could be part of an order-entry and processing system, working with
product and inventory databases, and perhaps an on-line payment system. Allowing
collaboration between people. A servlet can handle multiple requests concurrently; they
can synchronize requests to support systems such as on-line conferencing.

Forwarding requests. Servlets can forward requests to other servers and servlets.
This allows them to be used to balance load among several servers that mirror the same
content. It also allows them to be used to partition a single logical service over several
servers, according to task type or organizational boundaries. Being a community of active
agents. A servlet writer could define active agents that share work among each other.
Each agent would be a servlet, and the agents could pass data among themselves.

5.2.3.2 Servlet Architecture Overview

The central abstraction in the Servlet API is the Servlet interface. All servlets
implement this interface, either directly or, more commonly, by extending a class that
implements it such as HttpServlet. The Servlet interface provides for methods that
manage the servlet and its communications with clients. Servlet writers provide some or
all of these methods when developing a servlet.

When a servlet accepts a call from a client, it receives two objects: one is a
ServletRequest and the other is a ServletResponse. The ServletRequest class
encapsulates the communication from the client to the server, while the
ServletResponse class encapsulates the communication from the servlet back to the
client.

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The ServletRequest interface allows the servlet access to information such as
the names of the parameters passed in by the client, the protocol (scheme) being used by
the client, and the names of the remote host that made the request and the server that
received it. It also provides the servlet with access to the input stream,
ServletInputStream, through which the servlet gets data from clients that are using
application protocols such as the HTTP POST and PUT methods. Subclasses of
ServletRequest allow the servlet to retrieve more protocol-specific data. For example,
HttpServletRequest contains methods for accessing HTTP-specific header
information.

Page 310
Java Programming

The ServletResponse interface gives the servlet methods for replying to the
client. It allows the servlet to set the content length and mime type of the reply, and
provides an output stream, ServletOutputStream, and a Writer through which the
servlet can send the reply data. Subclasses of ServletResponse give the servlet more
protocol-specific capabilities. For example, HttpServletResponse contains methods
that allow the servlet to manipulate HTTP-specific header information.

The classes and interfaces described above make up a basic Servlet. HTTP
servlets have some additional objects that provide session-tracking capabilities. The
servlet writer can use these APIs to maintain state between the servlet and the client that
persists across multiple connections during some time period.

5.2.3.3 Servlet Lifecycle

Servers load and run servlets, which then accept zero or more requests from
clients and return data to them. They can also remove servlets. These are the steps of a
servlets lifecycle.

When a server loads a servlet, it runs the servlet's init method. Even though
most servlets are run in multi-threaded servers, there are no concurrency issues during
servlet initialization. This is because the server calls the init method once, when it loads
the servlet, and will not call it again unless it is reloading the servlet. The server can not
reload a servlet until after it has removed the servlet by calling the destroy method.
Initialization is allowed to complete before client requests are handled (that is, before the
service method is called) or the servlet is destroyed.

After the server loads and initializes the servlet, the servlet is able to handle client
requests. It processes them in its service method. Each client's request has its call to the
service method run in its own servlet thread: the method receives the client's request,
and sends the client its response.

Servlets can run multiple service methods at a time. It is important, therefore,


that service methods be written in a thread-safe manner. For example, if a service
method might update a field in the servlet object, that access should be synchronized. If,
for some reason, a server should not run multiple service methods concurrently, the
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
servlet should implement the SingleThreadModel interface. This interface guarantees
that no two threads will execute the servlet's service methods concurrently.

Servlets run until they are removed from the service, for example, at the request
of a system administrator. When a server removes a servlet, it runs the servlet's destroy
method. The method is run once; the server will not run it again until after it reloads and
reinitializes the servlet. When the destroy method runs, however, other threads might be
running service requests. If, in cleaning up, it is necessary to access shared resources
(such as network connections to be closed), that access should be synchronized. During a
Servlets lifecycle, it is important to write thread-safe code for destroying the servlet and,

Page 311
Java Programming

unless the servlet implements the SingleThreadModel interface, servicing client


requests.

5.2.3.4 Writing the Servlet

Servlets implement the javax.servlet.Servlet interface. While servlet writers


can develop servlets by implementing the interface directly, this is usually not required.
Because most servlets extend web servers that use the HTTP protocol to interact with
clients, the most common way to develop servlets is by specializing the
javax.servlet.http.HttpServlet class. This version of the tutorial concentrates on
describing this method of writing servlets.

The HttpServlet class implements the Servlet interface by extending the


GenericServlet base class, and provides a framework for handling the HTTP protocol. Its
service method supports standard HTTP/1.1 requests by dispatching each request to a
method designed to handle it.

By default, servlets written by specializing the HttpServlet class can have


multiple threads concurrently running its service method. If, for whatever reason, one
would like to have only a single thread running a service method at a time, then in
addition to extending the HttpServlet, the servlet should also implement the
SingleThreadModel interface. This does not involve writing any extra methods, merely
declaring that the servlet implements the interface. For example,

public class SurveyServlet extends HttpServlet


implements SingleThreadModel {

/* typical servlet code, with no threading concerns


* in the service method. No extra code for the
* SingleThreadModel interface. */
...

Interacting with Clients


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Servlet writers who are developing HTTP servlets that specialize the
HttpServlet class should override the method or methods designed to handle the HTTP
interactions that their servlet will handle. The candidate methods include,

doGet, for handling GET, conditional GET and HEAD requests


doPost, for handling POST requests
doPut, for handling PUT requests
doDelete, for handling DELETE requests

Page 312
Java Programming

By default, these methods return a BAD_REQUEST (400) error. An example HTTP


servlet that handles GET and HEAD requests follows; it specializes the doGet method.

The HttpServlet's service method, by default, also calls the doOptions


method when it receives an OPTIONS request, and doTrace when it receives a TRACE
request. The default implementation of doOptions automatically determines what HTTP
options are supported and returns that information. The default implementation of
doTrace causes a response with a message containing all of the headers sent in the trace
request. These methods are not typically overridden.

Whatever method we override, it will take two arguments. The first encapsulates
the data from the client, and is an HttpServletRequest. The second encapsulates the
response to the client, and is an HttpServletResponse. The following paragraphs
discuss their use.

An HttpServletRequest object provides access to HTTP header data, such as


any cookies found in the request and the HTTP method with which the request was made.
It, of course, allows to obtain the arguments that the client sent as part of the request.
How to access the client data might depend on the HTTP method of the request.

For any HTTP method, the getParameterValues method can be used, which will
return the value of a named parameter. (The method getParameterNames provides the
names of the parameters.) The request can be manually parsed.

For requests using the HTTP GET method, the getQueryString method will
return a String to be parsed.

For HTTP methods POST, PUT, and DELETE, there exists the choice between
two methods. If text data is expected, then it can be read using the BufferedReader
returned by the getReader method; if binary data is expected, then it should be read with
the ServletInputStream returned by the getInputStream method.

Note that either the getParameterValues method or one of the methods that
allow should be used to parse the data on own. They cannot be used together in a single
request.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
For responding to the client, an HttpServletResponse object provides two ways
of returning the response data to the user. The writer returned by the getWriter method
or the output stream returned by the getOutputStream method can be used. The
getWriter method should be used to return text data to the user, and getOutputStream
for binary data.

Before accessing the Writer or OutputStream, HTTP header data should be set.
The HttpServletResponse class provides methods to access the header data, such as the
content type and encoding, and content length of the response. After the headers are set,
the writer or output stream is obtained and the body of the response to the user can be
Page 313
Java Programming

sent. Closing the writer or output stream after sending the response to the client allows
the server to know when the response is complete.

The doPost method uses the getParameterNames and getParameterValues


methods to get the form data. Because it returns text to the client, doPost calls the
getWriter method. It sets the response header field, content type, before writing the
body of the response, and closes the writer when the response is complete.

5.2.3.5 Lifecycle Methods

Servlets that manage resources do so by overriding the lifecycle methods init


and destroy. These servlets might need to be given arguments at startup, in order to
initialize correctly.

Overriding the Init Method

During initialization, the servlet should prepare the resources it manages, to ready
the servlet for accepting service requests. It can do this without regard for multi-threading
concerns, since there is only a single thread running on behalf of the servlet during
initialization. As soon as the init method returns, the servlet can receive client requests.
If, for some reason, the servlet's required resources cannot be made available (for
example, a required network connection can not be established), or some other
initialization error occurs that would make it impossible for the servlet to handle requests,
the init method should throw an UnavailableException exception.

The init method takes a ServletConfig object as a parameter. The method


should save this object, so that it can be returned by the getServletConfig method. The
simplest way to do this is to have the new init method call super.init. If this is not
done, then the ServletConfig object must be stored, and the getServletConfig method
to be overridden, so that it can obtain the object from its new location.

An example of init method follows.

Initialization Parameters

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The specification of initialization parameters is server-specific. For example, they
are specified with a property when a servlet is run with the servlet runner. However the
initialization parameters are specified, they are always obtained the same way: with the
getInitParameter method. This method takes the parameter name as an argument. The
example init method calls getInitParameter. If, for some reason, there is a need to
get the parameter names, then it can be got with the getParameterNames method.

Overriding the Destroy Method

Page 314
Java Programming

When a server unloads a servlet, it calls the servlet's destroy method. The
destroy method should undo any initialization work and synchronize persistent state
with the current in-memory state.

Though it is often the case that a servlet that overrides the init method must also
override the destroy method to undo that initialization, this is not required.

For many servlets, however, there is initialization work that must be undone. For
example, assume there is a servlet that opens a database connection during initialization.
Its destroy method, shown as an example below, would close that connection.

/**
* Cleans up database connection
*/
public void destroy() {
try {
con.close();
} catch (SQLException e) {
while(e != null) {
log("SQLException: " + e.getSQLState() + '\t' +
e.getMessage() + '\t' +
e.getErrorCode() + '\t');
e = e.getNextException();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Providing Information about the Servlet
Some applets and applications, for example, the Java Web Server Administration
Tool, display information about a servlet. This information can include a short
description of the purpose of the servlet, its author, and perhaps its version number. The
Servlet API provides a method to return this information, getServletInfo. By default,
this method returns null.While servlet writers are not required to override this method, it
is strongly recommended. The simple servlet, shown as an example earlier, overrides this

ANNAMALAI
ANNAMALAI UNIVERSITY
method:
UNIVERSITY
5.2.3.6 Servlet Chaining

We can never have too much of a good thing, and that applies to servlets as much
as to anything else. It does not always make sense to keep all of the processing in one
place. Consider a Web site that wants to have a standardized header and footer on each
page, possibly with some advertising. They can make sure that every single HTML page
in the entire Web site has the up-to-date header/footer combination. This may be practical
for small sites, but what about sites with thousands of pages and constantly changing
navigation information? Or sites that need to display constantly updated data at the top of

Page 315
Java Programming

every page?The solution is something called "servlet chaining." In any browser-server


conversation, the browser will send the server a request. Usually the server will either
find a HTML page and send it back to the browser, or call a servlet and send the servlet's
output to the browser. With servlet chaining, though, the servlet's output is sent to another
servlet. The Web server may send the second servlet's output to the browser, or may send
it to a third servlet, and so on. The output from the last servlet in the chain gets sent to the
browser.

Servlet1
HTTP Request
Web
Browser Chaining
HTTP Servlet2
Response
HTTP
Service

WEB Server

When using a Java-based Web server (such as Sun's Java Web Server, the
reference platform for servlets) things get even more fun. JWS uses servlets for
everything, including a file servlet for sending HTML, graphics, and so on. We can chain
our servlets directly to the file servlet, so that any HTML page sent (we need to be careful
to check the MIME type) gets piped through another servlet first. We can even set JWS
to run any data with a specific MIME type through a servlet first: any output with a
Content-type of "text/html" could be run through our hypothetical header and footer
servlets.

Example

In order to keep things simple, we are going to put together a basic chained servlet
that will add a header to any HTML content passed through it. Then we'll chain the
servlet to the Java Web Server's file servlet. We have the option of deriving this filter
from GenericServlet or HttpServlet. If we know that the filter will only be used with
HttpServlets, we should use HttpServlet, which gives us access to a few extra features.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
On the other hand, for a generic filter that might be used with non-HTTP data, we should
derive from GenericServlet. In most cases it really doesn't matter -- for this example,
we'll use the slightly lighter weight GenericServlet class.

That decided, the first task is to get the standard ServletOutputStream, and use the
ServletRequest.getInputStream() method to obtain a ServletInputStream. Next, we make
sure we're dealing with HTML. We do this with the ServletRequest.getContentType()
method. If we are not dealing with HTML, we pass the input stream to the output stream
and exit. If it is HTML, we dump the header to the output stream and follow it with the
input stream. Here's the entire source code for the servlet:

Page 316
Java Programming

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HeaderServlet extends HttpServlet


{
public void service(HttpServletRequest req, HttpServletResponse
resp)
throws ServletException, IOException
{
ServletOutputStream out = resp.getOutputStream();
ServletInputStream in = req.getInputStream();

resp.setContentType(req.getContentType());

if(req.getContentType().equals("text/html"))
{
out.println("<HTML><HEAD>");
out.println("<TITLE>IntraExtraNets, Inc.</TITLE>");
out.println("</HEAD><BODY BGCOLOR=#FFFFFF>");
out.println("<HR>");
}
byte[] b = new byte[100];

while( in.read(b) > 0)


out.write(b); //send the original content back
out.flush();
}
}

Install this servlet in Java Web Server by opening the Web server in the
administration tool, clicking the "Servlets" button, and adding HeaderServlet as
"Header". Then click "Setup", select "Servlet Aliases", and change the alias for "/" from
"file" to "file, Header". On the "Advanced" tab in "Basic Setup" make sure, servlet
chaining is turned on. Whenever a file (other than another alias) is requested by a
browser, it will be pumped through this servlet first. Any files with a content type
"text/html" will have the header attached, and all other files will simply by passed
through.

5.2.3.7 Servlet Features


ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Servlets 1.1 includes a number of refinements to the original API, and some
useful features. Remember that these functions will initially only be supported by JWS
1.1, although JavaSoft has made the updated specification available for developers of
other servlet capable Web servers.

Session Tracking

The largest addition is certainly the HttpSession class. HttpSession adds


lightweight session tracking to servlet applications, using cookies or rewritten URLs. The
HttpSession's putValue() and getValue() methods can be used to store user identification
Page 317
Java Programming

information, shopping cart data, even database connections. To spread database


transactions over several page requests it can be carefully used.. Other methods have
been added to HttpServletRequest and HttpServletResponse to support session
management.

Standardized Cookies

The original servlets specification only supported cookies with a Java Web Server
specific class. Servlets 1.1 makes HTTP Cookie support a standard part of the API.

The Single Thread Model

Servlets 1.1 defines an empty interface called SingleThreadModel. If the servlets


implements this interface, no two separate threads will ever call the servlet's service()
method at the same time. The Web server will maintain a pool of instantiated servlets
instead. This has some performance advantages, such as allowing to easily spread
database requests over several connections, and automatically makes the servlet thread
safe. However, if this interface is used then data (such as hit counts) in class variables
cannot be stored, since changes made in one copy of the servlet will not be repeated in
the other copies.

More HttpServlet Options

In addition to doGet(), doPost() and doHead(), the new HttpServlets support the
HTTP OPTIONS, DELETE, PUT, and TRACE commands (some of which require HTTP
1.1 compatible browsers).

Servlets revisited

Servlets are Java technology's answer to CGI programming. They are programs
that run on a Web server and build Web pages. Building Web pages on the fly is useful
(and commonly done) for a number of reasons:

 The Web page is based on data submitted by the user. For example the
results pages from search engines are generated this way, and programs that process
orders for e-commerce sites do this as well.
ANNAMALAI
ANNAMALAI UNIVERSITY

UNIVERSITY
The data changes frequently. For example, a weather-report or news
headlines page might build the page dynamically, perhaps returning a previously built
page if it is still up to date.

 The Web page uses information from corporate databases or other such
sources. For example, this could be used for making a Web page at an on-line store that
lists current prices and number of items in stock.

Advantage of Servlets Over "Traditional" CGI

Page 318
Java Programming

Java servlets are more efficient, easier to use, more powerful, more portable, and
cheaper than traditional CGI and than many alternative CGI-like technologies.

Efficient. With traditional CGI, a new process is started for each HTTP request. If
the CGI program does a relatively fast operation, the overhead of starting the process can
dominate the execution time. With servlets, the Java Virtual Machine stays up, and each
request is handled by a lightweight Java thread, not a heavyweight operating system
process. Similarly, in traditional CGI, if there are N simultaneous request to the same
CGI program, then the code for the CGI program is loaded into memory N times. With
servlets, however, there are N threads but only a single copy of the servlet class. Servlets
also have more alternatives than do regular CGI programs for optimizations such as
caching previous computations, keeping database connections open, and the like.

Convenient. Already knowing Java. Why learn Perl too? Besides the convenience
of being able to use a familiar language, servlets have an extensive infrastructure for
automatically parsing and decoding HTML form data, reading and setting HTTP headers,
handling cookies, tracking sessions, and many other such utilities.

Powerful. Java servlets let to easily do several things that are difficult or
impossible with regular CGI. For one thing, servlets can talk directly to the Web server
(regular CGI programs can't). This simplifies operations that need to look up images and
other data stored in standard places. Servlets can also share data among each other,
making useful things like database connection pools easy to implement. They can also
maintain information from request to request, simplifying things like session tracking and
caching of previous computations.

Portable. Servlets are written in Java and follow a well-standardized API.


Consequently, servlets written for, say I-Planet Enterprise Server can run virtually
unchanged on Apache, Microsoft IIS, or WebStar. Servlets are supported directly or via a
plug-in on almost every major Web server.

Inexpensive. There are a number of free or very inexpensive Web servers


available that are good for "personal" use or low-volume Web sites. However, with the
major exception of Apache, which is free, most commercial-quality Web servers are
relatively expensive. Nevertheless, once there is a Web server, no matter the cost of that
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
server, adding servlet support to it (if it doesn't come preconfigured to support servlets) is
generally free or cheap.

Compiling and executing the Servlet using Javawebserver2.0


Before compiling set the classpath to jdk12 or 1.3\bin and jsdk.jar
Type the following program in an editor and give appropriate name.

Compile it using javac.

Page 319
Java Programming

Place the class file in Javawebserver2.0\servlets folder

Goto Javawebserver2.0\bin folder


Start httpd
Javawebserver will be up.

Finally to execute:

Open Internet Explorer and type “http://localhost:8080/servlet/filename and press enter,


output will be displayed as shown below for the examples

Example 1:

// HellowServlet.java
// Servlet Extends GenericServlet

import java.io.*;
import javax.servlet.*;

public class HelloServlets extends GenericServlet


{
public void service (ServletRequest req, ServletResponse response)
throws ServletException, IOException
{
response.setContentType("Text/html");
PrintWriter PW = response.getWriter();
PW.println("<B> hellow!");
PW.close();
}
}

Output for example1

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 320
Java Programming

Example 2
Program to print header information

// Extends HttpServlet
// Prints Header information

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HeaderInfo extends HttpServlet


{
public void doget (HttpServletRequest req, HttpServletResponse res)
throws IOException
{
res.setContentType("text/Plain");
PrintWriter out = res.getWriter();
out.println ("Response Header");
out.println();
Enumeration enum = req.getHeaderNames();
while(enum.hasMoreElements())
{
String name = (String) enum.nextElement();
String value = req.getHeader(name);
if (value!=null)
{
System.out.println(name + ":" + value);
}
}
}
}

ANNAMALAI
ANNAMALAI UNIVERSITY
Example 3 UNIVERSITY
Program for Creating Cookie

// Creating cookies

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class add CookieServlet extends HttpServlet

Page 321
Java Programming

{
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException,IOException
{
//get parameter from Http request
String data = request.getParameter ("data");

//create cookie
Cookie cookie = new Cookie ("myCookie", data);

//Add cookie to Http response


response.setCntentType("text/html");
res.setContentType("text/plain");

PrintWriter out = res.getWriter();


out.println("rent Header");
out.println();

Enumeration enum = req.get HeaderNames();

while (enum has more Elements ())


{
String name = (String)enum.nextElement();
String value = req.getHeader (name);
if (value!=null)
{
System.out.println (name + ":" +value);
}
}
}
}

5.2.4 Introduction to JSP

Java Server Pages (JSP) is a technology that lets to mix regular, static HTML with
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
dynamically-generated HTML. Many Web pages that are built by CGI programs are
mostly static, with the dynamic part limited to a few small locations. But most CGI
variations, including servlets, generate the entire page via the program, even though most
of it is always the same. JSP lets to create the two parts separately. Here's an example:

<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,

Page 322
Java Programming

<!-- User name is "New User" for first-time visitors -->


<% out.println(Utils.getUserNameFromCookie(request)); %>
To access the account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for all the rest of the on-line store's Web page.
</BODY></HTML>

Advantages of JSP

 Vs. Active Server Pages (ASP). ASP is a similar technology from


Microsoft. The advantages of JSP are two fold. First, the dynamic part is written in Java,
not Visual Basic or other MS-specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.

 Vs. Pure Servlets. JSP doesn't give anything that couldn't in principle do
with a servlet. But it is more convenient to write (and to modify!) regular HTML than to
have a zillion println statements that generate the HTML. Plus, by separating the look
from the content one put different people on different tasks: the Web page design experts
can build the HTML, leaving places for the servlet programmers to insert the dynamic
content.
 Vs. Server-Side Includes (SSI). SSI is a widely-supported technology for
including externally-defined pieces into a static Web page. JSP is better because it lets to
use servlets instead of a separate program to generate that dynamic part. Besides, SSI is
really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.

 Vs. JavaScript. JavaScript can generate HTML dynamically on the client.


This is a useful capability, but only handles situations where the dynamic information is
based on the client's environment. With the exception of cookies, HTTP and form
submission data is not available to JavaScript. And, since it runs on the client, JavaScript
can't access server-side resources like databases, catalogs, pricing information, and the
like.
Vs. Static HTML. Regular HTML, of course, cannot contain dynamic
information. JSP is so easy and convenient that it is quite feasible to augment HTML
pages that only benefit marginally by the insertion of small amounts of dynamic data.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Previously, the cost of using dynamic data would preclude its use in all but the most
valuable instances.

Overview

JavaServer Pages (JSP) lets to separate the dynamic part of the pages from the
static HTML. Simply write the regular HTML in the normal manner, using whatever
Web-page-building tools that are normally used. Then enclose the code for the dynamic
parts in special tags, most of which start with "<%" and end with "%>".

Page 323
Java Programming

Give the file a .jsp extension, and typically install it in any place where normally
a Web page is placed. Although what is written often looks more like a regular HTML
file than a servlet, behind the scenes, the JSP page just gets converted to a normal servlet,
with the static HTML simply being printed to the output stream associated with the
servlet's service method. This is normally done the first time the page is requested, and
developers can simply request the page themselves when first installing it if they want to
be sure that the first real user doesn't get a momentary delay when the JSP page is
translated to a servlet and the servlet is compiled and loaded. Note also that many Web
servers to define aliases that so that a URL that appears to reference an HTML file really
points to a servlet or JSP page.

Aside from the regular HTML, there are three main types of JSP constructs that to
embed in a page: scripting elements, directives, and actions. Scripting elements let to
specify Java code that will become part of the resultant servlet, directives let to control
the overall structure of the servlet, and actions let to specify existing components that
should be used, and otherwise control the behavior of the JSP engine. To simplify the
scripting elements, we have access to a number of predefined variables such as request
in the snippet above.

JSP Element Syntax Interpretation Notes


XML equivalent is
<jsp:expression>
expression
Expression is </jsp:expression>.
JSP
<%= expression %> evaluated and placed Predefined variables are
Expression request, response, out,
in output.
session, application,
config, and pageContext
(available in scriptlets also).
XML equivalent is
Code is inserted in <jsp:scriptlet>
JSP Scriptlet <% code %> code
service method.
</jsp:scriptlet>.

JSP
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY Code is inserted in
body of servlet class,
XML equivalent is
<jsp:declaration>
<%! code %> code
Declaration outside of service
method. </jsp:declaration>.

XML equivalent is
<jsp:directive.page att="
Directions to the val"\>. Legal attributes, with
JSP page <%@ page
servlet engine about default values in bold, are:
Directive att="val" %>
general setup. import="package.class"
contentType="MIME-Type"

Page 324
Java Programming

isThreadSafe="true|false"
session="true|false"
buffer="sizekb|none"
autoflush="true|false"
extends="package.class"
info="message"
errorPage="url"
isErrorPage="true|false"
language="java"
XML equivalent is
<jsp:directive.include
A file on the local file="url"\>.
system to be included The URL must be a relative
JSP include <%@ include
when the JSP page is
Directive file="url" %> one. Use the jsp:include
translated into a
action to include a file at
servlet.
request time instead of
translation time.
Comment; ignored To give a comment in the
JSP <%-- comment -- when JSP page is resultant HTML, use regular
Comment %> translated into HTML comment syntax of <--
servlet. comment -->.
To include the file at the time
the page is translated, use the
<jsp:include page directive with the
The page="relative Includes a file at the include attribute instead.
jsp:includ URL" time the page is Warning: on some servers, the
e Action requested. included file must be an HTML
flush="true"/> file or JSP file, as determined
by the server (usually based on
the file extension).
Possible attributes are:
<jsp:useBean att id="name"
The =val*/> or scope="page|request|session|ap
jsp:useBea <jsp:useBean att
Find or build a Java
plication"
=val*> Bean.
ANNAMALAI
ANNAMALAI UNIVERSITY
n Action ... UNIVERSITY
</jsp:useBean>
class="package.class"
type="package.class"
beanName="package.class"
Set bean properties, Legal attributes are
The either explicitly or by name="beanName"
jsp:setPro <jsp:setProperty
perty designating that value property="propertyName|*"
att=val*/>
Action comes from a request param="parameterName"
parameter. value="val"
The <jsp:getProperty Retrieve and output
jsp:getPro bean properties.

Page 325
Java Programming

perty name="propertyNa
Action me"

value="val"/>
The <jsp:forward
jsp:forwar
Forwards request to
page="relative
d Action
another page.
URL"/>
Generates OBJECT or
<jsp:plugin EMBED tags, as
The attribute="value"*>
jsp:plugin
appropriate to the
Action ... browser type, asking
</jsp:plugin> that an applet be run
using the Java Plugin.

5.2.5 Servlet and JDBC

Here is an html page which accepts employee no, name and salary. When the user
clicks the submit button, the manip servlet is executed.

<html>
<head>
<title>
Welcome to Servlet
</title>
</head>
<body>
<form method = "post" action="http://localhost:8080/servlet/Manip">
<pre>
Emloyee No:<input type = "text" name = "eno" size = "10"><br><br>
Name :<input type = "text" name = "ename" size = "10"><br><br>
Salary :<input type = "text" name = "sal" size = "10"><br><br>
<input type = "submit" name = "click"> <br><br>
</pre>
</form>

</html> ANNAMALAI
ANNAMALAI UNIVERSITY
</body>
UNIVERSITY
Manip.java (The servlet uses JDBC to connect to the database)

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.*;

Page 326
Java Programming

public class Manip extends HttpServlet


{
Connection c;
Statement s;
int flag;

public void doPost(HttpServletRequest req,HttpServletResponse res)


throws ServletException,IOException
{ res.setContentType("text/plain");
PrintWriter pw = res.getWriter();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:vad","scott","tiger");
s = c.createStatement();
ResultSet rs = s.executeQuery("select * from emp");
ArrayList ar = new ArrayList();
while ( rs.next())
{
ar.add(Integer.toString(rs.getInt(1)));
}
String no = req.getParameter("eno");
String name = req.getParameter("ename");
String sa = req.getParameter("sal");
int x = Integer.parseInt(no);
int sam = Integer.parseInt(sa);
Object[] it = ar.toArray();
for(int i = 0;i<it.length;i++)
{ String cv = (String) it[i];
if ( cv.equals(no))
{
flag = 1;
break;
}
else
{
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY flag = 0;
continue;
}
}
if ( flag == 1 )
{
pw.println("sorry u'r data is not accepted");
}
else if ( flag == 0 )
{

Page 327
Java Programming

s.executeUpdate("insert into emp values("+x+",'"+name+"',"+sam+")");


pw.println("One Row Inserted");
}
}
catch(ClassNotFoundException ce)
{}
catch(SQLException sq)
{}
}
}

5.3 Revision Points

JavaScript
JavaScript is one of a new breed of Web languages called scripting languages. It includes
a convenient syntax, flexible variable types, and easy access to the browser's features. It
can run on the browser without being compiled; the source code can be placed directly
into a Web page.
VBScript
VBScript is a scripting language for HTML pages on the World Wide Web and corporate
intranets.

Servlet
A Servlet is a server extension. It should be a small, self-contained, portion of code that is
executed at the web server in response to an HTTP request.

5.4 Intext Questions

1. Explain the life cycle of a Servlet.

2. What are cookies?

3. How is a Servlet differing from other server side technologies?

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4. What is Servlet Chaining?

5.5 Summary

JavaScript can be used to make the Web pages interactive and dynamic.
There are two types of JavaScript. Server-side and client-side JavaScript.
Client-side JavaScript is embedded directly in HTML pages.

Page 328
Java Programming

JavaScript scripts and programs can be included anywhere in the header or the
body of an HTML file.
Scripts are added into the web pages within a pair of <SCRIPT> tags.
JavaScript provides the ability for the programmers to generate output in
small dialog boxes - the alert() method.
JavaScript uses four data types - numbers, strings, boolean values and a null
value.
JavaScript has assignment, comparison, arithmetic, bit wise, logical, string,
and special operators.
The JavaScript statements consist of keywords used with the appropriate
syntax. A single statement may span multiple lines. Multiple statements may
occur on a single line if a semicolon separates each statement.
JavaScript core objects are Array, Boolean, Date, Function, Math, Number,
Object, and String. These objects are used in both client-side and server-side
JavaScript.
Servlets are an effective substitute for CGI scripts,

The servlet engine manages the life-cycle of servlets from when they are first
created through to their imminent destruction.
A standalone servlet engine is a fully functioning web server with support for
Servlets, for example, WebSphere, Java Web Server, IPlanet and W3's Jigsaw.
An add-on Servlet engine is a plug-in that can be added to a web server to
give it the Servlet support it was probably never designed to have.
The central abstraction in the Servlet API is the Servlet interface

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The ServletRequest class encapsulates the communication from the client to
the server.
The ServletResponse class encapsulates the communication from the servlet
back to the client.
Servlets run until they are removed from the service

5.6 Terminal Exercises

Page 329
Java Programming

1. What is JSP?

2. What is the difference between JSP and Servlets?

3. What are the different types of operators in JavaScript and VBScript?

4. Explain the JavaScript objects.

5.7 Supplementary Materials

1. The complete reference (Java 2 4th edition - Patrick Naughton & Herbert
Schildt)
2. Thinking in java by Bruce Eckel

5.8 Assignments

1. Write a Servlet to display the hit count


2. Write a Servlet to get a users name, and email address and store it in the
backend

5.9 Suggested Reading/Reference Books/Set Books

1. Core Java volume I & II - The Sun Microsystems Press (Java Series)
2. Java Servlet Programming - Oreily

5.10 Learning Activities

Collect Information on VBScript (not covered in this lesson) from the Internet.
ANNAMALAI
ANNAMALAI UNIVERSITY
5.11 Keywords
UNIVERSITY
JSP
JavaScript
VBScript
Servlet
Hyper Text Transfer Protocol (HTTP)

Page 330
Java Programming

Common Gateway Interface (CGI)

ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY

Page 331

You might also like