Core Java - Munishwar Gulati
Core Java - Munishwar Gulati
I S B N - 8 1 - 8 7 8 7 0 - 13 - 3
First Edition 2001
The export rights of this book are vested solely with the publisher.
Published by Silicon Media Press, Regd. Off. I-19, Lajpat Nagar - II,
New Delhi. Works : KJ-75, Kavi Nagar, Ghaziabad.
[email protected]. Ph - 4702867, 9810626977 Typeset by : Ram
Ganga Computers (P) Ltd. and Printed by : Siddharth Printers, D-30,
Sector-6, Noida. Ph 4444598, 9810236378.
Dedicated to our lovely daughter Priyasha
ontents
WHAT IS JAVA? ................................................................... 2
THE ORIGINS OF JAVA ....................................................... 3
Java and HotJava .................................................... 3
WHY PROGRAM IN JAVA? ................................................... 4
JAVA DEVELOPMENT KIT ................................................... 6
The Compiler ........................................................... 7
The Runtime Interpreter ........................................ 8
The Debugger ........................................................... 9
The disassembler ................................................... 9
The applet viewer ................................................... 10
The Document Generator ..................................... 10
Header File Generation ......................................... 11
PROGRAM TYPES IN JAVA ................................................ 11
Applications ........................................................... 11
Applets .................................................................. 13
How Applets Differ from Applications ...................... 14
EXERCISE ........................................................................ 16
IDENTIFIER ...................................................................... 18
KEYWORDS ...................................................................... 18
DATA TYPES ..................................................................... 18
Integer Data Types ................................................. 19
Floating-Point Data Types ....................................... 19
boolean Data Type .................................................. 20
Character Data Type .............................................. 20
Strings ................................................................... 20
Arrays .................................................................... 20
Casting Types ........................................................ 22
PRINTING DATA ................................................................ 23
CONSTANTS IN JAVA ........................................................ 23
Integer Constants ................................................... 24
Comments ............................................................. 25
BLOCK AND SCOPE .......................................................... 26
EXPRESSIONS AND OPERATORS ...................................... 27
Arithmetic Operators .............................................. 27
Increment & Decrement Operator ........................... 28
Relational Operators .............................................. 29
Logical Operators ................................................... 31
Bitwise Operators ................................................... 31
Boolean Operator ................................................... 32
Assignment operators ............................................. 33
String Operators .................................................... 34
Operator Precedence .............................................. 34
CONTROL STRUCTURES ................................................... 35
BRANCHING ...................................................................... 35
IF statement .......................................................... 36
Simple IF statement ............................................... 36
The If........ else statement ...................................... 37
Nested IF.........Else Statement ............................... 38
Other form of NESTED IF....... ELSE Statement ...... 40
THE SWITCH STATEMENT ................................................ 42
LOOPING .......................................................................... 44
The WHILE statement ............................................ 45
The FOR statement ............................................... 46
The DO...WHILE statement .................................. 48
BREAKING Loops ................................................... 49
EXERCISE ........................................................................ 51
Objects .................................................................. 54
Class ..................................................................... 55
Inheritance ............................................................ 55
Message and Method ............................................ 56
Encapsulation ........................................................ 56
JAVA CLASS ..................................................................... 57
Declaring Classes ................................................... 57
Declaring Methods ................................................. 57
Controlling the Access .......................................... 59
OBJECT CREATION .......................................................... 60
INHERITANCE ................................................................... 62
Abstract Class ........................................................ 63
Overriding Methods ............................................... 63
Overloading Methods .............................................. 64
CASTING ........................................................................... 65
Object Destruction ................................................. 67
INTERFACE ....................................................................... 67
Declaring Interfaces ............................................... 68
Implementing Interfaces ......................................... 68
PACKAGES ........................................................................ 73
Declaring Packages ................................................ 73
Importing Packages ................................................ 74
SOME JAVA PACKAGES .................................................... 74
EXERCISE ........................................................................ 75
INTRODUCTION ................................................................ 78
THREAD ............................................................................ 78
JAVA THREADS ................................................................ 79
CREATING THREADS ........................................................ 80
Creating Thread subclass ..................................... 81
Implementing Runnable ......................................... 84
The Thread API ...................................................... 86
Thread Priority and Scheduling .............................. 87
THREAD GROUPS ............................................................. 90
Threadgroup API .................................................... 90
SYNCHRONIZATION .......................................................... 92
Inter Thread Communication .................................. 95
EXERCISE ........................................................................ 96
EXCEPTIONS .................................................................... 98
HANDLING EXCEPTION ..................................................... 99
try and catch ......................................................... 99
throw ................................................................... 100
throws ................................................................. 102
Multiple catch ..................................................... 103
Finally ................................................................. 105
Nested try block ................................................... 106
CUSTOMIZED EXCEPTIONS ............................................ 107
EXERCISE ...................................................................... 109
Munishwar Gulati
Mini Gulati
As you move on to Chapter 4, you will know more about thread and
multithreading in java.
Chapter 6 tells you about the creating Java Applets and running the
applets using HTML code.
Authors
WHAT IS JAVA?
THE ORIGINS OF JAVA
WHY PROGRAM IN JAVA?
JAVA DEVELOPMENT KIT
PROGRAM TYPES IN JAVA
Introduction
Java programs are created as a text file with the file extension .java.
Java programs are compiled using the Java compiler which results in
the formation of compiled bytecode with the extension .class. A
machine code must run on the computer system it was compiled for,
whereas bytecodes can run on any computer system equipped to
handle Java programs. Bytecode is in a form that can be executed on
the Java virtual machine, the core of the Java runtime system, which
makes your application compatible to the client’s machine, thereby
enabling your program to run on any machine in the internet. A
virtual machine can be considered as a microprocessor that is
implemented in software and runs using the capabilities provided by
your operating system and computer hardware.
The origins of Java trace back to 1991, when a research group at Sun
was investigating consumer electronics products. They developed a
product called Star7 for which they planned to develop an operating
system in C++. Then James Gosling, the father of Java, developed a
new language for start7, based on C++, eliminating its shortcomings.
Initially it was named as Oak but later Sun renamed this language as
Java by the year 1994. HotJava, Java, and the Java documentation
and source code were made available over the Web, as an alpha
version, in early 1995.
In 1996, Java 1.0 was officially released and made available for
download over the Internet. JavaScript was also released. Then came
Java 1.1 with further enhancements and finally Java 1.2.2 which is
also called as Java 2 is the latest version. Netscape 2.0 now provides
support for both Java and JavaScript.
Java Is Object-Oriented
Java is totally an object oriented language. In Java, classes and
objects are at the center of the language. Everything is written inside
the classes. Functions , procedures, structures, unions are not
present in Java . Only classes and objects are used in Java thereby
making it totally object oriented language. Java supports all the
features of object-oriented programming such as class hierarchy,
inheritance, encapsulation, and polymorphism.
For writing Java programs, you must build on the classes and
methods of the Java API. For developing software in Java, you have
two choices:
Build on the classes you have developed, thereby reusing
them.
Rewrite your software from scratch, copying and tailoring
useful parts of existing software.
Java programs are reliable because Java does not allow the program
coming from the internet and running in the browser, called the
applet, to access the local system’s file system.Java’s reliability
extends beyond the language level to the compiler and the runtime
system. Compile-time checks both syntactic and semantic errors.
Runtime checks are also more extensive and effective thereby offering
reliability.
Chapter 1 : Introduction 5
Java is defensive by nature. When an applet arrives at its destination,
before it is interpreted, a security check is applied on it thereby
ensuring that the Java code, which has arrived, is a true Java code,
i.e., it does not contain any viruses. A Java code can also be signed
before sending it and the receiver can tally the signatures before
receiving it. If the signatures do not match, it means that any other
person has hacked the code.
Java Is Multithreaded
Java supports multithreading. Multithreading allows more than one
threa d of execution to tak e plac e with in a single pr og ra m .
Multithreading enables several different execution threads to run at
the same time inside the same program, in parallel, without interfering
with each other. Multithreading also allows Java to use idle CPU time,
to perfor m necessary g arbage colle ction and gen eral syste m
maintenance.
Robust
Java supports techniques such as garbage collection and exception
handling to handle situations when a program behaves in an
exceptional manner. Memory management issues and exceptional
behaviour of the program in different situations, are thus easily dealt
by Java, thereby making it a robust programming language. In
garbage collection a daemon thread (thread which becomes alive
when the system is comparatively free) keeps on freeing the objects
6 Chapter 1 : Introduction
which are not being referenced. Through exception handling any
unexpected behaviour, like trying to access an element of an array
beyond it’s upper bound, which may crash the program, is dealt with
exception handling techniques.
Powerful
Java is a very powerful language, which offers you a complete range
of classes, with number of small independent functions, so that you
can use them in your programs.
You can simply execute the archive file to automatically create a java
directory and build a directory structure to contain the rest of the
JDK support files. The JDK support files contains BIN folder, LIB
folder for library files, INCLUDE folder and JRE folder.
You can write Java programs using any text editor. The source file
uses the extension .java and consists of source code packages to
declare the source code packages and interfaces.
THE COMPILER
You must compile the source code to execute it. You can use Java
compiler, javac, convert the source files into bytecode files. These
files end with .class extension and can be executed using the Java
interpreter.
If you have defined more than one class in the source code, compiler
will generate separate bytecode files for each class defined. The Java
compiler is a command-line utility, the general syntax of which is as
follows:
javac Options Filename
The Filename argument specifies the name of the source code file you
want to compile. The Option argument specifies the way , the compiler
will create the executable Java class. Java compiler can take the
following options:
-classpath Path To override the CLASSPATH environment variable,
you can define the path with -classpath option.
-d Dir The -d option lets you define the root directory
wher e c om pi led cla s ses ar e stor ed . Th is is
im p orta nt when classe s a re orga n iz ed in a
hierarchical directory structure. With the -d option,
you can create the directory structure under the
directory specified by Dir.
-g The -g compiler option tells the compiler to generate
debugging tables for the Java classes. These tables
contains information for Java debugger.
-nowarn The -nowarn option turns off compiler warnings.
-O The -O option causes the compiler to optimize the
compiled code. The -O optimization option also
8 Chapter 1 : Introduction
suppresses the default creation of line numbers by
the compiler.
Setting Classes
Every Java program uses classes that are defined outside of the
program’s source code file. Most often these external classes are
contained in the Java API. However, you will also want to be able to
reuse classes that you develop. The Java compiler must be able to
locate these external classes in order to determine how to correctly
compile code that references them.
To enable Java Compiler to locate the classes easily, you must set the
CLASSPATH. Set CLASSPATH statement tells the JDK programs
about the location of external classes. In Windows based system, you
can set the CLASSPATH by executing the following statement at
console command line:
set CLASSPATH=path
A common CLASSPATH is .;c:\jdk1.2.2;c:\jdk1.2.2\lib\classes.zip.
This tells the Java compiler and other JDK tools to use the current
directory (.), the c:\jdk 1.2.2 directory, and the file
c:\jdk1.2.2\lib\classes.zip as a base for finding Java class files.
You would enter the following to set this CLASSPATH:
set CLASSPATH=.;c:\jdk1.2.2;c:\jdk1.2.2\lib\classes.zip
You can also put this statement in your AUTOEXEC.BAT file so that
it will be set automatically each time you start a DOS shell. Windows
NT users can use the System option in the Control Panel to set the
CLASSPATH variable.
THE DEBUGGER
This utility debugs the Java applications. Java Debugger is similar to
the interpreter as it also executes the bytecode files but it also
provides capabilities to stop program execution at selected breakpoints
and to display the values of class variables, thus making it capable
of finding error in the programs. The syntax for using the Java
debugger follows:
jdb Options
After starting jdb, it will announce that it is initializing, identify the
class that it is debugging, and print a simple prompt (>). Once you
are up and running, using the debugger, you can enter a question
mark (?) at the prompt (>) to receive a list of available debugging
commands.
THE DISASSEMBLER
Here is the tools which gives you the source code from the compiled
bytecode files. The disassembler takes the bytecode files and displays
the classes, fields (variables), and methods that have been compiled
into the bytecodes. This tool plays a major role for recovering the
source code design of those compiled Java classes for which no
source code is available - for example, those that you would retrieve
from the Web. The debugger is executed as follows:
javap options class
The debugger takes the full name of a class as its input and identifies
the variables and methods that have been compiled into the class’s
bytecodes. It also identifies the source bytecode instructions that
implement the class methods.
10 Chapter 1 : Introduction
The op tion control the typ e of informa tion display ed by the
disassembler. When no option is used, only public fields and
methods of the class are displayed. Other options are described
below:
-p Also displays the class’s private and protected fields
and methods.
-c displays the source bytecode instructions for the class
methods.
-classpath Overrides the classpath settings.
The applet viewer creates a window in which the applet can be viewed.
It provides complete support for all applet functions, including
networking and multimedia capabilities.
You can start the applet viewer from a command line using the
following syntax:
appletviewer Options URL
Here URL is the address of the html page which embedded the Java
applet. The options argument specifies the various options that you
can use while running the applet. The appletviewer supports only one
option:
-debug starts the applet viewer in the Java debugger,
which enables you to debug the applet.
e.g. appletviewer silicon.html
Here silicon.html is the HTML file containing the embedded Java
applet.
You can use the following syntax to invoke the header and stub file
generator:
javah options classname
Here, classname refers to the full class names of the classes for which
header files are to be generated. The options argument specifies the
various options that you can use while generating header and stub
files. The header and stub file generator can take the following
options :
-o combines all the files generated into a single file.
-d specifies the directory where javah is to put the
generated header and source files.
-td s p e c i f i e s t h e d i r e ct or y w h e r e j a v a h s t o r e s
temporary files used in the header file generation
process.
-stubs causes javah to generate C function stubs for class
methods.
-verbose is used to display status information concerning
the files generated.
-classpath is used to overrides the CLASSPATH environment
variable.
The Java language basically has two types of programs, the applets,
and the applications. Applets are small programs that have the
capability to run on the internet through a browser, whereas the
applications do not possess this capability. Browsers that are Java
enabled can only run Java applet. The Internet Explorer 3.1 and
above are able to run the applets successfully.
APPLICATIONS
Java is an object-oriented language. This means that the language is
based on the concept of an object. Everything is written in the form
of classes. The class names is case sensitive. A Java application
12 Chapter 1 : Introduction
means that it runs within the Java interpreter as a stand-alone
program and has text output.
public class Silicon
{
public static void main (String args[])
{
System.out.println(“Silicon Media!”);
}
}
The first statement of Silicon tells you that Silicon is a class, not just
a program. This name is used by the Java compiler as the name of the
executable output class. The Java compiler creates an executable
class file for each class defined in a Java source file. If more than one
class are defined in a .java file, then Java compiler will store each one
in a separate .class file.
After compiling the program with the Java compiler (javac), you are
ready to run it in the Java interpreter. The Java compiler places the
executable output in a file called Silicon.class. This file does not have
an extension .EXE although it is an executable file.
c:> javac Silicon.java
After compilation a .class file is made which contains the byte code.
To run the test program, type java test at the command prompt. The
program responds by displaying “Silicon Media!” on your screen. It
is executed as:
c:> java Silicon
Chapter 1 : Introduction 13
init();
Initialization of any methods and variables takes place at this stage.
The init method is called when the applet is first loaded.
start();
This stage starts the primary functions of an applet. For example, if
an applet plays a sound, it could start playing during this stage. This
method is called when the init method has finished and the applet is
ready to execute.
14 Chapter 1 : Introduction
stop();
This stage is used to stop any actions that is still in progress from the
start stage when an applet is exited. For example, a sound loop would
need to be stopped when a person left the Web page containing a
sound applet. This method is called when the page is left, or the
browser is minimized.
destroy();
Destroy is called automatically, and completes any memory cleanup
or garbage collection that needs to be done when an applet is
destroyed. This method is called when you quit a browser.
In Java, the data types are classified into two categories: simple and
composite. Simple data types are core types that are not derived from
any other types. Integer, floating-point, Boolean, and character types
are all simple types. On the other hand, composite types, are derived
from simple types, and include strings, arrays, classes etc.
There are four integer types: byte, short, int, and long depending
upon the amount of space required by them in memory.
Data Type Size Range
byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
int 32 bits -2,147,483,648 to +2,147,483,647
long 64 bits -2 63
TO 2 63 -1
The following are some examples of declaring integer variables:
int i;
short x;
long seconds;
byte red;
STRINGS
Strings are handled in Java by a special class called String. This
method of handling strings is very different from languages like C and
C++, where strings are represented simply as an array of characters.
The following are a few strings declared using the Java String class:
String account;
String name = “Mr. James”;
ARRAYS
Computer process data. Quite often the data are organized in some
orderly manner - for example, a statistical time series, or a list of
name in alphabetic order. A collection of data, whose elements form
an ordered sequence, is called array. The elements of an array can
be of any data type. Thus array is a secondary data type which can
be derived from a primary data type.
Now, the question arises, why use arrays when we have primary data
types. Consider an example, where you have to calculate the sum of
100 numbers. Answer is simple - Start a loop, every time give the
value of x and add it into the previous sum and after repeating the
loop 100 times, we get the required sum.
Here, the problem is that whenever a new value is given for x, the
previous value is deleted (after being added into sum) and no longer
remains in the memory, thus can’t be reused. Suppose after calculating
the average, you have to compare the every number with the average
of 100 numbers. In such case, you will either input the values again
or store all the numbers in separate variable, thus define 100
variables. Both the methods are cumbersome.
In such cases arrays play a vital role and the same array variable can
take the defined number of values and store them simultaneously for
reuse.
An array provides for the storage of a list of items of the same type.
Items in an array can be of either a simple or composite data type.
Arrays also can be multidimensional.
Chapter 2 : Java Languagae 21
One dimensional array
When a list of items is dependent on only one variable name and can
be created using only one subscript, such a variable is called a single-
subscripted variable or a one-dimensional array.
x
n
Here only one variable x with a subscript, takes different values and
its sum is calculated. The subscripted x; refers to the ith value of x.
The subscript must be non-negative integer. In Java, single subscripted
variable xi can be expressed as
x[1], x[2], x[3] ...... x[n]
Thus the same variable takes different values using arrays.
Declaration of array
Like all other variables, arrays is also declared before they are used.
The general form for array declaration is :
Data type variable-name [];
Arrays are declared with square brackets ([]). The following are a few
examples of arrays in Java:
int num[];
char[] name;
long xyz[][];
Square brackets can be placed either after the variable type or after
the identifier. As it is obvious from above examples, Java doesn’t
allow you to specify the size of an empty array when declaring the
array. This is because Java does not support pointers and thereby
there is no way of pointing anywhere in an array. The size of the array
can be set explicitly either by using a new operator or by assigning
a list of items to the array on creation.
x
n ,m
e.g. ij
i 1, j 1
CASTING TYPES
The process of converting one data type to another data type is called
casting. It is often required when a function returns a type different
than the type you need to perform an operation. For example, the read
member function of the standard input stream (System.in) returns an
int. You must cast the returned int type to a char type before storing
it, as in the following:
char c = (char)System.in.read();
In order to perform casting the desired type is placed in parentheses
to the left of the value to be converted. The System.in.read function
call returns an int value, which then is cast to a char because of the
(char) cast. The resulting char value is then stored in the char
variable c.
While casting, care should be taken that the destination type should
always be equal to or larger in size than the source type so that there
is no loss of information.
Chapter 2 : Java Languagae 23
Casts that result in no loss of information.
From Type To Type
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float double
To display the numbers using println(), you can use + sign to add the
variable into the string.
int year = 2001;
System.out.println(“Silicon Media! ” + year);
The output of above println() statement will be
Silicon Media! 2001
INTEGER CONSTANTS
Java can accept integer constants written in either the decimal, octal
or hexadecimal number system.
The decimal constants are written directly as per the value. The octal
values must be preceded by a zero & The Hex values must always be
preceded by a zero and either a small X or uppercase X.
e.g.
int a;
int b;
int c;
a = 10;
b = 0737;
c =0X7FFF;
The above method of initializing a variable is correct but lengthy,
where it is known that variable is to be started with a certain initial
value, the above two operations can be combined as shown below :
int a = 10;
int b = 0737;
int C = 0X7FFF;
Character Constant
A character constant can be any of the valid printing character is
ASCII character set enclosed in single quotes (‘ ‘). They are assigned
through an assignment statement just as in the case of integer and
floating point constants.
e.g. char grade = ‘A’
Chapter 2 : Java Languagae 25
Thus character constants can be written in above form. But the
special character like tab or back space or enter can’t be written in
above cited way. For most common special character, C provides
what are called escape sequence - the back slash character \ followed
by a letter. The backslash \ signals the compiler that the letter which
follows it has special significance. The escape sequence defined for
C are :
\n new line (i.e. linefeed - carriage return)
\t tab
\b backspace
\r carriage return
\f form feed
\\ backslash
\’ single quote
\” double quote
\f form feed
\udddd unicode character
\ddd octalc character
\ continuation
The above is called escape sequence and the different escape
sequences can be mixed freely with other character in coding.
e.g. System.out.println (“A\n BC\n DEF\n”)
will generate the output
A
BC
DEF
when the above statement is executed.
String Constants
A string constant is a list of characters, enclosed in double quotes
(“ “ ). Like constants discussed earlier, a string constant is also
assigned to an identifier through an assignment statement. The
compiler itself adds a null byte (i.e. \0) to the end of a string. This
null-byte is used by string handling functions to determine the end
of the string.
e.g. “This is a string constant”
In case the double quote is to be incorporated in the string it must be
preceded by a backslash.
COMMENTS
Comments basically can be written down in two ways. These are the
‘//’ and ‘/* */’.
26 Chapter 2 : Java Language
// is used to comment a single line. It is similar to the comments used
in C++. It can be placed anywhere in the line and the compiler would
ignore anything following it. /* */ is borrowed from C and is used
to mark a block as a comment entry. This is very useful when the
comment entry extends several lines.
There is another comment type (/** comment **/) which works in the
same fashion as the C-style comment type, with the additional benefit
that it can be used with the Java documentation generator tool,
javadoc, to create automatic documentation from the source code.
In Java, source code is divided into parts using opening and closing
curly braces: { and }. Anything between curly braces is considered as
a block which is independent of everything outside the braces. Blocks
are integral part of Java language syntax. Blocks in Java can be
nested, which means that code can be divided into individual blocks
nested under other blocks. One block can contain one or more nested
subblocks.
The concept of scope is linked with the life of variable in Java. The
scope of a variable is defined by the block in which it is declared. The
variable can be used from the block in which it is declared, to all
subsequent blocks inside it. But the same variable outside the block
can not be used. Consider the following set of instructions:
public class Varscope
{
public static void main(String args[])
{
{
int block1 = 100;
{
int block2 = 200;
System.out.println(“Block 1 variable “ + block1);
System.out.println(“Block 2 variable “ + block2);
}
block1 = block1+ 1;
System.out.println(“New block 1variable “ + block1);
block2= block2 + 1;
}
}
}
In the above listing, two variable block1and block2 are defined in the
outer and inner blocks respectively. The variable block1 can be used
in both the blocks as it has been declared in the outer block. But the
variable block2 can be used only in the inner block, as it has been
Chapter 2 : Java Languagae 27
declare in inner block. As soon as, you try to access block1 outside
the inner block you receive an error message.
ARITHMETIC OPERATORS
The usual integer operations found in most of the programming
languages are also available in Java. These include addition,
subtraction, multiplication and division.
Thus, the assignment operator = in Java is not used like the equal
sign of algebra.
It must also be noted that modules operator works only with int and
char values but not with float or double.
RELATIONAL OPERATORS
You can use relational operators, whenever you want to compare two
quantities or variables and on the basis of that, you want to take some
decision. The expression containing the relational operator is called
30 Chapter 2 : Java Language
relational expression and such expression can have a value of one (for
true relation) or zero (for false relation).
e.g. 10 < 20 is true
& 20 < 10 is false
Java has six relational operator. These operators and their meaning
are given below -
Operator Meaning
< is less than
< = is less than or equal to
> is greater than
> = is greater than or equal to
= = is equal to
! = is not equal to
A simple relational expression contains only one relational operator
and its general syntax is:
arth.exp1 relational operator arth.exp2
The arith.exp on both sides of the expression may be simple constant,
variables or combination of them. These arithmetic expressions are
first evaluated before comparing the two sides, as arithmetic operators
have a high priority over relational operators (Refer to table of
precedence).
class Compare
{
public static void main (String args[])
{
int a= 5, b = 3, c = 7;
System.out.println(“a = “ + a);
System.out.println(“b = “ + b);
System.out.println(“c = “ + c);
System.out.println(“a > b = “ + (a > b));
System.out.println(“a > c = “ + (a > c));
System.out.println(“c > b = “ + (c > b));
}
}
The output of the above class is as follows:
a = 5
b = 3
c = 7
a > b = true
a > c = false
c > b = true
Chapter 2 : Java Languagae 31
You can note that println() method prints the boolean result after
using the relational operators.
LOGICAL OPERATORS
Logical operators are used to test more than one relational expression
and lets you make decision on the basis of that. You can use following
logical operators in Java:
&& Logical AND
|| Logical OR
! Logical NOT
e.g. price < 40 && profit > 10
which says that price must be less than 40 and profit must be more
than 10, if both the condition are to be met. Such expressions, which
combines two or more relational expressions, are termed as a logical
expression or a compound relational expression.
These logical expression also yields a value of one (for true logical
statement) or zero (for false logical statement), according to the truth
table shown below.
Truth Table
Operator-1 Operator-2 && ||
1 1 1 1
1 0 0 1
0 1 0 1
0 0 0 0
In above example, the logical expression given true only if price is
less than 40 and profit is more than 10. If any of the two condition
yields a false value (0), the combined condition will yield a false (0)
value.
BITWISE OPERATORS
Java has a powerful set of special operators capable of manipulating
data at bit level, called bitwise operators. These operators are used
for testing the bits, and can operate on ints and chars but not on
floats or doubles. The following are the bitwise operators available in
Java.
Operator Meaning
& bitwise AND
! bitwise OR
^ bitwise exclusive OR
<< Shift left
>> Shift right
~ Bitwise Compliment
32 Chapter 2 : Java Language
The Bitwise relational operator i.e. AND, OR and XOR compare the
each bit binary equivalent of the two numbers. In AND operator if the
two bits being compared are 1, the resultant bit will be 1, otherwise
0. In bitwise OR, the resultant bit is 1 if any of the compared bit is
1. In XOR, the resultant will be 1 if exactly one of the bits is 1.
The last three bitwise operators work on the integers and are unary
operators. The right-shift operator >>, shift the binary number to the
right bit specified integer amount, whereas << shifts the binary
number to the left by specified integer amount. The Compliment
operator, flips all 0 to 1 and all 1’s to 0 thus giving you the 2’s
complement of the number.
BOOLEAN OPERATOR
Boolean operators act on Boolean types and return a Boolean result.
The following type of boolean operators are used.
Operator Meaning
Chapter 2 : Java Languagae 33
& Evaluation AND
| Evaluation OR
^ Evaluation XOR
&& Logical AND
|| Logical OR
! Negation
== Equal-to
!= Not-equal-to
?: Conditional
The evaluation operators (&, |, and ^) evaluate both sides of an
expression before determining the result. The logical operators (&&
and ||) avoid the right-side evaluation of the expression if it is not
needed.
ASSIGNMENT OPERATORS
In addition to standard assignment operators, Java provides a number
of assignment operators that are combinations of assignment operators
with various other operators. These are called compound assignment
operators. These are a form of shorthand that provides a more
concise way to modify a variable.
STRING OPERATORS
Similar to boolean type variables, strings can also be manipulated
using operators. For joining the strings, you have the concatenation
operator (+). The concatenation operator connects the two strings to
give a combined string.
OPERATOR PRECEDENCE
Every Java operator has a precedence associated with it. Precedence
refers to the order in which Java evaluates its operators. Following is
a list of all the Java operators from highest to lowest precedence:
. [] ()
++ -- ! ~
* / %
+ -
<< >> >>>
Chapter 2 : Java Languagae 35
< > <= >=
== !=
&
^
&&
||
?:
=
In the above list, all of the operators belonging to a particular row
have equal precedence. The precedence level of each row decreases
from top to bottom. This means that the [] operator has a higher
precedence than the * operator, but the same precedence as the ()
operator.
The control structures are used to control the flow of programs. The
flow of program is dictated by two different types of constructs:
branches and loops. Branches lets you decided on selectively executing
a different set of instruction for different conditions. Loops, on the
other hand, lets you repeat certain parts of a program for specified
number of times. Together, branches and loops provide you with a
powerful means to control the logic and execution of your code.
Java has two major decision making tools, which helps in taking
decision and instructing computer to execute the right set of
instructions. These includes:
36 Chapter 2 : Java Language
if....else statement
switch statement
IF STATEMENT
The if statement may be implemented in different forms depending on
the complexity of conditions to be tested.
if........else statement.
Nested if........ else statement.
else if ladder.
SIMPLE IF STATEMENT
The general form of a simple If statement is
If test condition
statement group;
Next Statement;
if
condition
False
True
Statements Group
Next Statement
Fig 2.1 If then statement
The statement group could have a single statement or a group of
statements, but each statement must be followed by semicolon(;).
The condition is defined as entity and it can have two values - true or
false. If the test condition is true, the statement group is executed,
otherwise, the statement group is skipped and the execution will
jump to next statement. If the condition is true both statement group
is executed followed by the Next Statement. The following figure
represent flow chart for the the If statement :
True if False
condition
True False
statement Statement
next
statement
As you can see from the flow chart, only one set of instruction are
being executed on the basis of true or false condition. In both the
cases, the control is transferred subsequently to next statement.
e.g.
........................
38 Chapter 2 : Java Language
if (code ==”M”)
Mheight = Mheight + height;
else
Fheight = Fheight + height;
System.out.println(“Height: ”);
In above program segment, if the code is equal to “M”, the height is
added to Mheight otherwise height is added to Fheight. In both cases,
the control is transferred to prinln statement.
Here you could note down that both the if and else statements are
followed by semi colon(;).
F if T
condition-1
F if T T if F
condition-2 condition-3
next statement
Cond. A
T F
Statement-1
Cond. B
T F
Statement-2
Cond. C
T F
Statement-3
Cond. D
T F
Statement-4 Statement-5
next statement
Your program may need to make more than two or three decisions
based on a single response. A series of If-else statements could do the
job, but, then there is an easier way: use the switch statement. With
the switch statement, the if-else tests are made into alternative
switches of one long conditional statement. Now, Java chooses the
first case, the second case, or whichever other case matches the
user’s response and executes the block of statement associated with
that case.
Switch
Expression
Expression
value-1
Expression Expression
Value-2 Value-3
next statement
Av.Marks College
90-100 IIT-DELHI
80-89 IIT-MUMBAI
70-79 UNIVERSITY OF ROORKEE
60-69 IIT-KANPUR
50-59 IIT-NOIDA
0-49 TRY YOUR LUCK NEXT TIME
Consider the following Swtif.java class.
public class Swtif
{
public static void main(String args[])
{
int marks = 89;
int c = marks/10;
switch(c)
{
case 9:
System.out.println("Admitted into " + "IIT-DELHI");
break;
case 8:
System.out.println("Admitted into " +"IIT-MUMBAI");
break;
case 7:
System.out.println("Admitted into " +"UNIVERSITY OF
ROORKEE");
break;
case 6:
System.out.println("Admitted into " + "IIT-KANPUR");
break;
case 5:
System.out.println("Admitted into " +"IIT-NOIDA");
44 Chapter 2 : Java Language
break;
default:
System.out.println("Admitted into " +"TRY LUCK NEXT
TIME");
break;
}
}
}
The Java language provides for three loop constructs for performing
loop operations. They are
The while statement
The for statement.
The do.. while statement
Thus the body of the loop is executed till the test condition with while
statement becomes false. When it become false, the control is
transferred to the statement immediately after the body of the loop.
The body of the loop may contain one or more statement, but it must
include a statement which increases or decreases the value of the
variable used in the test condition, thus providing a value which will
stop the loop. If no such statement has been used, the loop will
continually repeat itself for infinite number of times.
public class GN
{
public static void main(String args[])
{
int n = 1;
int sum = 0;
while (n <= 10)
{
sum = sum + n;
n++;
}
46 Chapter 2 : Java Language
System.out.println("This Sum is "+ sum );
}
}
In above case body of the loop is executed ten times, each time adding
the value n to the sum, thus giving the sum of first 10 numbers.
As the test condition is being executed after the body of the loop, the
do.....while statement creates an exit-control loop.
e.g. n =1;
do
{
sum = sum + n;
n++;
} while (n < 10);
Chapter 2 : Java Languagae 49
Here you could note that while expression takes value n< 10 and not
n <= 100. This is because the body of the loop is being executed first
and when test condition is being tested, only 9 more loops are
required to satisfy the condition. Therefore, test condition tells to
repeat the loop as long as the n remains less than 10.
BREAKING LOOPS
Loops performs the set of predefined operations repeatedly until the
control variable fails to satisfied. As the number of times, the loop is
executed is decided in advance, you can’t stop the looping process in
middle in normal course. But sometimes it is required to skip a part
of Loop or complete loop. e.g. consider the case of searching for a
particular name in a list containing 10 names. A program loop
written to read and test the 10 names, but it must be terminated as
soon as the desired name is found.
Similarly, here also, the break statement breaks the loop and transfers
the control to the statement immediately following the loop. In case
of nested looping, break statement would only exit from the loop
containing it i.e. the break will exit only a single loop.
The general form of break and continue statement can like shown
below
for (...............)
{
....................
if (test condition)
break;
}
......
Thus, you use break when you want to jump out of loop and terminate
it but if you don’t want to terminate loop and simply want to jump
immediately to the next iteration of the loop, use continue.
Chapter 2 : Java Languagae 51
1. What is a variable?
(a) A value that can not be changed.
(b) Text in a program that the compiler ignores.
(c) A place to store information in a program.
2. What is the process of fixing errors called?
(a) Defrosting
(b) Debugging
(c) Decomposing
3. State whether the following statements are TRUE and FALSE:
(a) Every line in a Java Program should end with a semicolon.
(b) In Java language, lowercase letters are significant.
(c) Every Java program ends with an END word.
(d) main () is where the program begins its execution.
(e) A line in a Java program may have more than one
statement.
(f) A System.out.println( ) statement can generate only one
line of output.
(g) The closing brace of the main() in a program is the logical
end of the program.
(h) Syntax errors will be detected by the compiler.
(i) All variables must be declared before their use in a
program.
(j) A n i n t e g e r v a r i a b l e w i ll b e i n i t i a l i z e d t o z e r o
automatically if not done explicitly.
(k) Comments must be restricted to one line only.
(l) Comments must begin at the start of a line only.
(m) In nested if statement, the last else gets associated
with the nearest if without an else.
(n) One if can have more than one else clause.
(o) You can always replace a switch statements by a
series of if..else statements.
(p) A switch expression can be of any type.
(q) A program stops its execution when a break statement
is encountered.
(r) A execution of a part of loop can’t be skipped.
4. If semicolons are needed at the end of each statement, why
does the comment line starting with // goes here not end with
a semicolon?
5. What is the major advantage of using /** **/ for comments?
6. Discuss the various basic datatypes.
7. What is a variable and what is meant by the “value” of a
variable? What is initialization? Why is it important?
52 Chapter 2 : Java Language
8. What is the significance of Block and Scope?
9. Differentiate between “break” and “continue” giving examples.
10. What is the difference between an if and a switch statement.
11. Find the sum of all odd no’s between 1 and 100. Try to use
different looping techniques.
12. Write a program to print the Floyd’s triangle shown below:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15.....
79.....................................................91
13. Write a program using do....while loop to calculate & print n
numbers of Fibonacci series:
1 1 2 3 5 8 13 21.........
( From third number in series, the number is sum of previous
two numbers)
14. Compare in terms of their functions, the following pairs of
statements:
(a) while and do ..while
(b) while and for.
(d) break and continue.
JAVA CLASS
OBJECT CREATION
INHERITANCE
CASTING
INTERFACE
PACKAGES
SOME JAVA PACKAGES
Object Oriented Programming
As a software developer, you will always look out for the approaches
that will help you develop quickest, cheapest and reliable softwares.
There are many approaches and technologies that have evolved since
the dawn of computing. The reason for having many approaches can
be contributed to improvements in hardware technology, new
innovations in computer science and changes in user expectations
over period of time.
OBJECTS
To understand the concepts of Objects, just look around your self to
locate real-world objects. Cars, TV, Motorbike, computers, pen etc.
are all objects. Let us pick computers and understand various aspect
of this object.
Next aspect associated with the object is - its state. The state of an
object is the particular condition it is in. For example, a computer can
be on or off. The methods-turn computer on and turn computer off-
are used to access the state of the computer. If the computer is on,
it could have a file open or closed. This is also another state of
computer. The files are objects in their own right. They contain
information and can be accessed through the proper software. Thus
software is a method for file.
CLASS
We have just discussed, how an object can simplify the process of
development. But how to develop objects. In object-oriented approach,
the most fundamental structure is class, which we use to develop
objects. A class is a template or prototype that defines a type of data
that is contained in an object and the methods that are used to access
this data. Using the same class, you can develop as many objects as
you want.
Thus in other words, objects which are similar in structure and other
attributes, are grouped together. This group is called Class. In
classes we have parent class, subclass, and superclass which allows
us the level of abstraction for grouping objects.
INHERITANCE
Its another advantage of object oriented database. Inheritance means
to inherit. When you define a class, it has some property and
attributes associated with it. Now you need another class which
contains all the properties and attributes of this class and few
additional attributes. You can define the new objects in terms of
existing class known as base class. All the objects created in lower-
56 Chapter 3 : Object Oriented Language
level of the base class will inherit the properties and attributes of all
classes above them.
Thus objects must interact with each other to bring out something
useful. At times, this interac tion is accompanied by various
parameters. For example operator has to open a file on the computer
and it also has to tell that the file should be opened in particular
software. Thus the particular software is parameter for opening a file.
This means that objects anywhere in a system can communicate with
other objects solely through messages accompanied by parameters.
ENCAPSULATION
After defining Class and Object, the data is bound to the object so that
access to the object can happen only through the ways that has been
defined for operating on it. This process of packaging an object’s data
together with its methods is called encapsulation. A powerful benefit
of encapsulation is the hiding of implementation details from other
objects. This gives a better security against illegal access.
All the classes in Java fan out from the Object base class. Object
serves as the superclass for all derived classes, including the classes
that make up the Java API.
Now, as we are well versed with the object oriented approach, let us
consider the Order Processing System for publisher. In this system,
we have items as books having title, number of page, rate, language,
quantity in stock and reorder level. These are the various attributes
important for Order Processing System.
Here books are objects and various methods must be identified for the
objects. The methods could be stock status, stock value, reordering
or reaching at reorder level, receiving stock etc. These are all the
methods which could be applied on the object in the system.
DECLARING CLASSES
To start with, we have to create the object. In OOPs, objects are
created by using a class of objects as a guideline. Therefore, we must
declare the class before creating the object. The syntax for declaring
classes in Java follows:
class Identifier {
ClassBody
}
Here, identifier specifies the name of the new class. The curly braces
surround the body of the class, classbody.
DECLARING METHODS
The state of the book object is defined by six data members. Now book
class itself is not useful, it also needs some methods. The most basic
syntax for declaring methods for a class follows:
58 Chapter 3 : Object Oriented Language
ReturnType Identifier(Parameters) {
MethodBody
}
Here, Returntype specifies the data type that the method returns,
Identifier specifies the name of the method, and Parameters specifies
the parameters required to the method. The parameters are optional.
You also have MethodBody enclosed by curly braces. As we have
already discussed that a method is synonymous with a message in
OOPs. Consider the following method for reordering the books:
void Reorder(int re_q, int quantity) {
if (quantity < re_q) {
// Reorder the book
}
else {
// Enough stock, no need to reorder
}
}
The Reorder() method is passed with two integers, re_q and quantity.
These value are then used to determine whether the books should be
ordered or not. If you make the Reorder() method a member of the
Book class, then you need not have to give the parameters with the
method. This is because both the parameters are already member
variable of Book, to which all class methods have access. The Book
class, with the addition of the Reorder() method, will look like as given
below:
class Book {
private string title ;
private int page;
private float rate;
private string lang;
private int quantity;
private int re_q;
public void Reorder() {
if (quantity < re_q) {
// Reorder the book
}
else {
// Enough stock, no need to reorder
}
}
public void Display(){
System.out.println(“Book Details”);
System.out.println(“———————”);
System.out.println(“Book Title : “+title);
Chapter 3 : Object Oriented Language 59
System.out.println(“Numer of pages “+ page);
System.out.println(“Price : “+ rate);
System.out.println(“Quantity in hand : “+ quantity);
System.out.println(“Language : “+ lang);
System.out.println(“Reorder Level : “+ re_q);
}
}
Once you have created the classes, you need to use the classes in the
program. You can create the object using special method called
constructor. The constructor method allows you to initialize variables
and perform any other operations when an object is created from the
class. You can also implement constructor in all your classes. The
constructor is always given the same name as class.
Till now, we have discussed only about creating new classes and
creating instance from the classes. Deriving all your classes from
Object isn’t a very good practice as you would have to redefine the
data and methods for each class. To reduce the workload, you can
derive subclasses from classes using the extends keyword.
The subclass inherits all the properties of class and it could be given
additional properties. The syntax for deriving a class using the
extends keyword follows:
class Identifier extends SuperClass {
ClassBody
}
Identifier refers to the name of the new subclass, SuperClass refers
to the name of the class you are deriving from, and ClassBody is the
new subclass body.
ABSTRACT CLASS
At times, you can create a superclass which act purely as templates
for more useable subclasses. In such a situation, superclass serves
as design templates for other classes. These types of superclasses are
referred to as abstract classes and cannot be used to create objects.
OVERRIDING METHODS
You can override methods in the derived classes. For example, the
Display() method in the Book, when used with the Compbook class,
64 Chapter 3 : Object Oriented Language
will display the incomplete information. Therefore, for any instance
of class Compbook, the Display()method must be redefined. To
incorporate the additional information of Compbook class, you would
override the Display() method with a version specific to Compbook
class. The Compbook class would then look something like this:
class Compbook extends Book{
String softw;
String Auth;
public Compbook() {
super();
String softw =”Flash 5”
String Auth = “M.N.Gulati”
}
public Compbook(string a, int b, int c, String d, int e,
int f, string g, string h) {
super (a,b,c,d,e,f);
this.softw = g;
this.Auth = h;
public void Display(){
System.out.println(“Book Details”);
System.out.println(“———————”);
System.out.println(“Book Title : “+title);
System.out.println(“Numer of pages “+ page);
System.out.println(“Price : “+ rate);
System.out.println(“Quantity in hand : “+ quantity);
System.out.println(“Language : “+ lang);
System.out.println(“Reorder Level : “+ re_q);
System.out.println(“Software : “+ softw);
System.out.println(“Author : “+ Auth);
}
}
Now, create an instance of the Compbook class as shown below:
Compbook Comp1 = new Compbook();
If this instance call the Display() method i.e. Compbook.Display(), the
new Display() method in Compubook is executed rather than the
original overridden Display() method in Book.
OVERLOADING METHODS
Similar to constructor overloading, you can overload the methods
also. In method overloading also, you send different types of
information (parameters) to send to a method. You can overload a
method by declaring another method with the same name but different
parameters.
Chapter 3 : Object Oriented Language 65
For example, the Reorder() method for the Book class could have two
different versions: one for general reorder by comparing the quantity
with reorder level and other for ordering the book if the quantity of the
book is less than a certain percentage of the reorder-level. (If the
reorder level is 200 books, you might like to place the order when the
stock is 300 books or 100 books).
The casting between data value of primitive data types simply converts
a data value of a primitive data type to another primitive data type.
While casting, care should be taken that the destination type should
always be equal to or larger in size than the source type so that there
is no loss of information. However, if the destination cannot hold
66 Chapter 3 : Object Oriented Language
larger value than the source, explicit casting must be done. Explicit
casting is done in the following way:
(data type)value
For example, the following set of commands converts a float value to
an int value.
………….
int i;
float f=6.7;
i=(int)f;
Casting Objects
You can also convert an object of a class to object of another class.
But the condition is that both these classes must be related to each
other by inheritance, i.e., one class must be a subclass or superclass
of the other class. You can divide the casting between classes into two
different situations:
Casting from a subclass to a superclass
Casting from a superclass to a subclass
Here also casting can either be implicit or explicit. In the case of
casting from a subclass to a superclass, you can cast either implicitly
or explicitly.
For example, and function that accepts the Book class will also accept
the Compbook class as Compbook class contains all the attributes
and methods of Book class.
OBJECT DESTRUCTION
In Java, each object of a class is allocated memory for its individual
attributes, but all the objects of the same class will share the same
methods. i.e. methods will be stored at one place and all objects will
use methods from there.
You may consider interfaces as abstract classes that are left completely
unimplemented. Completely unimplemented means that no methods
in the class have been implemented. Also the interface member data
should be static limited variable i.e. constant.
DECLARING INTERFACES
You will use the following syntax for creating interfaces:
interface Identifier {
InterfaceBody
}
Identifier specifies the name of the interface and InterfaceBody refers
to the abstract methods and static final variables that make up the
interface. As all the methods in an interface are abstract, you need
not to use the abstract keyword.
IMPLEMENTING INTERFACES
Implementing an interface is similar to deriving from a class, except
that you use implements keyword instead of extends keyword. The
syntax for implementing a class from an interface follows:
class <class-name> implements <interface-name>{
//instance-variables
//class-methods
//interface-methods
}
class-name specifies the name of the new class. Interface-name is the
name of the interface you are implementing, and in the body, you will
define instance variable, class-method and interface method.
Consider the following example, where sales order are being processed
by the publisher for general books and computer books. The method
of calculating the net order value has following components:
Quantity
Price
Normal Discount
Quantity Discount
Cash Discount
Trade Tax
Using the above variable, bills is to be generated for various parties,
who purchases, books or magzines. Both classes require the methods
Chapter 3 : Object Oriented Language 69
for the calculation of Normal Discount, Cash Discount, Quantity
Discount, Trade Tax and Net Amount. So here you can declare an
interface called Discount() which is defining these method prototypes
and a publisher name as a constant, since the publisher name has to
be used identically in both the classes.
// Declaring Interface
interface Discount
{
final static string publisher = "SiliconMedia";
public float Tot_Cost();
public float Normal_Dis();
public float Cash_Dis();
public float Qty_Dis();
public float Trade_Tax();
}
// Declaring the Class Book
class Book{
protected int ISBN;
String party;
String title;
protected int price;
protected int qty;
protected int total_cost;
int paymode;
Book(int bisbn, string bparty, string btitle, int bprice, int
bqty, char bpaymode)
{
ISBN = bisbn;
party = bparty;
title = btitle;
total_cost = bprice * bqty;
paymode = bpaymode;
qty = bqty;
price = bprice;
}
}
// Declaring the Class Magzine derived from Class Book and
//implementing interface Discount
class Magzine extends Book implements Discount {
Magzine(int misbn, string mbparty, string mtitle, int
mprice, int mqty, int mpaymode)
{
super(misbn, mparty, mtitle, mprice, mqty,
mpaymode);
70 Chapter 3 : Object Oriented Language
}
public float Normal_Dis() {
if (total_cost > 25000)
return ((float) 0.15 * total_cost);
else
return ((float) 0.10 * total_cost);
}
public float Cash_Dis() {
if (paymode > 1)
return 0;
else
return ((float) 0.02 * total_cost);
}
public float Qty_Dis() {
if (qty > 1000)
return ((float) 0.03 * total_cost);
else
return 0;
}
public float Trade_Tax() {
float Gros_Cost = total_cost - Normal_Dis() - Qty_Dis()
- Cash_Dis();
return ((float) 0.04 * Gros_Cost);
}
public float Tot_Cost() {
return (total_cost - Normal_Dis() - Qty_Dis() - Cash_Dis()
+Trade_Tax());
}
void print_Bill()
{
System.out.println(Discount.publisher + "\n " );
System.out.println("ISBN : " + ISBN);
System.out.println("Title : " + title);
System.out.println("Purchaser : " + party);
System.out.println("Quantity : " + qty);
System.out.println("Price : " + price);
System.out.println("Normal Discount " + Normal_Dis());
System.out.println("Quantity Discount :" + Qty_Dis());
System.out.println("Cash Discount :" + Cash_Dis());
System.out.println("Trade Tax :" +Trade_Tax());
System.out.println("Net Cost : " + Tot_Cost());
System.out.println("______________\n");
}
Chapter 3 : Object Oriented Language 71
}
// Declaring the Class Text book derived from Class Book and
//implementing interface Discount
class Textbook extends Book implements Discount{
Textbook(int misbn, string mparty, string mtitle, int
mprice, int mqty, int mpaymode)
{
super(misbn, mparty, mtitle, mprice, mqty,
mpaymode);
}
public float Normal_Dis() {
if (total_cost > 50000)
return ((float) 0.20 * total_cost);
else
return ((float) 0.10 * total_cost);
}
public float Cash_Dis() {
if (paymode > 1)
return 0;
else
return ((float) 0.03 * total_cost);
}
public float Qty_Dis() {
if (qty > 1000)
return ((float) 0.02 * total_cost);
else
return 0;
}
public float Trade_Tax() {
float Gros_Cost = total_cost - Normal_Dis() - Qty_Dis()
- Cash_Dis();
return ((float) 0.01* Gros_Cost);
}
public float Tot_Cost() {
return (total_cost - Normal_Dis() - Qty_Dis() - Cash_Dis()
+ Trade_Tax());
}
void print_Bill()
{
System.out.println(Discount.publisher + "\n " );
System.out.println("ISBN : " + ISBN);
System.out.println("Title : " + title);
System.out.println("Purchaser : " + party);
System.out.println("Quantity : " + qty);
72 Chapter 3 : Object Oriented Language
System.out.println("Price : " + price);
System.out.println("Normal Discount " + Normal_Dis());
System.out.println("Quantity Discount :" + Qty_Dis());
System.out.println("Cash Discount :" + Cash_Dis());
System.out.println("Trade Tax :" +Trade_Tax());
System.out.println("Net Cost : " + Tot_Cost());
System.out.println("______________\n");
}
}
public class calc{
public static void main(String args[ ]){
Magzine M1 = new Magzine(1097, “RGC”, “MediaQuest”,
100, 500, 1);
M1.print_Bill();
Textbook T1 = new Textbook(1001, “RGC”, “SAD”, 75,
1000, 1);
T1.print_Bill();
}
}
The output of the above calc.java would be as follows:
ISBN : 1097
Title : MediaQuest
Purchaser : RGC
Quantity : 500
Price : 100
Normal Discount 7500.0005
Quantity Discount :0.0
Cash Discount :1000.0
Trade Tax :1660.0
Net Cost : 43160.0
______________
ISBN : 1001
Title : SAD
Purchaser : RGC
Quantity : 1000
Price : 75
Normal Discount 15000.0
Quantity Discount :0.0
Cash Discount :2250.0
Trade Tax :577.5
Net Cost : 58327.5
______________
Chapter 3 : Object Oriented Language 73
You can group related classes and interfaces together into a single
unit called package. When you are handling a large group of classes
and interface, it makes you job easier if you group together the
classes and interface.
DECLARING PACKAGES
You use the following syntax for the package statement:
package Identifier;
You can place the above statement at the beginning of a compilation
unit, before any class declaration. Every class located in a compilation
unit with a package statement is considered part of that package.
You can also place the packages into other packages. While doing so,
you must follow the directory structure containing the executable
classes to match the package hierarchy.
74 Chapter 3 : Object Oriented Language
IMPORTING PACKAGES
You can also use the classes from the other packages by using import
statement. This statement lets you to import classes from other
packages into a compilation unit. The syntax for the import statement
follows:
import Identifier;
Here, identifier is the name of the class or package of classes you are
importing. For example, the following statement will import all classes
of java.lang package.
import java.lang.*;
If you want to import a particular class from the package, you could
specify the class name.
import java.lang.String
The above statement will import the String class from Java.lang
package.
Java comes with certain built-in packages that perform all important
tasks. These include:
Java.lang package contains all the fundamental classes like
the Security Manager class, System class, Thread class etc.
Java.util package contains the utility classes like the Date
class etc.
Java.io consist of the classes responsible for the input output
operations, like the disk I/O etc.
Java.applet carries the necessary functionality for creating
and managing the applets.
Java.awt contains the GUI components meant for the interface
designing, event handling etc., like the Button class, Label
class etc.
Java.net package contains the classes for operations over the
net like establishing connection to a remote server etc.
Chapter 3 : Object Oriented Language 75
Now, how a single CPU is able to execute more than one thread at a
time. In single-processor systems, only a single thread of execution
occurs at a given instant. The CPU moves back and forth among
various threads to create the illusion that threads are being processed
at a time. Single-processor systems support logical concurrency and
not physical concurrency. Logical concurrency occurs when multiple
threads execute with separate, independent flows of control. The
Physical concurrency occurs when the threads are actually executed
at the same time. This happens only in multiprocessor system. The
important feature of multithreaded programs is that they support
logical concurrency irrespective of the fact that whether physical
concurrency is actually achieved.
Chapter 4 : Multithreading 79
Thread States
A thread has a life span and during the life it passes through five
stages: new, ready, running, inactive and finished. As soon as thread
is born or created, it enters the new state. When started by start()
method, it is ready to run. When start() method calls the run()
method, the thread comes in running state.
However, the thread may not always be in the running state. It may
become inactive for one or more reason. When a thread is inactive, it
implies that the thread is alive and that it can be allocated CPU time
by the system for execution. Some of the events that may cause a
thread to become inactive include the following:
Time not allotted by CPU in single processor system.
The thread has been put to sleep for a certain period of time
using the sleep() method.
The thread is waiting for execution as wait() method has been
called.
The thread has been suspended using the suspend() method.
A thread that is inactive may either be resumed, in which case it
enters the ready state again, or it can be stopped in which case it
enters the finished state.
80 Chapter 4 : Multithreading
The thread creating process involves two steps - writing the code that
is executed in the thread and writing the code that starts the thread.
In all the program developed so far, you have used single thread.
When you start a Java application, the virtual machine (VM) runs the
main() method inside a Java thread. The Java virtual machine
provides a multithreaded environment, but it starts user applications
by calling main() in a single thread.
This method limits the use of run() method as the Thread objects to
be under the Thread class in the class hierarchy. At many a times,
you may want to add a run() method to a preexisting class that does
not inherit from Thread.
class SiliconThread{
public static void main(String args[]) {
SMThread sm1 = new SMThread("Running Thread sm1
: ");
SMThread sm2 = new SMThread("Running Thread sm2
: ");
sm1.start();
sm2.start();
boolean Live_sm1 = true;
boolean Live_sm2= true;
do {
if(Live_sm1 && !sm1.isAlive()){
Live_sm1 = false;
System.out.println("1st thread is finished.");
}
if(Live_sm2 && !sm2.isAlive()){
Live_sm2 = false;
System.out.println("2nd thread is finished.");
82 Chapter 4 : Multithreading
}
}while(Live_sm1 || Live_sm2);
}
}
The output comes something like given below. You may get a different
output as you run the program each time, the output will be different.
This is because the random number that is being used to delay the
display of each thread.
Running Thread sm2: This
Running Thread sm1: This
Running Thread sm1: book
Running Thread sm2: book
Chapter 4 : Multithreading 83
Running Thread sm1: on,
Running Thread sm2: on,
Running Thread sm1: java
Running Thread sm2: java
Running Thread sm1: is
Running Thread sm2: is
Running Thread sm1: quick
Running Thread sm2: quick
Running Thread sm1: and
Running Thread sm2: and
Running Thread sm2: easy
2nd thread is finished.
Running Thread sm1: easy
1st thread is finished.
The above output shows that thread sm2 is executed first and
displayed “This” to the console window. It then waited to execute
while thread sm1 displayed “This” and “book”. Then thread sm1
waited while thread sm2 continued its execution and display “book”.
Now again thread sm2 waited and sm1 displayed “on”. The process
continues and the threads sm1 and sm2 are displayed till all the
strings has been displayed. When execution is completed, message
“1st thread is completed” and “2nd thread is completed” is displayed.
The run() method uses the getName() method of class Thread to get
the name of the currently executing thread. It then prints each word
of the output display message while waiting a random length of time
between each print. (4000*Math.random()).
IMPLEMENTING RUNNABLE
Here, you will create another program similar to previous program
but the threads you create will be objects of a class (Say SMclass)
which is not a subclass of Thread. Instead, the class SMclass will
implement the Runnable interface and Objects of SMclass will be
executed as threads by passing them as arguments to the Thread
constructor.
import java.lang.Thread;
import java.lang.System;
import java.lang.Math;
import java.lang.InterruptedException;
import java.lang.Runnable;
class SiliconThread1{
public static void main(String args[]) {
Thread sm1 = new Thread(new SMclass("Running
Thread sm1: "));
Thread sm2 = new Thread(new SMclass("Running
Threadsm2 :"));
sm1.start();
sm2.start();
boolean Live_sm1 = true;
boolean Live_sm2= true;
do {
if(Live_sm1 && !sm1.isAlive()){
Live_sm1 = false;
System.out.println("1st thread is finished.");
}
if(Live_sm2 && !sm2.isAlive()){
Live_sm2 = false;
System.out.println("2nd thread is finished.");
}
} while(Live_sm1 || Live_sm2);
}
}
Here, the main() method differs in the way that it creates thread sm1
and sm2. The program first created instances of SMclass and then
passed them to the Thread() constructor, creating instances of class
Thread. The Thread() constructor takes as its argument any class
that implements the Runnable interface.
The advantage of using the Runnable interface is that your class does
not need to extend the Thread class. This will be very helpful feature
when you start using multithreading in applets in the coming chapters.
The only disadvantages to this approach are ones of convenience. You
have to do a little more work to create your threads and to access their
methods.
86 Chapter 4 : Multithreading
THE THREAD API
Constructor
The Thread class has seven different constructors :
public Thread();
public Thread(Runnable target);
public Thread(Runnable target, String name);
public Thread(String name);
public Thread(ThreadGroup group, Runnable target);
public Thread(ThreadGroup group, Runnable target, String name);
public Thread(ThreadGroup group, String name);
These constructors has three different parameters - thread name,
thread group, and a Runnable target object.
name is the (string) name to be assigned to the thread. Every
java thread must have a name. You can set the name during
construction or with setname() property.
public final void setName(String name);
If you fail to specify a name, the system generates a unique
name of the form Thread-N, where N is a unique integer.
You can retrieve the name of a thread using the getName()
method.
public final String getName();
Although Java assign the thread names but still it is good
practice to assign the names as they provide the programmer
with a useful way to identify particular threads during
debugging.
target is the Runnable instance whose run() method is executed
as the main method of the thread.
group is the ThreadGroup to which this thread will be added.
Waking Up a Thread
Following methods relating to thread wakeup are declared in Java
API:
public void interrupt();
public static boolean interrupted();
public boolean isInterrupted();
You can use interrupt() method on the thread object to send a wake-
up message. It causes an InterruptedException to be thrown in the
thread. It also sets a flag that can be checked by the running thread
using the interrupted() or isInterrupted() method.
Sleep() method
You can use sleep() method to pause the current thread for a specified
period of time. There are two methods that has been defined for
sleep().
Chapter 4 : Multithreading 89
public static void sleep(long millisecond);
public static void sleep(long millisecond, int nanosecond);
E.g. Thread.sleep(500) will pause the current thread for half a
second. During this time the thread would not be in runnable state.
When the specified time expires, the current thread again becomes
RUNNABLE.
Daemon Threads
When you require threads which run in the background to provide
services to other threads, are called Daemon threads.
public final boolean isDaemon();
public final void setDaemon(boolean on);
The daemon thread typically executes a continuous loop of instructions
that wait for a service request, perform the service, and wait for the
next service request.
The Java virtual machine (VM) has a default daemon thread, known
as the garbage collection thread. It is a low priority thread, executing
only when there is nothing else for the system to do.
You can use the setDaemon() method to set the daemon status of
thread. To check whether a thread is a deamon thread or not, you may
use isDaemon() method. This method returns true if this thread is a
daemon thread.
THREADGROUP API
Constructors
The ThreadGroup class has following two constructors:
public ThreadGroup(String name);
public ThreadGroup(ThreadGroup parent, String name);
Both of these constructors require you to specify the new thread
group. The first constructor which doesn’t take the parent name,
creates the new group as a child of the currently executing thread
group.
Chapter 4 : Multithreading 91
Priority
You can also manage the priority of the threads inside a group using
setMaxpriority() method. When this method is called, no thread
within the group can use setPriority() method to set a priority higher
than the specified maximum value.
public final int getMaxPriority();
public final void setMaxPriority(int pri);
ThreadGroup Tree
Thread Group is like a folder. It could contain other Thread
Group and Threads. There are two methods which gives
information about the threads and groups.
public int activeCount();
public int activeGroupCount();
To count the num ber of th reads th at ar e memb er of
ThreadGroup tree, you can use activeCount() method. To
count the number of ThreadGroups that are members of any
ThreadGroup, use activeCountGroup() method.
To list the threads or group in the ThreadGroup object, you
can use one of the following enumerate() methods :
public int enumerate(Thread list[]);
public int enumerate(Thread list[], boolean recurse);
public int enumerate(ThreadGroup list[]);
public int enumerate(ThreadGroup list[], boolean
recurse);
The enumerate() method with recurse parameter having true
value, list all the threads and groups inside the ThreadGroup.
If recurse is false, only the threads or groups in this immediate
ThreadGroup object are retrieved. If no recurse parameter is
used with enumerate() method, it is similar to the situation,
where recurse parameter is true.
You can use the parentOf() method to check whether the
current thread group is a parent of specified group. It returns
true if this thread group is the parent of the specified group
otherwise false.false otherwise. Following is this method’s
syntax:
public final boolean parentOf(ThreadGroup g);
If you want to find out the parent of the thread group, you can
use the getParent() method. It returns the parent of this
thread group, or null if this ThreadGroup is the top-level
ThreadGroup. Following is this method’s syntax:
public final ThreadGroup getParent();
The real problem lies when two or more threads are accessing the
same object. For example, when one thread is updating the data and
second thread is reading the same data. Concurrency requires the
programmer to take special precautions to ensure that Java objects
are accessed in a thread-safe manner. Over the years, many
concurrency-control solutions have been proposed and implemented.
class SiliconThread{
public static void main(String args[]) {
SMThread sm1 = new SMThread("Running Thread sm1
: ");
SMThread sm2 = new SMThread("Running Thread sm2:
");
sm1.start();
sm2.start();
boolean Live_sm1 = true;
boolean Live_sm2= true;
do {
if(Live_sm1 && !sm1.isAlive()){
Live_sm1 = false;
System.out.println("1st thread is finished.");
}
if(Live_sm2 && !sm2.isAlive()){
Live_sm2 = false;
System.out.println("2nd thread is finished.");
}
}while(Live_sm1 || Live_sm2);
}
}
If you remove the keyword synchronized, and run the program, the
output will be unsynchronized, i.e. the threads will be executed
randomly.
The wait() method unlocks the monitor from the current thread and
put the thread to sleep until some other thread enters the same
monitor and calls notify() method. The notify() method will wake up
the first thread that called wait() on the same object. In case there are
many threads that have been suspended using wait() method on the
same object, you can resume all of them by using notifyAll() method.
There are two additional varieties of the wait() method. The first
version takes a single parameter - a timeout value in milliseconds.
The second version has two parameters - a more precise timeout
value, specified in milliseconds and nanoseconds.
wait(long milliseconds);
wait(long milliseconds, int nanoseconds);
96 Chapter 4 : Multithreading
The Java language eliminates whole classes of errors that result from
the use of dangerous programming constructs. The more simple and
familiar is the language, the less are the chances of occurrence of
programming errors.
Exceptions may also be thrown directly by Java code using the throw
statement. These exceptions are thrown when code detects a condition
that could potentially lead to a program malfunction. The exceptions
thrown by user programs are generally not objects of a subclass of
RuntimeException. These non-runtime exceptions are referred to as
program exceptions.
Chapter 5 : Exception Handling 99
A try block is a block of code beginning with the try keyword followed
by a left and right curly brace. Every try block is associated with one
or more catch blocks. Here is a try block:
try
{
// method calls
}
When you place the call in the try block, method will catch the
exception thrown by the method it calls. To handle the exception
thrown, you can have the catch block. Different catch blocks handle
different types of exceptions.
Consider the following code, which has a try block and catch block to
handle exception of type Exception.
try
{
// method calls
}
catch( Exception x )
{
// handle exceptions
}
Inside the try block, as soon as the exception condition arises, an
object of that specific type of exception is automatically created and
100 Chapter 5 : Exception Handling
thrown. As soon as the try block throws any type of exception,
execution of the try block ceases and control is transferred to catch
block. The thrown object is then matched with the catch block. If the
block matches, then the statements for handling the exception
written within the catch block are executed.
THROW
In the above example, the exception has been thrown automatically.
Such exceptions are called implicit exceptions. At times it is required
Chapter 5 : Exception Handling 101
to throw the exception explicitly. This is used when you create your
own exceptions and you want to throw them. All the system-defined
exceptions are thrown automatically, but the user-defined exceptions
must be thrown explicitly using the throw clause. It takes the form as:
try
{
// statements
throw new Udef_Exception();
//statements
}catch(Udef_Exception obj1)
{
System.out.println(“User defined exception caught”);
}
Here, the exception is thrown using throw and catch block catches
the exception. The Udef_Exception is a class made specifically to
handle an exception and it is encapsulating some specific kind of user
defined behaviour.
Here, both publisher() and book() do not have the catch block.
Therefore, they must send the warning using throws keyword as
shown below:
import java.io.* ;
Chapter 5 : Exception Handling 103
import java.lang.Exception ;
public class Throws {
public static void main( String args[] ) {
try
{
publisher() ;
}catch( Exception e )
{
System.out.println( “Caught publisher() and Book()
without Catch block”) ;
}
}
static void publisher() throws Exception {
book() ;
}
static void book() throws Exception {
throw new Exception() ;
}
}
The output of the above set of instructions is :
Caught publisher() and Book() without Catch block
MULTIPLE CATCH
The try block may have a list of things to do and in the process, it
could throw more than one expectation. It is similar to playing shots
in different direction on the cricket field. Therefore, we need a fielder
at various positions, if we want to catch the shot. Same principle
applies here, you must provide enough catch block (our fielder) to
catch all the exceptions thrown by the try block.
FINALLY
The finally clause is another clause that can appear with try block. It
can either substitute the catch block or appear along with the catch
block. The finally clause ensures that the block of the clause must be
executed after the try block, irrespective of the fact whether the
exception was thrown by the try block or not. It could take one of the
following form:
try{
..............
}finally {
...............
}
or
try{
..........
}catch(<exception> obj){
.............
}
finally{
...............
}
Consider the following example, which throws an ArithmeticException
and then execute the finally block.
class ArthExcp
{
public static void main(String args[ ])
106 Chapter 5 : Exception Handling
{
try
{
int count1 = 6;
int count2 = 12;
int k = count1/(count2 - 2* count1);
System.out.println(k);
}catch(ArithmeticException e)
{
System.out.println(“##Wrong Count 2##”);
}
finally
(
System.out.println(“Executing Finally”);
}
}
}
The output of the above program comes as follows:
##Wrong Count 2##
Executing Finally
Thus, the finally block is always executed, irrespective of the fact that
whether try block throws an exception or not.
Consider the following example, where nested try blocks have been
used.
class ArthExcp1
{
public static void main(String args[ ])
{
String message[] = {"This","code","has","more", "than",
"defined", "strings"};
try
{
for(int ctr = 0; ctr <=message.length; ctr ++){
System.out.println(message[ctr]);
try{
int count2 = 12;
int k = count2/ctr;
System.out.println(k);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("More arrays than defined");
}
}
}catch(ArithmeticException e){
System.out.println("##Wrong ctr##");
}
}
}
Here, outer try statement is displaying the strings, whereas inner try
block is calculating the integer k. The inner try block takes the
exception ArrayIndexOutOfBoundsException, while outer try block
takes the ArithmeticException.
When you execute the above code, you get the following output
This
##Wrong ctr##
You may note that the message that appears is for ArithmeticException
while Arithmetic exception is thrown by the inner try block. Thus the
exception traverse from inner blocks to outer blocks.
Java also provides the windows and other graphical user interface are
also provided and handled by Abstract Windows Toolkit (java.awt
package). The AWT package lets you create all type of graphical user
interface including Windows and dialog box, pull down menus,
buttons, labels check box and all other user interface components. It
also provides event handling to respond to mouse clicks, mouse
movements, and keyboard input. It will be discussed in more details
in the coming chapters.
Also, there are many tools available for developing java applications
and applets. It includes, but not limited to, SunSoft Java WorkShop,
Symantec Café and Visual Café, and Rogue Wave JFactory. These
tools offers visual programming techniques for developing applications
and applets using Java.
SECURITY IN APPLETS
As you know, any thing that can execute code is potential security
risk. The risk becomes more when codes are being downloaded from
web. Security is one of the primary concerns of Java’s developers,
keeping that in mind, some of Java’s functionality is blocked for
applets. In general, the applets are different from application in
following aspect :
The applet execution depends on the browser setting. If the
browser has been set for high security restrictions, the applet
cannot read, write or execute files on that browser.
Chapter 6 : Java Applets 113
Applets can communicate only with the site from where the
applet was run.
Applets cannot load programs like executable files and shared
libraries from the machine where browser is displaying the
applet.
An applet requires a browser to run it. Therefore, it takes
longer to execute an applet than an application. The amount
of memory that can be used by an applet is decided by the
browser, whereas there is no such restriction on applications.
You have already seen, how we can create and run an applet using
browser, in chapter 1. Applet always requires a browser around it to
be able to get executed. No applet can run outside browser. Unlike
application, it doesn’t have a main() method which is the starting
point of application. Rather each applet starts out with a class
definition, like this:
public class First_Applet extends java.applet.Applet {
..............
}
First_Applet is the name of the applet class which is always declared
as a public class. All applets are derived from java.applet.Applet
class, also referred as the Applet class.
import java.applet.Applet
public class First_Applet extends Applet {
..............
}
The java.applet package is the smallest package in the Java API. It
consists of a single class - the Applet class - and three interfaces:
AppletContext, AppletStub, and AudioClip.
The Applet class contains 21 access methods that are used to display
images, play audio files, respond to events, and obtain information
about an applet’s execution environment, referred to as the applet’s
context.
init();
Initialization of any methods and variables takes place at this stage.
The init method is called when the applet is first loaded. Thus you can
use the init() method to set the initial behaviour of applet. You can set
fonts, load images, initialize variables or set parameters here. To give
an applet the type of functionality you want, you must override the
init() method. The init() method takes the following form :
public void init(){
.......................}
stop();
This stage is used to stop any actions that is still in progress from the
start stage when an applet is exited. For example, a sound loop would
need to be stopped when a person left the Web page containing a
sound applet. This method is called when the page is left, or the
browser is minimized. You should always stop an applet before you
destroy it; you can also use the stop() method to stop applet execution
when a pause in the flow is needed.
public void stop(){
..................
}
destroy();
Destroy is called automatically, and completes any memory cleanup
or garbage collection that needs to be done when an applet is
destroyed. This method is called when you quit a browser. This
method is the last thing that happens when the user leaves the page
containing the applet.
public void destroy(){
.....................
}
paint();
It is one of the most widely used method in any applet. Whenever
something needs to be displayed or redisplayed on the applet window,
the paint() method handles the task.
For viewing applets, you must have the basic knowledge of HTML and
HTML tags. Applets are placed on a Web page in the same way that
anything is put on a page. HTML commands are used to describe the
applet, and the Web browser loads it along with the other parts of the
page.
If you have used HTML to create a Web page, you know that it’s a way
to combine formatted text, images, sound, and other elements together.
HTML uses special commands called tags that are surrounded by <
and > marks, e.g. <IMG> & </IMG> for the display of images, <P> &
</P> for the insertion of a paragraph mark, and <CENTER> &
</CENTER> to center the text .
For running Java applets on a Web page, you require the use of two
special HTML tags: <APPLET> and <PARAM>. These tags are included
on a Web page along with all other HTML code.
PARAMETER TAG
The parameter tag is used to pass named parameters to a Java applet.
It is a separating tag that has two attributes: NAME and VALUE. The
NAME attribute identifies the name of a parameter and the VALUE
attribute identifies its value.
Parameters are passed to the applet once it’s loaded. All parameters
are sent as strings whether or not they are encased in quotation
marks.
The java.io - I/O package, provides classes that are required for
reading and writing data to and from different input and output
devices - including files. It includes package for input and output
stream class hierarchy and stream filters to simplify I/O processing.
It also has the package to perform random-access I/O and the
StreamTokenizer class to construct input parses. The most important
classes contained in the I/O package follow:
< Input stream classes
< Output stream classes
< File classes
< The StreamTokenizer class
java.text, the text package, contains the classes that are used for
internationalization. The text package contains classes and interfaces
for handling text specific to a particular locale. The text package
provides the classes that enables text to be mapped to a specific
language and region. The classes and interfaces defined in the text
package rely on Unicode 2.0 character encoding and can be used to
adapt text, numbers, dates, currency, and user-defined objects to the
conventions of any country. Some of the more important classes
included in the text package follow:
< Formatting classes
< The Collator class
< The TextBoundary class
The Java SQL package, - java.sql (also known as JDBC package) , lets
you develop database applications capable of performing SQL queries.
Using SQL package, you can make a Java application to interact with
virtually any relational database using SQL. The few important
classes and interfaces included in the SQL package follow:
< The DriverManager class
< The Connection interface
< The Statement and ResultSet interfaces
The Language Package
The Java language package is the heart of Java API. It provides the
core classes that make up the Java programming environment. The
language package includes classes representing numbers, strings,
and objects, as well as classes for handling compilation, the runtime
environment, security, and threaded programming. Unlike other
packages, you don’t have to import the java.lang package, it is
imported automatically into every Java program.
This method causes the current thread to wait. wait() for forever and
wait(long timeout) or wait(long timeout, int nanos)until it is notified
via a call to the notify or notifyAll method, or until the specified
timeout period has elapsed. The wait(long timeout, int nanos) lets you
define the timeout period in nanos for a finer control.
This method determines the runtime class descriptor for the class
with the specified name. E.g. forName() method can be used to get
information about the Float class:
Class info = Class.forName(“java.lang.Float”);
It can throw the following exception :
ClassNotFoundException if the class could not be found.
Returns a Field object that reflects the specified public member field
of the class or interface represented by this Class object.
This method loads the class with the specified name, resolving it if the
resolve parameter is set to TRUE. This method must be implemented
in all derived class loaders, because it is defined as abstract. It can
also throw the following exception:
ClassNotFoundException if the class is not found.
This method finds the system class with the specified name, loading
it if necessary. A system class is a class loaded from the local file
system with no class loader in a platform-specific manner. It could
throw the following exceptions:
ClassNotFoundException if the class is not found.
NoClassDefFoundError if a definition for the class is not
found.
Object type wrappers are useful because many Java classes operate
on objects rather than primitive data types. Furthermore, by creating
object versions of the simple data types, it is possible to add useful
member functions for each data type.
The Byte class wraps the fundamental byte type and provides a
variety of methods for working with byte numbers. Some of the more
important methods implemented by Byte follow:
static int parseByte(String s, int radix);
static int parseByte(String s);
long shortValue();
long longValue();
long intValue();
float floatValue();
double doubleValue();
parseByte() parse strings for a byte value and return the value
as a byte.
int/short/long/float/doubleValue()
return the value of a byte converted to the
appropriate type.
This class implements an object type wrapper for float values. Object
type wrappers are useful because many Java classes operate on
objects rather than primitive data types. In addition, the Float class
provides support constants and methods for working with float
values. The methods implemented by the Float class follow:
boolean isNaN();
static boolean isNaN(float v);
boolean isInfinite();
static boolean isInfinite(float v);
short shortValue();
long longValue();
int intValue();
double doubleValue();
byte byteValue();
static int floatToIntBits(float value);
static float intBitsToFloat(int bits);
isNaN() returns whether or not the Float value is the
special not-a-number (NaN) value.
isInfinite() returns whether or not the Float value is infinite,
which is represented by the special
NEGATIVE_INFINITY and POSITIVE_INFINITY final
static member constants.
floatToIntBits() determines the IEEE 754 floating-point single
precision representation of the specified float value.
IntBitsToFloat() determines the float representation of the specified
IEEE 754 floating-point single precision value.
import java.lang.System;
import java.lang.Boolean;
import java.lang.Character;
import java.lang.Integer;
import java.lang.Long;
import java.lang.Float;
import java.lang.Double;
public class wrapp{
public static void main(String args[]){
Boolean b1 = new Boolean(“TRUE”);
Boolean b2 = new Boolean(“FALSE”);
System.out.println(b1.toString()+” or“+b2.toString());
for(int j=0;j<16;++j)
System.out.print(Character.forDigit(j,16));
System.out.println();
Integer i = new Integer(Integer.parseInt(“ef”,16));
140 Chapter 8 : The Language Package
Long l = new Long(Long.parseLong(“abcd”,16));
long m=l.longValue()*i.longValue();
System.out.println(Long.toString(m,8));
System.out.println(Float.MIN_VALUE);
System.out.println(Double.MAX_VALUE);
}
}
The output of the above program is
TRUE or FALSE
0123456789abcdef
50062143
1.4E-45
1.7976931348623157E308
import java.lang.System;
import java.lang.Math;
public class MathApp {
public static void main(String args[]) {
System.out.println(Math.E);
System.out.println(Math.PI);
System.out.println(Math.abs(-1234));
System.out.println(Math.cos(Math.PI/4));
System.out.println(Math.sin(Math.PI/2));
System.out.println(Math.tan(Math.PI/4));
System.out.println(Math.log(1));
System.out.println(Math.exp(Math.PI));
System.out.println(Math.sqrt(49.00));
System.out.println(Math.pow(2,4));
for(int i=0;i<5;++i){
System.out.print(Math.random());
System.out.println(\n);
}
System.out.println();
}
}
The output of the above program is
2.718281828459045
3.141592653589793
1234
6.123031769111886E-17
Chapter 8 : The Language Package 143
1.0
0.9999999999999999
0.0
23.140692632779267
7.0
16.0
0.7474941425264944
0.3570842695525769
0.81586852214149
0.5440026029429945
0.4635666300132165
import java.lang.System;
import java.lang.String;
public class strapp {
public static void main(String args[]) {
String s = "SILICONMEDIA.org";
System.out.println(s);
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println("["+s+"]");
s=s.trim();
System.out.println("["+s+"]");
s=s.replace( S , P );
s=s.replace( M , Q );
s=s.replace( A , R );
System.out.println(s);
int i1 = s.indexOf( P );
int i2 = s.indexOf( Q );
int i3 = s.indexOf( R );
char ch[] = s.toCharArray();
ch[i1]= S ;
ch[i2]= M ;
ch[i3]= A ;
s = new String(ch);
System.out.println(s);
}
}
The output of the following program would be:
SILICONMEDIA.org
SILICONMEDIA.ORG
siliconmedia.org
[SILICONMEDIA.org]
[SILICONMEDIA.org]
PILICONQEDIR.org
SILICONMEDIA.org
import java.lang.System;
import java.lang.String;
import java.lang.StringBuffer;
public class strbpp {
public static void main(String args[]) {
StringBuffer s1 = new StringBuffer(" Book s are ");
s1.append("Cool");
s1.append( ! );
s1.insert(0,"Siliconmedia");
s1.append( \n );
s1.append("This is ");
s1.append(true);
s1.setCharAt(38, T );
s1.append( \n );
s1.append("Aiming at #");
s1.append(1);
String s = s1.toString();
System.out.println(s);
}
}
The output of the above code is :
Siliconmedia Book s are Cool!
This is True
Aiming at #1
Write a program to find out the total memory and the free
memory in your computer. Extend the program to execute the
to applications - Windows Browser and Notepad.
Solution:
import java.lang.System;
import java.lang.Runtime;
import java.io.IOException;
public class RuntimeMemApp {
public static void main(String args[]) throws
IOException {
Runtime rt = Runtime.getRuntime();
System.out.println(rt.totalMemory());
System.out.println(rt.freeMemory());
rt.exec(“C:\\Windows\\Explorer.exe”);
rt.exec(“C:\\Windows\\Notepad.exe”);
}
}
This interface indicates that an object can be cloned using the clone
method defined in Object. The clone method clones an object by
copying each of its member variables. It throws
CloneNotSupportedException if the object doesn’t support the
Cloneable interface or if it explicitly doesn’t want to be cloned. T h e
definition for the Cloneable interface follows:
public interface java.lang.Cloneable {
}
The BitSet class is used to create objects that maintain a set of bits.
The bits are maintained as a growable set. The capacity of the bit set
is increased as needed. Bit sets are used to maintain a list of
that indicate the state of each element of a set of conditions. Flags are
boolean values that are used to represent the state of an object. The
class java.util.BitSet is derived directly from Object but also
implements the Cloneable interface. The definition of Bitset class can
be given as below:
public class BitSet extends Object implements
Cloneable {
// public constructors
public BitSet();
public BitSet(int nbits);
// public instance methods
public void and(BitSet set);
public void clear(int bit);
public Object clone();
public boolean equals(Object obj);
Chapter 9 : The Utility Package 157
public boolean get(int bit);
public int hashCode();
public int length();
public void or(BitSet set);
public void set(int bit);
public int size();
public String toString();
public void xor(BitSet set);
}
Two BitSet constructors are provided. One allows the initial capacity
of a BitSet object to be specified. The other is a default constructor
that initializes a BitSet to a default size.
and() logically ANDs the BitSet with another BitSet.
clear() clears the specified bit.
clone() overrides the clone method in Object. It can be
used to clone the bit set.
equals() used to compare the contents of two BitSets.
get() gets the value of a specified bit in the set.
hashCode() overrides the hashCode method in Object and can
be used to get a hash code for the instance.
length() Returns the “logical size” of this BitSet: the index
of the highest set bit in the BitSet plus one.
or() logically ORs the BitSet with another.
set() sets the specified bit.
size() returns the amount of space, in bits, used to store
the set.
toString() formats the BitSet as a String.
xor() logically XORs the BitSet with another BitSet.
Similar to the real world dictionary, which stores the words and
arrange them in order to easily reach to word’s definition, Java
dictionary stores keys in order and lets you reach to the value of keys.
In Java dictionary, one object is used as the key to access another
object. This abstraction will become clearer as you investigate the
Hashtable and Properties classes. The abstract class
java.util.Dictionary extends Object.
public class Dictionary extends Object {
// public constructors
public Dictionary();
// public instance methods
public abstract Enumeration elements();
public abstract Object get(Object key);
public abstract boolean isEmpty();
public abstract Enumeration keys();
public abstract Object put(Object key, Object value);
public abstract Object remove(Object key);
public abstract int size();
}
Elements are added to a Dictionary using put and are retrieved using
get. Elements may be deleted with remove. The methods elements
and keys each return an enumeration of the values and keys,
respectively, stored in the Dictionary.
elements() returns an Enumeration of all elements in a
Dictionary.
get() retrieves an object from a Dictionary based on its
key.
isEmpty() used to determine if the Dictionary is empty.
keys() returns an Enumeration of all keys in a Dictionary.
put() inserts a new element into the Dictionary. To
retrieve an element use the get method.
remove() removes an object from a Dictionary.
size() returns the number of elements in the Dictionary.
Chapter 9 : The Utility Package 161
The Java Hashtable class is very similar to the Dictionary class from
which it is derived. Objects are added to a hash table as key-value
pairs.
public class Hashtable extends Dictionary {
// public constructors
public Hashtable(int initialCapacity, float loadFactor);
public Hashtable(int initialCapacity);
public Hashtable();
// public instance methods
public void clear()
public Object clone()
public boolean contains(Object value)
public boolean containsKey(Object key)
public boolean containsValue(Object value)
public Enumeration elements()
public Set entrySet()
public boolean equals(Object o)
public Object get(Object key)
public int hashCode()
public boolean isEmpty()
public Enumeration keys()
public Set keySet()
public Object put(Object key, Object value)
public void putAll(Map t)
public protected void rehash()
public Object remove(Object key)
public int size()
public String toString()
public Collection values()
// protected instance methods
protected void rehash();
}
The Hashtable class provides three constructors. The first constructor
allows a hash table to be created with a specific initial capacity and
load factor. The load factor is a float value between 0.0 and 1.0 that
162 Chapter 9 : The Utility Package
identifies the percentage of hash table usage that causes the hash
table to be rehashed into a larger table.
import java.lang.System;
import java.util.Hashtable;
import java.util.Enumeration;
public class HashApp {
public static void main(String args[]){
Hashtable h = new Hashtable();
h.put("Title","Java 2");
h.put("Author","Munishwar Gulati");
h.put("Pages","240");
h.put("ISBN","81-87870");
System.out.println("Book: "+h);
Enumeration enum = h.keys();
System.out.print("keys: ");
while (enum.hasMoreElements())
System.out.print(enum.nextElement()+", ");
System.out.print("\nelements: ");
enum = h.elements();
while (enum.hasMoreElements())
Chapter 9 : The Utility Package 163
System.out.print(enum.nextElement()+", ");
System.out.println();
System.out.println("Title: "+h.get("Title"));
System.out.println("Author: "+h.get("Author"));
System.out.println("Pages: "+h.get("Pages"));
System.out.println("ISBN: "+h.get("ISBN"));
h.remove("ISBN");
System.out.println("Book: "+h);
}
}
The output of the above program is as follows:
Book: {I S BN=8 1 -87 870, Auth or =M unish war G ula ti,
Title=Java 2, Pages=240}
keys: ISBN, Author, Title, Pages, “elements: 81-87870,
Munishwar Gulati, Java 2, 240,
Title: Java 2
Author: Munishwar Gulati
Pages: 240
ISBN: 81-87870
Book: {Author=Munishwar Gulati, Title=Java 2,
Pages=240}
import java.lang.System;
import java.util.Properties;
public class SystemApp {
public static void main(String args[]) {
long time = System.currentTimeMillis();
System.out.print(“Milliseconds elapsed since January 1,
1970: “);
System.out.println(time);
Properties p=System.getProperties();
p.list(System.out);
System.exit(13);
}
}
-- listing properties --
java.specification.name=Java Platform API Specification
awt.toolkit=sun.awt.windows.WToolkit
java.version=1.2.2
java.awt.graphicsenv=sun.awt.Win32GraphicsEnvironment
user.timezone=Asia/Calcutta
java.specification.version=1.2
java.vm.vendor=Sun Microsystems Inc.
user.home=C:\WINDOWS
java.vm.specification.version=1.0
os.arch=x86
java.awt.fonts=
java.vendor.url=http://java.sun.com/
Chapter 9 : The Utility Package 165
user.region=US
file.encoding.pkg=sun.io
java.home=C:\JDK1.2.2\JRE
java.class.path=C:\jdk1.2.2\LIB\CLASSES.ZIP;c:\jdk1.2.2
line.separator=
java.ext.dirs=C:\JDK1.2.2\JRE\lib\ext
java.io.tmpdir=C:\WINDOWS\TEMP \
os.name=Windows 95
java.vendor=Sun Microsystems Inc.
java.awt.printerjob=sun.awt.windows.WPrinterJob
java.library.path=C:\JDK1.2.2\BIN;.; C:\WINDOWS\SYSTEM;
java.vm.specification.vendor=Sun Microsystems Inc.
sun.io.unicode.encoding=UnicodeLittle
file.encoding=Cp1252
java.specification.vendor=Sun Microsystems Inc.
user.language=en
user.name=M N Gulati
java.vendor.url.bug=http://java.sun.com/cgi-bin/bugreport...
java.vm.name=Classic VM
java.class.version=46.0
java.vm.specification.name=Java Virtual Machine Specification
sun.boot.library.path=C:\JDK1.2.2\JRE\bin
os.version=4.90
java.vm.version=1.2.2
java.vm.info=build JDK-1.2.2-W, native threads, sy...
java.compiler=symcjit
path.separator=;
file.separator=\
user.dir=C:\jdk1.2.2
sun.boot.class.path=C:\JDK1.2.2\JRE\lib\rt.jar;C:\JDK1.2....
Milliseconds elapsed since January 1, 1970: 998373250270
import java.lang.System;
import java.util.Vector;
import java.util.Enumeration;
public class VectorApp {
public static void main(String args[]){
Vector v = new Vector();
v.addElement("Media");
v.addElement("Books");
v.addElement("the");
v.insertElementAt("Silicon",0);
v.insertElementAt("are",3);
v.insertElementAt("Best",5);
System.out.println("Size: "+v.size());
Enumeration enum = v.elements();
while (enum.hasMoreElements())
System.out.print(enum.nextElement()+" ");
System.out.println();
v.removeElement("are");
v.insertElementAt("-",3);
System.out.println("Size: "+v.size());
for(int i=0;i<v.size();++i)
System.out.print(v.elementAt(i)+" ");
System.out.println();
}
}
The output of above program is as follows:
Size: 6
Silicon Media Books are the Best
Size: 6
Silicon Media Books - the Best
Even though they are based on the Vector class, Stack objects are
typically not accessed in a direct fashion. Instead, values are pushed
onto and popped off the top of the stack.
public class Stack extends Vector {
public Stack(); // public constructors
// public instance methods
public empty();
public peek();
public pop();
public push(Object item);
public search(Object o);
}
Chapter 9 : The Utility Package 171
empty() used to determine whether the Stack contains
items.
peek() used to peek at the top item on the Stack.
pop() retrieves the last item added to the Stack.
push() adds a new item to the Stack.
search() examines the Stack to see whether the specified
object is in the Stack.
import java.lang.System;
import java.util.Stack;
public class StackApp {
public static void main(String args[]){
Stack s = new Stack();
s.push(“one”);
s.push(“two”);
s.push(“three”);
System.out.println(“Top of stack: “+s.peek());
while (!s.empty())
System.out.println(s.pop());
}
}
The output of the following program is as follows:
Top of stack: three
three
two
one
import java.lang.System;
import java.util.Random;
public class RandomApp {
public static void main(String args[]){
Random r = new Random();
for(int i=0;i<4;++i) {
System.out.print(r.nextInt()+" ");
System.out.print( \n ); }
System.out.println();
r = new Random(123456789);
for(int i=0;i<4;++i) {
System.out.print(r.nextDouble()+" ");
System.out.print( \n ); }
System.out.println();
r.setSeed(234567890);
for(int i=0;i<4;++i) {
System.out.print(r.nextGaussian()+" ");
System.out.print( \n ); }
System.out.println();}
}
The output of the above program is as follows :
1981421951
-2108552511
-1409224881
-1652793132
0.664038103272266
0.45695178590520646
0.39050647939140426
0.8933411602003871
0.11378145160284904
0.41229626309333445
-1.5726230841498485
0.07568285309772235
174 Chapter 9 : The Utility Package
The Java I/O package, also known as java.io, gives classes support
for reading and writing data to and from different input and output
devices, including files, strings, and other data sources. The I/O
package includes classes for inputting streams of data, outputting
streams of data, working with files, and tokenizing streams of data.
Here, we will not take an exhaustive look at every class and method
contained in the I/O package. Instead, you can view this chapter as
a tutorial on how to perform basic input and output using the more
popular I/O classes.
The data going in must come out after processing. In Java, you use
output streams to output data to various output devices, such as the
screen. The Java output streams provide a variety of ways to output
data. The primary output stream classes used in Java programming
are as follows:
< OutputStream
< PrintStream
< BufferedOutputStream
< DataOutputStream
< FileOutputStream
Java also supports character output streams, which are virtually
identical to the output streams just listed except that they operate on
characters rather than bytes. The character output stream classes
are called writers instead of output streams. A corresponding writer
class implements methods similar to the output stream classes just
listed except for the DataOutputStream class.
< Writer
< PrintWriter
< BufferedWriter
< FileWriter
Java supports stream-based file input and output through the File,
FileDescriptor, FileInputStream, and FileOutputStream classes. It
supports direct- or random-access I/O using the File, FileDescriptor,
and RandomAccessFile classes besides Random-access I/O.
Chapter 10 : The I/O Package 185
1. How can you read data from a file? How can you write and
append data to a file?
2. What is the difference between reader and input streams?
3. Fill in the Blanks:
a) ______ method closes the random access file stream.
b) _______ method creates a directory.
c) _______ method flushes the print stream.
d) _______ method prints the newline character.
e) _______ method writes a byte value to the buffered
output stream.
f) _______ method determines the length in bytes of the
underlying file.
THE COORDINATES
THE GRAPHICS CLASS
THE COLORS
THE COLOR CLASS
THE FONT CLASS
THE FONTMETRICS CLASS
THE DIMENSION CLASS
THE IMAGE CLASS
Java Graphics
The Java Abstract Windowing Toolkit (AWT) provides numerous
classes that support window program development. These classes are
used to draw text and graphics, create and organize windows,
implement GUI components, handle events, perform image processing
and obtain access to the native Windows implementation. The most
important classes included in the windowing package are as follow:
< Graphical classes
< Font classes
< Dimension classes
< Components Classes
< Container Classes
< Layout manager classes
< The MediaTracker class
T h e G r a p h i c s c l a s s i s p a r t o f t h e A W T. I t ’ s c o n t a i n e d i n
java.awt.Graphics. It’s the basic class for everything you’ll draw on-
screen. Applets have associated Graphics instances, as do various
components such as buttons. Drawing methods, such as drawLine,
work on a Graphics instance, everytime you draw something, you will
call a Graphics instance:
public void paint(Graphics g) {
g.drawLine(10,10,20,20);
}
The following are few of the important methods of Graphics Class:
public abstract Graphics create()
public Graphics create(int x, int y, int width, int height)
public abstract void translate(int x, int y)
public abstract Color getColor()
public abstract void setColor(Color c)
public abstract void setPaintMode()
public abstract void setXORMode(Color c1)
public abstract Font getFont()
public abstract void setFont(Font font)
public FontMetrics getFontMetrics()
public abstract FontMetrics getFontMetrics(Font f)
public abstract void clipRect(int x, int y, int width, int height)
public abstract void copyArea(int x, int y, int width, int
height, int dx, int dy)
public abstract void drawLine(int x1, int y1, int x2, int y2)
public abstract void fillRect(int x, int y, int width, int height)
public void drawRect(int x, int y, int width, int height)
public abstract void clearRect(int x, int y, int width, int
height)
public abstract void drawRoundRect(int x, int y, int width, int
height,int arcWidth, int arcHeight)
public abstract void fillRoundRect(int x, int y, int width, int
height, int arcWidth, int arcHeight)
public void draw3DRect(int x, int y, int width, int height,
boolean raised)
public void fill3DRect(int x, int y, int width, int height,
boolean raised)
public abstract void drawOval(int x, int y, int width, int
height)
public abstract void fillOval(int x, int y, int width, int height)
public abstract void drawArc(int x, int y, int width, int height,
int startAngle, int arcAngle)
194 Chapter 11 : Java Graphics
public abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle)
public abstract void drawPolygon(int xPoints[], int yPoints[],
int nPoints)
public void drawPolygon(Polygon p)
public abstract void fillPolygon(int xPoints[], int yPoints[], int
nPoints)
public void fillPolygon(Polygon p)
public abstract void drawString(String str, int x, int y)
public void drawChars(char data[], int offset, int length, int x,
int y)
public void drawBytes(byte data[], int offset, int length, int x,
int y)
public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer)
public abstract boolean drawImage(Image img, int x, int y,
int width, int height, ImageObserver observer)
public abstract boolean drawImage(Image img, int x, int y,
Color bgcolor, ImageObserver observer)
public abstract boolean drawImage(Image img, int x, int y,
int width, int height, Color bgcolor, ImageObserver observer)
public abstract void dispose()
public void finalize()
public String toString()
Following is the description of important methods of Graphics Class.
create() creates a new graphics object.
create(int x, int y, int width, int height)
creates a new Graphics object using the specified
parameters.
translate() translates the Graphics object to the new x and y
origin coordinates.
getColor() returns the current color.
setColor() sets the current color.
setPaintMode() sets the paint mode to overwrite the destination
with the current color.
setXORMode() sets the paint mode to XOR the current colors with
the specified color.
getFont() returns the current font used for the graphics
context.
setFont() sets the graphics context’s font.
getFontMetrics() returns the font metrics for the current font.
clipRect() sets the current clipping rectangle for the Graphics
class.
Chapter 11 : Java Graphics 195
copyArea() copies a specified section of the screen to another
location.
drawLine() draws a line on the graphics context from one
point to another point specified by the input
parameters.
fillRect() fills the specified rectangular region with the
current Color.
drawRect() draws the outline of a rectangle using the current
color and the specified dimensions.
clearRect() clears a rectangle by filling it with the current
background color of the current drawing surface.
drawRoundRect() draws the outline of a rectangle with rounded
edges using the current color and the specified
coordinates.
fillRoundRect() fills a rectangle with rounded edges using the
current color and the specified coordinates.
draw3DRect() draws a highlighted 3D rectangle at a default
viewing angle.
fill3DRect() fills a highlighted 3D rectangle using the current
color and specified coordinates at a default viewing
angle.
drawOval() draws the outline of an oval shape using the
current color and the specified coordinates.
fillOval() fills an oval using the current color and the specified
coordinates.
drawArc() draws an arc outline using the current color that
is bounded by the specified input coordinates.
fillArc() fills an arc using the current color that is bounded
by the specified input coordinates.
drawPolygon() draws a polygon using the current color and the
specified coordinates.
fillPolygon() fills a polygon using the current color and the
specified coordinates.
drawString() draws a string using the current font at the specified
coordinates.
drawChars() draws a string using the current font at the specified
coordinates.
drawBytes() draws a string using the current font at the specified
coordinates.
drawImage() draws an image at a specified location within the
specified bounding rectangle.
dispose() disposes of the Graphics object.
finalize() disposes of the Graphics object once it is no longer
referenced.
196 Chapter 11 : Java Graphics
toString() returns a string representation of the Graphics
object.
The method for drawing ovals is drawOval(). You can use the drawOval()
method as shown below:
public void paint(Graphics g) {
g.drawOval(15, 20, 50, 100);
}
198 Chapter 11 : Java Graphics
In Java, you create a font for the text and select it as the font to be
used by the graphics context before actually drawing any text. The
Font object models a textual font and includes the name, point size,
and style of the font. The setFont() method selects a font into the
current graphics context.
Font f = new Font(“Arial”, Font.BOLD + Font.ITALIC, 20);
g.setFont(f);
Now you’re ready to draw some text using the font you’ve created,
sized up, and selected. You use the drawString() method, defined in
the Graphics class, for drawing text.
g.drawString(“SILICONMEDIA”,10,40);
Chapter 11 : Java Graphics 199
All the methods defined for drawing images, i.e. drawImage(), are
variations on the same theme - they all draw an image at a certain
location as defined by the parameters x and y.
The AWT’s normal color model is RGB; in this model, a color is defined
by its red, green, and blue components. Each of these three values is
an int with a value between 0 and 255. An RGB value can be stored
in an int with bits 31 through 24 being unused, bits 23 through 16
for the red value, bits 15 through 8 storing the green value, and bits
0 through 7 for the blue component of the color.
Following table shows the numeric values for the red, green, and blue
components of some basic colors.
Color Red Green Blue
White 255 255 255
Black 0 0 0
Red 255 0 0
Green 0 255 0
Blue 0 0 255
Yellow 255 255 0
Purple 255 0 255
The AWT package also provides you another color model - the HSB
model. In this model, colors are represented as hue, saturation, and
brightness.
Hue Th e v a l u e r un s f r o m 0 t o 1 / 4 P I , w i t h 0
corresponding to red and 1/4 PI to violet.
Saturation Determines how far from gray a color is. The value
runs from 0 to 1. A value of 0 corresponds to a gray
scale. By varying this parameter, you can fade out
a color picture.
Brightness Determines how bright a given color is. The value
runs from 0 to 1. A brightness of 0 gives you black.
A value of 1 gives you the brightest color of the
given hue and saturation possible.
Using HSB color model, you can convert a color image to black and
white by just setting the saturation of all the pixels to 0. If you change
hue from 0 to 1/4 PI, you can get a countimous spectrum of colour.
Chapter 11 : Java Graphics 201
The class hierarchy for the Color class derives from the class
java.awt.Object. Following are the important methods of Color class:
public final static Color white
public final static Color lightGray
public final static Color gray
public final static Color darkGray
public final static Color black
public final static Color red
public final static Color pink
public final static Color orange
public final static Color yellow
public final static Color green
public final static Color magenta
public final static Color cyan
public final static Color blue
public Color(int r, int g, int b)
public Color(int rgb)
public Color(float r, float g, float b)
public int getRed()
public int getGreen()
public int getBlue()
public int getRGB()
public Color brighter()
public Color darker()
public int hashCode()
public boolean equals(Object obj)
public String toString()
public static Color getColor(String nm)
public static Color getColor(String nm, Color v)
public static Color getColor(String nm, int v)
public static int HSBtoRGB(float hue, float saturation,
float brightness)
public static float[] RGBtoHSB(int r, int g, int b, float[]
hsbvals)
public static Color getHSBColor(float h, float s, float b)
The public final static Color <colorname> represent the Static value
representing the <colorname>. The color class also provides three
constructors that allow a color to be constructed from its red, green,
and blue (RGB) color components. Following are the descripion of
various methods of Color class.
getRed() returns the red component of this Color.
getGreen() method returns the green component of this Color.
202 Chapter 11 : Java Graphics
getBlue() returns the blue component of this Color.
getRGB() returns the RGB value of this Color.
brighter() brightens this Color by approximately 1.5 times
brighter than the current color by modifying the
RGB color value.
darker() Returns a color about 70 percent as bright as the
original color.
hashCode() returns this Color’s hash code.
equals() compares the Object parameter with this Color
object.
toString() returns a string representation of the Color class.
getColor() returns the specified color property based on the
name that is passed in.
HSBtoRGB() Produces an integer containing the RGB values of
a color-with blue in the lowest byte, green in the
second byte, and red in the third byte-when given
the three HSB values.
RGBtoHSB() Returns an array of floats containing the h, s, and
b values of the equivalent color to the specified r,
g, and b values.
getHSBColor() returns a Color object representing the RGB value
of the input HSB parameters.
Consider the following program, which displays the variations of
color from red to green to blue with changing hue. Here, we have
taken a variation in hue and using for loop, filled the rectangle with
changing hue.
import java.awt.*;
import java.applet.Applet;
public class colourvar extends Applet{
int count;
int rwidth;
public void init()
{
}
public void paint(Graphics g)
{
float hu,sa,br;
int xpt,ypt,i;
Color temp_color;
int blockwidth,blockheight;
float incr;
count = 256;
incr = (float)(0.25*Math.PI/count);
Chapter 11 : Java Graphics 203
// Hue change form 0 to 90 and we are dividing it into
// 256 parts to fill 256 blocks
rwidth = 1024;
blockwidth =(int)(rwidth/count); /* width of rectangle*/
blockheight = 150;
sa = (float)1.0; /* highest saturation*/
br = (float)1.0; /* max brightness*/
ypt = 10;
xpt = 0;
for(i=0;i<count;i++) {
hu = incr*i;
temp_color = Color.getHSBColor(hu,sa,br);
/* new colour*/
g.setColor(temp_color); /* setting new color*/
xpt+= blockwidth;
// value x changing which indicated that rectangle x point
//is moving to right by width of rectangle
g.fillRect(xpt ,ypt ,blockwidth,blockheight);
/* drawing filled rectangle with new color*/
}
}
}
The output here is printed in black and white, but on your coloured
screen, you will get the continuous colours from red to green to blue.
The class hierarchy for the Font class derives from the class
java.lang.Object. The Font class implements a system-independent
set of fonts that control text display. Java font names are mapped to
system-supported fonts. The Courier, Dialog, DialogInput, Helvetica,
TimesRoman, and ZapfDingbats fonts are the system-independent
font names provided by Java.
public class Font {
204 Chapter 11 : Java Graphics
public static final int PLAIN
public static final int BOLD
public static final int ITALIC
public Font(String name, int style, int size)
public String getFamily()
public String getName()
public int getStyle()
public int getSize()
public boolean isPlain()
public boolean isBold()
public boolean isItalic()
public static Font getFont(String nm)
public static Font getFont(String nm, Font font)
public int hashCode()
public boolean equals(Object obj)
public String toString()
}
getFamily() returns the font family that this font belongs to.
getName() returns the name of the Font object.
getStyle() returns the style of the Font object.
getSize() returns the size of the Font object.
isPlain() returns the plain style state of the Font.
isBold() returns the bold style state of the Font.
isItalic() returns the italic style state of the Font.
getFont() returns a Font based on the system properties list
and the name passed in.
hashCode() returns a hash code for this font.
equals() compares an object with the Font object.
toString() returns a string representation of the Font.
You’ll find that you often need to precisely position text in an applet.
To precisely position the text, you must be aware of certaing basic
font measurement terms:
Height() The height of the tallest character in a font.
Baseline() The bottom of all characters are positioned on this
imaginary line.
Ascent() Measures the height of the character above the
baseline.
Descent() Measures the height (or, more appropriately, depth)
of the character below the baseline.
Chapter 11 : Java Graphics 205
The FontMetrics class provides an easy way to find out how much
space text drawn with a given instance of Font will be. The class
h ie ra r chy f or th e F on tM et r i cs c l a ss d er ive s fr om t h e c l a s s
java.lang.Object. Following are the important methods :
public Font getFont()
public int getLeading()
public int getAscent()
public int getDescent()
public int getHeight()
public int getMaxAscent()
public int getMaxDescent()
public int getMaxDescent()
public int getMaxAdvance()
public int charWidth(int ch)
public int charWidth(char ch)
public int stringWidth(String str)
public int charsWidth(char data[], int off, int len)
public int bytesWidth(byte data[], int off, int len)
public int[] getWidths()
public String toString()
getFont() returns the font that FontMetrics refers to.
getLeading() gets the line spacing of the font.
getAscent() gets the ascent value for a Font.
getDescent() gets the descent value for a Font.
getHeight() gets the height of a line of text using the current
Font.
getMaxAscent() returns the maximum value of a font’s ascent.
getMaxDescent() returns the maximum value of a font’s descent.
getMaxDecent() calls the getMaxDescent() method.
getMaxAdvance() gets the maximum amount for a character’s
advance value.
charWidth() returns the width of a particular character for the
current font.
stringWidth() returns the width of a specified string using the
current font.
charsWidth() returns the width of a specified string of characters
using the current font.
bytesWidth() returns the width of a specified array of bytes.
getWidths() gets the advance widths of the first 256 characters
of the font.
Consider the following example, which uses various Fontmetrics
class methods.
import java.awt.*;
206 Chapter 11 : Java Graphics
public class fontm3 extends java.applet.Applet{
Font f1=new Font("Arial",Font.BOLD,20);
String message;
FontMetrics f1_met;
FontMetrics a_font;
int m_width, f1_height,f1_ascent, f1_descent;
int y;
public void paint(Graphics g){
g.setFont(f1);
g.setColor(Color.blue);
f1_met = g.getFontMetrics();
message = "SILICONMEDIA";
m_width = f1_met.stringWidth(message);
f1_height = f1_met.getHeight();
f1_ascent = f1_met.getAscent();
f1_descent = f1_met.getDescent();
y = 30;
g.drawString(message,10,y);
y += f1_height + 1;
g.drawString("Width of message"+ m_width,10,y);
y += f1_height + 1;
g.drawString("Height of font"+ f1_height,10,y);
y += f1_height + 1;
g.drawString("Ascent of message"+ f1_ascent,10,y);
y += f1_height + 1;
g.drawString("Descentof message"+ f1_descent,10,y);
}
}
The class hierarchy for the Image class derives from the class
java.lang.Object. An Image class is actually an abstract class. You
must provide a platform-specific implementation to use it.
public abstract class Image {
public abstract int getWidth(ImageObserver observer);
public abstract int getHeight(ImageObserver observer);
public abstract ImageProducer getSource();
public abstract Graphics getGraphics();
public abstract Object getProperty(String name,
ImageObserver observer);
Image getScaledInstance(int width, int height, int hints);
public static final Object UndefinedProperty;
public abstract void flush();
}
getWidth() returns the width of the Image.
GetHeight() returns the height of the Image.
GetSource() returns the ImageProducer interface responsible
for producing the Image’s pixels.
208 Chapter 11 : Java Graphics
The Component class is the superclass of the set of AWT classes that
implement graphical user interface controls. These components
include windows, dialog boxes, buttons, labels, text fields, and other
common GUI components. The Component class provides a common
set of methods that are used by all these subclasses. The class
h i e r a r ch y f or t h e C o m p o n e n t cl a s s d e r i v e s f r o m t h e c l a s s
java.lang.Object. Following are the various important methods of
Component Class:
public Container getParent()
public Toolkit getToolkit()
public boolean isValid()
public boolean isVisible()
public boolean isShowing()
public boolean isEnabled()
public Color getForeground()
public synchronized void setForeground(Color )
public Color getBackground()
public synchronized void setBackground(Color )
public Font getFont()
public synchronized void setFont(Font )
public synchronized ColorModel getColorModel()
public void setsize(int , int )
public void setsize(Dimension )
public synchronized void setbounds(int , int , int
, int )
public void validate()
public void invalidate()
public Graphics getGraphics()
Chapter 12 : Interactive Interface Elements 211
public FontMetrics getFontMetrics(Font )
public void paint(Graphics )
public void update(Graphics )
public void paintAll(Graphics )
public void repaint()
public void repaint(long )
public void repaint(int , int , int , int )
public void repaint(long , int , int , int , int
)
public void print(Graphics )
public void printAll(Graphics )
public boolean imageUpdate(Image , int ,
int , int , int , int )
public Image createImage(ImageProducer )
public Image createImage(int , int
public boolean prepareImage(Image ,
ImageObserver )
public boolean prepareImage(Image , int ,
int , ImageObserver )
public int checkImage(Image , ImageObserver
)
public int checkImage(Image , int , int
, ImageObserver )
public void addNotify()
public synchronized void removeNotify()
public void requestFocus()
public String toString()
public void list()
public void list(PrintStream )
public void list(PrintStream , int )
This class contains more than 100 methods, few of which are
explained below:
getParent() returns this component’s parent (a Container
class).
GetPeer() returns this component’s peer (a ComponentPeer
interface).
getToolkit() returns the toolkit of this component. The toolkit
creates the peer for the component.
isValid() determines whether this component is valid.
isVisible() determines whether this component is visible.
isShowing() determines whether this component is shown on
the screen.
isEnabled() determines whether this component is currently
enabled.
212 Chapter 12 : Interactive Interface Elements
getlocation() returns the location of this component in its
parent’s coordinate space.
size() returns the current size of the component.
bounds() returns the bounding rectangle of the component.
enable() enables a component.
disable() disables a component.
show() shows the component.
hide() hides the component from view.
getForeground() returns the foreground color of the component.
setForeground() sets the foreground color of the component.
getBackground() returns the background color of the component.
setBackground() sets the background color of the component.
getFont() returns the font of the component.
setFont() sets the font of the component.
getColorModel() gets the color model that displays this component
on an output device.
move() moves a component to a new location within its
parent’s coordinate space.
setsize() resizes the component to the specified width and
height.
setBounds() completely changes the bounding box of the
component by changing its size and location.
preferredSize() returns the preferred size of the component.
getminimumSize() returns the minimum size of the component.
layout() called when the component needs to be laid out.
validate() validates a component by calling its layout()
method.
invalidate() invalidates a component, forcing the component
and all parents above it to be laid out.
getGraphics() returns a Graphics context for the component.
getFontMetrics() returns the current FontMetrics for a specified
font.
paint() paints the component on the screen using the
Graphics context parameter.
update() repaints the component in response to a call to the
repaint() method.
paintAll() paints the component along with all its
subcomponents.
repaint() forces a component to repaint itself.
print() prints the component using the Graphics context.
printAll() prints the component and all of its subcomponents
using the Graphics context.
Chapter 12 : Interactive Interface Elements 213
imageUpdate() repaints the component when the specified image
has changed.
createImage() creates an Image using the specified
ImageProducer.
prepareImage() prepares an Image for rendering on this component.
checkImage() checks the status of the construction of the Image
to be rendered.
inside() determines whether the x and y coordinates are
within the bounding rectangle of the component.
getComponentAt() returns the Component at the specified x and y
coordinates.
deliverEvent() delivers an event to the component or one of its
subcomponents.
postEvent() posts an event to the component resulting in a call
to handleEvent().
handleEvent() handles individual events by the component.
mouseDown() called if the mouse is down.
mouseDrag() called if the mouse is dragged.
mouseUp() called when the mouse button is released.
mouseMove() called if the mouse is moved.
mouseEnter() called if the mouse enters the component.
mouseExit() called if the mouse exits the component.
keyDown() called when a key is pressed.
keyUp() called when a key is released.
addNotify() notifies a component to create a peer object.
removeNotify() notifies a component to destroy the peer object.
gotFocus() called when the component receives the input
focus.
processFocusEvent() called when the component loses the input focus.
requestFocus() requests the current input focus.
nextFocus() switches the focus to the next component.
toString() returns a string representation of the Component
class.
list() prints a listing of the component to the print
stream.
The AWT containers contain classes that can contain other elements.
Windows, panels, dialog boxes, frames, and applets are all containers.
Whenever you want to display a component such as a button or pop-
up menu, you’ll use a container to hold it.
214 Chapter 12 : Interactive Interface Elements
The Container class has a number of methods that make it easy to add
and remove components as well as to control the relative positioning
and layout of those components.
public abstract class Container extends Component {
public synchronized Component getComponent(int n)
throws ArrayIndexOutOfBoundsException
public synchronized Component[] getComponents()
public Component add(Component comp)
public synchronized Component add(Component comp,
int pos)
public synchronized Component add(String name,
Component comp)
public synchronized void remove(Component comp)
public synchronized void removeAll()
public LayoutManager getLayout()
public void setLayout(LayoutManager mgr)
public synchronized void validate()
public void paintComponents(Graphics g)
public void printComponents(Graphics g)
public synchronized void addNotify()
public synchronized void removeNotify()
public void list(PrintStream out, int indent)
}
getComponent() returns the component at the specified index.
getComponents() returns an array of Component objects contained
within the Container.
add() adds a Component to the container at the end of
the container’s array of components.
remove() r em oves t h e s p e ci f i e d c o m p o n e n t f r o m t h e
Container’s list.
removeAll() removes all components within Container.
getLayout() returns this Container’s LayoutManager.
setLayout() sets the current LayoutManager of the Container.
preferredSize() returns the preferred size of this Container.
minimumSize() returns the minimum size of this Container.
paintComponents()
paints each of the components within the container.
printComponents()
prints each of the components within the container.
addNotify() notifies the container to create a peer interface.
removeNotify() notifies the container to remove its peer.
list() prints a list for each component within the
container to the specified output stream at the
specified indentation.
Chapter 12 : Interactive Interface Elements 215
The addNotify() method of sets the peer of the Canvas using the
function getToolkit().createCanvas(). Using peer interfaces allows you
to change the user interface of the canvas without changing its
functionality.
Labels are text items that appear as static text on the screen. They are
similar to drawString, but are often used to identify text fields. By
using a label instead of drawString, you can use the Layout Managers
to control text placement in a platform- and monitor-independent
manner. Following are the various constructors and methods
new Label(String label) Produces a label with the specified
string.
new Label(String label,int pos) Produces a label with the string
aligned according to the second
value, which should be one of the
three constants Label.CENTER,
Label.LEFT, or Label.RIGHT.
String getText() Returns the label string.
setText(String newlabel) Changes the label text.
Consider the following applet code which adds three labels to the
applet:
import java.awt.*;
import java.applet.Applet;
public class label extends Applet{
Label Head;
Label labels[];
public void init(){
int i;
labels = new Label[2];
Head= new Label("ORDER FORM", Label.CENTER);
216 Chapter 12 : Interactive Interface Elements
Head.setBackground(Color.blue);
Head.setForeground(Color.white);
Font f1= new Font("Arial",Font.BOLD,20);
Head.setFont(f1);
add(Head);
labels[0] = new Label("Name". Label.LEFT );
f1= new Font("Arial",Font.BOLD,15);
labels[0].setFont(f1);
labels[1] = new Label("Address", Label.LEFT);
labels[1].setFont(f1);
for(i=0;i<2;i++) {
add(labels[i]);
}
}
}
The TextArea class implements scrollable text entry objects that span
multiple lines and columns. It provides four constructors that allow
the number of rows and columns and the default text display to be
specified.
new TextArea() Defines a default empty TextArea.
new TextArea(int rows, int columns)
D ef in es a n em pt y TextA r ea wi th th e
specified number of rows and columns.
new TextArea(String the_contents)
Defines a TextArea that contains the
specified string.
new TextArea(String the_contents, int rows, int columns)
Chapter 12 : Interactive Interface Elements 219
Defines a TextArea containing the specified
string and with a set number of rows and
columns.
appendText(String new_text)
Appends the specified string to the current
contents of the TextArea.
int, getColumns() Returns the current width of the TextArea
in columns.
int, getRows() Returns the current number of rows in a
TextArea.
insertText(String the_text, int where_to_add)
Inserts the specified string at the specified
location.
replaceText(String new_text, int start, int stop)
Takes the text between start and stop,
inclusive, and replaces it with the specified
string.
Consider the following code for creating text area.
import java.awt.*;
import java.applet.Applet;
public class text1 extends Applet{
Label Head;
GridLayout g1;
TextArea texta;
public void init(){
int i;
g1 = new GridLayout(1,2);
setLayout(g1);
Head= new Label("Enter your Description");
Font f1= new Font("Arial",Font.PLAIN,15);
Head.setFont(f1);
add(Head);
texta = new TextArea(5, 20);
add(texta)
}
}
The output is shown in Fig . 12.3
Java buttons are just like the buttons in every other GUI. They are
text surrounded by a shape, and they generate an ACTION_EVENT
event-the argument is a button’s label-after the user clicks them.
220 Chapter 12 : Interactive Interface Elements
Radio buttons are created using the Checkbox class. AWT creates a
radio button group by associating a CheckboxGroup instance with all
the checkboxes in the group. A CheckboxGroup can be assigned with
the Checkbox constructor or using the setCheckboxGroup() method.
Only one object in the checkbox group is allowed to be set at any given
time.
Scrolling lists display multiple lines of text, and each line corresponds
to a selection item. Scroll bars are displayed if the text is larger than
the available space. The user can select one or more of the lines. Your
program can read the user’s selections. It is different from Choicelist
or drop-down menu, because it provides the capability to support
multiple menu selections, to specify the size of the list window, and
to dynamically update the list during program execution.
The AWT not only lets you specify the absolute location of components,
but also gives you Layout Managers that let you define the relative
placement of components that will look the same on a wide spectrum
of display devices.
The BorderLayout divides the container into five parts; four form the
four borders of the container and the fifth is the center. You can add
one component to each of these five areas. Because the component
can be a panel, you can add more than one interface element, such
as a button, to each of the five areas. The following are the various
important methods
addLayoutComponent() Adds the specified component to
the layout, using the specified
constraint object.
getHgap() Returns the horizontal gap between
components.
getLayoutAlignmentX() Returns the alignment along the x
axis.
getLayoutAlignmentY() Returns the alignment along the y
axis.
getVgap() Returns the vertical gap between
components.
invalidateLayout() Invalidates the layout, indicating
that if the layout manager has
cached information it should be
discarded.
layoutContainer() Lays out the container argument
using this border layout.
maximumLayoutSize() Returns the maximum dimensions
for this layout given the components
in the specified target container.
minimumLayoutSize() Determines the minimum size of
the target container using this
layout manager.
preferredLayoutSize() Determines the preferred size of
the target container using this
layout m ana ge r, based on th e
components in the container.
removeLayoutComponent() Removes the specified component
from this border layout.
Chapter 12 : Interactive Interface Elements 229
setHgap() Sets the horizontal gap between
components.
setVgap() S e t s th e ve r t ica l g a p b e t we e n
components.
Consider the following example:
import java.awt.*;
import java.applet.Applet;
public class buttonDir extends Applet {
public void init() {
setLayout(new BorderLayout());
add(new Button("TOP"), BorderLayout.NORTH);
add(new Button("BOTTOM"), BorderLayout.SOUTH);
add(new Button("LEFT"), BorderLayout.EAST);
add(new Button("RIGHT"), BorderLayout.WEST);
add(new Button("CENTER"), BorderLayout.CENTER);
}
}
This is the default Layout Manager that every panel uses unless you
use the setLayout method to change it. It keeps adding components
to the right of the preceding one until it runs out of space; then it
starts with the next row. Following are the various methods different
from the BorderLayout:
getAlignment() Gets the alignment for this layout.
setAlignment(int align) Sets the alignment for this layout.
Consider the following example:
import java.awt.*;
import java.applet.Applet;
public class myButtons extends Applet {
Button button1, button2, button3;
public void init() {
button1 = new Button("Ok");
button2 = new Button("Open");
button3 = new Button("Close");
add(button1);
add(button2);
add(button3);
}
}
Using this layout you can place your object in CENTER, EAST,
NORTH, NORTHEAST, NORTHWEST, SOUTH, SOUTHEAST,
SOUTHWEST and WEST direction.
Following is the list of interfaces that can be used for various purpose
ActionListener The listener interface for receiving action
events.
AdjustmentListener The listener interface for receiving
adjustment events.
AWTEventListener The listener interface for receiving
notification of events dispatched to objects
t h a t a r e in s t a n ce s o f C om p o n e n t o r
MenuComponent or subclasses.
ComponentListener The listener interface for receiving
component events.
ContainerListener The listener interface for receiving
container events.
FocusListener The listener interface for receiving keyboard
focus events on a component.
HierarchyBoundsListener The listener interface for receiving ancestor
moved and resized events.
HierarchyListener The listener interface for receiving
hierarchy changed events.
InputMethodListener The listener interface for receiving input
method events.
ItemListener The listener interface for receiving item
events.
KeyListener The listener interface for receiving keyboard
events (keystrokes).
MouseListener The listener interface for receiving
interesting mouse events (press, release,
click, enter, and exit) on a component.
MouseMotionListener The listener interface for receiving mouse
motion events on a component.
TextListener The listener interface for receiving text
events.
WindowListener The listener interface for receiving window
events.
The handleEvent method serves as the default handler for all events,
and it has the option of responding to an event or letting it pass
through. If handleEvent doesn’t handle an event, it returns false, in
which case the parent object’s handleEvent method is called. This
process continues until an event is handled or the top of the object
tree is reached.
All types of Events that can occur in the system are defined in Event
Class. The Event class is used primarily by the handleEvent method,
which is defined as:
public boolean handleEvent(Event evt)
Once handleEvent method gets the information about the event
occured, it calls a more specific event-handler method to deal with the
event. For example, if a mouse is pressed, the Event Object’s id
memory variable is set to MOUSE_DOWN, which is a constant defining
the Mouse down event.
The Event class is a critical component of the Java AWT. Event objects
are constructed and passed into methods such as postEvent when an
event occurs.
The Event class defines a set of constants, which specify the different
types of possible events. The partial list of constants is given below,
which is quite self-explanatiory:
static int KEY_ACTION
static int KEY_ACTION_RELEASE
static int KEY_PRESS
static int KEY_RELEASE
static int LEFT
static int LIST_DESELECT
static int LIST_SELECT
Chapter 12 : Interactive Interface Elements 235
static int LOAD_FILE
static int LOST_FOCUS
static int META_MASK
static int MOUSE_DOWN
static int MOUSE_DRAG
static int MOUSE_ENTER
static int MOUSE_EXIT
static int MOUSE_MOVE
static int MOUSE_UP
static int NUM_LOCK
static int PAUSE
static int PGDN
static int PGUP
static int PRINT_SCREEN
static int RIGHT
static int SAVE_FILE
static int SCROLL_ABSOLUTE
static int SCROLL_BEGIN
static int SCROLL_END
static int SCROLL_LINE_DOWN
static int SCROLL_LINE_UP
static int SCROLL_LOCK
static int SCROLL_PAGE_DOWN
static int SCROLL_PAGE_UP
static int SHIFT_MASK
static int TAB
Object target
static int UP
long when
static int WINDOW_DEICONIFY
static int WINDOW_DESTROY
static int WINDOW_EXPOSE
static int WINDOW_ICONIFY
static int WINDOW_MOVED
int x
int y
The id field is used by the AWT to distinguish between event types.
The id field indicates what type of event it is and which other Event
variables are relevant for the event.
Both Java and C++ uses main() function as the entry point for the
program. But the difference in the two function is that while C++
function takes two parameters : int argc - to identify the number of
arguments being passed and argv[][] - the character array that
contains the program arguments, the Java main() function only takes
takes a single args[] parameter of the String class. The number of
arguments passed via the main() method invocation is determined by
args.length.