Java Programming
Java Programming
ANNAMALAI UNIVERSITY
DIRECTORATE OF DISTANCE EDUCATION
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
UNIT - IV
UNIT - V
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.
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.
Object-Oriented
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.
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.
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 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.
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:
Page 6
Java Programming
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!";
}
}
Java's primitive data types are very similar to those of C. They include boolean,
byte, short, int, long, float, double, and char.
Java prevents casting between arbitrary variables. Only casts between numeric
variables and between sub and superclasses of the same object are allowed.
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
byte
Page 7
Java Programming
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
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
char
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
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:
Instead, \n and the string concatenation operator, + are used like this:
Note that a statement can be broken across multiple lines, but a String literal
cannot be.
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.
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
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
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
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;
k = i%j;
System.out.println("i%j is " + k);
}
}
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.
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
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.
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
It isn't necessary to escape the double quote inside single quotes. The following
line is legal in Java
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.
The full Unicode character sequence can be used to name the variables.
if
else
else if
while
for
do while
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
switch case
break
continue
Page 17
Java Programming
Arrays have lengths and can access that length by referencing the variable
arrayname.length, the length of the args array is tested as follows.
class Hello {
if (args.length > 0) {
System.out.println("Hello " + args[0]);
}
}
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 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.
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 ==.
class Hello {
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:
class Hello {
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!");
}
}
}
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:
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(".");
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!");
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(".");
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
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.
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 (".");
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.
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
class Hello {
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 !=.
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.
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:
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.
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 {
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!");
}
}
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
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
and then stops because j is two and the outermost loop is exited.
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
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");
}
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.
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
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.
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.
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.
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
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
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];
Page 38
Java Programming
Watch the fenceposts! Since array subscripts begin at zero you need 101
components if you want to include the square of 100.
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.
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
Here's how the elements in a four by five array called M are referred to:
Page 39
Java Programming
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 {
int[][] matrix;
matrix = new int[4][5];
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 {
double[][] id;
id = new double[4][4];
Page 40
Java Programming
}
else {
id[row][col] = 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:
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?
A class is a blueprint or prototype that defines the variables and the methods
common to all objects of a certain kind.
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 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.
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.
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.
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.
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.
Page 44
Java Programming
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:
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.
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.
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.
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().
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.
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.
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().
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.
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:
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.
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;
}
Page 50
Java Programming
we'll learn how to instantiate some Employee objects and then we'll execute some
operations on them.
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:
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:
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:
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
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
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.
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.
Page 54
Java Programming
Initializing an Object
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:
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:
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.
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.
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:
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:
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:
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:
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.
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.
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 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
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.
Save this code in a file called HelloWorld.java. Use exactly that name including
case.
Compiling and Running Hello World
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
line prompt and type
javac HelloWorld.java
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
%
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:
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:
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.
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:
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
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.
Overriding Methods
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Replacing a Superclass's Method Implementation
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.
The BackgroundThread class overrides the run method from its superclass
Thread and completely replaces Thread's implementation of it.
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:
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:
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.
Also, a subclass cannot override methods that are declared static in the
superclass. In other words, a subclass cannot override a class method.
Subclass must override methods that are declared abstract in the superclass, or
the subclass itself must be abstract.
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:
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:
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) {
}
...
}
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.
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
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:
Page 70
Java Programming
...
}
abstract 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.
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.
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:
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.
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):
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
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.
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.)
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.
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 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
Strings
Two classes that implement character data. The String and StringBuffer Classes is
a thorough lesson on the use of both types of strings.
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
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.
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 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.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.
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.
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.
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.
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.
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.*;
Interfaces can also be used to define a set of constants that can be used by the
classes.
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:
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:
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. 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.8 Assignments
4. Write a program to find the second largest and second smallest element in an
array.
Page 83
Java Programming
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.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
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.
class genExc
{
Page 86
Java Programming
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;
Page 87
Java Programming
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;
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);
}
}
The call-stack
Page 88
Java Programming
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
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");
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
Example 5
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();
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
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");
}
class simpleThread
Page 94
Java Programming
{
public static void main (String args[]) throws Exception
{
Thread cur = Thread.currentThread();
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());
System.out.println (Thread.currentThread().getName());
Page 95
Java Programming
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 :
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.
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
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.
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");
}
Page 97
Java Programming
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.
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
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.
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.
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");
}
Page 99
Java Programming
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.
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.
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.
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.
Page 101
Java Programming
{
Thread thr = new Thread (this);
thr.start();
}
class runWtest
{
public static void main(String args[])
{
waitTest wt = new waitTest();
Thread.yield ();
wt.notifyIt();
}
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 102
Java Programming
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.
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.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
FilterOutputStream, is itself an abstract class with three descendents.
Page 104
Java Programming
Example
import java.io.*;
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
output:
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:
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
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
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
import java.io.*;
Output
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 109
Java Programming
RandomAccessFile
Represents a random access file.
StreamTokenizer
Breaks the contents of a stream into tokens.
This small example uses the file streams to copy the contents of one file into
another.
Page 110
Java Programming
import java.io.*;
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);
}
}
}
Page 111
Java Programming
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.
This might be done, so that the more convenient readXXX() methods can be used,
such as readLine(), implemented by DataInputStream.
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
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
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.*;
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
<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.
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.
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>
*/
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
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
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
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.*;
add(label1);
add(label2);
}
public void paint(Graphics g)
{
msg="An example for the Label Class";
showStatus(msg);
}
}
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
label 1 = new Label("Enter your Name:");
label2 = new LabeI("This is just a LABEL : ");
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
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
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
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;
Page 121
Java Programming
courseList.add(str[i]);
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 :
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
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
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.*;
add(b1);
add(b2);
ANNAMALAI
ANNAMALAI UNIVERSITY
} UNIVERSITY
public void actionPerformed(ActionEvent e)
{
msg = "You have selected : "+e.getActionCommand();
repaint();
}
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.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public String getLabelf)
returns the label of the button
java.awtCheckbox
Page 127
Java Programming
is , checkboxes can be used for multiple selections, whereas, radio button is a single
choice button.
import java.awt. *;
import java.awt.event. *;
import java.applet. *;
import java.util.*;
Page 128
Java Programming
The statements
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.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public void setLabel(String sir)
sets the label displayed along 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.*;
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
add(lbl);
add(cb1);
add(cb2);
ANNAMALAI
ANNAMALAI UNIVERSITY
}
UNIVERSITY
add(cb3);
Page 130
Java Programming
repaint();
}
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.
The third argument - false, indicates that this option by default is not selected,
ANNAMALAI
ANNAMALAI UNIVERSITY
when displayed.
UNIVERSITY
Description of Checkbox Class :
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.*;
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();
}
Page 132
Java Programming
}
}
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.*;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
public void init()
{
setFont(new Font("TimesRoman", Font.PLAIN,14));
setBackground(Color.cyan);
setForeground(Color.black);
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();
}
The statements
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 134
Java Programming
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.*;
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
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);
}
}
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.
Page 136
Java Programming
setLayout(new LayoutManager());
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 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.
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.
Page 137
Java Programming
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.*;
}
}
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:
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:
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
Page 139
Java Programming
setLayout(new BorderLayout());
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.
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".
The Card Layout uses the following special form of the add
method:
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:
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.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
GridLayout(int rows, int cols, int hgap, int vgap)
GridLayout(int rows, int cols)
Page 141
Java Programming
One may create his own Layout Manager by implementing the LayoutManager
Interface. This interface has the following 5 methods:
removeLayoutComponent(Component comp)
preferredLayoutSize(Container parent)
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.
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.
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.
ActionEvent
AdjustmentEvent
ItemEvent
TextEvent
Multiple low-level events may get generated for each high level user event.
ComponentEvent
ContainerEvent
FocusEvent
KeyEvent
MouseEvent
PaintEvent
WindowEvent
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
Page 144
Java Programming
AdjustmentEvent.
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.
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.
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.
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.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
FocusEvent Component FocusListener
Page 146
Java Programming
focusLost(FocusEvent evt)
Adapter classes
Page 147
Java Programming
ComponentListener ComponentAdapter
ContainerListener ContainerAdapter
FocusListener FocusAdapter
KeyListener KeyAdapter
MouseListener MouseAdapter
MouseMotionListener MouseMotionAdapter
WindowListener WindowAdapter
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.
Page 149
Java Programming
import java.net.*;
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);
}
}
}
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.
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.
TCP ServerSocket
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.
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.
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.
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.
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 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.
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.
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
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.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
3.2 Content
Data
Data is collection of records.
Database
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.
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
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 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 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
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
File-Processing System
Although File processing system is a great improvement over manual record keeping
systems, they suffer from these limitations
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
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
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.
Page 164
Java Programming
Characteristics of Database
Users Data
Meta Data
Indexes
Application Metadata
Also Business Rules or Logics are stored in database.
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.
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:
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.
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
Page 166
Java Programming
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
Almost all full-scale database systems are RDBMS's. Small database systems, however,
use other designs that provide less flexibility in posing queries.
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.
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.
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.
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.
Page 170
Java Programming
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.
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 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
Page 172
Java Programming
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.
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.
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.
Page 174
Java Programming
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.
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
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:
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
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
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.
Page 177
Java Programming
E-R Diagrams are standardized, but only loosely. According to standard used above
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.
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
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.
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 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
Functional Dependency
CourseId CourseFee
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
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.
R.x ; R.y
Page 180
Java Programming
Key: It is a group of one or more than one attributes that uniquely identifies a row
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.
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.
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
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.
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
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.
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
Relations in 2NF too can have anomalies. Consider HOUSING Relation below:
CityHall 1200
105
106 CityWoodsl 1000
Relation: HOUSING
StudentId BldgName
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
Page 184
Java Programming
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
Page 185
Java Programming
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.
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:
FundID, InvestmentType
Page 186
Java Programming
FundID, Manager
Manager
In this last step, we have retained the determinant "Manager" in the original relation
Rorig.
Id Major Minor
10 Physics Geography
10 Math Geography
10 Physics Computers
10 Math Computers
10 Geology Economics
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)
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
Create 2 relations each storing data only for one multi multi-value attribute.
So dividing the single relation into two relations we have eliminated multi valued
Dependencies and above-discusses updation and deletion anomaly.
There must be at least 3 attributes in the relation, call them A, B, and C, for example.
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
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
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.
Under our loose definition, several software packages now available qualify as
relational, e.g.
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.
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
Page 189
Java Programming
Table Student
Table Instructor
InstructorName InstructorPhone
Gary 111-222-3333
Tim 111-219-3267
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.
Page 190
Java Programming
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.
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.
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
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.
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.
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
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
Page 197
Java Programming
SQL was developed by IBM Corporation Inc. in mid 1970. Oracle corporation
introduced the first commercially available implementation of SQL.
Features of SQL
Non-procedural language
Unified language
Common language for all relational databases.
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:
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.
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.
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.
NCLOB ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
A character large objects containing fixed-width multi-byte
characters. Maximum size is 4GB.
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
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
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:
Constraints:
Constraints are a part of the table definition that limits the values entered to its
columns.
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.
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.
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
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
sql>desc tablename;
sql>desc employee;
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 203
Java Programming
Alter/Modify table
Example:
The following example adds primary key constraint to the already created
employee table.
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Viewing & Updation
Syntax:
Page 204
Java Programming
Example :
Syntax:
Updation:
Syntax:
Example:
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Note: The identical rows in the above output can be deleted as said below:
Deletion:
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
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.5 Summary
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
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
1. http://www.oracle.com
2. http://www.jcc.com/sql_stnd.html
3. http://www.sun.com/java/list.html
DBMS RDBMS
OODBMS SQL
Normalization ODBC
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 209
Java Programming
UNIT – IV
Snapshot
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.
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.
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.
Page 211
Java Programming
maintaining a connection via "keep-alive" messages with each client, even when no work
is being done.
Client Server
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 212
Java Programming
Client Database
Database Server
Program Program Database
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
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
Page 214
Java Programming
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
4.2.4 Types of JDBC technology drivers
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
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
Vendor Specific
Protocol
Page 217
Java Programming
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 218
Java Programming
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.
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
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Driver, DriverManager and related methods (below table)
Page 221
Java Programming
Int GetMajorVersion ()
Int getMinorVersion ()
Boolean jdbcCompliant ()
java.sql.DriverManager
Connection getConnection (String url,
java.util.Properties info)
int getLoginTimeout
java.io.PrintStream getLogStream ()
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
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.
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.
float
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY getFloat (int columnlndex)
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
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.
java.sqLDate
This package gives a Java program the capability to handle SQL DATE
information with only year, month, and day values.
String toString ()
int getHours ()
ANNAMALAI
ANNAMALAI UNIVERSITY
int UNIVERSITY getMinutes ()
int getSeconds ()
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.
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)
String toString ()
Page 227
Java Programming
int getNanos ()
OS
void setNanos (int n)
OS
boolean after (TimeStamp ts)
JDBC Calls
Opening a Connection
Open a connection
m_con.close();
Page 228
Java Programming
The Statement interface provides three different methods for executing SQL statements:
Create a statement
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
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
// Create Table
import java.sql.*;
Connection con =
DriverManager.getConnection("jdbc:odbc:Mydata","scott","tiger");
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");
import java.sql.*;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection("jdbc:odbc:Mydata","scott","tiger");
Page 232
Java Programming
System.out.println(result.getInt(1) + result.getString(2));
}
}
catch(Exception e)
{
System.out.println("Errors" + e);
}
}
}
import java.sql.*;
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());
}
}
}
// 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();
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
}
}
// 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.*;
Page 235
Java Programming
PreparedStatement ps = con.prepareStatement(s);
ps.clearParameters();
int i = 10;
ps.setInt(1,i);
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();
}
}
}
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();
}
}
}
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.
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
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.8 Assignments
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.
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.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
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.
Server-Side JavaScript
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.
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.
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:
Page 245
Java Programming
Navigator 3 has introduced the NOSCRIPT, which provides a way for alternate
text to be specified for non-JavaScript browsers.
<NOSCRIPT>
JavaScript Script appears here<BR> Download Netscape Navigator 2.0 to use it.
</NOSCRIPT>
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.
<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
Page 246
Java Programming
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.
The alert () method is used exactly - to warn the user or alert him or her to
something. Examples of this type of use include:
Page 247
Java Programming
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>
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 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:
Boolean:
A Boolean literal can take two values: true or false. This type of literal comes in
handy when comparing data and making decisions.
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.
Var example;
Page 249
Java Programming
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..
Page 250
Java Programming
Page 251
Java Programming
=
Comparison = Returns true if the operands are equal.
Operators
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
!= Returns true if the operands are not equal.
Page 252
Java Programming
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
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.
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
% (Modulus)
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)
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)
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
Operator U Description
sage
Bitwise AND a & b Returns a one in each bit position if bits of both operands
are ones.
Bitwise XOR a ^ b Returns a one in a bit position if bits of one but not both
operands are one.
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
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)
and (&&) expr1 && Returns expr1 if it converts to false. 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>
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
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
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:
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
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:
void
The void operator is used in either of the following ways:
1. javascript:void (expression)
2. javascript:void expression
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 { }.
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
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
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
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
Syntax
for ([initial-expression;] [condition;] [increment-expression]) {
statements
}
Arguments
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.
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.
}
ANNAMALAI
ANNAMALAI UNIVERSITY
return result UNIVERSITY
function
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.
Examples
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
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
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
Page 270
Java Programming
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
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)
}
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.
Object Description
Object Description
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.
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.
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
Properties
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
Methods
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
Page 277
Java Programming
Properties
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
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
Method Summary
Object Description
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
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
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
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
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
Page 281
Java Programming
Option
The Option constructor or the HTML OPTION tag. To create an Option object
with its constructor:
Once an Option object is created, it can be added to a selection list using the
Select.options array.
Parameters
Property
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
document.myForm.musicTypes.options[i].selected = true
<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
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
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.
Properties
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
Submit
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
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
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.
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
Event-Description
Page 287
Java Programming
Event handlers are scripts, in the form of attributes of specific HTML tags, which
you as the programmer can write
Object Event-Handlers-Available
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 = " " ;
<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
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
Example 1
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>
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.
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";
}
<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
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.
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
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>
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
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
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
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 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
Page 298
Java Programming
Assigning Values
Variable_name = value
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 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.
States(5) = "California"
States(6) = "New York"
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)
Operator Precedence
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.
Page 301
Java Programming
String &
concatenation
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
If..Then..Else
Select..Case
If..Then..Else
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
The simplest version of an If statement is one that contains only a condition and a
single statement:
Page 302
Java Programming
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.
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
For example, the following Select statement assigns different shipping fees based
upon the State where the order is being sent:
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
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
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:
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:
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
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
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
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.
While condition
statement
statement
...
ANNAMALAI
ANNAMALAI UNIVERSITY
Wend UNIVERSITY
First VBScript
Page 307
Java Programming
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>
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).
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.
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.
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.
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 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
Page 312
Java Programming
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.
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.
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.
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.
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
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.*;
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];
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.
Session Tracking
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.
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.
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.
Page 319
Java Programming
Finally to execute:
Example 1:
// HellowServlet.java
// Servlet Extends GenericServlet
import java.io.*;
import javax.servlet.*;
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.*;
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);
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
Advantages of JSP
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.
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
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.
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
Page 327
Java Programming
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.
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
Page 329
Java Programming
1. What is JSP?
1. The complete reference (Java 2 4th edition - Patrick Naughton & Herbert
Schildt)
2. Thinking in java by Bruce Eckel
5.8 Assignments
1. Core Java volume I & II - The Sun Microsystems Press (Java Series)
2. Java Servlet Programming - Oreily
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
ANNAMALAI
ANNAMALAI UNIVERSITY
UNIVERSITY
Page 331