Вы находитесь на странице: 1из 272

Second Edition

Wintech Computers
Table Of Contents

Training Cycle 1

1. Introduction to Java Page No.


1.1 Internet Programming Languages l

1.2 Scripting Languages 2


1.3 SMALL TALK, VB SCRIPT, JavaScript & VRML 2
1.4 Drawbacks of Internet Programming languages 3

1.5 Overview of Java 3

1.6 Features of Java 4

1.7 Java Architecture 4


1.8 Java Development Environment 6

1.9 Paradigm of Java 6

1.10 Java and C++- Some Differences 7

Training Cycle 2

2. Fundamentals of Java
2.1 Introduction 8

2.2 Setting Up Your Computer 8

2.3 Code Comments 9

2.4 Variables and Data Types 10

2.5 Expressions 12

2.6 Control Flow Statements 12

Training Cycle 3

3. Object-Oriented Programming Concepts


3.1 What is an Object ? 17

3.2 What are Messages ? 19

3.3 What are Classes ? 20

3.4 What is Inheritance ? 21

Training Cycle 4

4. Objects and Classes In Java


4.1 Life Cycle of Classes 23
4.2 A Brief Introduction to Classes 23
4.3 Life Cycle of an Object 27
4.4 Creating Classes 33
4.5 Implementing Methods 41

4.6 Packages 57

4.7 Interfaces 57
Training Cycle 5

5. Arrays and Strings


5.1 Arrays 60
5.2 Strings 62

Training Cycle 6

6. Exceptions
6.1 Exception Handling 66
6.2 Catching and Handling Exceptions 68
63 try 68
6.4 The Catch Block(s) 69
6.5 The finally Block 70

Training Cycle 7

7. Multithreading
7 1 Multitasking 74
7.2 Multithreading 74
7.3 Thread Properties 77
74 Thread Priorities 80
7.5 Synchronization 82
7.6 Deadlocks 83

Training Cycle 8

8. Input and Output


8 1 Introduction 86
8.2 The InputStream Class 86
8.3 Using The standard Input/Output Objects 87
8.4 The Reader Class 88
8.5 The OutputStream Class 90
8.6 The Writer Class 91
8.7 PrintWnter Class 92
88 Print Streams 93
8.9 Data Streams 93
8 lOFileClass 95
8.11 Random Access File Streams 96
8.12Buffernu' 98
Training
Cycle: 1
Wintech Computers JAVA 2

1. Introduction to Java

1.1 Internet Programming Languages


Internet programming was given a boost with the advent ofWWW to satisfy the demand for
Internet based applications which grew manifold. These applications required a language for their
development. These languages were required to provide a dynamic and an interactive content to
static Web Pages. The Client/Server model was the obvious choice for Internet applications.
A common Interface between the client and server ends was CGI (Common Gateway Interface).
Many scripting languages such as PERL, TCL, etc. evolved in addition to standard programming
languages such as C and C++

1.1.1 Common Gateway Interface (C G I)


It is a standard that describes how HTTP compatible WWW servers access external programs so
that the data is returned to the user in a form of an automatically generated web page.

CGI programs called scripts, come into play when a web user fills out a form on a server which
generates output which is handled by the scripts. These scripts bring other programs into play as
necessary.

1. Client sends a request to Server


2. Server interacts with CGI
3. CGI response is sent to Server
4. The Serverin turn sendsthe response in the standard format to browser.

ACGI application implements a client server paradigm with server heavy and client light that is,
most of the process is in the server side. A CGI can be written in any language such as C, C++,
VB or Shell Scripts of Unix. Scripting languages such as PERL 4, TCL are also extensively used
to.write CGI applications.

1.1.2 Forms
One of the prominent uses of CGI is to process forms. Forms are subset of HTML that allows
user to apply information. Forms interfaces make Web browsing an interactive process.
1.1.3 Gateways
Web Gateways are programs or scripts used to access information that is made readable to a
client, Example, data retrieved from a database. Gateways are used to access services not directly
accessible through Web. Notethat these gateways are not the network gateways.

Training Cycle 1
Wintech Computers JAVA 2
1.2 Scripting Languages

A scripting language is simple programming language designed to enable computer users to Write
useful programs quickly. They enable you to automate certain tasks.
Examples: PERL, TCL, VB Script, Java Script.

1.2.1 Practical Extraction and Reporting Languagef P.E.R.L.)


Most widely used language for CGI programming. Is described as acompiled scripting language.
Alternative to C but combines elements of C with Unix scripting (Sh, AWK) and text
manipulation routine. PERL, scripts are used for serve r side applications only.

1.2.2 Tool Command Language (TCL)


Full fledged Web based applications can be build that are server heavy and client light, It is a
scripting language toolkit with which quick and easy Xwindows GUI's can be build for Unix
platforms. Slow to execute.

ActiveX technology of Microsoft is also used to write programs for Internet, mainly for client
side applications.

1.3 SMALL TALK. VB SCRIPT. Java Script & VRML

1.3.1 VB Script
No GUI building capacity but relies on HTML from Microsoft provides access to
applications via OLE. These scripts are used for client side forms and are
embedded in HTML.

1.3.2 Small Talk:


Dynamic, fully OOP language. Isolates from rest of the application development and
doesn't integrate with these.

1.3.3 Virtual Reality Modeling Language (VRML):


It is used for animation and describing 3D objects. No competitor in this area and is
bound to become popular.

1.3.4 Java Script:


Developed by Netscape. Most of the present day browsers can execute programs in Java Script.
Has no GUI features and relies on HTML. Scripts written in Java script can be embedded in
HTML Pages. Has become a popular scripting language. Mainly used for client side forms based
on HTML.

Training Cycle 1
JAVA 2
Wintech Computers

1.4 Drawbacks of Internet Programming languages

Any language for the Internet should have the following features:
1 Portable, Robust and Safe.
2. High performance with good graphics capabilities.
3. Uniform behavior across all platforms.
4. Ability to deal with Web tools, formats and protocols.
All the above-mentioned features are not present in the above-mentioned languages. Hence the
language Java gives aboast to Internet Programming. In the next section we will study what is
Java and features of Java .

1.5 Overview of Java

1.5.1 History of Java


Sun Micro Systems began aproject for software to run on TV and VCR sets -i.e., Interactive TV
&VCR Ateam ofSoftware Engineers led by James Gosling and others laid specifications for
this project in January 1991. By September 1992 the basic system was drafted. These interactive
sets were called Set-top boxes. The hardware was called 7; 0/S was named Green and the
programming language was called OAK.
Later the language was renamed to Java , as OAK was already registered. Meanwhile in 1993,
the development ofMOSAIC (Browser) led to the widespread use of WWW. Gosling realized by
chance that Java was well suited for the Web because it was secure and most importantly
architecture neutral. In September 1994 a browser called HotJava was developed. Later Java
replaced the original compiler in C. HotJava was the first commercial product to be developed
entirely in Java . On May 23" 1995 Java was formally released.
Seeing the immense potential software companies began to license the technology to develop
their products in Java . The Java Development Kit 1.0 was released on Jan23" 1996. Sun's game
plan is to popularize Java . Java isfreely distributed on the Internet.
1.5.2 Overview of Java
Java is loosely based on the C++ syntax, and meant to be Objective oriented. But however Java
is interpreted, for that matter any application can have JVM built-in. JVM verifies these byte
codes when down loaded by the broker for integrity. JVM s are available for almost al) operating
systems now. JVM converts these byte codes into machine specific instructions at runtime.
Though the concept of an intermediate software level for addressing portability is not new. Java
's success is due to its Object Orientation, security features, being a full-fledged and high
performing Internet programming language and having rich features such as multithreading and
dynamic loading capabilities. Java got its first break through when Internet's most popular
browser vendor Netscape Inc. announced its support. One by one all major software/hardware
vendors followed suit, as Sun expected. Though Microsoft was ambivalent initially, subsequently
it also announced its support. Now, there is no stopping of Java . It is pervading all conceivable
software applications for the standards to be supported by yesterday's, today's and tomorrow's
software for the Web.

Training Cycle 1 3
Wintech Computers JAVA 2
1.6 Features of Java
Java is out and out an OOP language. Unlike C++, it enforces the programmers to adhere to
OOP

Java is portable and architecture neutral


Write once and run anywhere is the slogan for Java That is Java programs once compiled can
be executed on any machine that is Java enabled.

Java is distributed

Java is for the Internet, which is distributed in its approach. Of all the transformations that Java
promises to catalyze, none is so pivotal to the InfoTech industry as this distributed nature of Java
Its aim is to phase shift the way computing is being done today. The software package that has
just-in-case features crammed in will become redundant.

Just as Java supports distributed and tiny specific applications called applets which spawns the
Web of computers, the post Java user simply would download an applet of his choice and have it
on his system for the duration till the applet completes it's job it is expected to do.

Java has a set of classes grouped together for explicit support for network programming. The
language supports creation and addressing of network servers, clients and the works, which form
a part of the distributed computed model

Robust

Java based applications/ applets are well behaved and will not let system crash. They also
behave uniformly across different platforms

Security
Java environment protects against intentional and unintentional attacks such as worms and
viruses

Dynamic
As Java is object oriented, it allows for runtime extensibility.

Java is high performing


It supports multi threading just-in-time compiling and native code usage.

Multithreaded
Java supports threads. Therefore different parts of an application can be in execution at the same
time Java can be used to build stand-alone applications. Java is simple compared to C++ or
VC++.

1.7 Java Architecture

Java architecture provides a portable, robust, high performing environment for development.
Java provides portability by compiling the bytecodes for the Java Virtual Machine, which is
then interpreted on each platform by the run-time environment. Java also provides stringent
compile and run-time checking, and automatic memory management in order to ensure solid

Training Cycle 1 4
Wintech Computers JAVA 2

code. Strong security features protect system against ill-behaved programs. Java is a dynamic
system, able to load code when needed from a machine in the same room or across the planet.

1.7.1 Compilation of code


When you compile the code, the Java compiler cfeates machine code (called bytecodes) for
hypothetical machine called Java Virtual Machine. JVM is supposed to execute the bytecodes.
The JVM is created for overcoming the issue of portability. The code is written and compiled for
one machine and interpreted on all other machines. This machine is called Java Virtual Machine.

This bytecodes is then run through an interpreter on the actual hardware, which converts this
bytecodes into machine code required for that particular hardware, and executes it. Bycompiling
the program to the JVM, all code is guaranteed to run on any computer that has the interpreter
ported to it.

During run-time the Java interpreter tricks the bytecodes file into thinking that it is running on a
Java Virtual Machine. In reality this could be an Intel Pentium running Windows 95 or Sun
SPARC workstation running Solaris or Apple Macintosh running System 7 and all could receive
code from any computer through Internet and run the Applets.

Let's see in detail how this happens. The responsibility of running the code compiled for JVM
falls to the interpreter. The interpreter process can be divided into three steps: verification of the
code, loading, and execution. The bytecodes verifier ensures that the code sticks to Java standard
and does not violate system integrity. The bytecodes verifier checks that the code does not have
forged pointers, access restriction violations, object mismatching, operand stack over or
underflows incorrect bytecode parameters illegal data conversion.

After this, the code is loaded by the class loader. This section of interpreter loads the Java file
that is reference and any inherited or referenced classes that code will need. After the loading is
complete, all the code is sent though to the run-time system for execution on hardware. Execution
can happen in two ways:

1. The interpreter can compile native code at run-time, then run this native code at full
speed. Here the conversion overhead is performed at the beginning of execution.
2. The interpreter will convert the code to the platform specific configuration a piece at
a time. Here the conversion overhead is performed as a background thread during
execution.

Note that the Java compiler is machine dependent and so is the interpreter. It is only the
bytecodes that are machine independent. The bytecodes can be potted to any machine and can be
executed if that machine has a Java interpreter. All current versions of web browsers have in
built Java interpreters. In fact almost all-latest versions of software products are Java aware i.e.
they have a Java interpreter in built into them. Although Java programs can be easily ported
across the Internet, it need not always be the case. You can develop standalone Java based
applications independent of the Net.

Training Cycle 1
Wintech Computers JAVA 2

1.8 Java Development Environment

To code, edit, debug and test the Java programs, one needs to have a Java development
environment. At the minimum this will consist of a Java compiler, interpreter and an applet
viewer where applets can be tested.
Sun's Java Development Kit (JDK) latest version is JDK 1.1 can be freely downloaded from the
Internet (from Sun's Web site). The JDK consists ofall the necessary tools to code and test your
programs. Java compiler is available on DOS, Win 3.x, Win 95, Windows NT SOLARIS
MAC, etc.

Hardware requirements are:


Preferably a fast 486 or Pentium, 16 MB RAM is ideal although a minimum of 4 MB RAM will
do for WIN 3.1; A minimum of 50 MB free disk space

Sun's JDK has an applet viewer test and view applets.

There are many products that offer Integrated Development and Debugging Environment (IDE).
These have more advanced features for editing, testing and debugging programs. Most of them
are visual tools. Some of these are listed below.

Symantec Cafe (from Symantec Inc.)


It has an IDDE. Compiles faster than Sun's JDK Visual application development tool comes
with Cafe Studio and Cafe's debugger. Includes API documentation and Sun's Java
Language Reference.

Visual Cafe (from Symantec Inc.): As above plus advanced GUI design features.

Delphi Latte (from Borland): Visual Development tools similar to Cafe.

Visual Age (from IBM): Has an editor, debugger, browser and Project Manager Full
documentation Visual Age's Data Access uses Java Database Connectivity (JDBC) for
database access

Visual J++ (from Microsoft): An editor debugger and an App Wizard. Good API
documentation. Execution slower than Cafe Good GUI features. Supports ActiveX controls.

1.9 Paradigm of Java


Java as a programming language evolved keeping in view certain criteria and features. In fact it
was built around a model that had these features. Some of the features of this model we have seen
like the object oriented, architecture neutral, robust, secure etc. Some additional features are
explained below.

Dynamic downloading of applets


Applets should be downloadable on to a client machine as and when required.

Training Cycle 1
Wintech Computers JAVA 2

Elimination of Fatware phenomenon


Most of the times, most of the features of today's software products are not used. And they hog
memory. Java based products could eliminate these by giving the users only those features of a
product that the user needs at a time. The remaining features of a product can remain on the
server itself.

Changing the economic model of the software


Pay by use software as described above would drastically alter the way software is sold, further
the economic model of software will undergo a change.

Up-to-date software availability


As Java will always be available on the Net, one can have access to the latest versions of the
software.

Continuous product innovation


With instant feedback from the market forces new products can evolve or existing products
undergo rapid changes to suit the ever-demanding clients.

Supports Network Centric Computing


Java should be able to support low cost Network computers.

Unification of developers, innovators and users


Java is architecture neutral and so it brings together developers, innovators and users. There will
be greater interaction among them, which in turn, could lead to better software services.

Supports CORBA & DCOM


Java supports Common Object Request Broker Architecture (CORBA) and Distributed Common
Object Model (DCOM of Microsoft). This ensures that certain standards for object-oriented
programming are met.

1.10 Java and C++ - Some Differences

No pointers in Java .
No structures or Unions.
No defines.
No multiple inheritances.
No individual functions.
No goto
No operator overloading.
No automatic coercion (casting).
No garbage collection in C++.

Training Cycle 1
Training
Cycle: 2
Wintech Computers JAVA 2

2. Fundamentals of Java

2.1 Introduction

The basic requirements for developing applications/ applets in Java language are:

1) Java Compiler
2) Java Interpreter
3) Java enabled browser for applets.

2.2 Setting Uo Your Computer

Before you can write and run the simple Java program in this lesson, you need to install the Java
platform on your computer system.
The Java platform is available free of charge from the java.sun.com web site. You can choose
between the Java 2 Platform software for Windows 95/98/NT or for Solaris. The download page
contains the information you need to install and configure the Java platform for writing and
running Java programs.

2.2.1 Writing a Program


The easiest way to write a simple program is with a text editor. So, using the text editor of your
choice, create a text file with the following text, and be sure to name the text file
ExampleProgram. j ava. Java programs are case sensitive, so if you type the code in yourself,
pay particular attention to the capitalization

//A Very Simple Example


class ExampleProgram
(
public static void main(String[] args)
{
System.out.println("I'm a Simple Program");
}
}
To fully understand what is happening, let's examine the program line by line First, you must
understand that Java relies heavily on classes. In fact the first statement of ExampleProgram
reminds you that ExampleProgram is a class, not just a program Furthermore, by looking at the
class statement, you can see that the name of the class is defined as ExampleProgram 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 there is more than
one class defined in a Java file, the Java compiler stores each class in a separate class file

The ExampleProgram contains one method or member function. The single method in
ExampleProgram class is called main and should be familiar if you have used C or C++ The
main() method is where execution begins when the class is executed in the Java interpreter The
main() method is defined as being public static with a void return type public means that the
method can be called from anywhere inside or outside the class static means that the method is
the same for all the class. The void return type means the main( ) does not return a value.
Training Cycle 2
Wintech Computers JAVA 2

2.2.2 Compiling the Program


A program has to be converted to a form the Java VM can understand so any computer with a
Java VM can interpret and run the program. Compiling a Java program means taking the
programmer-readable text in your program file (also called source code) and converting it to
bytecodes, which are platform-independent instructions for the Java VM
The Java compiler is invoked at the command line on Unix and DOS shell operating systems as
follows:

javac ExampleProgram.java

2.2.3 Interpreting and Running the Program


Once your program successfully compiles into Java bytecodes, you can interpret and run
applications on any Java VM, or interpret and run applets in any Web browser with a Java VM
built in such as Netscape or Internet Exploier Interpreting and running a Java program means
invoking die Java VM byte code interpreter, which converts the Java byte codes to platform-
dependent machine codes so your computer can understand and run the program.
The Java interpreter is invoked at the command line on Unix and DOS shell operating systems as
follows

]ava ExampleProgram

At the command line, you should see

I'm a Simple Program

2.3 Code Comments

Code comments are placed in source files to describe what is happening in the code to someone
who might be reading the file, to comment-out lines of code to isolate the source of a problem
for debugging purposes, or to generate API documentation To these ends, the Java language
supports three kinds of comments double slashes and C-style

2.3.1 Double Slashes


Double slashes (,' ) are used in the C* * programming language, and tell the compiler to treat
eveivthmtj from the slashes to the end of the line as text

//A Very Simple Example


class ExampleProgram
I
public static void main(String[] args)
{
System.out.print In("I'm a simple Program");
\
}

2.3.2 C-Style Comments


Instead of double slashes, you can use C-style comments (/ * */) to enclose one or more lines of
code to be treated as text

Training ( >cle 2
Wintech Computers JAVA 2

/* These are
C-style comments
*/
class ExampleProgram
{
public static void main(String[] args)
{
System.out.println("I'm a Simple Program");

In addition to the above two Java introduces a new comment tag the /** I am being documented
*/. These comments are similar to the multiple-line comment or the C-style comments but start
with a /** instead of /*. These comments are used by the javadoc utility to create
documentation.

2.4 Variables and Data Type

Like other programming languages, Java allows you to declare variables in your programs. You
use variables to contain data that can change during the execution of the program. All variables
in Java have a type, a name, and scope.

Example.
int count = 0;
String[] args

Data Types
All variables in the Java language must have a data type. A variable's data type determines the
values that the variable can contain and the operations that can be performed on it. For example,
the declaration int count declares that count is an integer (int). Integers can contain only
integral values (both positive and negative), and you can use the standard arithmetic operators (+,
-, *, and /) on integers to perform the standard arithmetic operations (addition, subtraction,
multiplication, and division, respectively).

There are two major categories of data types in the Java language: primitive and reference. The
following table lists, by keyword, all of the primitive data types supported by Java, their sizes
and formats, and a brief description of each.

Type 1 Size/Format
I Description
(integers)
Byte 8-bit two's complement Byte-length integer
Short 16-bit two's complement Short integer
Int 32-bit two's complement Integer
Long J64-bit two's complement Long integer
(real numbers)

Training Cycle 2 10
Wintec h Computers
JAVA 2

Float 32-bit IEEE 754 Single-precision floating point


Doubl
e
64-bit IEEE 754 Double-precision floating point
(other types)
Char 16-bit Unicode character A single character
Boole
true or false A boolean value (true or false)
an

Variable Names
Aprogram refers to avariable's value by its name. In Java, the following must hold true for a
variable name
It must be a legal Java identifier comprised ofa series ofUnicode characters Unicode
is a character-coding system designed to support text written in diverse human
languages It allows for the codification of up to 65,536 characters, currently 34,168
have been assigned This allows you to use characters in your Java programs from
various alphabets, such as Japanese, Greek, Cyrillic, and Hebrew This is important
so that programmers can write code that is meaningful in their native languages.
It must not be a keyword ora boolean literal (true or false).
It must not have the same name as another variable whose declaration appears in the
same scope

Operators
Operators perform some function on either one or two operands or three operands Operators that
require one operand are called unary operators. For example, ++ is a unary operator that
increments the value of its operand by 1 Operators that require two operands are binary
operators For example, =is a binary operator that assigns the value from its right-hand operand
to its left-hand operand And finally tertiary operators are those that require three operands The
Java language has one tertiary operator: which is a short-hand if-else statement
The operators that being common used are listed below
Arithmetic Operators
Relational and Conditional Operators
Bitwise Operators
Assignment Operators

Arithmetic Operators
The Java language supports various arithmetic operators for all floating-point and integer
numbers These include + (addition), - (subtraction), * (multiplication), / (division), and *
(modulo). For example, you can use this Java code to add two numbers.
addThis + toThis

Relational and Conditional Operators


A relational operator compares two values and determines the relationship between them. For
example, != returns true if the two operands are unequal. The countChars method uses != to
determine whether the value returned by in.read is not equal to -1 This table summarizes
Java's relational operators

Training Cycle 2 11
JAVA 2
Wintech Computers

0 < index && index < NUM_ENTRTS

Bitwise Operators
Abitwise operator allows you to perform bit manipulation on data. This table summarizes the
bitwise and logical operators available inthe Java language.

Operator Use Operation


opl
>> Shift bits of opl right by distance op2
op2
opl
<< Shift bits of opl left by distance op2
op2
opl >
>>> shift bits of opl right by distance op2 (unsigned)
op2
opl & op2 bitwise and
opl | op2 bitwise or
opl A op2 bitwise xor
~op2 bitwise complement

Assignment Operators
You use the basic assignment operator, =, to assign one value to another.

For example:

int count = 0;

Java also provides several short cut assignment operators that allow you to perform arithmetic,
logical, or bitwise operation and an assignment operation all with one operator. Suppose you
wanted to add a number to a variable and assign the result back into the variable, like this:

i = i + 2;

2.5 Expressions

Expressions perform the work of a Java program. Among other things, expressions are used to
compute and assign values to variables and to help control the execution flow of a program. The
job of an expression is two-fold: perform the computation indicated by the elements of the
expression and return some value that is the result of the computation.
2.6 Control Flow Statements

As the name implies, control flow statements control the flow of the program. In other words,
control flow statements govern the sequence in which a program's statements are executed

Training Cycle 2 12
Wintech Computers JAVA 2

while
Generally speaking, a while statement performs some action while a certain condition remains
true. The general syntax of the while statement is:

while (expression)
statement

That is, while expression is true, do statement.

For example:

class fibo
{
public static void main(String args[])
{
int numl=l, num2=l;
System.out.println(numl);

while (num2<200)
{
r(.. .System, out .println (num2);
^ ^ num2 += numl; rr?sxtf3 ncyjmZ - n<ju"nj^-f ruu/n-4,
P^w^l-cefeif^ numl. = num2 - numl;

} 0-S^S>c-+erv^J^ j. ^ ^[ -f ^ ^ 9
7M Skdr-erwc^ 2. - i ^ ^
The above code executes the statement in the while loop until the statement in the while loop
returns false. ^ A^ ^J^CJU JL*^ T^< 2W\
After execution
1) 9-*- I - S
C:\Javafiles>java fibo
1

1 ^ 3^^
8
13
21
34
55
89
144

You can use the if construct and the break and continue keywords to execute selective statements
or to exit the while loop.

13
Training Cycle 2
Wintech Computers JAVA 2
The if-else Statement
The if-else branch is the most commonly used branch in Java programming. It is used to select
conditionally one of two possible outcomes
This is the simplest version ofthe if statement: the statement governed by the if is executed if
some condition is true. Generally, the simple form of if can bewritten like this:
if (expression)
statement
else
statement
Ifyou need more than two conditional outcomes, you can string together aseries ofif-else
branches to get the desired effect. The following example shows multiple if-else branches
if (x == 0)
y = 5;
else if(x == 2)
y=2 5;
else if (x >= 3)
y = 125;

The above example makes three different comparisons, each with its own
statement executed on a true conditional result.

The switch Statement


Use the switch statement to conditionally perform statements based on some expression. For
example, suppose that your program contained an integer named month whose value indicated
the month in some date. Suppose also that you wanted to display the name of the month based on
its integer equivalent. You could use Java's switch statement to perform this feat:
i n t month;

switch (month)
(
case 1: System.out.println("January"); break;
case 2: System.out.println("February"); break;
case 3: System.out.println("March"); break;
case 4: System.out.println("April"); break;
case 5: System.out.println("May"); break;
case 6: System.out.printIn("June"); break;
case 7: System.out.println("July"); break;
case 8: System.out.println("August"); break;
case 9: System.out.println("September"); break;
case 10: System.out.println("October"); break;
case 11: System.out.println("November"); break;
case 12: System.out.println("December"); break;
)
The switch statement evaluates its expression, in this case, the value of month, and
executes the appropriate case statement.

Loop Statements
You were introduced to Java's while statement above. Java has two other looping constructs
that you can use in your programs: the for loop and the do-while loop.
Use the for loop when you know the constraints of the loop (its initialization instruction,
termination criteria, and increment instruction) For instance, for loops are often used to iterate
over the elements in an array, or the characters in a string.

Training Cycle 2 14
Wintech Computers JAVA 2
// a is an array of some kind

int i;
int length = a.length;
for (i = 0; i < length; i-fr) {

// do something to the i th element of a

}
You know when writing the programs, that you want to start at the beginning ofthe array, stop at
the end, and hit every element. Thus the for statement is a good choice. The general form of the
for statement can be expressed like this:

for {initialization; termination; increment)


statements

initialization is a statement that initializes the loop-is executed once atthe beginning ofthe loop
termination is an expression that determines when to terminate the loop. This expression is
evaluated at the top of each iteration of the loop. When the expression evaluates to false, the
for loop terminates. Finally, increment is an expression that gets invoked for each iteration
through theloop. Any (or all) of these components can be empty statements (a single semi-colon
by itself)

Java provides another loop, the do-whil loop, which is similar to the while loop you met
earlier except that the expression is evaluated at the bottom of the loop:

do{
statements
} while (booleanExpression);

The do-while statement is a less commonly used loop construct in programming but does have
its uses. For example, the do-while is convenient to use when the statements within the loop
must be executed at least once. For example, when reading information from a file, you know
that you will always have to read at least one character:

int c;
Reader in;

do
{
c in.read();

)
while (c 1- -1);

Training Cycle 2 1S
Training
Cycle: 3
Wintech Computers JAVA 2

3. Object-Oriented Programming Concepts


You've heard it a lot in the past several years. Everybody is saying it. OOP !!
What is all the fuss about objects and object-oriented technology? Is it real? Or is it
hyped? Well, the truth isit's not. Object-oriented technology does, in fact, provide many
benefits to software developers and their products. However, historically a lot ofhype has
surrounded this technology, causing confusion in both managers and programmers alike.
Many companies fell victim to this hardship (or took advantage of it) and claimed that
their software products were object-oriented when, in fact, they weren't. These false
claims confused consumers, causing widespread misinformation and mistrust of object-
oriented technology.

However, in spite of overuse and misuse of the term object-oriented, the computer
industry is now beginning to overcome the hype. Understanding is growing about this
technology and its benefits.
This lesson slashes through the hype and explains the key concepts behind object-
oriented programming, design, and development.

What Is an Object?
An object is a software bundle of variables and related methods. Software objects are
oftenused to model real-world objects you find in everyday life.
What Are Messages?
Software objects interact and communicate with each otherusing messages.
What Are Classes?
Aclass is a blueprint or prototype that defines the variables and the methods common to
all objects of a certain kind.
What Is Inheritance?
(Orwhat does my grandmother's money have to dowith all of this?)
A class inherits state and behavior from its superclass. Inheritance provides a powerful
and natural mechanism for organizing and structuring software programs.
This lesson provides a basis for understanding key object-oriented terminology and
concepts. Understanding these new terms and concepts is just the beginning. As you
begin to design and program in the Java language, a truly object-oriented language, the
power of objects and classes will become apparent.

Training Cycle 3 16
Wintech Computers JAVA 2

3.1 What Is an Object?

As the name object-oriented implies, objects are key to understanding object-oriented


technology. You can look around you now and see many examples of real-world
objects: your dog, your desk, your television set, and your bicycle.

These real-world objects share two characteristics: they all have state and they all have
behavior. For example, dogs have state (name, color, breed, hungry) and dogs have
behavior (barking, fetching, and slobbering on your newly cleaned slacks). Bicycles have
state (current gear, current pedal cadence, two wheels, number of gears) and behavior
(braking, accelerating, slowing down, changing gears).

Software objects are modeled after real world objects in that they, too, have state and
behavior. A software object maintains its state in variables and implements its behavior
with methods.

Definition: An object is a software bundle of variables and related methods.

You can represent real-world objects using software objects. You might want to represent
real-world dogs as software objects in an animation program or a real-world bicycle as a
software object within an electronic exercise bike. However, you can also use software
objects to model abstract concepts. For example, an event is a common object used in
GUI window systems to represent the action of a user pressing a mouse button or a key
on the keyboard.

Private
n li / J*C / JvImplementation

Everything that the software object knows (state) and can do (behavior) is expressed by
the variables and methods within that object. A software object that modeled your real-
world bicycle would have variables that indicated the bicycle's current state: its speed is
10 mph, its pedal cadence is 90 rpm, and its current gear is the 5th gear. These variables
and methods are formally known as instance variables and instance methods to
distinguish them from class variables and class methods (described later in What Are
Classes?).

17
Training Cycle 3
Wintech Computers JAVA 2

The following figure illustrates a bicycle modeled as a software object.

10mph
90rpm
Gear
Implementation

5th gear

The software bicycle would also have methods to brake, change the pedal cadence, and
change gears. (The bike would not have a method for changing the speed of the bicycle
as the bike's speed is really just a side effect of what gear it's in, how fast the rider is
pedaling, whether the brakes are on, and how steep the hill is.)
Anything that an object does not know or cannot do is excluded from the object For
example, your bicycle (probably) doesn't have a name, and it can't run, bark, or fetch
Thus there are no variables or methods for those states and behaviors in the bicycle class.
As you can see from the diagrams, the object's variables make up the center or nucleus of
the object.. Methods surround and hide the object's nucleus from other objects in the
program. Packaging an object's variables within the protective custody of its methods is
called encapsulation. Typically, encapsulation is used to hide unimportant
implementation details from other objects. When you want to change gears on your
bicycle, you don't need to know how the gear mechanism works, you just need to know
which lever to move. Similarly in software programs, you don't need to know how aclass
is implemented; you just need to know which methods to invoke. Thus the
implementation details can change at any time without affecting other parts of the
program.

This conceptual picture of an object-a nucleus of variables packaged within aprotective


membrane of methods-is an ideal representation of an object and is the ideal that
designers of object-oriented systems strive for. However, it's not the whole story Often
for implementation or efficiency reasons, an object may wish to expose some of its
variables or hide some of its methods.

In many languages, including Java, an object can choose to expose its variables to other
objects allowing those other objects to inspect and even modify the variables Also an
object can choose to hide methods from other objects forbidding those objects from
invoking the methods. An object has complete control over whether other objects can
access its variables and methods and in fact, can specify which other objects have access
Variable and method access in Java is covered in Controlling Access to Members of a
Class

Training Cycle 3
Wintech Computers
JAVA It

The Benefits of Encapsulation


Encapsulating related variables and methods into aneat software bundle is asimple yet
powerful idea that provides two primary benefits to software developers:
Modularity~The source code for an object can be written and maintained
independently of the source code for other objects. Also, an object can be
easily passed around in the system. You can give your bicycle to someone
else and it will still work.

Information hiding-An object has apublic interface that other objects can
use to communicate with it. But the object can maintain private
information and methods that can be changed at any time without
affecting the other objects that depend on it. You don't need to understand
thegear mechanism on your bike in order to use it.

3.2 What Are Messages?

Asingle object alone is generally not very useful and usually appears as acomponent of a
larger program or application that contains many other objects. Through the interaction of
these objects, programmers achieve higher order functionality and more complex
behavior. Your bicycle hanging from a hook in the garage is just a bunch of titanium
alloy and rubber; by itself the bicycle is incapable ofany activity. The bicycle is useful
only when another object (you) interacts with it (starts pedaling).
Software objects interact and communicate with each other by sending messages to each
other. When object A want object B to perform one of B's methods, object A sends a
message to object B.

Message

Object A

Object B

Sometimes the receiving object needs more information so that it knows exactly what to
do-for example, when you want to change gears on your bicycle, you have to indicate
which gear you want. This information is passed along with the message as parameters.
Three components comprise a message:

1. The object to whom the message is addressed (Your Bicycle)


2. The name of the method to perform (changeGears)
3. Any parameters needed by the method (lower gear)

These three components are enough information for the receiving object to perform the
desired method. No other information or context is required.

Training Cycle 3 19
Wintech Computers JAVA 2

The Benefits of Messages

An object's behavior is expressed through its methods, so (aside from direct


variable access) message passing supports all possible interactions between
objects.
Objects don't need to be in the same process or even on the same machine to send
and receive messages back and forth to each other.

3.3 What Are Classes?

In the real world, you often have many objects of the same kind. For example, your
bicycle is just one of many bicycles in the world. Using object-oriented terminology, we
say that your bicycle object is an instance of the class of objects known as bicycles.
Bicycles have some state (current gear, current cadence, two wheels) and behavior
(change gears, brake) in common. However, each bicycle's state is independent of and
can be different from other bicycles.

When building bicycles, manufacturers take advantage of the fact that bicycles share
characteristics by building many bicycles from the same blueprintit would be very
inefficient to produce a new blueprint for every individual bicycle they manufactured.

In object-oriented software, it's also possible to have many objects of the same kind that
share characteristics: rectangles, employee records, video clips and so on. Like the
bicycle manufacturers, you can take advantage of the fact that objects of the same kind
are similar and you can create a blueprint for those objects. Software "blueprints" for
objects are called classes.

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

For example, you could create a bicycle class that declares several instance variables to
contain the current gear, the current cadence, and soon, for each bicycle object. The class
would also declare and provide implementations for the instance methods that allow the
rider to change gears, brake, and change the pedaling cadence.
The values for instance variables are provided by each instance of the class. So, after
you've created the bicycle class, you must instantiate it (create an instance of it) before
you can use it. When you create an instance of a class, you create an object of that type
and the system allocates memory for the instance variables declared by the class. Then
you can invoke the object's instance methods to make it do something. Instances of the
same class share the same instance method implementations (method implementations
are not duplicated on a per object basis), which reside in the class itself.

In addition to instance variables and methods, classes can also define class variables and
class methods. You can access class variables and methods from an instance of the class

Training Cycle 3 20
Wintech Computers JAVA 2

or directly from a classyou don't have to instantiate a class to use its class variables and
methods. Class methods can only operate on class variablesthey do not have access to
instance variables or instance methods.

The system creates a single copy of all class variables for a class the first time it
encounters the class in a programall instances of that class share its class variables. For
example, suppose that all bicycles had the same number of gears. In this case defining an
instance variable for number of gears is inefficienteach instance would have its own
copy of the variable, but the value would be the same for every instance. In situations
such as this, you could define a class variable that contains the number of gears. All
instances share this variable. If one object changes the variable, it changes for all other
objects of that type.
Instance and Class Members discusses instance variables and methods and class variables
and methods in detail.

Objects vs. Classes


You probably noticed that the illustrations of objects and classes look very similar to one
another. And indeed, the difference between classes and objects is often the source of
some confusion In the real world it's obvious that classes are not themselves the objects
that they describe-a blueprint of a bicycle is not a bicycle. However, it's a little more
difficult to differentiate classes and objects in software. This is partially because software
objects are merely electronic models of real-world objects or abstract concepts in the first
place. But it's also because many people use the term "object" inconsistently and use it to
refer to both classes and instances.

In the figures, the class is not shaded because it represents a blueprint of an object rather
than an object itself. In comparison, an object is shaded, indicating that the object
actually exists and you can use it.

The Benefit of Classes


Objects provide the benefit of modularity and information hiding. Classes provide the
benefit of reusability. Bicycle manufacturers reuse the same blueprint over and over
again to build lots of bicycles. Software programmers use the same class, and thus the
same code, over and over again to create many objects.

3.4 What Is Inheritance?

Generally speaking, objects are defined in terms of classes. You know a lot about an
object by knowing its class. Even if you don't know what apenny-farthing is, if I told you
it was abicycle, you would know that it had two wheels, handle bars, and pedals.
Object-oriented systems take this astep further and allow classes to be defined in terms
of other classes. For example, mountain bikes, racing bikes, and tandems are all different
kinds of bicycles. In object-oriented terminology, mountain bikes, racing bikes, and
tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the
superclass of mountain bikes, racing bikes, and tandems.

21
Training Cycle 3
Wintech Computers JAVA 2

Each subclass inherits state (in the form of variable declarations) from the superclass
Mountain bikes, racing bikes, and tandems share some states: cadence, speed, and the
like Also, each subclass inherits methods from the superclass. Mountain bikes, racing
bikes, and tandems share some behaviors: braking and changing pedaling speed, for
example.
However, subclasses are not limited to the state and behaviors provided to them by their
superclass What would be the point in that? Subclasses can add variables and methods to
the ones they inherit from the superclass. Tandem bicycles have two seats and two sets of
handle bars; some mountain bikes have an extra set of gears with a lower gear ratio
Subclasses can also override inherited methods and provide specialized implementations
for those methods. For example, if you had a mountain bike with an extra set of gears,
you would override the "change gears" method so that the rider could actually use those
new gears.
You are not limited to just one layer of inheritance. The inheritance tree, or class
hierarchy, can be as deep as needed Methods and variables are inherited down through
the levels In general, the further down in the hierarchy a class appears, the more
specialized its behavior

The Benefits of Inheritance

Subclasses provide specialized behaviors from the basis of common elements


provided by the superclass Through the use of inheritance, programmers can
reuse the code in the superclass many times.
Programmers can implement superclasses called abstract classes that define
"generic" behaviors The abstract superclass defines and may partially implement
the behavior but much of the class is undefined and unimplemented Other
programmers fill in the details with specialized subclasses

Training Cycle 3 22
Training
Cycle: 4
Wintech Computers JAVA 2

4. Objects and Classes in Java (OOP II)

In the lesson entitled Object-Oriented Programming Concepts, You will read about the concepts
behind object-oriented programming. Now it's time to get to work and put those concepts to
practical use in Java.

4.1 The Life Cycle of Classes

To understand objects, you must understand classes. To understand classes, you need to
understand objects. It's a circular process of learning. But you've got to begin somewhere. So,
let's begin with two classes- Point and Rectangle- that are small and easy to understand.
This section provides a brief discussion of these classes and introduces some important concepts
and terminology.
Here, you will learn how to create a Rectangle object from the Rectangle class, use it, and
eventually get rid of it.

Creating Classes
This section provides a complete description of a larger class, stack, and describes all of the
components of a class that provide for the life cycle of an object created from it. It talks first
about constructors, then about member variables and methods, and finally about the finalize
method.

4.2 A Brief Introduction to Classes

Following is the code for a class called simplePoint that represents a point in 2D space:
public class SimplePoint
{
public int x = 0;
public int y = 0;
}

This segment of code declares a class- a new data type really- called simplePoint. The
simplePoint class contains two integer member variables, x and y. The public keyword
preceding the declaration for x and y means that any other class can freely access these two
members.

You create an object from a class such as simplePoint by instantiating the class. When you
create a new simplePoint object (we show you how shortly), space is allocated for the object
and its members x and y. In addition, the x and y members inside the object are initialized to 0
because of the assignment statements in the declarations of these two members.

Training Cycle 4
Wintech Computers JAVA 2

Now, here's a class, simpieRectangie, that represents a rectangle in 2D space:


public class SimpieRectangie
{
public int width = 0;
public int height = 0;
public SimplePoint origin = new SimplePoint();
}

This segment of code declares a class (another data type)simpieRectangie that contains two
integer members, width and height. simpieRectangie also contains a third member, origin,
whose data type is simplePoint. Notice that the class name simplePoint is used in a variable
declaration as the variable's type. You can use the name of a class anywhere you can use the
name of a primitive type.

Just as width "is an" integer and height "is an" integer, origin "is a" simplePoint. On the
other hand, a simpieRectangie object "has a" simplePoint. The distinction between "is a" and
"has a" is critical because only an object that "is a" simplePoint can be used where a
simplePoint is called for.

As with simplePoint, when you create a new simpieRectangie object, space is allocated for
the object and its members, and the members are initialized according to their declarations.
Interestingly, the initialization for the origin member creates a simplePoint object with this
code: new simplePoint () as illustrated here in the figure below:

A Point Object

This diagram shows the difference between primitive types and reference types. Both width and
height are integers and are fully contained within simpieRectangie. On the other hand,
origin simply references a simplePoint object somewhere else.
The simplePoint and simpieRectangie classes as shown are simplistic implementations for
these classes. Both should provide a mechanism for initializing their members to values other
than 0. Additionally, SimpieRectangie could provide a method for computing its area, and
because SimpieRectangie creates asimplePoint when it's created, the class should provide for
the clean up of the simplePoint when simpieRectangie gets cleaned up. So, here's a new
version of simplePoint, called Point, that contains a constructor which you can use to
initialize a new Point to a value other than (0,0):

Training Cycle 4 24
Wintech Computers JAVA 2

public class Point


{
public int x = 0;
public int y = 0;
// a constructor!
public Point(int x, int y)
{
this.x = x;
this.y = y;

Now, when you create a Point, you can provide initial values for it like this:
new Point(44, 78)

The values 44 and 78 are passed into the constructor and subsequently assigned to the x and y
members of the new Point object as shown here in the Figure below:
A Rectangle Object A Point Object
\

Now, let's brief up the SimpieRectangie Class. Here's a new version of SimpieRectangie,
called Rectangle, that contains four constructors, a method to "move" the rectangle, a method to
compute the area ofthe rectangle, and a finalize method to provide for clean up: '
public class Rectangle
{
public int width = 0;
public int height = 0;
public Point origin;
// four constructors
public Rectangle()

origin = new Point(0, 0) ;

public Rectangle(Point p)

origin = p;

public Rectangle(int w, int h)

this(new Point(0, 0), w, h) ;

Training Cycle 4
25
Wintech Computers ..
JAVA 2

}
public Rectangle(Point p, int w, int h)
{
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y)
{
origin.x = x;
origin.y = y;
}
// a method for computing the area of the rectangle
public int area()
{
return width * height;
}
// clean up!
protected void finalize() throws Throwable
{
origin = null;
super.finalize();

The four constructors allow for different types ofinitialization. You can create a new Rectangle
and let it provide default values for everything, or you can specify initial values for the origin,
the width and the height, or for all three when you create the object. You'll see more of this
version of the Rectangle class in the next section.

This section glossed over some details and left some things unexplained, but it provides the basis
you need to understand the rest ofthis lesson. After reading this section, you should know that
objects are created from classes
an object's class is its type
how "is a" differs from "has a"
the difference between reference and primitive types.

You also should have a general understanding or a feeling for the following:

How to create an object from a class


What constructors are
What the code for a class looks like
What member variables are
How to initialize objects
What methods look like

Training Cycle 4 26
Wintech Computers JAVA 2

Now, let's look in detail at the life cycleof an object, specifically how to create, use, and destroy
an object

4.3 The Life Cycle of an Object

Typically, a Java program creates many objects from a variety of classes. These objects interact
with one another by sending each other messages. Through these object interactions, a Java
program can implement a GUI, run animation, or send and receive information over a network
Once an object has completed the work for which it was created, it is garbage-collected and its
resources are recycled for use by other objects Follow the links below to learn about the typical
phases of the life of an object:

1 Creating Objects

2 Using Objects

3 Cleaning Up Unused Objects

4.3.1 Creating Objects


In Java, you create an object by creating an instance of a class or, in other words,
instantiating a class Often, you will see a Java object created with a statement like the
following, which creates a new Rectangle object from the Rectangle class given in the
previous section:

Rectangle rect = new Rectangle!);

This single statement performs three actions:

1. Declaration: Rectangle rect is a variable declaration that declares to the


compiler that the name rect will be used to refer to a Rectangle object. Notice
that a class name is used as the variable's type.
2. Instantiation: new is a Java operator that creates the new object (allocates space
for it).

3 Initialization: Rectangle o is a call to Rectangle's constructor, which


initializes the object

Declaring an Object
The declaration of an object is not a necessary part of object creation, although it often appears
on the same line Like other variable declarations, object declarations can also appear alone, like
this:

Rectangle rect;

Training Cycle 4
27
Wintech Computers JAVA 2

Variables and Data Types in the previous lesson discussed variable declarations in detail. To
declare an object, you just follow the same rules and declare a variable to refer to that object by
declaring its type and name:

type name

In Java, classes and interfaces can be used as data types. So type can be the name of a class such
as the Rectangle class or the name of an interface. Classes and interfaces are both reference
types (the variable's actual value is a reference to the value or set of values represented by the
variable) In this tutorial, a reference may also be called an object reference or an array
reference, depending on the data to which the reference refers.

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

Instantiating an Object
The new operator instantiates a class by allocating memory for a new object of that type, new
requires a single, postfix argument: a call to a constructor. Each Java class provides a set of
constructors used to initialize new objects of that type. The new operator creates the object, and
the constructor initializes it Here's an example of using the new operator to create a Rectangle
object:
new Rectangle(100, 200);

Here, Rectangle (ioo, 200) is the argument to new. The new operator returns a reference to the
newly created object This reference can be assigned to a variable of the appropriate type, as
shown here

Rectangle rect = new Rectangle(100, 200);

After this statement, rect refers to a Rectangle object whose origin is at (0, 0), width is 100,
and height is 200.

Initializing an Object
As shown in the code for the Rectangle class, classes can provide one or more constructorsto
initialize a new object ofthat type. You can recognize a class's constructors because they have
the same name as the class and have no return type. Here are the declarations for Rectangle's
constructors:

public Rectangle(Point p)
public Rectangle(int w, int h)
public Rectangle(Point p, int w, int h)
public Rectangle ()

Training Cycle 4 M
Wintech Computers JAVA 2

Each of these constructors lets you provide initial values for different aspects of the rectangle:
the origin, the width and height, all three, or none. If a class has multiple constructors, they all
have the same name but a different number of arguments or different typed arguments. The
compiler differentiates the constructors, and knows which one to call, depending on the
arguments. So when the compiler encounters the following code, it knows to call the constructor
that requires two integer arguments (which initializes the width and height of the new rectangle
to the values provided by the arguments):
Rectangle rect = new Rectangle(100, 200);

And when the compiler encounters the next line ofcode, it knows to call the constructor that
requires a Point (which provides the initial values for the origin of the new Rectangle):
Rectangle rect = new Rectangle(new Point(44,78));

The Rectangle constructor used below doesn't take any arguments.


Rectangle rect = new Rectanglef);

A constructor that takes no arguments, such as the one shown, is the default constructor. If a
class (like the simplePoint and simpieRectangie classes shown at the very beginning ofthis
lesson) does not explicitly define any constructors at all, Java automatically provides a no-
argument constructor that does nothing. Thus all classes have at least one constructor
This section talked about how to use a constructor. Providing Constructors for Your Classes later
in this lesson explains how to write constructors for your classes
4.3.2 Using Objects
Once you've created an object, you probably want to use it for something. You may need
information from it, want to change its state, or have it perform some action.

Objects give you two ways to do these things:


1 Manipulate or inspect its variables
2. Call its methods.
Ideal object-oriented programming discourages the direct manipulation of an object's variables;
you could potentially put the object into an inconsistent state. Instead, an ideal object provides
methods through which you can inspect or change its state. These methods ensure that the object
never gets into an inconsistent state. However, in practical situations, it sometimes makes sense
to use an object's variables directly.
Both the Point class and the Rectangle class allow free access to their member variables.
You cannot put a Point object in an inconsistent state by setting x or y directly, and you
cannot put a Rectangle object in an inconsistent state by setting width, height, or origin.
Java provides an access control mechanism whereby classes can restrict or allow access to its
variables and methods. A class should protect variables against direct manipulation by other
objects if those manipulations could endanger the object's state. State changes should then be

Training Cycle 4 29
Wintech Computers
JAVA 2

affected and therefore controlled by method calls. If an object grants access to its variables you
can assume that you can inspect and change them without adverse effects To learn more about
Java's access control mechanism, refer to Controlling Access to Members ofa Class.
So, back to the Rectangle object. Suppose aRectangle object represents arectangular object in
a drawing program and the user just dragged it to a new location. You need to update the
Rectangle object's point of origin. The Rectangle class provides two equivalent ways ofdoine
this:

1 Manipulate the object's origin variable directly.


2. Call the move method.

Rectangle's origin member is accessible to other classes (it's declared public), so you can
assume that manipulating a Rectangle's origin member directly is safe.
4.3.3 Referencing an Object's Variables
This section focuses on how to move the Rectangle by modifying its origin variable directly.
The next section shows you how to move the rectangle by calling the move method
Assume you created a rectangle named rect as described in the previous section To move rect
to a new location, you would write:

rect.origin = new Point(15, 37);

This statement moves the rectangle by setting its point oforigin to a new position rect. origin
is the name of rect's origin variable. You can use these kinds of object variable names in the
same manner as you use other variables names. Thus, as in the previous example code, you can
use the = operator to assign a value to rect. origin.

The Rectangle class has two other variables- width and height- that are accessible to objects
outside of the class. You can use the same notation to access them and calculate the rectangle's
area using this statement (or you could just call the area method):
area = rect.height * rect.width;

In general, to refer to an object's variables, append the name of the variable to an object reference
with an intervening period (.):

objectReference.variable

The first part of the variable's name, objectReference, must be a reference to an object. You
can use an object name here just as was done in the previous examples with rect You also can
use any expression that returns an object reference. Recall that the new operator returns a
reference to an object. So you could use the value returned from new to access a new object's
variables:

height = new Rectangle().height;

Training Cycle 4 30
Wintech Computers JAVA 2

This statement creates a new Rectangle object and immediately gets its height Effectively, the
statement calculates the default height of a Rectangle Note that after this statement has been
executed, the program no longer has a reference to the Rectangle that was created because the
program never stored the reference in a variable. Thus the object becomes eliuible for garbage
collection

Here's a final word about accessing an object's variables to clear up a point of some confusion
that beginning Java programmers often have All objects of the same type have the same
variables All Rectangle objects have origin, width, and height variables that they got from
the Rectangle class When you access a variable through an object reference, you reference that
particular object's variables Suppose that bob is also a rectangle in your drawing program and it
has a different height and width than rect The following instruction calculates the area of the
rectangle named bob. which differs from the previous instruction that calculated the area of
rect:

area = bob.height * bob.width:

4.3.4 Calling an Object's Methods

To move rect to a new location using its move method, you write this:
rect.move I IS, H7) ;

This Java statement calls rect's move method with two integer parameters, 15 and 37 It moves
the rect object because the rect method assigns new values to origin.x and origin.y and is
equivalent to the assignment statement used previously
rect.origin = new Point(15, 37);

The notation used to call an object's method is similar to that used when referring to its variables:
You append the method name to an object reference with an intervening period (.). Also, you
provide any arguments to the method within enclosing parentheses If the method does not
require any arguments, use empty parentheses

objectReference.methodName(argumentList) ;
Or
objectReference.methodName();

As stated previously in this lesson, objectReference must be a reference to an object You can
use a variable name here, but you also can use any expression that returns an object reference
The new operator returns an object reference, so you can use the value returned from new to call a
new object's methods

new Rectangle(100, 50).area()

Training Cycle 4
Wintech Computers JAVA 2

The expression new Rectangle (ioo, 50) returns an object reference that refers to a Rectangle
object As shown, you can use the dot notation to call the new Rectangle's area method to
compute the area of the new rectangle.

Some methods, like area, return a value. For methods that return a value, you can use the
method call in expressions. You can assign the.return value to a variable, use it to make
decisions, or control a loop. This code assigns the value returned by area to a variable:

int areaOfRectangle new Rectangle(100, 50).area();

Remember that invoking a method on a particular object is the same as sending a message to that
object. In this case, the object is the rectangle called rect. You will probably get a different
response if you send the same message to bob.

4.3.5 Cleaning Up Unused Objects


Many other object-oriented languages require that you keep track of all of the objects you create
and that you explicitly destroy them when they are no longer needed. This technique of
managing memory is tedious and often error-prone. Java allows you to create as many objects as
vou want (limited, of course, by what your system can handle), and you never have to worry
about destroying them. The Java runtime environment deletes objects when it determines that
they are no longer being used. This process is called garbage collection. The next section
discusses this in more detail

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

The Garbage Collector


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

The garbage collector runs in a low-priority thread and runs either synchronously or
asynchronously depending on the situation and the system on which Java is running. It runs
synchronously when the system runs out of memory or in response to a request from a Java
program

The Java garbage collector runs asynchronously when the system is idle, but it does so only on
systems, such as Windows 95/NT, that allow the Java runtime environment to note when a
thread has begun and to interrupt another thread. As soon as another thread becomes active, the
garbage collector is asked to get to aconsistent state and terminate.

Training Cycle 4 ^2
Wintech Computers JAVA 2

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

During finalization, an object may wish to free system resources such as files and sockets orto
drop references to other objects so that they in turn become eligible for garbage collection. The
finalize method for the Rectangle class releases the Point object by setting its reference to
origin to null:

protected void finalize() throws Throwable


{
origin = null;
super.finalize();
}

The finalize method is a member of the object class. The object class is the top of Java's
class hierarchy and the parent of everything. A class should override the finalize method to
perform any finalization necessary for objects of that type. Note that Rectangle's finalize
method calls super.finalize to give the parent class a chance for final cleanup as well.
Generally speaking, a finalize method should call super.finalize as the last thing it does.
You can read more in Writing a finalize Method.

4.4 Creating Classes

Now that we've covered how to create, use, and destroy objects, it's time to show you how to
write the classes from which objects are created. This section shows you the main components of
a class through a small example that implements a last-in-first-out (LIFO) stack. The following
diagram lists the class and identifies the structure of the code.

Training Cycle 4 33
Wintech Computers
JAVA 2

Class Declaration Class Body

public class Stack

Variable * prtm vkter Msmi


Constructor
w -f

Methods

m>>jtw

ff'{tjriiis.&tt()' * *)- , -

- return false;

protected vsrld ffwfltwO throws Thrombi {


Cleanup
itte nulls
$u$r.final *3*Q;
r

This implementation of a stack uses another object, a vector, to store its elements, vector is a
growable array of objects and does a nice job of allocating space for new objects, as space is
required. The stack class makes use of this code by using a vector to store its elements.
However, it imposes LIFO restrictions onthe vector- that is, you can only add elements to and
remove elements from the top of the stack.

The Class Declaration


The previous diagram shows that two primary components make up the implementation of a
class: the class declaration and the class body. The class declaration declares the name of the
class along with other attributes. The class declaration for the stack class is fairly simple and
indicates that the class is public and that its name is stack. Often, a minimal class declaration
such as this one is all you'll need.

Training Cycle 4 34
Wintech Computers JAVA 2

However, the class declaration can say more about the class, such as the name of the superclass
and if it can be subclassed.

The Class Body


The class body follows the class declaration and is embedded within curly braces {and}. The
class body contains declarations for all instance variables and class variables (known collectively
as member variables) for the class. In addition, the class body contains declarations and
implementations for all instance methods and class methods (known collectively as methods) for
the class.

Providing Constructors for Your Classes


A class may contain one or more constructors that provide for the initialization of an object
created from the class. This method shows you how to write a constructor

Declaring Member Variables


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

classDeclaration
i
member variable declarations
method declarations
)

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

Implementing Methods
As you know, objects have behavior that is implemented by its methods. Other objects can ask
an object to do something by invoking its methods. This section tells you everything you need to
know about writing methods for your Java classes. For more information about how to call
methods see Using Objects

In Java, you define a class's methods in the body ofthe class for which the method implements
some behavior Typically, you declare a class's methods after its variables in the class body
although this is not required

Controlling Access to Members of a Class


Member variables and methods are known collectively as members When you declare a member
of a Java class, you can allow or disallow other objects of other types access to that member
through the use of access specifiers

Understanding Instance and Class Members


A lava class can contain two different types of members instance members and class members
This page shows you how to declare both types of rnembeis and how to use them

Training Cycle 4
Wintech Computers JAVA 2

Writing a finalize Method


The finalize method is a special method, declared in the object class that allows a class to
provide for the clean up of objects of that type.

4.4.1 The Class Declaration

The left side of the following diagram shows the possible components of a class declaration in
the order they should or must appear in your class declaration. The rigrif side describes their
purposes. The required components are the class keyword and the class name and are shown in
bold. All the other components are optional, and each appears on a line by itself (thus "extends
super" is a single component). Italics indicate an identifier such as the name of a class or
interface. If you do not explicitly declare the optional items, the Java compiler assumes certain

pu&Tic Class Is publicly accessible.


abstract Class cannot be instantiated

final Class cannot be subclassed.


class tiameOfClass Name of the Class.

extends 5uper Superclass of the class.


implements Interfaces Interfaces implemented by the class.
{
OassBody

defaults: a nonpublic, nonabstract, nonfinal subclass of Object that implements no interfaces.

The following list provides a few more details about each class declaration component. It also
provides references to sections later in this trail that talk about what each component means, how
to use each, and how it affects your class, other classes, and your Java program.

public

By default, a class can be used only by other classes in the same package. The public modifier
declares that the class can be used by any class regardless of its package. Look in Creating and
Using Packages for more information about how to use public to limit access to your classes and
how it affects your access to other classes.

abstract

Declares that the class cannot be instantiated. For a discussion about when abstract classes are
appropriate and how to write them, see Writing Abstract Classes and Methods.

final

Declares that the class cannot be subclassed. Writing Final Classes and Methods shows you how
to use final and discusses the reasons for using it.

36
Training Cycle 4
Wintech Computers JAVA 2

class NazaeOfClass

The class keyword indicates to the compiler that this is a class declaration and that the name of
the class is NameOfClass.

extends Sqpex

The extends clause identifies super as the superclass of the class, thereby inserting the class
within the class hierarchy. Reality Break! The Spot Applet in this lesson shows you a subclass of
Applet and talks briefly about the responsibilities and benefits of subclasses. Managing
Inheritance in the next lesson goes into further detail on this subject.

implements Interface*

To declare that your class implements one or more interfaces, use the keyword implements
followed by a comma-delimited list of the names of the interfaces implemented by the class.
Implementing an Interface explains how the spot applet implements an interface. Details about
writing your own interfaces can be found in Creating Interfaces.

4.4.2 The Class Body


The class body contains all of the code that provides for the life cycle of the objects created from
it: constructors for initializing new objects, declarations for the variables that provide the state of
the class and its objects, methods to implement the behavior of the class and its objects, and
when necessary, a finalize method to provide for cleaning up an object after it has done itsjob.
Variables and methods collectively are called members.
\\TArr^jv\v\vir\*Aai^rLarfvrvvv^"rv^v^^v^vvTVvvv"g^^ri ^*i*i**i*i*r*i?'^*iTir"77^7 " t ?"?* W?TT""""?"TTT*"*f"

Note: Constructors are not methods. Nor are they members.

The stack class defines one member variable in its body to contain its elements-the -items
Vector. It also defines one^constructorthe default constructor-and four methods: push, pop,
isEmpty, and finalize. Recall that finalize is a special method that provides for the clean up
of stack objects.

Providing Constructors for Your Classes


All Java classes have constructors that are used to initialize a new object of that type. A
constructor has the same name as the class. For example, the name of the stack class's
constructor is stack, the name of the Rectangle class's constructor is Rectangle, and the name
of the Thread class's constructor is Thread, stack defines a single constructor.

public Stack()
{
items = new Vector(lO);
}

Training Cycle 4 37
Wintech Computers JAVA 1

Java supports name overloading for constructors so that a class can have any number of
constructors all of which have the same name Following is another constructor that could be
defined by stack This particular constructor sets the initial size of the stack according to its
parameter
public Stack(int initialsize)
{
items = new Vector(initialsize);
}
Both constructors share the same name, stack, but they have different parameter lists. The
compiler differentiates these constructors based on the number of parameters in the list and their
types.
Typically, a constructor uses its arguments to initialize the new object's state. When creating an
object, choose the constructor whose arguments best reflect how you want to initialize the new
object
Based on the number and type ofthe arguments that you pass into the constructor, the compiler
can determine which constructor to use The compiler knows that when you write the following
code, it should use the constructor that requires a single integer argument:
new Stack(10);

Similarly, when you write the following code, the compiler chooses the default constructor:
new Stack ( i ;

When writing your own class, you don't have to provide constructors for it. The default
constructor is automatically provided by the runtime system for any class that contains no
constructors The default provided by the runtime system doesn't do anything So, if you
want to perform some initialization, you will have to write some constructors for your class.
The constructor for the following subclass of Thread performs animation, sets up some default
values, such as the frame speed and the number of images, and then loads the images:
class AnimationThread extends Thread
{
int fraraesPerSecond;
int numlmages;
Image[] images;

Anirnat ionThread (int fps, int num)


{
super("AnimationThread");
this.framesPerSecond = fps;
this.numlmages = num;

this.images - new Image[numlmages];


for (int i = 0; i <= numlmages; i+ f)
{ -
// Load all the images.

training Cycle 4 38
Wintech Computers JAVA 2

Note how the body of a constructor is like the body of a method; that is, it contains local
variable declarations, loops, and other statements. However, one line in the
AnimationThread constructorthat you wouldn't see in a method is the second line:

super("AnimationThread");

This line invokes a constructor provided by the superclass of AnimationThread, namely,


Thread. This particular Thread constructor takes a string that sets the name of Thread.
Often a constructor wants to take advantage of initialization code written in a class's
superclass. Indeed, some classes must call their superclass constructor in order for the object
to work properly. If present, the superclass constructor must be the first statement in the
subclass's constructor: An object should perform the higher-level initialization first.
When declaring constructors for your class, use the following access specifiers in the constructor
declaration to specify what other objects can create instances of your class:

private

No other class can instantiate your class. Your class may contain public class methods
(sometimes called factory methods), and those methods can construct an object and return it,
but no other classes can.

protected

Only subclasses of your class can create instances of it.


public

Any class can create an instance of your class.

package

Only classes within the same package as your class can construct an instance of it.
Constructors provide a way to initialize a new object. Initializing Instance and Class
Members describes other ways you can provide for the initialization of your class and a
new object created from the class. That section also discusses when and why you would
use each technique.

Declaring Member Variables

stack uses the following line of code to define its single member variable:
private Vector items;

This declares a member variable and not some other type of variable (like a local variable)
because the declaration appears within the class body but outside of any methods or constructors.
The member variable declared is named items, and its data type is Vector. Also, the private
keyword identifies items as a private member. This means that only code within the stack class
can access it.

Training Cycle 4 ,9
Wintech Computers JAVA 2

This is a relatively simple member variable declaration, but declarations can be more complex.
You can specify not only type, name, and access level, but also other attributes, including
whether the variable is a class or instance variable and whether it's a constant. Each component
of a member variable declaration is further defined below:
AccessLevel

Lets you control which other classes have access to a member variable by using one of four
access levels, public, protected, package, and private. You control access to methods in the same
way. Controlling Access to Members of a Class covers access levels in detail.
static

Declares this is a class variable rather than an instance variable. You also use static to declare
class methods Understanding Instance and Class Members later in this lesson talks about
declaring instance and class variables.

final

Indicates that the value of this member cannot change. The following variable declaration
defines a constant named avogadro, whose value is Avogadro's number (6.023 % 1023) and
cannot be changed:

final double AVOGADRO = 6.023e23;

It's a compile-time error if your program ever tries to change a final variable. Byconvention, the
name of constant values is spelled in uppercase letters.
transient

The transient marker is not fully specified by The Java Language Specification but is used in
object serialization which is covered in Object Serialization to mark member variables that
should not be serialized.

volatile

The volatile keyword is used to prevent the compiler from performing certain optimizations on
a member This is an advanced Java feature, used by only a few Java programmers, and is
outside the scope of this tutorial
type
Like other variables, a member variable must have a type. You can use primitive type names
such as int, float, or boolean. Or you- can use reference types, such as array, object, or
interface names

name

A member variable's name can be any legal Java identifier and, by convention, begins with a
lowercase letter You cannot declare more than one member variable with the same name in the
same class, but a subclass can hide a member variable of the same name in its superclass.

Training Cycle 4 40
Wintech Computers JAVA 2

Additionally, a member variable and a method can have the same name. For example, the
following code is legal:
public class Stack
{
private Vector items;
// a method with same name as a member variable
public Vector items()

4.5 Implementing Methods

This figure shows the code for stack's push method. This method pushes an object, the one
passed in as an argument, onto the top of the stack, and returns it.
Fig-

Method
Declaration public Object push(Object item)

Method Body

II

Like a class, a method has two major parts: method declaration and method body. The method
declaration defines all of the method's attributes, such as access level, return type, name, and
arguments, as illustrated here
Fig:
Access Return Method
Arguments
Level Type Name
viame /

1pufelic 0&;jct pttsh<Gbject tti)

The method body is where all the action takes place. It contains the Java instructions that
implement the method.

The Method Declaration


At minimum, a method declaration has a name and a return type indicating the data type ofthe
value returned by the method:

re t urn Type meth odName ()

Training Cycle 4
41
Wintech Computers JAVA 2

This method declaration is very basic. Methods have many other attributes such as arguments,
access control, and so on. This section will cover these topics as well as expand upon the features
illustrated in the method declaration above.

Passing Information into a Method


Perhaps the most commonly used optional component of a method declaration are method
parameters. Similar to functions in other programming languages, Java methods accept input
from the caller through its parameters. Parameters provide information to the method from
outside the scope of the method.

The Method Body


The method body is where all of the action of a method takes place; the method body contains all
of the legal Java instructions that implement the method.

4.5.1 Details of a Method Declaration

A method's declaration provides a lot of information about the method to the Compiler, to the
runtime system, and to other classes and objects. Included is not only the name of the method,
but also such information as the return type of the method, the number and type of the arguments
required by the method, and which other classes and objects can call the method.

While this may sound like writing a novel rather than simply declaring a method, most method
attributes can be declared implicitly. The only required elements of a method declaration are the
method's name, its return type, and a pair of parentheses (). This figure shows the elements of a
method declaration.

*ece$UV*J <Mm$ levelft*warned.


static This is a class method

abstract This method *s not implemented.


final Method cannot be overridden

rtativa Methpd^implemeritea Inanotherfanguajj*.


synchronized Method requires a monitor to run.
retarnType n&toOiBm The return type and method name.
{ paraalist ) The list of arguments
throws xc$pfcf&,....!. The excep^Gnsthrey^MtftismeihQ^^

Each element of a method declaration is further defined below:


accessLevel

Training Cycle 4 42
Wintech Computers JAVA 2

As with member variables, you control which other classes have access to a method using one of
four access levels: public, protected, package, and private. Controlling Access to Members of a
Class covers access levels in detail.

static

As with member variables, static declares this method as a class method rather than an instance
method. Understanding Instance and Class Members talks about declaring instance and class
methods.

abstract

An abstract method has no implementation and must be a member of an abstract class. Refer to
Writing Abstract Classes and Methods for information about why you might want to write an
abstract method and how such methods affect subclasses.

final

A final method cannot be overridden by subclasses. Writing Final Classes and Methods discusses
why you might want to write final methods, how they affect subclasses, and whether you might
want to write a final class instead.

native

If you have a significant library of functions written in another language such as C, you may
wish to preserve that investment and use those functions from Java. Methods implemented in a
language other than Java are called native methods and are declared as such using the native
keyword.

synchronized

Concurrently running threads often invoke methods that operate on the same data. These
methods may be declared synchronized to ensure that the threads access information in a thread-
safe manner. Synchronizing method calls is covered in Doing Two or More Tasks at Once:
Threads. Take particular note of the section entitled Synchronizing Threads.

reiurnType
Java requires that a method declare the data type of the value that it returns. If your method does
not return a value, use the keyword void for the return type. Returning a Value from a Method
talks about the issues related to returning values from a method.

methodName

A method name can be any legal Java identifier. You need to consider several issues in regards
to Java method names. These are covered in Method Names.
( paramlist )

Training Cycle 4 ...


Wintech Computers JAVA 2

You pass information into a method through its arguments. See this in the next section,
[throws exceptions]

If your method throws any checked exceptions, your method declaration must indicate the type
of those exceptions.

4.5.2 Returning a Value from a Method


You declare a method's return type in its method declaration. Within the body of the method, you
use the return operator to return the value. Any method that is not declared void must contain a
return statement. The stack class declares the isEmpty method, which returns a boolean:

public boolean isEmpty()


(
if (items.size() == 0)
return true;
else
return false;
)

The data type of the return value must match the method's return type, you can't return an
object type from a method declared to return an integer The isEmpty method returns either the
boolean value true or false, depending on the outcome of a test. A compiler error results if you
try to write a method in which the return value doesn't match the return type

The isEmpty method returns a primitive type. Methods also can return a reference type For
example, stack declares the pop method that returns the object reference type
public synchronized Object pop()
{
int len = items.size();
Object obj = null;
if (len == 0)
throw new EmptyStackException();
obj = items.elementAt(len - 1);
items.removeElementAt(len - 1) ;
return obj;
}
When a method returns an object such as pop does, the class of the returned object must be either
a subclass of or the exact class of the return type This can be a source of confusion, so let's look
at this more closely. Suppose you have a class hierarchy where imaginaryNumber is a subclass
of java. lang. Number, which is, in turn, a subclass of Object

Now suppose you have a method declared to return a Number:

public Number returnANumber() (

Training Cycle 4 "*4


Wintech Computers JAVA 2

The returnANumber method Can return an ImaginaryNumber but not an Object


ImaginaryNumber "is a" Number because it's a subclass of Number However, an Object is not
necessarily a Numberit could be a string or some other type You also can use interface names
as return types In this case, the object returned must implement the specified interface

4.5.3 A Method's Name


Java supports method name overloading so that multiple methods can share the same name For
example, suppose you are writing a class that can render various types of data (strings, integers,
and so on) to its drawing area You need to write a method that knows how to render each data
type In other languages, you have to think of a new name for each method, for example,
drawstring, drawinteger, drawFioat, and so on. In Java, you can use the same name for all of
the drawing methods but pass a different type of parameter to each method So, in your data
rendering class, you can declare three methods named draw, each of which takes a different type
of para meter

class DataBenderer
(
void draw(String s)
i

void draw'1nt i)

void draw(lloat f]

Overloaded methods are differentiated by the number and type of the arguments passed into the
method In the code sample, drawtstring s) anddrawiint i) are distinct and unique methods
because they require different argument types You cannot declare more than one method with
the same name and the same number and type of arguments because the compiler cannot
differentiate them. So, draw(string s) and drawtstring t) are identical and result in a
compiler error
A class may override a method in its superclass The overriding method must have the same
name, return type, and parameter list as the method it overrides

4.5.4 Passing Information into a Method


When vou write your method, you declare the number and type of the arguments required by that
method You declaie the type and name for each argument in the method signature For example,
the following is a method that computes the monthly payments for a home loan based on the
amount of the loan, the interest rate, the length of the loan (the number of periods), and the future
value of the loan (presumably the future value of the loan is zero because at the end of the loan,
you've paid it off):

Training Cycle 4
Wintech Computers JAVA 2

double computePayment(double loanAmt, double rate, double


futureValue, int numPeriods)
(

double I, partiall, denominator, answer;

I = rate / 1 0 U .0 ;
partiall = Math.pcw((l + I), (0.0 - numPeriods));
denominator = (1 - partiall) / I;
answer = ((-1 * loanAmt) / denominator)
- ((futureValue * partiall) / denominator);
return answer;
I

This method takes four arguments: the loan amount, the interest rate, the future value and the
number of periods The first three are double-precision floating-point numbers, and the fourth is
an integer

As with this method, the set of arguments to any method is a comma-delimited list of variable
declarations where each variable declaration is a type/name pair:
type name

As you can see from the body of the computePayment method, you simply use the argument
name to refer to the argument's value

Argument Types
In Java, you can pass an argument of any valid Java data type into a method This includes
primitive data types such as doubles, floats and integers as you saw in the computePayment
method, and reference data types such as objects and arrays. Here's an example of a constructor
that accepts an array as an argument. In this example, the constructor initializes a new Polygon
object from a list of Points (Point is a class that represents an x, y coordinate):

Polygon polygonFrom(Point[] listOfPoints)

Unlike some other languages, you cannot pass methods into Java methods But you can pass an
object into a method and then invoke the object's methods.

Argument Names
When you declare an argument to a Java method, you provide a name for that argument. This
name is used within the method body to refer to the item

A method argument can have the same name as one of the class's member variables. If this is the
case, then the argument is said to hide the member variable. Arguments that hide member
variables are often used in constructors to initialize a class. For example, take the following
circle class and its constructor

Training Cycle 4 46
IAVA 2
Wintech Computers JAVA *

class Circle
{
int x, y, radius;
public Circle(int x, int y; int radius)
{

}
}

The circle class has three member variables: x, y and radius. In addition, the constructor for
the circle class accepts three arguments each of which shares its name with the member
variable for which the argument provides an initial value.

The argument names hide the member variables. So using x, y or radius within the body of the
constructor refers to the argument, not to the member variable. To access the member variable,
you must reference it through thisthe currentobject:

class Circle
{
int x, y, radius;
public Circle(int x, int y, int radius)
{
this.x = x;
this.y = y;
this.radius = radius;
}
}

Names of method arguments cannot be the same as another argument name for the same method,
the name of any variable local to the method, or the name of.any parameter to a catch clause
within the same method.

Pass by Value
In Java methods, arguments artpassed by value. When invoked, the method receives the value
of the variable passed in. When the argument is of primitive type, pass-by-value means that the
method cannot change its value. When the argument is of reference type, pass-by-value means
that the method cannot change the object reference, but can invoke the object's methods and
modify the accessible variables within the object.

This is often the source of confusion-a programmer writes a method that attempts to modify the
value of one its arguments and the method doesn't work as expected. Let's look at such method
and then investigate how to change it so that it does what the programmer originally intended.

Consider this series of Java statements, which attempts to retrieve the current color of a Pen
object in a graphics application:

Training Cycle 4 47
Wintech Computers JAVA 2

int r = -1, g = -l, b = rl;


pen.getRGBCoior(r, g, b);
System.out.println("red = " + r + ", green = " + g +
", blue = " + b) ;

At the time when the getRGBCoior method is called, the variables r, g, and b all have the value -
1. The caller is expecting the getRGBCoior method to pass back the red, green and blue values of
the current color in the r, g, and b variables.

However, the Java runtime passes the variables' values (-l) into the getRGBCoior method; not a
reference to the r, g, and b variables. So you could visualize the call to getRGBCoior like this:
getRGBCoior(-1, -1, -1).
1

When control passes into the getRGBCoior method, the arguments come into scope (get
allocated) and are initialized to the value passed into the method:
class Pen

{
int redValue, greenValue, blueValue;
void getRGBCoior(int red, int green, int blue)
{
// red, green, and blue have been created
// and their values are -1

So getRGBCoior gets access to the values of r, g, and b in the caller through its arguments red,
green, and blue, respectively. The method gets its own. copy of the values to use within the
scope of the method. Any changes made to those local copies are not reflected in the original
variables from the caller.

Now, let's look at the implementation of getRGBCoior within the Pen class that the method
signature above implies:

class Pen
{
int redValue, greenValue, blueValue;

// this method does not work as intended


void getRGBCoior(int red, int green, int blue)
{
red = redValue;
green = greenValue;
blue = blueValue;
}

Training Cycle 4 48
Wintech Computers JAVA 2

This method will not work as intended. When control gets to the println statement in the
following code, which was shown previously, getRGBCoior's arguments, red: green, and blue,
no longer exist. Therefore the assignments made to them within the method had no effect; r, g,
and b are all still equal to -l.

int r = -1, g = -1, b = -1;


pen.getRGBCoior(r, g, b);
System.out.println("red = " + r + ", green = II

", blue = " + b);

Passing variables by value affords the programmer some safety: Methods cannot unintentionally
modify a variable that is outside of its scope. However, you often want a method to be able to
modify one or more of its arguments. The getRGBCoior method is a case in point The caller
wants the method to return three values through its arguments. However, the method cannot
modify its arguments, and, furthermore, a method can only return one value through its return
value So, how can a method return more than one value, or have an effect (modify some value)
outside of its scope?

For a method to modify an argument, it must be of a reference type such as an object or array
Objects and arrays are also passed by value, but the value of an object is a reference So the
effect is that arguments of reference types are passed in by reference Hence the name A
reference to an object is the address ofthe object in memory. Now, the argument in the method is
referring to the same memory location as the caller.

Let's rewrite the getRGBCoior method so that it actually does what you want First, you must
introduce a new type ofobject, RGBCoior, that can hold the red, green and blue values ofa color
in RGB space:

class RGBCoior
I
public int red, green, blue;
)

Now, we can rewrite getRGBCoior so that it accepts an RGBCoior object as an argument The
getRGBCoior method returns the current color of the pen by setting the red, green and blue
member variables of its RGBCoior argument
class Pen
{
int redValue, greenValue, blueValue;
void getRGBCoior(RGBCoior aColor)
{
aColor.red = redValue;
aColor.green = greenValue;
aColor.blue = blueValue;

Training Cycle 4
49
Wintech Computers
JAVA. 2

And finally, let's rewrite the calling sequence:

RGBCoior penCoior = new RGBCoior();


pen.getRGBCoior(penCoior) ;
System.out.println("red = " + penCoior.red + " green
= " +

penCoior.green + ",
blue = " + penCoior.blue);

The modifications made to the RGBCoior object within the getRGBCoior method affect the
object created in the calling sequence because the names penCoior (in the calling sequence) and
a color (in the getRGBCoior method) refer to the same object.

4.5.5 The Method Body

In the code sample that follows, the method bodies for the isEmpty and pop methods are shown
in bold:

class Stack {
static final int STACK_EMPTY = -1;
Object[] stackelements;
int topelement = STACK_EMPTY;

boolean isEmpty() (
if (topelement == STACK_EMPTY)
return true;
else
return false;
1
Object pop() (
if (topelement == STACK_EMPTY)
return null;
else (
return stackelements[topelement];
1

Besides regular Java language elements, you can use this in the method body to refer to
members in the current object. The current object is the object whose method is being called.
You can also use super to refer to members in the superclass that the current object has hidden
or overridden. Also, a method body may contain declarations for variables that are local tp that
method.

this

Training Cycle 4 50
Wintech Computers JAVA 2

Typically, within an object's method body you can just refer directly to the object's member
variables However, sometimes you need to disambiguate the member variable name if one of
the arguments to the method has the same name.
For example, the following constructor for the HSBCoior class initializes some of an object's
member variables according to the arguments passed into the constructor. Each argument to the
constructor has the same name as the object's member variable whose initial value the argument
contains

class HSBCoior
{
int hue, saturation, brightness;
HSBCoior (int hue, int saturation, int brightness)
(
this.hue = hue;
this.saturation = saturation;
this.brightness = brightness;

You must use this in this constructor because you have to disambiguate the argument hue from
the member variable hue (and so on with the other arguments). Writing hue = hue; makes no
sense. Argument names take precedence and hide member variables with the same name. So to
refer to the member variable you must do sothrough the current object~this~explicitly.

Some programmers prefer to always use this when referring to a member variable ofthe object
whose method the reference appears. Doing so makes the intent of the code explicit and reduces
errors based on name sharing.

You can also use this to call one of the current object's methods. Again this is only necessary if
there is some ambiguity in the method name and is often used to make the intent of the code
clearer

super "

If your method hides one of its superclass's member variables, your method can refer to the
hidden variable through the use of super Similarly, if your method overrides one of its
superclass's methods, your method can invoke the overriden method throught the use of super
Consider this class:
class AsillyClass
(
boolean aVariable;
void aMethodf)
(
aVariable = true;

and its subclass which hides aVariable and overrides aMethod:

Training Cycle 4 51
Wintech Computers JAVA 2

class ASillierClass extends ASillyClass


{
boolean aVariable;
void aMethod()
I
aVariable = false;
super.aMethod();
System.out.ptintln(aVariable);
System.out.println(super.aVariable);
)

First aMethod sets aVariable (the one declared in ASillierClass that hides the one declared in
ASillyClass) to false. Next aMethod invoked its overriden method with this statement:
super.aMethod();

This sets the hidden version ofthe aVariable (the one declared in ASillyClass) to true. Then
aMethod displays both versions ofaVariable which have different values:

false
true

Local Variables
Within the body of the method you can declare more variables for use within that method. These
variables are local variables and live only while control remains within the method. This method
declares a local variable i that it uses to iterate overthe elements of its array argument
Object findObjectInArray(Object o, Object(] arrayOfObjects)
<
int i; // local variable
for (i = 0; 1 < arrayOfObjects.length; i++)
i

if (arrayOfObjects[ij -- c)
return o;
I
return null;
)
After this method returns, i no longer exists

4.5.6 Controlling Access to Members of a Class

One of the benefits of classes is that classes can protect their member variables and methods
from access by other objects Why is this important? Well, consider this You're writing a class
that represents a query on a database that contains all kinds of secret information; say employee
records or income statements for your startup company

Certain information and queries contained in the class, the ones supported by the publicly
accessible methods and variables in your query object, are OK for the consumption of any other
object in the system. Other queries contained in the class are there simply for the personal use of
the class. They support the operation of the class but should not be used by objects of another

Training Cycle 4 52
JAVA 2
Wintech Computers

type-you've got secret information to protect. You'd like to be able to protect these personal
variables and methods at the language level and disallow access by objects ofanother type
In Java, you can use access specifiers to protect both a class's variables and its methods when
you declare them. The Java language supports four distinct access levels for member variables
and methods: private, protected, public, and, ifleft unspecified, package.
The following chart shows the access level permitted by each specifier

Specifier class subclass package world

Private X
Protected X X* X
Public X X X X

Package X X

The first column indicates whether the class itself has access to the member defined by the
access specifier As you can see, a class always has access to its own members. The second
column indicates whether subclasses of the class (regardless of which package they are in) have
access to the member The third column indicates whether classes in the same package as the
class (regardless of their parentage) have access to the member The fourth column indicates
whether all classes have access to the member

Let's look at each access level in more detail

Private
The most restrictive access level is private A private member is accessible only to the class in
which it is defined Use this access to declare members that should only be used by the class.
This includes variables that contain information that if accessed by an outsider could put the
object in an inconsistent state, or methods that, if invoked by an outsider, could jeopardize the
state of the object or the program in which it's running Private members are like secrets you
never tell anybody

To declare a private member, use the private keyword in its declaration. The following class
contains one private member variable and one private method:
class Alpha
(
private int iamprivate;
private void privateMethod()
(
System.out.println("privateMethod");

Objects of type Alpha can inspect or modify the iamprivate variable and can invoke
privateMethod, but objects of other types cannot For example, the Beta class defined here:

Training Cycle 4 53
Wintech Computers .....
JAVA 2

class Beta
{
void accessMethodf)
1
Alpha a = new Alpha();
a.iamprivate = 10; // illegal
a.privateMethod(); // illegal

cannot access the iamprivate variable or invoke privateMethod on an object of type Alpha
because Beta is not of type Alpha.

When one of your classes is attempting to access a member varible to which it does not have
access, the compiler prints an error message similar to the following and refuses to compile your
program:

Beta.Java:9: Variable iamprivate in class Alpha not


accessible from class Beta.
a.iamprivate = 10; // illegal

1 error

Also, ifyour program is attempting to access a method to which it does not have access, you will
see a compiler error like this:

Beta.Java:12: No method matching privateMethod() found in


class Alpha.
a.privateMethod(); // illegal
1 error

New Java programmers might ask if one Alpha object can access the private members of another
Alpha object. This is illustrated by the following example. Suppose the Alpha class contained an
instance method that compared the current Alpha object (this) to another object based on their
iamprivate variables:

class Alpha
{
private int iamprivate;
boolean isEqualTo(Alpha anotherAlpha)
(
if (this.iamprivate == anotherAlpha.iamprivate)
return true;
else
return false;
)
)
This is perfectly legal Objects of the same type have access to one another's private members.
This is because access restrictions apply at the class or type level (all instances of a class) rather
than at the object level (this particular instance of a class).

Note this is a Java language keyword that refers to the current object. For more information
about how to use this see The Method Body.

Training Cycle 4 54
Wintech Computers JAVA 2

Protected
The next access level specifier is protected, which allows the class itself, subclasses (with the
caveat that we referred to earlier), and all classes in the same package to access the members.
Use the protected access level when it's appropriate for a class's subclasses to have access to the
member, but not unrelated classes. Protected members are like family secrets-you don't mind if
the whole family knows, and even a few trusted friends but you wouldn't want any outsiders to
know.

To declare a protected member, use the keyword protected. First, let's look at how the
protected specifier affects access for classes in the same package. Consider this version of the
Alpha class which is now declared to be within a package named Greek and which has one
protected member variable and one protected method declared in it:
package Greek;

class Alpha
{
protected int iamprotected;
protected void protectedMethod()
(
System.out.println("protectedMethod");
)
)

Now, suppose that the class Gamma was also declared to be a member of the Greek package (and
is not a subclass of Alpha). The Gamma class Can legally access an Alpha object's iamprotected
member variable and can legally invoke its protectedMethod:
package Greek;
<3>
class Gamma
{
void accessMethod))
{
Alpha a = new Alpha();
a.iamprotected = 10; // legal
a.protectedMethod)); // legal
)

That's pretty straightforward. Now, let's investigate how the protected specifier affects access
for subclasses ofAlpha.

Let's introduce a new class, Delta, that derives from Alpha but lives in a different package-
Latin. The Delta class can access both iamprotected and protectedMethod, but only on
objects of type Delta or its subclasses. The Delta class cannot access iamprotected or
protectedMethod on objects of type Alpha. accessMethod in the following code sample
attempts to access the iamprotected member variable on an object of type Alpha, which is
illegal, and on an object of type Delta, which is legal. Similarly, accessMethod attempts to
invoke an Alpha object's protectedMethod which is also illegal:

Training Cycle 4
Wintech Computers JAVA 2

import Greek.*;

package Latin;

class Delta extends Alpha


(
void accessMethod(Alpha a, Delta d)

a.iamprotected = 10; // illegal


d.iamprotected = 10; // legal
a.protectedMethod(); // illegal
d.protectedMethodO ; // legal

If a class is both a subclass of and in the same package as the class with the protected member,
then the class has access to the protected member.

Public
The easiest access specifier is public. Any class, in any package, has access to aclass's public
members. Declare public members only ifsuch access cannot produce undesirable results ifan
outsider uses them. There are no personal or family secrets here; this is for stuff you don't mind
anybody else knowing.

To declare a public member, use the keyword public For example,


package Greek;

public class Alpha


I
public int iampublic;
public void publicMethod()
{
System.out.println("publicMethod");
)
)

Let's rewrite our Beta class one more time and put it in adifferent package than Alpha and make
sure that itis completely unrelated to (not a subclass of) Alpha:
import Greek.*;

package Roman;

class Beta

(
void accessMethod()
{
Alpha a = new Alpha();
a.iampublic =10; // legal
a.publicMethodO ; // legal

Training Cycle 4
Wintech Computers JAVA 2

}
As you can see from the above code snippet, Beta can legally inspect and modify the iampublic
variable in the Alpha class and can legally invoke publicMethod.

4.6 Packages

The package access level is what you get if you don't explicitly set a member's access to one of
the other levels. This access level allows classes in the same package as your class to access the
members. This level of access assumes that classes in the same package are trusted friends. This
level oftrust is like that which you extend to your closest friends but wouldn't trust even to your
familv.

For example, this version of the Alpha class declares a single package-access member variable
and a single package-access method. Alpha lives in the Greek package:
package Greek;

class Alpha
{
int iampackage;
void packageMethod()
{
System.out.println("packageMethod");
}

1he Alpha class has access both to iampackage and packageMethod. In addition, all the classes
declared within the same package as Alpha also have access to iampackage and
packageMethod. Suppose that both Alpha and Beta were declared as part of the Greek package:
package: Greek;

class Beta
{
void accessMethod!)
{
Alpha a = new Alpha();
a.iampackage = 10; // legal
a.packageMethod(); // legal

Beta can legally access iampackage and packageMethod.

irfaces

In English, an interface is adevice or system that unrelated entities use to interact. According to
his definition, a remoie control is an interface between you and a television set, the English
nS^s'n,"'!
milila T? Ibetween
yis the interface b8!Weenpeople
T ofPCOP,C- anJranks.
different ,hC PrfOCo1
Similarly,faJava
behavior enforced
interface *" the
is adevice
Training ( \cle 4
57
Wintech Computers JAVA 2

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

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

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


An interface can also include constant declarations

1 he syntax for the Interface is


interface!

// List abstract methods & Constants

Examp]e:
interface Collection
(
public static final int MAX=500;
public abstract void add ( Obiect ob);
public abstract int Current) );

Interfaces are used to

1 Define protocols for an abstract class without worrying about specific implementation
2. Capture similarities between unrelated classes without forcing aclass relationship
3. Declare methods that one or more are expected to implement
4 Provide security for applications

An interface can extend many interfaces, and also a class can implement any number of
interfaces An interface can be implemented in a class by using the keyword implements.

public class Abed extends Applet implements ActionListener

// Implementation of Interface

58
Training Cycle 4
Wintech Computers JAVA 2

Most often interfaces are used to bring about a relationship between different classes

Training Cycle 4
59
Training
Cycle: 5
Wintech Computers JAVA 2

5. Arrays and Strings

In this section you will study about arrays and Strings. Arrays we use for managing large amount
of same data, and String we use for storing sequence of characters.

5.1 Arrays

When you want to manage a large number of variables, you need to organize them in more
efficient manner. Declaring many variables, which are of the same type, is one way dealing with
them. Arrays provide an efficient alternate.
As for other variables, before you can use an array you must first declare it. Again, like other
variables, a declaration of an array has two primary components: the array's type and the array's
name. An array's type includes the data type of the elements contained within the array. For
example, the data type for an array that contained all integer elements is array of integers. You
cannot have a generic arraythe data type of its elements must be identified when the array is
declared. Here's a declaration for an array of integers:

int arrayOflnts;

The int [ ] part of the declaration indicates that arrayOflnts is an array of integers. The
declaration does not allocate any memory to contain the array elements.

If your program attempted to assign or access any values to any elements of arrayOflnts
before memory for it has been allocated the compiler will print an error like this one and refuse
to compile your program.

testing.Java:64: Variable arrayOflnts may not have been


initialized.

To allocate memory for the elements of the array, you must instantiate the array. You do this
using Java's new operator. (Actually, the steps you take to create an array are similar to the steps
you take to create an object from a class: declaration, instantiation, and initialization. You can
learn more about creating objects in the Creating Objects section of the next lesson.
The following statement allocates enough memory for arrayOflnts to contain ten
integer elements.

int[] arrayOflnts = new int[10]

In general, when creating an array, you use the new operator, plus the data type of the array
elements, plus the number of elements desired enclosed within square brackets ('[' and ']').

elementType[] arrayName = new elementType[arraySize]

Once you have allocated an array, you can access a specific element in the array by specifying its
index within square brackets. All array indexes start at zero. For example, this statement assigns
the value 28 to the second element of month days.

Training Cycle 5
60
Wintech Computers JAVA 2

Int month_days[];
month_days=new int[12];

Putting together all the pieces, here is a program that creates an array of
the number of days in each month.

class Array
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31j
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has + month days[3] +" days.

When you run this program, it prints the number ofdays in April. As mentioned, Java array
indexes start with zero, so the number of days in April is month_days[3] or 30

Output

C:\JCODE>java Array
April has 30 days.

Multidimensional Arrays
In Java, multidimensional arrays are actually arrays ofarrays. These as you might expect look
and act like regular multidimensional arrays. However, as you will see, there are acouple of
subtle differences. To declare a multidimensional array variable specify each additional index
using another setof square brackets.
int twoD[][] = new int[4][5];

This allocates 4 by 5 array and assigns it to twoD. Internally this mark is


implemented as an array of arrays of int.

61
Training Cycle 5
Wintech Computers JAVA 2

5.2 Strings

Asequence ofcharacter data is called a string and is implemented in the Java environment by the
string class (a member of the j ava. lang package).
Example:

String[] args;

This code explicitly declares an array named args that contains String objects. The empty
brackets indicate that the length of the array is unknown at compilation time because the array is
passed in at runtime.
string objects are immutable-that is, they cannot be changed once they've been created. The
java.lang package provides a different class, StringBuffer, which you can use to create
and manipulate character data on the fly. The string and StringBuffer Classes covers
thoroughly the use of both the String and StringBuffer classes.

5.2.2String

Creating a String
Many strings are created from string literals. When the compiler encounters a series of
characters enclosed in double quotes, it creates a string object whose value is the text that
appeared between the quotes. When the compiler encounters the following string literal, it
creates a string object whose value is Gobbledy gook.

"Gobbledy gook."

You can also create string objects as you would any other-Java object: using the new keyword.

new String("Gobbledy gook.");

Training Cycle 5 ,,
Wintech Computers JAVA 2

Constructors and Methods


String() Initializes a newly created String object so
that it represents an empty character
sequence.
String(byte[] bytes) Construct a new String by converting the
specified array of bytes using the platform's
default character encoding.
String(byte[] bytes, int offset, int length) Construct a new String by converting the
specified subarray of bytes using the
platform's default character encoding.
CharAt(int index) Returns the character at the specified index.

CompareTo(Object o) Compares this String to another Object.

Equals(Object anObject) Compares this string to the specified object.

indexOf( String str) Returns the index within this string of the
first occurrence of the specified substring.
LastIndexOf(int ch) Returns the index within this string of the last
occurrence of the specified character.
LengthO Returns the length of this string.

valueOf(Object obj) Returns the string representation of the


Object argument
Substring(int beginlndex) Returns a new string that is a substring of this
string.

The + concatenates two string, producing a String object as the result. This allows you to chain
together a series of + operations.

String age="9";
String s="He is " + age + " years old."
System.out.println(s);

One practical use ofstring concatenation is found when you are creating very long strings.
Instead of letting long strings wrap within your source code, you can break them into smaller
pieces, using the +to concatenate them. Here is an example.
// Using concatenation to prevent long lines.
class Concat
(
public static void main(String args[])
(
String longstr="This could have been " +
"a very long line that would w +
"wrapped around. But string concatenation " +
"prevents this. ";

System.out.println(longstr);

Training Cycle 5 63
JAVA 2
Wintech Computers

5.2.3String Buffers
StringBuffer, is used when you want to manipulate the contents of the string on the fly. So
when you wish to change the contents ofstring, you have to use StringBuffer class

Creating a StringBuffer
The constructor method used by reverselt to initialize the dest requires an integer argument
indicating the initial size of the new StringBuffer.

StringBuffer(int length)

reverselt could have used stringBuf f er's default constructor that leaves the buffer's length
undetermined until a later time. However, it's more efficient to specify the length of the buffer if
you know it, instead ofallocating more memory every time you append a character to the buffer.

Constructors and Methods


StringBufferO Constructs a string buffer with no characters
in it and an initial capacity of 16 characters.
StringBuffer(int length) Constructs a string buffer with no characters
in it and an initial capacity specified by the
length argument.
StringBuffer(String str) Constructs a string buffer so that it represents
the same sequence of characters as the string
argument; in other words, the initial contents
of the string buffer is a copy of the argument
string.
append(Object obj) Appends the string representation of the
Object argument to this string buffer.
charAt(int index) The specified character of the sequence
currently represented by the string buffer, as
indicated by the index argument, is returned.
insert(int index, char[] str, int offset, int len) Inserts the string representation of a subarray
of the str array argument into this string
buffer.
reverse() The character sequence contained in this
string buffer is replaced by the reverse of the
sequence.
setCharAt(int index, char ch) The character at the specified index of this
string buffer is set to ch.

Example: Below is given an example class which reverses a given string

Training Cycle 5 64
Wintech Computers JAVA 2

class ReverseString
(
public static String reverselt(String source)
(
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);
for (i = (len - 1); i >= 0; i)
(
dest.append(source.charAt(i));
}
return dest.toString();

Training Cycle 5 6?
Training
Cycle: 6
Wintech Computers JAVA 2

6. Exceptions

The term exception is shorthand for the phrase "exceptional event". It can be defined as
follows:

Definition: An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions.

Many kinds of error can cause exceptions ~ problems ranging from serious hardware
errors, such as a hard disk crash, to simple programming errors, such as trying to access
an out of - bounds array element. When such an error within a Java method, the method
creates an exception objects and hands it off to the runtime system. The exception object
contains information about the exception, including its type and the state of the program
when the error occurred. The runtime system is then responsible for finding some code to
handle the error .In Java terminology, creating an exception object and handing it to the
runtime system is called throwing an exception.

After a method throws an exception, the runtime system leaps into action to find someone
to handle the exception. The set of possible "someone" to handle the exception is the set
of method s in the call stack of the method where the error occurred. The runtime system
searches backwards through the call stack, Beginning with the method in which the error
occurred, until it finds a method that contains appropriate if the type of the exception
thrown is the same as the type of exception handled by the handler. Thus the exception
bubbles up through the call stack until an appropriate handler is found and one of the
calling methods handles the exception. The exception handler chosen is said to catch the
exception.

If the runtime system exhaustively searches all of the methods on the callstack without
finding an appropriate exception handler, the runtime system, and consequently the Java
program terminates.

By using exceptions to manage errors, Java programs have the following advantages over
traditional error management techniques:

Advantage 1 : Separating Error Handling Code from "Regular " Code

Advantage 2 : Propagating Errors Up the call stack

Advantage 3 : Grouping Error Types and Error Differentiation

6.1 Exception Handling

Java requires that a method either catches or specify all checked exceptions that can be
thrown within the scope of the method. This requirement has several components that

Training Cycle 6 66
Wintech Computers JAVA 2
Wintech Computers JAVA 2

Catch
A method can catch an exception by providing an exception handler for that type of
exception The next page. Dealing with Exceptions introduces an example program.
Talks about catching exceptions, and shows you how to write an exception handler for
the example program.

Specify
If a method chooses not to catch an exception, the method must specify that it can throw
that exception. Why did the Java designers make this requirement? Because any
exception that can be thrown by a method is really part of the method's public
programming interface: callers of a method must know about the exceptions that can
throw in order to intelligently and consciously decide what to do about those exceptions.
Thus, in the method signature you specify the exceptions that the method can throw.

Checked Exceptions
Java has different types of exceptions, including I/O exceptions, runtime exceptions, and
exceptions of your own creation, to name a few. Of interest to us in this discussion are
runtime exceptions. Runtime exceptions are those exceptions that occur within the Java
runtime system This includes arithmetic exceptions (such as when dividing by zero),
Pointer exceptions (such as trying to access an object through a null reference), and
indexing exceptions (such as attempting to access an array element through an index that
is too large or too small).

Runtime exception can anywhere in a program and in a typical program can be very
numerous. The cost of checking for runtime exceptions often exceeds the benefits of
catching or specifying them. Thus the compiler does not require that you catch or specify
runtime exceptions, although you can. Checked exceptions that are not runtime
exceptions and are checked by the compiler; the compiler checks that these exceptions
are caught or specified.

Some consider this a loophole in Java's exception handling mechanism, and programmers
are tempted to make all exceptions runtime exceptions. In general, this is not
recommended. Runtime exceptions ~ the Controversy contains a thorough discussion
about when and how to use runtime exceptions.

Exceptions that can be thrown within the scope of the method


The statement "exceptions that can be thrown within the scope of the method" may seem
obvious at first: just look for the throw statement. However, this statement includes more
than just the exception that can be thrown directly by the method, the key is in the phrase
within the scope of. This phrase includes any exception that can be thrown while the flow
of control remains within the method. This statement includes both.

Training Cycle 6 67
Wintech Computers JAVA 2

Exceptions that are thrown directly by the method with Java's throw
statement.

Exceptions that are thrown indirectly by the method through calls to other
methods

6.2 Catching and Handling Exceptions

The three sections that follow cover the three components of an exception handler ~ the
try, catch, and finally blocks They show you how to write an exception handler code
during various scenarios

class Excl
(
static void subroutine!)
{
int d = 0;
int a = 10 / d;
)
public static void mainfString args[]l
{
Excl . subrouti iit

The resulting stack trace from the default exception handler shows how the entire call
stack displayed:
Java.lang.ArithmeticExecption: / by zero
at Excl.subroutine(Excl.Java:4)
at Excl.main(Excl.Java:7)

6.3 try

Using try and catch


Although the default exception handler provided by the Java run-time system that is
useful for debugging, you will usually want to handle an exception yourself Doing so
provides two benefits First, it allows you to fix the error Second, it prevents the program
from automatically terminating Most users would be confused if your program stopped
running and printed a stack trace whenever an error occurred' Fortunately, it is quite easy
to prevent this.
To guard against and handle a run-time error, simpiy enclose the code that you want to
monitor inside a try block Immediately following the try biock, include a catch clause
that specifies the exception type that you wish to catch. To illustrate how easily this can
be done, the following program includes a try- block and a catch clause which processes
the ArithmeticException generated by the division-bv-zero error

68
Training Cycle 6
Wintech Computers JAVA 2

class Exc2
{
public static void main(String args[])
{
int d,a;
try
{
d=0;
a=42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero");
}
System.out.println("After catch statement.");
}
}
This program generates the following output

Division by zero
After catch statement

6.4 The Catch Block(s)

Diplaying a Description of an Exception


Throwable overrides the toString() methods (defined by Object) so that it returns a string
containing a description ofthe exception. You can display this description in a println()
statement by simply passing the exception as an argument. For example catch block in
the preceding program can be written like this:

catch(ArithmeticException e)
{
System.out.println("Exception: " + e);
A=0;
}

Output
Exception: Java.lang.ArithmeticException

While it is of no particular value in this context, the ability to display a description of an


exception is valuable in other circumstances - particularly when you are experimenting
with exceptions or when you are debugging.

Training CycJe 6 69
Wintech Computers JAVA 2

6.5 The finally Block

When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path
that alters the normal flow through the method. Depending upon how the method is
coded, it is even possible for an exception to cause the methods to return prematurely.
This could be a problem in some For example, if a method opens a file upon entry and
closes it upon exit, then you will not want the code that keywords is designed to address
this contingency.
finally creates a block of code that will be executed after a try/catch block has completed
and before the code following try / catch block. The finally block will execute whether or
not an exception is thrown. If an exception is thrown, the finally block will execute even
if no catch statement matches the exception. Any time a method is about to return to the
caller from inside a try/catch block, via an uncaught exception, or an explicit return
statement, the finally clause is also executed just before the method returns This can be
useful for closing file handles and freeing up any other resources that might have been
allocated at the beginning of a method with the intent of disposing of them before
returning. The finally clause is optional. However, each try statement requires at least one
catch or a finally clause.
Lets look at the overall framework for try, multiple catch blocks, and finally

try
(
//statement s
//some are safe, some might throw an exception
)
catch(SpcificException e)
I
//do something, perhaps try to recover
)
catch(OtherException e)
{
//handling for OtherException
)
catch(GeneralException e)
(
//handling for GeneralException
)
finally
(
//code that must he executed under
//successful or unsuccessful conditions
)
//more lines of method code..

If an exception occurs the corresponding catch block is executed After the catch block,
the finally block is executed.

The Throw Statement


Throwing an exception, in its most basic form is simple. You need to do two things First,
you create an instance of an object that is a subclass of java.lang Throwable Next you
use the throw keyword to actually throw the exception.

Training Cycle 6
Wintech Computers JAVA 2

The general form of throw is shown here:

throw Throwablelnstance

Here, Throwablelnstance must be an object of type Throwable or a subclass of


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

Here is a sample program that creates and throws an exception. The handler that catches
the exception rethrows it to the outer handler.

//Demonstrate throw

class ThrowDemo
(
static void demoproc()
(
try
(
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System, out. println("Caught inside deraoproc") ;
throw e;

public static void main(String args[])


{
try
(
demoproc() ;
)
catch(NullPointerException e)
(
System.out.println("Recaught: " + e);
)
)

Ouput

C:\JCODE>java ThrowDemo
Caught inside demoproc.

Training Cycle 6 71
Wintech Computers JAVA 2

Recaught: java.lang.NullPointerException: demo

The program gets two chances to deal with the same error First, main( ) sets up an
exception context and then calls demoproc( ). The demoproc then sets up another
exception-handling context and immediately throws a new instance of
NullPointerException. which is caught on the next line The exception is then rethrown.

72
Training Cycle 6
Training
Cycle: 7
Wintech Computers JAVA 2

7. Multithreading

Almost all the present day operating systems support multitasking and multithreading.
Java has multithreading built into it.

What is multitasking and multithreading?

7.1 Multitasking

It is the feature of an Operating System (OS) to run more than one program at a time.
For example you can have Word and Excel running simultaneously. There are two ways
multitasking is achieved.

a) Cooperative multitasking
b) Preemptive multitasking.

In a cooperative multitasking such as in Windows 3.1 or Mac OS each program passes


control to others after using up of its share of CPU's time slice. But if a program hogs the
CPU time and doesn't pass control to another task, then all other tasks have to wait for
their share of CPU's time.

In preemptive multitasking each program is given a certain amount of time with the
system and then the control is passed on to the next program. This ensures that each task
or thread gets an equal share of time on the system. Windows 95 is a preemptive
multitasking operating system.

7.2 Multithreading

7.2.1 What is a thread?


A thread is a flow of control within a program. Each computational unit is a thread. You
could have a thread for computing prime numbers in the background and a GUI can take
care of the user input for starting or stopping. In Java the garbage collection is itself a
thread to manage memory. Multithreading is having (running) multiple threads at the
same time. Actually each thread is given a time slot for execution after which control
passes over to next thread. This is not apparent to the user and for him it appears as if
each thread has a dedicated CPU for its execution. This is possible due to the much faster
CPU speeds. Another definition is that a thread is a separate flow of control within a
program.

The difference between multitasking and multithreading is that in multitasking you have
different processes executing at the same time, whereas in multithreading within a
program you have different tasks executing at the same time.

Training Cycle 7 74
Wintech Computers JAVA 2

7.2.2 Creating Threads


Java has a class called Thread from which you can create a class that can be
multithreaded. There are two ways to go about this.

1) Create a class that extends the Thread class or


2) Create a class that implements the Runnable interface.

We shall have a look at the first way that is using the Thread class.
class classname extends Thread
(
public void run ()
<
// Thread body of executions.
}
\

Sample Program 7.1: A simple program for a thread

import java.io.*;

class Runprimes
(
public static void main (String args[])throws Java.io.lOException
(
PrimeThread getPrimes = new PrimeThread ( );
getPrimes.start ( );
char ch;
while((ch = (char)System.in.read( ))=='\n')
getPrimes.stop ( );

class PrimeThread extends Thread


(
boolean keepRunning = true;

public void run ( )


I
int no= 3;
int mod = 0;
boolean flag = true; int count=0; int p=l;
while ( keepRunning )
(
for ( int i = 2; i < no; i++)
(
if ( ( mod = no * i ) == 0 )
(
flag = false-
break;

Training Cycle 7 75
Wintech Computers JAVA 2

if(flag )
1
if (p==D
{
System.out.println ( '1' );
System.out.println ( '2' );
P=2;
)

System.out.println ( no );
)

no++;
flag = true;
count++;
if ( count > 20000 )
keepRunning = false;
}
System.out.println ( "Thread Stopped ");
System.exit { 0 );
1
)

7.2.3 Methods of the Thread Class

Java.lang.Thread

public Thread ():


Constructs a new thread The thread must have a run method and a start method to
activate the run method.
public void run ():
This method which must be overridden should contain the code of the thread
should perform.
public void start ():
Starts the thread. This will cause the run () method to be called and return
immediately so that the thread runs concurrently.

public static void sleep (long millesecs)


The currently executing thread waits ( sleep ) for the specified time in
milliseconds and then permitting otherthreads to take over control.

public void interrupt ():


Sends an interrupt request to a thread.
public staticboolean interrupted ():
Returns whether or not athread has been interrupted

Training Cycle 7 76
Wintech Computers JAVA 2

7.3 Thread Properties

There are four states to a thread.

a) new
b) runnable
c) blocked
d) dead

a) new
A class that is a thread ( created by extending the Thread class) is constructed
with the new operator. This doesn't mean that the new thread is ready for
execution. It just means that the thread is being prepared (determination of
memory needed etc.) by the start () method.

b) runnable
A runnable thread which is ready for execution and is waiting for its turn to
execute. A thread is in this state once the start method is invoked. When the
thread actually begins to execute it is said to be running.

How and when a runnable begins running is dependent on the operating system.
Most of the OSs that perform time slicing give equal opportunities for the threads
to run.

c) blocked
A thread is in a blocked state when its execution is temporarily halted. This could
happen due to any of the four reasons given below.

i. sleep () method of the thread is called


ii. The suspend () method of the thread is called
iii. The thread calls the wait () method
iv. The thread calls an operation that is in turn blocking an 1/0 and which
will not return until the I/O operations are complete.

The thread can get back into runnable state if


i. The sleep period expires
ii Athread that has been suspended, resumes with the resume () method
iii. A thread that is waiting, is called by notify or notifyall
iv A thread is waiting for completion of I/O operations and if I/O
operation is completed.

When a thread is in a blocked state and is activated by a call that doesn't match,
then an illegalThreadStateException is thrown.

77
Training Cycle 7
Wintech Computers JAVA 2

d) Dead Threads
A thread is dead if it dies because the run method exits or is killed by its stop
method. When a thread is stopped, a ThreadDeath object is thrown. This object is
a child class of the Error class and so the user need not catch it.

Java.lang Thread

public final boolean isAlive ():


Returns true if the thread has started but not stopped.
public static void yield ():
yields the execution to the next runnable thread.
public final void suspend ():
The current thread Suspends thread execution
public final void resume ( ):
Resumes the thread and is valid only after suspend () has been invalid
public final void stop ():
Kills the thread.
public final void join ():
Waits until the thread dies.

Sample Program 7.2:


import java.awt.*;

public class Bounce extends Frame


f
private Canvas canvas;
public Bounce()
{
setTitle("Bounce Thread");
canvas = new Canvas( )
add ("Center", canvas)
Panel p = new Panel( )
p.add(new Button ("Start"));
p.add(new Button("Close"));
add("South", p);
)
public boolean handleEvent(Event e)
{
if(e.id == Event.WINDOW_DESTROY)
System.exit(0);
return super.handleEvent(e);
)
public boolean action (Event e, Object arg)
{
if(arg.equals("Start"))
{
Ball b = new Ball(canvas);

TrainingCycle 7 78
Wintech Computers JAVA 2

b.start) );
)
else
if ( arg.equals("Close"))
System.exit(0);
else return super.action(e, arg );
return true;
)
public static void main ( String [] args )
{
Frame f = new Bounce( );
f.resize ( 300, 200 );
f.show ( );
)
)
class Ball extends Thread
{
private Canvas box;
private static final int XSIZE = 10;
private static final int YSIZE = 10;
private int x=0;
private int y =0;
private int dx = 2;
private int dy =2;

public Ball(Canvas c)
(
box=c;
)
public void draw()
{
Graphics g = box.getGraphics();
g.fillOval ( x, y, XSIZE, YSIZE );
g.dispose ( );
)

public void move ( )


I
Graphics g =box.getGraphics( );
g.setXORMode ( box.getBackground ( ) );
g.fillOval ( x, y, XSIZE, YSIZE);
x+= dx;
y+= dy;
Dimension d = box.size();
if(x < 0)
(
x=0;
dx = -dx;
)

if ( x+XSIZE >= d.width)


{
x=d.width-XSIZE;
dx = -dx;
}

if(y <0)

79
Training Cycle 7
Wintech Computers JAVA 2

(
y=0;
dy=-dy;
)
if(y+YSIZE >=d.height)
{
y=d.height - YSIZE;
dy=-dy;
}
g.fillOval(x,y,XSIZE,YSIZE)
g.dispose();

public void run( )


f
draw() ;
for(int i=l;i<=1000; i++)
(
move();
try
(
sleep(500);.
)
catch ( InterruptedException e )

7.4 Thread Priorities

Every thread has a property called "priority" which determines the priority for its
execution. By default a thread inherits the priority of its parent thread. You can set the
priority of a thread from a range 1 to 10 using the setPriority method. There is a thread
scheduler which picks up the thread with the highest priority runs unless it yields (yield
method ), causes to be runnable or another higher priority thread interrupts it.

Given below are methods rehted priority of threads.

Java. lang. Thread

public final void setPriority (int newPriority):


Sets the priority for the thread. Where newPriority is an integerbetween 1
to 10.

Training Cycle 7 80
Wintech Computers JAVA 2

public final static int MIN PRIORITY.


This is the minimum priority a thread can have which is 1.

public final static int MAX PRIORITY:


The maximum priority a thread can have which is 10.

public final static int NORM_PRIORITY:


A default priority which is equal to 5.

7.4.1 Cooperating and Selfish Threads


A thread that doesn't allow other threads to execute by monopolizing the system is called
selfish thread. Others are cooperating threads. In time slicing operating systems such as
WIN 95, the OS interrupts to pass control to other tasks, so selfish threads don't have a
chance to hog the resources for long duration.
So you must design the threads in such a way that selfish threads are avoided by
preferably including yield() or sleep() in every loop.

7.4.2 Thread Groups


You can categorize threads into groups, so that you can have control over these related
threads with a single command or operation. For example, in an applet you have a ball
bouncing and also a timer that displays the seconds. These two cases can have separate
threads and can be grouped together so that both can be stopped with a single stop
command. This is achieved by using the ThreadGroup class.

Example: ThreadGroup tg = new ThreadGroup (stringname);

Java.lang.Thread

public ThreadGroup ( String name):


Creates a new ThreadGroup with its parent as the thread group of current thread,
name is the new thread group.

public ThreadGroup (ThreadGroup parent, String name)


Creates a new Thread Group, where Parent is a Parent of new ThreadGroup.

public int activeCount ()


Returns the maximum number of active threads in the group.

public final ThreadGroup getParent ()

Training Cycle 7 81
Wintech Computers JAVA 2

Returns the Threadgroup of this ThreadGroup.

public final void resume ()


Resumes all the Threads in the group including those of child threadgroups

public final void stop ( )


Stops all the Threads in the group including those of child threadgroups

public final void suspend()


Suspends all the Threads in the group including those of child threadgroups

7.5 Synchronization

A problem arises when different threads act upon a common object A thread could be
interrupted when it is attempting to modify an object, and then another Thread actually
modifies that particular object Consequently the first thread is made to run again, and
this time the object is modified once more This leads to errors, which must be prevented.
These type of problems can be avoided by the synchronized method With this method,
Java guarantees that the thread can finish execution before another thread as per the
priority can act upon same object

When an object with one or more synchronized methods are created, Java sets up a queue
of all the threads existing to act on the object When one thread completes, the highest
priority thread in the queue is given control

Any object with one or more synchronized methods is called a monitor. The monitor can
block threads and notify them when it becomes available

How Synchronization works

1) If a class has one or more synchronized methods, each object of the class
gets a queue that holds all the threads waiting to execute one of the
synchronized methods
2) A thread can get into a queue two ways
a) by calling the method while another thread using the object or
b) by calling the wait while using the object
3) We thread scheduler chooses the highest priority among those in the queue
4) When a synchronized method call returns or when a method calls wait,
another thread gets access to the object
5) If a thread is in a queue by a call to wait, then to activate it, a call to notify
must be made

Java lang Object

Training Cycle 7 g2
Wintech Computers JAVA 2

void notify ():


Notifies the threads waiting on the monitor object that the state of the
object has changed. This method must be called from within a
synchronized method otherwise an IllegalMonitorStateException is
thrown.

void wait ():


Causes a thread to wait until it is notified. This method must be ca)led
from within a synchronized method only otherwise exception will be
thrown.

Here are three general rules to be followed for threads.

i) Declare the methods of different threads as synchronized, ifthey modify the


same object.
ii) In case a thread has to wait for it to modify an object, it should wait inside the
object by entering a synchronized method and a call to wait.
iii) Whenever a method changes the state ifan object, it should call notify, so
that waiting threads get a chance to see ifthe object has changed.

7.6 Deadlocks

There is yet another problem with multithreading. Asituation can arise when one thread
waits for another thread to complete, whereas the second thread waits for the first one to
complete Such situation is called a deadlock and must be avoided while designing
threads. Java cannot solve deadlock problem,

7.6.1 Daemon Threads


Adaemon thread is one that serves other threads. It has no other role. When only daemon
threads remain the program exits. There are some threads that do not affect the end ofa
program and user need not worry about stopping. Then other threads finish the run
methods, then the application automatically terminate. Such threads that don't effect the
end of a program must be made adaemon thread and must be called before the thread is
started. Normally daemon threads carry on some background program

java.langThread

void setDaemon (boolean on):


This marks the thread inwhich it is declared as a daemon thread.

83
Training Cycle 7
JAVA 2
Wintech Computers

7.6.2 Runnable Interface


Java doesn't support multiple inheritance. Therefore we cannot directly include a run
method in a class thatinherits from some ether class. Forexample in an applet wewant to
have athread, but since an applet extends from an Applet class we cannot directly include
the run method. This is where the Runnable interface comes into picture. With this
interface we make a reference to the Runnable object which then calls the run method.
Therefore we can have multithreads that don't necessarily inherit from the Thread class.

Sample Program 7.3

class Animation extends Applet implements Runnable


{
public void run ( }
{
/ / thread code here

public class ThreadTester


{
public static void main(String args[])
{
Animation a= new AnimationO;
Thread t= new Thread(a);

java.lang.Thread

Thread(Runnable target):
Constructs a new thread that calls the run method of the
target.

java.lang.Runnable

void run();
You must override this method with code to execute the
thread.

Training Cycle 7 84
Training
Cycle: 8
Wintech Computers JAVA 2

8. Input and Output

8.1 Introduction

In this chapter we shall study how to handle input and output. The input source can be
from a keyboard, a file or the network and the output destination is either the screen, a
file or the network. The data is sent or received as a sequence of bytes or characters.

An object from which a sequence ofbytes or characters can be read is as input stream and
the object to which a sequence of bytes or characters can be sent is an output stream. A
stream is a flowing sequence of characters. In Java all input and output is treated as a
stream of characters.

The package java.io defines four root classes from which most of the package's stream
subclasses are derived. They are called InputStream, OutputStream, Reader and Writer.
The InputStream and OutputStream classes areused to manipulate on BYTES and
Reader and Writer classes are used to manipulate on CHARACTERS.

8.2 The InputStream class

The basicjob of the InputStream class is to read bytes from whatever stream it is attached
to be it the keyword, a disk or the Internet. The InputStream has two attributes:

1) When a call for information is made to the InputStream, the method called will
wait until input is available. This is called blocking.
2) The InputStream works with bytes and not characters. In Unicode a character is
16 bits. Therefore when receiving characters from the input stream, you don't
receive the higher order byte of the Unicode.

The hierarchy diagram shows the InputStream classes.

Input Stream
SequencelnputStream
Piped InputStream

Filter InputStream
LineNumber InputStream
PushBack InputStream
Buffered InputStream
Data InputStream

Datalnput
Random Access File
DataOutput

Training Cycle 8 86
Wintech Computers JAVA 2

File InputStream
ByteArray InputStream
StringBuffer InputStream
Object InputStream
Stream Tokenizer

8.3 Using standard Input/Output objects

Trrree static Input/Output (UO) objects have been created by default. All three of these
objects are public static members of the System class. These are defined below

Object Type Purpose

System, in BufferedlnputStream Standard Input.


System.out PrintStream Standard Output
System, err PrintStream Error Output

Java.io.InputStream

Public abstract int read () throws Reads a byte of data and returns the byte read
lOexception or -1 if end of the stream. Throws lOException
in case of any errors
Public int read (byte[ ]) throws Reads into an Array.
lOException

Public read ( byte b [ ], int off, int len Reads into an array with Offset and limit.
) throws lOException

Public void close () throws Closes the Stream


lOException

Public long skip (long n ) throws Skips n number of bytes


lOException

Public int available ( ) throws Non Blocking bytes readily availabe


lOException

Public void mark (int readlimit) This method places a marker up to where bytes
can be read from input stream If the limit
is exceeded then the marker is not
considered.

87
Training Cycle 8
JAVA 2
Wintech Computers

Public void reset () throws This method returns to the last marker
lOException

Public boolean markSupported () Not all streams supports markers. This method
return true if the stream supports it

Sample Program 8.1 For InputStream

import java.io.*;
class ReadKeysl
{
public static void main(String args[])
{
StringBuffer s=new StringBuffer!);
char c;
try
{
Reader in=new InputStreamReader(System.in);
while((c=(char)in.read())!='\n')
{
s.append(c);
}
)
catch(Exception e)
{
System.out.println("Error: " + e.toString());
}
System.out.println(s);'

8.4 The Reader Class

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

PipedReader
StringReader
FilterReader
PushbackReader
BufferedReader
LineNumberReader

Training Cycle 8 88
Wintech Computers
JAVA 2

Public int read() throws lOException Reads a byte ofdata and returns the byte
read or -1 if end of the stream. Throws
lOException in case ofany errors
Public abstract void closeQ throws Closes the Stream
lOException
Public void mark(int readAhead Limit")" This method places a marker up to where
throws lOException bytes can be read from input stream. If the
limit is exceeded then the marker is not
considered
Public int read(char chug') throws Reads into an Array.
lOException
Public abstract int read(char chub J, int off, Reads with an Offset and limit.
int len) throws IOExeeption
ReadyQ Tell whether this stream is ready to be read
ResetQ Reset the stream
Public boolean markSupported () Checks whether mark is supported by the
stream

Sample Program 8.2 - Reader Class

import java.io.

public class ReaderProgram


{
public static void main(String args[]) throws
lOException
{
int c=0;
if ( args.length!=1)
{
System.out.println("Usage: Java ReaderProgram

<FileName>");
System.exit(0) ;
}
Reader rd = new FileReader(args[0] );

while((c=rd.read())!=-l)
{
System.out.println((char)c) ;
}
rd.close();
}
}
Explanation: The above sample program takes a filename as argunent and displays the
contents of the file If the filename is not given as an argument tin. execution of the

89
Training Cycle 8
Wintech Computers JAVA 2

program stops giving an error message ( Usage: Java ReaderProgram Filename> ).


Here, rd is the instance of the class Reader and FileReader opens the file for reading and
returns an handle to rd. Using a while loop, the contents are read and displayed on the
screen. The readQ method reads a character from the file and returns the corresponding
acsii value of that character

8.5 The OutputStream Class

The OutputStream class prevides means ta write a sequence of bytes to a screen, a file or
the network Blocking takes place in the OutputStream classes also The hierarchy
structure is shown below

Java io.OutputStream

Public abstract void write(int b) throws Writes a Byte of Data


lOException
Public abstract void write(byte b[]) throws Writes all bytes in array b
lOException
Public abstract void write(byte b[], int off, Writes bytes in array b with Offset off and
int len) throws lOException len bytes.
Public void closeQ throws Exception Closes The OutputStream
Public void flushQ throws Exception Sends any Buffered data to its destination

Sample Program 8.2: For OutputStream

import java.io.FileOutputStream;
import java.io.*;

class Mainl
{
public static void main (String args[]) throws lOException
/
i

if (args.length!= 1)
(
System.err.println("Usage: Java Main
<output_file>");
System.exit(-1);

try

Training Cycle 8 90
Wintech Computers JAVA 2

FileOutputStream out = new


FileOutputStream(args[0]);
FileOutputStream out2= new
FileOutputStream (out. getFDO );
String str = "Hello World\n";
byte[] buf = new byte[str.length()];
str.getBytesfO, str.length(), buf, 0);
out.write(buf);
out2.write(buf);
out2.close i); // will close 'out' too
)
catch (lOException e)
(
e.printStackTrace();

8.6 Writer Class

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

Writer has the following subclasses.

Writer
Buffered Writer
CharArray Writer
Filter Writer
Piped Writer
Print Writer
Siring Writer
OutputStream Writer
FileWriter

The methods of the writer class are as follows

public void write(int c ) throws Writes a single Character.


10\1 xcepjion_
public void wiite(char b[ ] ) throws Writes an array of characters
lOfxception
public void write(diar b[ ], int off, int Writes an array of characters with
len) throws lOException specified offset and length
public void write(String str) tliiows Writes a String
lOException

91
Trainiii" Cxcii' X
Wintech Computers JAVA 2

public void write(String str, int off, int Writes a portion of String
len) throws lOException
public abstract void close() Closes the Stream
public abstract void flush() Flushes of any buffered data.

Sample Program 8.3 - CopvProqram

import java.io.*;

public class CopyProgram


{
public static void main(String argsf]) throws
lOException
{
int c=0;

if (args.length!= 2)
{
System.out.println("Usage: Java CopyProgram
<Source> <destination>");
System.exit(0) ;
}

Reader rd = new FileReader(args[0]);

Writer wr = new FileWriter(args[1]);

while((c=rd.read())!= -1)
{
wr.write (c);
}

System.out.println("File copied from "+args[0] +


ti *- ~ M
to " +args[1]);
rd.close();
wr.close();

8.7 PrintWriter Class

This class two methods that are used for outputting the text The PrintWriter converts all
of their arguments to character representation It converts 16-bit bytecode representations,
whereas PrintStream converts to 8-bit ASCII representation

Training Cycle 8 92
Wintech Computers JAVA 2

The use of PrintStream class is not formally deprecated in JDK 1.1 . But, instead use of
PrintWriter is strongly encourged. There is a difference between the print methods which
are there in the PrintStream class and print methods of PrintWriter class.

The differences are, the print methods of PrintStream class does not force the immediate
writing of data (called flushing ). It can remain buffered until a newline character is
written or an explict flush is done on the PrintStream. Whereas, in PrintWriter class the
characters are written immediately and there is no need for an explicit flush.
8.8 Print Streams

The PrintStream class has two methods that are normally overloaded for outputting text.
Whereas the methods of Input and Output Streams handle a byte or an array of bytes,
these methods can handle objects as well.

Java.io. PrintStream

Public void print (type varname ) This method sends the characters to a
buffer where they are stored until the
buffer is flushed with a 'W character.
When characters are printed out, they are
in ASCII not UNICODE.Type can be
object, integer, long, float, double,
boolean, String, array of characters and
varname is Name of the variable.

Public void println(type varname ) This method not only prints out the
characters hut also a new line thus flushing
out the buffer.

8.9 Data Streams

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

java.io.DatalnputStream

Methods for reading

Public final boolean readBoolean () Reads a boolean value.


Throws lOEXception
Public final byte read Byte () Reads an 8-bit byte.
Throws lOException

93
Training Cycle 8
JAVA 2
Wintech Computers

Public final char readChar () Reads a 16 bit Unicode character.


Throws lOException
Public final double readDouble () Reads a 64 bit double.
Throws lOException
Public final float readFloat () Reads a 32 bit float.
Throws lOException
Public final void readFully( byte b[ ]) Read bytes, blocking until all bytes are
throws lOException read. Ties up resources.
Public final void readFully(byte b[ ], int Reads bytes, blocking till all bytes are
off, int len) throws lOException read, start from an offset for the maximum
number of bytes to be read.
Public final int readlnt() throws Reads a 32-bit integer.
lOException:
Public final String readLine () Returns a string until all bytes in
Throws lOException a line, converted to Unicode
characters. A line is terminated by
'\n' V or EOF.
Public final long readLong () Reads a 64 bit long integer
Throws lOException
Public final short readShort () Reads a 16 bit short integer.
Throws lOException
Public final String readUTF() Reads a string of characters in UTF format
Throws lOException
Public final int skipBytes( int n ) Skips the n bytes
Throws lOException

Java, io.DataOutputStream

Methods for writing

Public final void writeBoolean (boolean Writes a boolean value.

b)
Public final void writeByte ( byte b ) Writes one 8 bit byte.
Public final void WriteBytes(String s) Writes the string to output stram
Public final void writeChar (char c) Writes a 16 bit Unicode character.
Public final void writeDouble (double d) Writes a 64 bit double.
Public final void writeFloat (float f) Writes a 32 bit float.
Public final void writelnt ( int i) Writes a 32 bit integer.
Public final void writeLong (long 1) Writes a 64 bit long integer.
Public final void writeShort { short sj Writes a 16 bit short integer.
Public final void writeUTF ( String s ) Writes a string of characters in UTF
format. UTF is Unicode Text Format.

Training Cycle 8 94
Wintech Computers JAVA 2

8.10 File Class

The File class holds a specific information about a specific file and methods for getting
the statusof a file. In addition to information about files, you can create instances of the
File class that represent directories.

There are 3 ways to create an instance of a File class.

Java.io.File

Public File ( String path ) Here you create an object based on


uponthe directory structure in the
path.
Public File ( String path, String File input = new File ("text",
name) input'txt");
Public File ( String dir, String name) File input = new File ( dir,
"input.txt");
Public String getName () The name of the file in a string

Public String getPath () The path of the file in the File


class.
Public String getAbsolutePath ( ) The file name with the path of executable
appended to the front
The name of the parent directory ifthere is
Public String getParent () one otherwise-null
Public boolean isFile () There if file instance is valid and a
normal file .
Public boolean exists ( ) True ifthefpe exists
Public boolean canWrite () True if file exists and if it can be written
on

Public boolean canRead () True if file exists and readable


Public int lastModifed () The last time of file was modified
Publ ic boolean rename To (File dest) Renames a file, returns true if
renaming is successful
Public boolean mkdir ( ) Creates a directory structure
Public String [ ] list () Lists the contents of the directory in the
File class, this method only works with
instances of the File class that are
directories.

95
Training Cycle 8
Wintech Computers JAVA 2

Sample Program 8.4

import java.io.*;
class Filelnfo
(
public static void main(String args[])
{
char c;
File file=new File("ras.txt") ;

if (file.exists() )
(

System.out.println("File name " +


file.getName());
System.out.printIn("Path " +
file.getPathO ) ;
System.out.println("Abs Path " +
file.getAbsolutePath());
System.out.println("Wirtable " +
file.canWrite());
System.out.println("Readable " +
file.canRead());
System.out.println("Length " +
file.lengthO + "B") ;
}
else
System.out,println("Sorry, file not
found.");

8.11 Random Access File Streams

This class lets you to read or write data anywhere in a file Disk files are random access
files where mnetwork files are not Random access Files can be either only read or read
(r) and write (rw), These files have pointers to indicate the next record that will be
accessed

Java.io.RandomAccessFile

Public RandomAccessFile ( String name, This constructor takes a filename provided


String mode ) by name and opens a file for either read
only or read-write.
Public long getFilePointer () throws Returns the current location of the file
lOException pointer in bytes

Training Cycle 8 96
Wintech Computers JAVA 2

Public void seek(long pos) throws This method moves the file pointer to the
lOException specified position ( pos) in the file.
Public long length () throws lOException This method returns the length of the file
in bytes.
Public int read (} Reads a single byte and moves the pointer
forward by a byte.
Public int read (byte b [ ]) Reads and files a byte array from the file
and moves the pointer as many size as the
array size.
Public int read (byte b[ ], int off, int len) Reads an array of bytes of length leo and
places them in the array at off. The pointer
is moved by len bytes
Public final String readLine () Returns the entire line terminated by '\n'
or EOF
Public final readUTF() Returns a single from a UTF formatted file

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

RandomAccessFile implements both Datalnput and DataOutput Interfaces as


DatalnputStream and DatalnputStream. Hence we can use all the methods of Datalnput
and DataOutput while using RandomAccessFile class for reading or writing.

Sample Program 8.5

import java.io.*;
class FilePrint
{
public static void main(String args[]
{
try

RandomAccessFile file=new
RandomAccessFile("FilePrint.Java","rw");
while(file.getFilePointer()<file.length())
System.out.println(file.readline());
}
catch(Exception e)
(
System.out.println("Error: " +
e.toString());
}

97
Training Cycle 8
Wintech Computers JAVA 2

8.12 Buffering

A buffer is a temporary storage to hold data, It is used to improve the efficiency in


reading input and writing output. For example you can have a large number of bytes
temporarily stored in a buffer, from where they all be written on to disk in one go.
Similarly you can have a buffer for reading data. This reduces the access time for reading
and writing from a disk.

There are two buffer stream classes in Java.


1. BufferedlnputStream
2. BufferedOutputStream

java.io.BuffredlnputStream

Public BufferedlnputStream Creates a new buffered stream with a


(InputStream in) default buffer size.
Public BufferedlnputStream( Creates a new
InputStream in, int n ) Buffered with user
defined size

Java.io.BufferedOutputStream

Creates a new buffered stream with


Public BufferedOutputStream default size for outputting. Once the
(OutputStream out) default buffer is full, the data is actually
is written

java.io.LineNumberlnputStream

Public LineNumberlnputStream Constructs an input stream that keeps


(InputStream in) track of line numbers
Public void setLineNumber( int lineno ) Sets the current line number
Public int getLineNumber () Returns the current line number

Training Cycle 8
98
Training
Cycle: 9
Wintech Computers JAVA 2

9. ABSTRACT WINDOW TOOLKIT (AWT)

9.1 Introduction

GUI is the order of day. Almost all client end models are GUI based Java provides a
class library called Abstract Window Toolkit (AWT) for GUI programming With
these tools you can build Windows style user interfaces for any platform

9.2 Frame

The simplest GUI is a window. In AWT the top-level window which is itself not
contained in another window is called a frame This is a class in the awt package The
package java.awt contains all classes dealing with creating windows features All
measurements in AWT package are in pixels

To create a window you have to follow these steps:


1) Create the frame by a call to new.
2) Re-size the frame, as the initial size will be sized at 0 by 0 pixels and so not visible
3) Call the show method in the frame class to actually display the window. The
measurement of frame is in pixels.
The measurement of frame is in pixels.

9.1 Sample Program: To display a simple window

import java.awt.*; //import java.awt package.


class Mywindow
{
public static void main(String args[ ])
{
Frame f = new Frame ();//Creates an object of type Frame
f .setsize(300,200 ); //Resize the object to 300 by 200 pixels
f. show ( ); //Display the window
}

Both show () and resize () are methods of class Frame. This program only displays a
window It does not have any other functionality For example you cannot even close it.

Training Cycle 9 jq|


Wintech Computers JAVA 2

9.3 Event Driven Programming

In order to make your window respond, you need to include button, check boxes, scroll
bars etc. When a user clicks, drags, double clicks etc., these buttons' actions are triggered
to perform some operations. These operations and their results will depend on the code
you write for these buttons. This kind of programming is called event driven
programming. Events being a key control such as click, double click, drag and drop etc. It
is the event handlers who handle these events. In Java events are objects, a collection of
rich hierarchy of event types which are defined in the java.awt.event package. Through
this package, instances of various event classes are constructed when users use GUI
components.
For example, when the user clicks on a button, the system constructs an instance ofclass
ActionEvent, in which it stores details about the event. At this point, the programmer has
three options.
Ignore the event
Have the event handled by the components
Delegate event handling to some other object or objects called listeners

9.3.1 Ignoring the Event


In the absence of any explicit event handling code, events will be ignored. For example
consider a Java based mail tool, with text area for composing messages, a text field for
entering a e-mail address, and a send button. While entering a message the many events
would be generated and the only time the program cares about the event is when the user
clicks on the send button So here we are ignoring other events and handling the events,
which are required for the program.

9.3.2 Handling the event in the Originating component


Aself-contained component is one that handles its own events. None of the standard. A
WT components is self-contained. Ifyou want acomponent to handle its own events you
need to create a subclass. The subclass must do two things.

Enable receipt of events, by calling enableEvents().


Provide aprocessActionEvent() method, which would be called when the
component

102
Training Cycle 9
IAVA 2
Wintech Computers

9.2 Sample Program: implementing self-contained button

import java.awt.*;
import java.awt.event.*;
import Java.applet.*;

public class ButtonDemo2 extends Applet


{
MyButton myButton;
static int i=0;
public void init()
{
myButton=new MyButton("Test Button");
add(myButton);
}

class MyButton extends Button


{
public MyButton(String label)
{
super(label);
enableEvents(AWTEvent.ACTION_EVENT_MASK);

protected void processActionEvent(ActionEvent ae)


{
showStatus("Action event: " + i++) ;
super.processActionEvent(ae);
}

Explanation: The constructor calls enableEvents( ),passing in


AWTEvent ACTION EYENTMASK, which tells the button component that you are
interested in action events When a user clicks on a self button te system generates an
action event and then checks whether the self button has enabled action events Since
action events are enabled the system calls the TrocessActionEvent () method in which we
write statements that are to be executed whenever the user clicks the self button.

Bv passing in different values to enableF.vents you can make a component to catch many
different kinds of events; all of the event handlers have names of the format
processXXXEventO, where XXX stands for the event type. The following code produces
a simple applet that demonstrates the use of self button.

Example

Training Cycle 9 103


Wintech Computers JAVA 1

import Java.applet.*;
import java.awt.*;
/*<applet code="SelfButtonl" height-"200" width-"100"X/applet>*/
public class SelfButton Test extends Applet
public void init()
{
add(new Button(" Push Me ");
}
}

9.3.3 Delegating the event


One of the fundamental principles of object oriented design is that a task should be
performed by the object that is best suited to the task. There will times when self-
contained components are not the way to go, because the component may not be the object
best suited to handle its own events

The process of assigning a different object to handle components events is called


delegation. The event handling objects are called listeners. To tell a button that it should
delegate the handling of action events to some listener, you call the buttons
addActionListener() method, passing a reference to the desired listener. Every
component class in the A WT class has one addXXXListener() method for each event
type that the component generates.

9.3 Sample Program

import java.awt. Button;


import Java.applet.Applet;
import java awt.event.*;
/*<applet code="ButtonDelegateTest" height="200" width="100"x/applet>*/
public class ButtonDelegateTest extends Applet
{
public void init()
{
Button b = new Button(" I hava a Listener");
add(b);
TestListener listener = new TestListener(); b.addActionListener( listener);
}
}
class TestListener implements ActionListener
{
public void actionPerformed ( ActionEvent e)
{

TrainingCycle 9 104
JAVA 2
Wintech Computers

System.out.println(" Listenr here: The button was clicked ");


}

Explanation: In the above program, when the button with ActionListener is clicked, the
listener receives an actionperformed call. The listener class should implement this
method to do what ever is supposed to happen.

In the above program, the applet will have abutton. The button delegates action handling
to a third object, which is an instance of class TestListener

9.3.4 Java Event Types


There are actually concrete event types which are contained in the java.awt.event
package. All ofthe event classes extends from two abstract super classesJava, utiI.
EvenfObject and Java.AWTEvent. The event inheritance hierarchy is shown below
java util.EventObject

ava. awt AWTEvent

ActionEveritAdjustmentEvent ComponentEvent Item Event TextEvent

ContainerEve wEvent

KeyEvent MouseEvent

The ancestor of the hierarchy is java.util.EventObject, which provides a method called


getSourceQ. This method returns component in which the event took place. One level
below java util EventObject is java.awt AWTEvent, which provides a method called
getlD(). This method returns an int that describe the nature if the event For Ex Calling
getlD() on an instance of MouseEvent results in an inr whose value might be
MouseEvent MOUSEPRESSED, MouseEvent MOUSE DRAGGED, or one of the
several other possible values, depending on which specific mouse activity triggered the
event.

9.4 PaintO Method

Once you have created a window, you would like to add features into it The features can
be graphic or text. The paint() method of Graphics class is used to do this. Graphics is a

Training Cycle 9 105


Wintech Computers JAVA 2

class of the awt package. In fact, all drawing whether iftext or graphics must go through
the Graphics class. The paint() method takes one parameter, an instance of class
Graphics. In your code you must override this method to perform your operations.
For Example, to display the text in the window, you use drawstring (; method
public abstract void draw String(String str, int x, int y);

Example:

public void paint ( Graphics g )


{
g. drawstring ("This is my window", 75,100); //Call method to display the
//window
}

Note The text is display at position starting from x coordinate to y coordinate is in pixels.
9.4 Sample Program:

import java.awt.*;
import java.awt. event. *;
public class MyWindow2 extends Frame
{
public boolean handleEvent (Event e)
{
if(e id = Event WINDOWDESTROY)
System. exit(0); /Method to exit application
return super.handleEvent (e);
}
public void paint (Graphics g)
{
g.drawString("This is my window",75,100);
}
public static void main( String args[])

Training Cycle 9 106


Wintech Computers JAVA 2

MyWindow2 f = new MyWindow2();


f.resize ( 300, 300 );
f.show ();

9.5 Frame Properties

The size() method of Component class ( parent ofFrame ) returns the size of the frame
inclusive of the borders The client area is the actual space available to the user that is
size minus the borders. The insets( ) method returns the dimensions of the client area
initially, when an object ofFrame is instantiated the size is 0 by 0 pixels. This has to be
re-sized by the resize() method.

9.5 Sample Proeram:

mport java.awt.*;
import java.awt.event.*;
publicclass MyFrame extends Frame
{
public MyFrame()
{
setSize(300,250);
}
public boolean handleEvent(Event e)
{
if(e. id==Event.WINDOW_DESTROY)
System.exit(O);
return super.handleEvent(e);
}
public void paint(Graphics g)
{
int w=size().width;int h=size().height;
g.drawString("Width and Height of Client window is "+w+","+h,50,100);

Training Cycle 9 107


Wintech Computers JAVA 2

public static void main(String args[])


{
Frame f=new MyFrame();
f.show();

9.6 Fonts

Text can displayed in various Styles, Fonts and Font Types. Font is an object in
Java

Styles: Plain, Bold, italic, Bold italic.


Sizes: 10, 12, 14 etc
Fonts: Helvetica, Times Roman, Courier, Dialog, and Symbol.

public Font(String name, int style, int size);


public final static int BOLD;

Example:

Font f = new Font ("Times Roman ", Font.BOLD+Font.ITALIC, 14 );

Here we have an instance of Font class that is set to the parameters as given in the
brackets.

9.6 Sample Program

Training Cycle 9 108


Wintech Computers JAVA 2

import java.awt.*;
import java.awt.event.*;
class MyWindow3 extends Frame

public boolean handleEvent ( Event e )


{
if ( e.id == Event.WINDOW_DESTROY )
System.exit ( 0 ); // Method to exit application return
return super.handleEvent ( e );
}

public void paint ( Graphics g )


Font f = new Font("Times Roman", Font.BOLD+Font.ITALIC, 14 )
String s = "This is a good text style "; //declare a string
g.setFont ( f );
g.drawstring ( s, 75, 100 );
}

public static void main(String args[] )


{
Frame fo = new MyWindow3 ();
fo.resize ( 300, 300 );
fo.show ( );

}
}

In Java you have to be careful when you mix fonts. Different letters have different widths
and heights. For example letters like 'k' or T may hit the lower part assay 'g' or 'y' ifthe
preceding line. Then letters like W occupy more width than an T or T. All these
properties have to be considered while dealing with text.
There are methods like getFontMetrics () which handle these problems.
Syntax:

public FontMetrics getFontMetrics (Font font );

9.6.1 Fonts
We shall study the methods available for Fonts, Color, Shapes etc. The methods are hsted
below for the respective classes

java.awt.Font

public Font (String name, int style, int size );


To create a new font object. Font( " HELVETICA", Font.BOLD + Font.ITALIC, 14);

Training Cycle 9 109


Wintech Computers JAVA 2

java awt FontMetrics

Public int getAscent () Gets the ascent of the font.


Public intgetDescentQ Gets the fonts descent.
Public int getLeadint () Gets the leading of the font.
Public int getHetght () Gets the height of the foist.
Public in( getMaxAscent () Gets the maximum ascent of all characters
Public int getiWaxDescent () Gets the maximum descent of all
characters of the font
Public int stringWidth ( String s ) Gets the width of a string named s

9.6 Sample Program: Font Metrics

import java.awt.*;
import java.awt.event.*;
class Mywindow extends Frame
{
Mywindow()
{
super("FontMetrics Example");
setSize(150, 75);
show();

public boolean handleEvent(Event e)


{

Training Cycle 9 110


JAVA 2
Wintech Computers

if(e.id==Event.WINDOW_DESTROY)
System.exit(0);
return super.handleEvent(e);

public void paint(Graphics g)


i
Font f = new Font("Courier", Font.ITALIC+Font. BOLD,
18);
FontMetrics fm = g.getFontMetrics(f) ;
Int y =0;
g.setColor(Color.blue);
g.setFont(f);
g.drawstring("First Line", 0, y + fm.getAscent()) ;
y += fm.getHeight();
g.drawstring("Second Line", 0, y + fm.getAscent()) ;
}

public static void main(String[] args)


{
new Mywindow();
}

java.awt.Graphics

public abstract void setFont(Font f): Selects a font for


displaying text f is object of Font

public abstract FontMetrics getFontMetrics ( ): Gets the


measurements ( metrics ) of the current font.

public abstract void drawString (String s, int x, int y ): Draws


the text in the font color selected.

9.7 Colors

Standard Colors

Black blue :yan darkgray pink

green lightgray magenta orange red

Training Cycle 9 111


Wintech Computers JAVA 2

white yellow gray

Syntax:
public final static Color color

Example. Color.darkGray,

Java.awt.Color

public Color( int r, int g, iot b ): Creates a color object


r for red 0 - 255
g for green 0 - 255
b for blue 0 - 255

Java. awt.Graphics

public abstract void setColor ( Color c): Changes the current color
C: new color object

9.8 Graphical Shapes

java.awt.Graphics

Public abstract void draw Line (int x I, (x 1, y I):start point


intyl, intx2, int y2) (x2, y2: end point
Draws a line between the two points.
Public abstract void draw Arc (int x, int y, This draw an arc bounded by
int w, int h, int startangle, int arcangle) rectangle that starts at (x, Y) have
width w and height h, and start angle
startanle and endangle= startangle-
arc angle.
Public void drawPolygon (Polygon p ) Draws a polygon joining the points in the
object p of polygon
Public void addPoint( int x, int y ) is a method of class polygon.

Training Cycle 9 112


Wintech Computers JAVA 2

Public void drawRect( int x, int y, int w, Draws the outline of a rectangle.
int h): (x, y): : top left hand corner coordinates
W: width of rectangle.
H: Height of rectangle.
Public void drawRoundReet (int x, int y, This draws the outline of a rectangle with
int w, int h, int arcw, int arch) rounded corners
Arcw: horizontal diameter of the are at
the corner.
Arch: vertical diameter of the are at the
corner

Public void draw3DRect( int x, int y, int Draws the outline of the rectangle and if
w. int h, boolean raised) raised is true, then the rectangle appears
above the window that is raised
Public abstract void drawOval( int x, int Draws the outline of an oval bounded by
y, int w, int h): a rectangle of ( x, y, w, h )

9.7 Sample Program: Drawing arcs


import java.applet.*;
import java.awt.*;
/*<applet code="DrawArcs" height="100" width="200"x/applet>*/
public class DrawArcs extends Applet
{
public void paint(Graphics g)
{
g.drawArc(15,15,80,80,0,180);
g.fillArc(100,15,70,80,0,270);

9.8 Sample Program: Drawing different shapes


import java.awt *;
import java applet*
import java.awt.event.*;
class DrawShapes extends Frame
{
public boolean handleEvent(Event e)
{
if (eid==Event WINDOW DESTROY )

Training Cycle 9 113


Wintech Computers JAVA 2

System.exit(0) ;
return super.handleEvent (e);

public void paint(Graphics g){


g. setColor(Color. blue);
g.drawRect(2 0, 20, 200, 200 );
g.drawOval( 85,30,5 0,50);
g.drawOval(90,45,6, 6) ;
g.drawOval(123, 45, 6, 6) ;
g.drawLine(110,45, 110, 60) ;
g.drawLine(110,80,110,160);
g.drawLine(110,160, 80, 200) ;
g.drawLine(110,160,14O,2O0);
g.drawLine(80,100,14 0,100);
g.drawArc(100,65,20,10, 0,-180) ;

public static void main(String args[;


{
Frame f = new DrawShapes();
f.resize(300,300);
f.show ();

Filling the Shapes

The bounded areas of the shapes can be filled with color. To do this you have to first
set a color object and then call the methods below.

public abstract void fillRect( int x, int y, ink w, int h)


public abstract void fillRoundRect( in tx, int y, int w, int h, int arcw, int arch)
public void fiU3DRect( int x, int y, int w, int h, boolean raised )
public abstract void fillOval ( int x, int y, int w, int h )
public abstract void fillArc (int x, int y, int w, int h, int startAngle, int arcAngle )
public abstract void fillPolygon ( Polygon p)
public abstract void fillPolygoo (int xpoints[ ], int ypoints[ ], int npoints
public abstract void setXORoiode( Color color)

Here color is any one of the standard colors. This color sets as atoggle between old color
and current color contexts. This kind of painting is called XOR mode. The earlier
methods were overridden paint methods.

114
Training Cycle 9
Wintech Computers JAVA 2

9.9 Sample Program: filling shapes

import java.awt.*;
import java.awt.event.*;

public class FillShapes extends Frame


{
int[] x={20,55,445,480},y={ 100,45,45,100};
int[]xl={200,125,125,200,200},yl={200,230,380,380,200};

public boolean handleEvent(Event e)


{
if(e.id==Event.WINDOW_DESTROY)
System.exit(0);
return super.handleEvent (e);
}

public static void main(String args[])


{
Frame f=new FillShapes( );
f,resize(500,300);
f.show();
}

public void paint(Graphics g)


{
String str="My Home";
setTitle(str);
g.setColor(Color.blue);
g.fillRect(20,100,4 60,280);
g.setColor (Color.red);
g.fillPolygon(x,y,4);
g.setColor(Color.white) ;
g.fillRect(50,200,150,180) ;
g.setColor(Color.green);
g.fillPolygon(xl,yl,5);
g.setColor(Color.gray);
g.fillRect(2 70,140,110,130);
g.setColor (Color.black);
g.drawLine(325,140,325,270);
for (int j=150;j<270;j+=15)
g.drawLine(270,j,380,j);
g.setColor(Color.white);
String s= "Welcome to my happy home";
g.drawString(s,2 60,3 00);
}

Training Cycle 9 j Ig
Wintech Computers IAVA 2

9.9 Images

So far we have seen how to draw simple lines and shapes Most ofthe graphics are stored
in file formats such as GIF, 3PEG examples are pictures, photographs etc These tiles can
be read into Java using an object called Toolkit Toolkit object contains methods that can
handle images

Example

String name = "blueball.gif:


Image image = Toolkit getDefaultToolkit.getlmage( name ),

This statement gets the image named blueball gifand stores it in an object image
of class Image

java.awt.Toolkit

public static Toolkit getDefaultToolkit (): Returns the default toolkit This gets the
default toolkit

public abstract Image getlmage( String filename) Gets the specified image
Returns: an image which gets its pixel data from the specified file
filename : the name of the file containing the image ( gif or jpeg image )

I java.awt.Graphics

public abstract boolean drawlmage( Image image, int x, int y, int w, int h,
ImageObserver observer): This draws the image
Returns: true if a 11 bits of image are available; false otherwise.
Image: the image object to be drawn
(x,y): starting coordinates of image ( left hand top corner)
w,h width an height of the image
observer An object of the Image Observer that has to
be notified of the drawing process, can be null

public abstract boolean drawlmage ( Image image, int x, int y,


ImageObserver observer ) This is similar to previous method
except that it draws a sealed image, note there are no width and heights mentioned

Training Cycle 9 116


Wintech Computers JAVA 2

Returns: true if all bits of image are available; false otherwise. These two calls may
be returned if even before image is actually drawn.

9.10 Buffering:

Images fill up the windows slowly. This could be an irritation, especially if you resize the
window or make some other modifications. There will also be a flicker if the screen is
redrawn This occurs because graphics are not persistent in Java. What happens is that
each time a window is redrawn, AWT calls its update method. This method first erases
the window and then redraws. But with images it is not necessary to erase the screen, we
only have to override the update method. This is done by the following code.

public void update ( Graphics g )


{
paint ( g );
}

In order to speed up the whole process, what is done is that the entire screen image is
loaded into an image buffer, from where the screen can be accessed much faster.
However this leads to using up a great deal of memory. This is worth when there are
going to be frequent changes to the window.

A buffer will hold all the image content. First we create a buffer and work with Graphics
context that is attached to the buffer and not the screen. You create a buffer with
createlmage method and the getGraphics method.

java.awt.Component

public void update (Graphics g ): Updates without erasing current


image

public Image createlmage (int w , int h): This method creates an off
screen buffer.

w and h: width and height of image.


Eg; Image bufimage = createlmage ( client-width, client-height );

java.awt.Image

Training Cycle 9 |-
Wintech Computers JAVA 2

public abstract Graphics getGraphics (): This gets the graphics context to draw into
the image buffer.
Returns: a graphics context to draw to the off-screen image.

java.awt.Graphics

public abstract void copyArea ( int x, int y, int w, int


h, int dx, int dy): This method copies an area of the x
and y w and h dx and dy screen. Coordinates of top
left corner of source area, width and height of source
area. Horizontal(dx) and vertical(dy) distances from
source area to target area..

public abstract void dispose( ): You must use this to release


resources to the operating system. The graphics that you create should be disposed
with this method, but the ones created by paint or update.

Java.awt.Component

public void repaint(): Causes a repaint of thewindow by calling update.


Public void repaint(int x, int y, int w, int h): This causes a part of the component
defined by x, y, w, h to be repainted.

9.11 Building User Intefaces

So far we have seen how to create a window, display text and draw shapes. These
features didn't support any functionality. What is essential is to make the GUI respond to
user actions. We need to add button check boxes etc, and write code for them so that they
behave the way we want them to.

In Java all buildings blocks of GUI are called components. These components are placed
in an object called a container, which is similar to a parent window. Then you write code
for the components. The steps involved are

1. Place the components in a window.


2. Position thecomponents within a window, and
3. Handle user input to make these components respond to user's actions(
events).

118
Training Cycle 9
Wintech Computers JAVA 2

Adding Buttons

To add buttons to your window you use the following methods.

java.awt. Button

public Button ( String s ): Creates a button, s* is the label of the


button,that will appear on the button,
eg: Button bottonName = new Button(label);

setBackground ( Color.color ): Sets the color of the button.

Eg. okButton.setBackground ( Color.green);

java.awt.Frame

public void setTitle ( title of window): Sets the title for the window
Eg: setTitle ( "My window ");

j ava.awt. Container

public Component add ( button name ): adds the button to the window.

9.11.2 Positioning the Buttons


Once we have the buttons ready we need to position them in the window This is done
with the setLayoutQ method

java.awt. Container

public void setLayout ( LayoutManager mgr ): Sets layout manager for the
container.

Training Cycle 9
119
Wintech Computers JAVA 2

Eg: setLayout( new FlowLayout());

9.12 FlowLayout ()

The FlowLayout() object adds buttons in a row and starts a new row when one row is
full, It centers the buttons and automatically repositions them when the window is
resized. Aflow layout manager is actually a layout manager. The layout manager takes
care of positioning the buttons. This setLayout () method is to be declared before adding
buttons.
9.10 Sample Program: Simple program to make a button respond
importjava.awt.*;
import java.awt.event.*;
public class MyButtons extends Frame implements ActionListener
{
public MyButtons ()

setTitle ("My Buttons "); // Title ofthe window. setLayout (new FlowLayout ()); // Sets
the layout /using layout manager
add( new Button ("Yellow")); //Creating buttons with //respective labels
add( new Button ("Blue"));
add( new Button ("Orange"));
add( new Button ("Cyan"));
add( new Button ("Pink"));
add( new Button ("Red"));
Button b= new Button("Green");
add(b);
b.addActionListener(this);
addWindowListener(newMywindowadapO);
}
public void actionPerformed(ActionEvent e)

System.out.println(" Button Green is Pressed");


public static void main(String args[]){
Frame f = new MyButtons();
fsetSize(300,300),
fsetVisible(true);
}
class Mywindowadap extends WindowAdapter{
public void windowClosing(WindowEvent we)(
System.exit(O);
}
}

120
Training Cycle 9
Wintech Computers JAVA 2

9.13 Panels

Panels are sort of smaller containers where the components can be placed. For example if
you want all the buttons collectively in one area of the window, then you can place them
in a panel, so that the panel can then be placed in one part of the window. The panel
functions as a container and provides a precise functioning of the components. The panel
has no visible boundaries and is just an organizin j tool for the GUI design. Panel is class
from which we can create objects. To have a panel in a window you

1. build a panel, and then


2. add the panel to the window.

Example:

public class MyPanel extends Frame


{
public MyPanel () //Constructor
{
setTitle("My panel " ); //Sets the title for the
window.
Panel p = new Panel ( ); //Construct a panel p.
p.setLayout(new FlowLayout ());// Call layout
manager for the panel.
p.add ( new Button ( " Tick ")); // Add buttons to the
panel.
p.add ( new Button ( " Reset "));
p.add ( new Button ( " Close "));
add ( " South ", p ); //Position the panel at the
bottom of window

main should be written here


}

In this sample code we called the layout manager of the panel object, not that of the
window. This aligns the buttons in the panel. The panel belongs tojava.awt.Container.
The syntax for this

java.awt.Container

public Component add ( String name, This adds a component to the container.
Component c) Name Name is a string like "South" as
defined on Borderlayout manager ( The

Training Cycle 9 121


Wintech Computers JAVA 2

default manager for frames)


c : c is the component to be added.

9.14 Panel Positions

North

West Center East

South

9.15 Canvas

As you have seen, a panel provides a rectangular place to the user interfaces. You also
need area where you can draw shapes etc. To do this you add a canvas to a window. A
canvas is nothing but a rectangular area where you can draw shapes. Canvas is necessary
to avoid your drawing to interfere with the buttons.

CanVas is a class from which you derive your own classes.

Example:

Class MyCanvas extends Canvas //Creates a class MyCanvas from


Canvas

{
public void paint ( Graphics g )
{
g.drawRect (

In a canvas class you use the paint () method to actually draw your shapes.

122
Training Cycle 9
Wintech Computers JAXA 2

9.11 Sample Program

import java.awt.*;
import java.applet.*;
/*<applet code="CreateCanvas" height="200'
width="100"></applet>*/
public class CreateCanvas extends Applet
{
private Canvas c;
public void init ( )
{
c = new Canvas( );
c.setBackground( Color.green) ;
c.resize( 250,60);
add(c);
}
}

Text Input
By now you have an idea of how to add buttons and make them respond to a simple
clicking event But these buttons don't accept text input from the user
The areas used to input text are called text fields. TextField is a class. TextFields are
added to a panel just like buttons. Methods defined in the TextField class are given
below

java.awt TextField

public TextField ( String text, int cols ) This constructs a new TextField

Text Is the text to be displayed


Cols The width of the text field is column, which is the no of characters
you expect to enter in the text field If the user enters more it is scrolled.

java awt TextComponeni

public void setText ( String t): Changes the text of text component
t New Text

public String getText (): Returns the text contained in the text component

Training Cycle 9 123


Wintech Computers JAVA l

9.12 Sample Program

import java.awt.*;
import java.applet.*;

public class Addition extends Applet


{
Label prompt;
TextField input;
int number;
int sum;
public void init()
{
prompt=new Label("Enter integer and press Enter;");
input=new TextField(lO);
add(prompt);
add(input);
sum=0;
}
}
public boolean action(Event e, Object o)
{
number =Integer.parselnt(o.toString()); input.setText("");

catch(NumberFormatException ex){ requestFocus();


return true;
}
sum=sum+number;
showStatus{lnteger.toString(surn));
return true;
}

9.15.1 Input Validation

When you enter text into a text field it is to be validated. If the text entered is not correct
then appropriate action has to be taken. In most cases the focus should be resumed ro
where the wrong entry was made. This is done using the requesttFocus () method in the
component class. More at this in the subsequent chapters.

9.16 Text Areas

If more than a line of text is to be input a textField will not do. The TextArea component
is to be used. In this component you can enter any number of lines. The methods dealing
with TextAreas are given below.

Training Cycle 9 124


Wintech Computers JAVA 2

java.awt.TextArea

public TextArea (int rows, int cols): constructs atextArea


rows: number of rows
clos: number of columns

MytextArea = new TextArea (10, 60) //10 hn.es of60 colum~rs each

Training Cycle 9 125


Wintech Computers
JAVA 2

9.16.1 Editing text


The following methods are used Inserts a string s into the text area.
for editing text.Public void
S: The string to be insert
insertTert( String s, int pos)
Eg: void insertText ( " Very
pos: The position at which string is to be
Good ", 20 );
inserted, 0 is 1st position. New lines are
treated as one character.
Public void appendText(String Append the text in sto the existing text.
s):
Public void replaceText String Replace a range of text with another text.
s, int start, in' end)

9.13 Sample Program: For Text Areas

import java.awt.*;

public class MyTextArea extends Frame


{
TextArea ta;
public MyTextArea() // Constructor
{
setTitle ("My Text Area "),
Panel p = new Panel();
p.setLayout(new FlowLayout
p.add(new Button("Print")),
p.add( new Button(" Close";
add("South",p);
ta= new TextArea(8,40);
add("Center", ta);
}
public static void main(String args[]){
Frame f = new MyTextArea();
f.setSize(300,300);
f.setVisible(true);
}

Training Cycle 9 126


Wintech Computers JAVA 2

9.16.2 Selecting Text

You can select portions ofthe text in the text area using the methods given below.

java.awt.TextComponent

Public void selectAH () Selects all text in the text area

public void select(int start, int end) Select the range of text,
start: Starting position of text
end: ending position of text.
public int getSelectionStart() Returns the first position of selected text.

public int getSelectionEndQ Returns the last position of selected text

Public String getSelectedTextQ Returns a string containing selected text.

Training Cycle 9 127


Wintech Computers JAVA 2

import java.awt.*;
import java.awt.event.*;

public class SelectTextArea extends Frame


{
TextArea ta;
String str;
public SelectTextArea()
{
setTitle("My Text Area");
Panel p=new Panel();
p.setLayout(new FlowLayout());
p. add(new Button(" Print"));
p.add(new Button("Close"));
add("South", p);
ta=new TextArea(8,40);
add("Center",ta);
ta.setText("This program is for testing");
}
public boolean handleEvent(Event e)
{
if(e.id==Event.WINDOW_DESTROY)
System.exit(0);
return super.handleEvent(e);
}
public boolean action(Event e,Object obj)
{
if (obj.equals("Print"))
System.out. println(ta.getSelectedText());
else if(obj.equals("Close"))
System. exit(0);
else return super.action(e,obj);
return true;
}

public static void main(String args [])


{
Frame f=new SelectTextArea();
f.resize(300,300);
f. show();
}
}

9.17 Label Fields

Text fields have to be given labels, so that the user can knot what tie has to
enter into these fields. Whereas buttons have their names displayed of on them,
text fields have labels that get displayed alongside. These labels are simple text
strings and don't react to user input.

Training Cycle 9 128


Wintech Computers JAVA 2

java.awt.Label

Public Label (String s ) Creates a label with text s


s: The label text.
Public Label ( String s, int Creates a label with text s
align ) s: The label text.
align: Alignment either LEFT, CENTER or
RIGHT

9.18 Check Boxes

Check boxes provide the user a set of choices. He cannot enter text into these. He can
only select or deselect the check boxes. These save the trouble oferror checking.
Checkbox is an object of awt package.

The user clicks the check box and the box gets checked accordingly. Check boxes have
only two states - true or false.

Example:

class MyFrame extends Frame


{
public MyFrame()
{
panel P;
bold = new Checkbox ("Bold"); //Creates the check box
p.add(bold); //Adds the panel

private Checkbox bold;

An action is triggered when auser clicks on the check box. The event identified by a
particular check box is called target The method getStateQ returns the state of the check
box - false ifunchecked, true ifchecked. For example ifan event object is e, then we can
write e.target.equals(bold).

java awt Checkbox

Training Cycle 9
129
Wintech Computers JAVA 2

public Checkbox( String label) Creates a check box with a label on it.

public boolean getState () Returns the state of check box

public void setstate ( boolean Sets the check box to a new state, either
state )
true or false.

Sample Program 9.14

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class MyCheckbox extends Applet


{
private Font f;
private TextField t;
private Checkbox checkBold, checkltalic;

public void init ()


{
t= new TextField("Sarnp/Oe Text", 30);

checkBold=new Checkbox("Bold");
checkltalic=new Checkbox("Italic");
f=new Font("TimesRoman", Font. PLAIN, 14);
t.setFont(f);

add(t);
add(checkBold);
add(checkltalic);

public boolean action (Event e', Object o)


{
int b,i;
if (e. target instanceof Checkbox) {
if (checkBold.getState() ==true)
b=Font. BOLD;
else
b=Font. PLAIN;
if (checkltalic.getState() ==true)
i=Font. ITALIC;
else
i=Font. PLAIN;
}
return true;
}}

Training Cycle 9 130


Wintech Computers JAVA 2

9.19 Checkbox Group (Radio buttons)

A group of check boxes are preferred when a user has to select only one of
the several choices. These are actually radio buttons grouped together.
They permit only one of the buttons to be selected. The awt package has a
class CheckBoxGroup to provide for the grouping of the radio buttons.

CheckBoxGroup cbg = new CheckBoxGroup ();


mini = new Checkbox ( "Minimize", cbg, false );
maxi = new Checkbox ( "Maximize", cbg, true );

Notethat in a group of check boxes only one can be initially set to true. How does the
check box group identify the event?

java.awt.Checkbox

public Checkbox ( String I, CheckboxGroup cbg, boolean state


): This creates a check box with label of string 1, belongs
to cbg an object CheckboxGroup, and third parameter js a
boolean true or false.

Training Cycle 9
131
Wintech Computers JAVA 2

Sample Program 9.15: Radio Buttons

import java.applet.*;
import java.awt.*;
/*<applet code="RadioButtonl" width=*"200"
height="100"></applet>*/
public class RadioButtonl extends Applet
{
private Font f;
private TextField t;
private CheckboxGroup radio;
private Checkbox radioBold, radioltalic, radioPlain;
public void init()

t=new TextField("Sample Text", 30);


radio=new CheckboxGroup();
add(t); ..*.
add(radioPlain=new Checkbox("Plain",radio,true));
add(radioltalic = new Checkbox ("Italic",radio,false));
add(radioBold=new Checkbox("Bold", radio, false));
}}

9 20 CHOICE BOXES

In Java drop down list box are called choice boxes. These are preferred when choices to
user are many, so that using radio buttons will look crowded on the screen. When auser
clicks on the choice box, alist ofchoices drops down from which he is to select one item.
Choice is a class ofawt package is used to create achoice box.
Example.
cbox = new Choice ();
This creates anobject cbox of Choice box type.

java.awt.Choice

. public void additem ( string item ): Adds an item to the choice box
component.

Note: Once an item is added to the choice box, it cannot be removed.

Example

cbox = new Choice ( );


cbox.additem("Times Roman ");
cbox.additem(" Helvetica");

132
Training Cycle 9
JAVA 2
Wintech Computers

Sample Program 9.16: For choice box.

import java.applet.*;
import java.awt.*;
/*<applet code="MyChoice" height="100' width="200"x/applet>*/
public class MyChoice extends Applet
{
private Font f;
private TextField t;
private Choice choiceButton;

public void init()

t=new TextField("Sample Text", 16);


t.setEditable(false);
choiceButton = new ChoiceO;
choiceButton.additem("TimesRoman");
choiceButton.additem("Courier");
choiceButton.additem("Helvitica");
f=new Font(choiceButton.getltem(O),Font.PLAIN, 14);
t.setFont(f);

add(choiceButton);
add(t);

9.21 List component


The list component is similar to Choice box., but with all the items displayed, so that the
user can view them at the same time. In a Choice box the user had to click on it for the
list to drop down In the list component one can select one or more items whereas this is
not possible in the Choice box. Given below are the methods that deal with the List
component.

java.awt.List

public List(int rows, boolean ms) This is a constructor to create a list


object.
Rows: The number of Items to be shown
Boolean ms: A flag indicating whether
multiple row selection is permitted or
not.

public String getltem (int index ) Gets an item from the list indicated
by index.

Training Cycle 9 133


Wintech Computers JAVA 2

Index: The position of the item to get

public void select (int index ) selects an item in a list component


index: position at the item selected for
initial selection.
Public String[] getSelectedltemsQ Returns an array of selected Items.

9.22 The 1.2 AWTEvent Model

As of JDK l 2, the AWT has a new event model. The old, containment-based model still
works, but its use is discouraged because the 1.2 model is so much more flexible,
powerful, and efficient.

Introduction to the 1.2 AWTEvent Model

In the 1.2 AWT event model, events are generated by event sources. One or more
listeners can register to be notified about events of a particular kind from a particular
source. Sometimes this model is called delegation, since it allows the programmer to
delegate authority for event handling to any object that implements the appropriate
listener interface. The 1.2 AWT event model lets you both handle and generate AWT
events.

Event handle: can be instances of any class. As long as a class implements an event
listener interface, its instances can handle events. In every program that has an event
handler, you'll see three bits of code:
1. In the class statement of the event handler, code declaring that the class
implements a listener interfaces (or extends a class that implements a listener
interface). For example:
public class MyClass implements ActionListener {

2. Code that registers an instance )f the event handling class as a listener upon one
or more components. For example:
someComponent.addActionListener(instance :M
yClass);

3. The implementation ofthe methods in the listener interface. For example.


public void actionPerformed(ActionEvent e)
{
...//code that reacts to the action...

134
Training Cycle 9
Wintech Computers JAVA 2

A Simple Example
Here is a bare-bones 1.2 applet that illustrates event handling. It contains a single button
that beeps when you click it.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code="Beeper" height="100" width="200"x/applet>*/
public class Beeper extends Applet implements ActionListener
{
Button button;
public void init( )
{
setLayout(new BorderLayout());
button = new Button("Click Me");
add("Center", button);
button, addActionLi stener(thi s);
}
public void actionPerformed(ActionEvent e)
{
Toolkit.getDefaultToolkit().beep(),
}

The Beeper class implements the ActionListener interface, which contains one method:
actionPerformed. Since Beeper implements ActionListener, a Beeper object can register
as a listener for the action events that buttons generate. Once the Beeper has been
registered using the Button addActionListener method, the Beeper's actionPerformed
method is called every time the button is clicked.

9.23Handling Standard AWT Events

This section tells you how to write a listener for each kind of event the AWT defines in
1.2 First, it gives an overview of the AWT listeners. After that, each listener type is
discussed in its own subsection.

In the table that follows, each row describes a particular group ofevents corresponding to
one listener interface. The first column gives the name of the listener interface, with a
link to the tutorial page that discusses that listener The second column lists the methods
that the listener interface contains

Training Cycle 9 i *
Wintech Computers JAVA 2

To see which AWT 1.2 components can generate which kinds of events see Events
Generated by AWT Components.

ActionListener ActionPerformed

AdjustmentListner
AdjustmentValueChanged

ComponentHidden
componentMoved
ComponentListener
componentResized
componentShown
ComponentAdded
ContainerListner
componentRemoved
FocusGained
FocusListener
focusLost
Item StateC hanged
ItemListner

KeyPressed
keyReleased
KeyListener
keyTyped

MouseClicked
mouseEntered
MouseListner mouseExited
mousePressed
mouseReleased
MouseDragged
MouseMotionLi stener
mouseMoved
TextListener TextValueChanged
WindowActivated
windowClosed
windowClosing
windowListener windowDeaciivated
windowDeiconified
windowlconified
windowOpened

The AWT events described in the preceding table can be divided into two groups: low-
level events and semantic events Low-level events represent window-system occurrences
or low-level input. Clearly, mouse and key events - both of which result directly from
user input are low-level events.

Training Cycle 9 136


JAVA 2
Wintech Computers

Component, container, focus, and window events are also low-level events. Component
events let you track changes to a component's position, size, and visibility. Container
events let you know when any component is added to or removed from a particular
container. Focus events tell you when a component gains or loses the keyboardfocus -
the ability to receive characters typed at the keyboard. Window events keep you informed
of the basic status of any kind of Window, such as a Dialog or a Frame.
Mouse events are broken into two groups ~ mouse motion events and all other mouse
events - so that an object can listen for mouse events such as clicks without requiring the
system overhead necessary for generating and forwarding mouse motion events, which
tend to occur frequently.
Semantic events include action, adjustment, item, and text events. These events are the
result ofcomponent-specific user interaction. For example, a button generates an action
event when the user clicks it, and a list generates an action event when the user
doubleclicks an item in it. Adjustment events occur when a user somehow changes the
value of a scrollbar. When a user selects an item in a group of items (such as a list), an
item event is generated. Text events occur whenever the text in a text area or text field
changes.

The next few pages have details on each type of event.

9.24 Events Generated by AWT Components

This table lists the kinds of events that each 1.2 AWT component can generate.

Types of Events It Can Generate


AWT Component acti adjust ;Comp contai foe ite \kei mo mouse |tex|win
on mem onent Iner us jmjy use motion jt jdow
Button X X X IX X X
Canvas X X ;X|X X
Checkbox X X X XX X
CheckboxMenuItem X

Choice x X X X X X

Component X X ix X X

Container X X IX IX X

X X XX X X

Frame X X X;X
Label X X X X X

List X X x jx X X

Menultem
X

Panel ;X X IX X
Scrollbar X X X X X
ScrollPane |X X X

Training Cycle 9 137


Wintech Computers
JAVA 2

TextArea IX X xxx X
TextComponent X X XXX
TextField X X X xxx X
Window
xxx
iArfrttt XX X X

Writing an Action Listener


Action listeners are probably the easiest - and most common - event handlers to
implement You implement an action listener to respond to the user's indication that some
implementation-dependent action should occur.
When the user clicks abutton, doubleclicks alist item, chooses amenu item, or presses
return in a text field, an action event occurs. The result is that an actionPerformed
message is sent to all action listeners that are registered on the relevant component.
Action Event Methods

The ActionListener interface contains a single method, here is the lone ActionListener
method

void actionPerformed(ActionEvent)
Called by the AWT just after the user informs the listened-to component that an action
should occur.

Examples of Handling Action Events


Here is the action event handling code from an applet named Beeper:
public class Beeper ... implements ActionListener
(

//where initialization occurs:


button.addActionListener(this);

public void actionPerformed(ActionEvent e)


(
//Make a beep sound...
)

The ActionEvent Class

The actionPerformed method has a single parameter: an ActionEvent object. The


ActionEvent class defines two useful methods:

String getActionCommand()

Returns the string associated with this action. Most objects that can generate actions
support a method called setActionCommand that lets you set this string. If you don't set
the action command explicitly, then it's generally the text displayed in the component.

Training Cycle 9 138


Wintech Computers JAVA 2

For objects with multiple items, and thus multiple possible actions, the action command
is generally the name of the selected item.

int getModifiers()

Returns an integer representing the modifier keys the user was pressing when the action
event occurred. You can use the ActionEvent-defined constants SHIFTMASK,
CTRL_MASK, META_MASK, and ALT_MASK to determine which keys were pressed.
For example, if the user Shift-selects a menu item, then the following expression is
nonzero:

actionEvent.getModifiers() &
ActionEvent.SHIFT_MASK

Also useful is the getSource method, which returns the object (a component or menu
component) that generated the action event. The getSource method is defined in one of
ActionEvent's superclasses, EventObject

Writing a Component Listener


A Component object just after the component is hidden, made visible, moved, or resized
generates one or more component events. An example of a component listener might be
in a GUI builder tool that's displaying information about the size ofthe currently selected
component, and that needs to know when the component's size changes. You shouldn't
need to use component events to manage basic layout and rendering.
The component hidden and component visible events occur only as the result ofcalls to a
Component's setVisible method (or its deprecated equivalents, show and hide). For
example, a window might be miniaturized into an icon (iconified), without a component
hidden event being generated.

Component Event Methods

The ComponentListener its corresponding adapter class,, contain four methods:


void componentHidden(ComponentEvent)
Called by the AWT after the listened-to component ishidden as the result ofthe
setVisible method being called.

voidcomponentMoved(ComponentEvent)
Called by the AWT after the listened-to component moves, relative to its container. For
example, ifawindow is moved, the window generates a component moved event, but the
components it contains do not.

void componentResized(ComponentEvent)
Called by the AWT after the listened-to component's size (rectangular bounds) changes.
voidcomponentShown(ComponentEvent)

Training Cycle 9 I-_


Wintech Computers JAVA 2

Called by the AWT after the listened-to component becomes visible as the result
of the setVisible method being called

Writing a Container Listener


Container events are generated by a Container just after a component is added to or
removed from the container These events are for notification only -- no container listener
need be present for components to be successfully added or removed

Container Event Methods

The ContainerListener, contain two methods

void componentAdded(ContainerEvent)

Called bv the AWT just after a component is added to the listened-to container

void componentRemoved(ContainerEvent)

Called by the AWT just after a component is removed from the listened-to container.

The ContainerEvent Class

Each container event method has a single parameter: a ContainerEvent object. The
ContainerEvent class defines two useful methods:

Component getChild()

Returns the component whose addition or removal triggered this event.


Container getContainer()

Reiurns the container that fired this event

Writing a Focus Listener


Focus events are generated whenever a component gains or loses the keyboardfocus -
the ability to receive keyboard events From the user's point of view, the component with
the keyboard focus is usually prominent - with a thicker bolder than usual, for example -
- and the window containing the component is also more prominent than other windows
on-screen This lets the user know which component any typing will go to. At most one
component in the window system can have the keyboard focus.
Exactly how components gain the focus depends on the window system Typically,
the user sets the focus by clicking a window or component, by tabbing between
components, or by otherwise interacting with a component You can request that a
component get the focus by invoking the Component requestFocus method.

140
Training Cycle 9
Wintech Computers JAVA 2

Focus Event Methods

The FocusListener interface contain two methods:

void focusGained(FocusEvent)

Called by the AWT just after the listened-to component gets the focus.
void focusLost(FocusEvent)

Called by the AWT just afterthe listened-to component loses the focus.
Examples of Handling Focus Events

The below code block show you how to handle Focus event.

component. addFocusListener(new MyFocusListener(V);

public class MyFocusListener extends FocusAdapter {


public void focusGained(FocusEvent evt) {
// The component gained the focus.
}
public void focusLost(FocusEvent evt) {
// The component lost the focus.
}
}

where component can any component say Button.


The FocusEvent Class

Each focus event method has a single parameter: a FocusEvent object. The FocusEvent
class defines a method, is Temporary, which returns true if a focus lost event is
temporary. It's essential knowledge when you wish to indicate that a particular
component will get the focus if its window regains the focus.
The most common message you'll send to aFocusEvent object is getComponent (defined
in ComponentEvent) which returns the component that just gained or lost the focus,
causing the focus event.

Writing an Item Listener

Item events are generated by components that implement the ItemSelectable interface.
These are components that maintain state - generally On/off State for one or more items.
The 1.2 AWT components that generate item events are checkboxes, checkbox menu
items, choices, and lists.

Item Event Methods

The ItemListener interface has just one method, so it has no corresponding


adapter class. Here's the method:

Training Cycle 9 ...


Wintech Computers JAVA 2

void itemStateChanged(ItemEvent)

Called by the AWT justafter a state change in the listened-to component.

Examples of Handling Item Events


Write an example here

The ItemEvent Class

Each item event method has a single parameter: an ItemEvent object. The ItemEvent
class defines the following handy methods:

Object getltem()

Returns the component-specific object associated with the item whose state changed.
Often this is a String containing the text on the selected item. For an item event
generated by a List, this is an Integer that specifies the index of the selected item.

ItemSelectable getItemSelectable()

Returns the component that generated the item event.

int getStateChangeQ

Returns the new state of the item. The ItemEvent class defines two states:
SELECTED and DESELECTED

Writing a Key Listener


Key events tell you when the user types at the keyboard. Specifically, key events are
generated by the component with the keyboard focus when the user presses or
releases keyboard keys You can be notified about two basic kinds of key events: the
typing of a Unicode character, and the pressing or releasing of a key on the keyboard.
The first kind of event is called a key typed event. The second kind are keypressed
and key released events

In general, you should try to use key typed events unless you need to know when the
user presses keys that don't correspond to characters. For example, if you want to
know when the user types some Unicode character ~ even one that results from the
user pressing several keys in sequence listen for key typed events. On the other
hand, if you want to know when the user presses the Fl character, you need to listen
for key pressed/released events.
wwwwwwww

Note: To generate keyboard events, a component must have the keyboard


focus

To make a component get the keyboard focus, follow these steps:

Training C>cle 9 '*


Wintech Computers JAVA 2

1. Make sure the component that the user will be typing into can get the
keyboard focus. For example, on some systems, labels might not be able
to get the keyboard focus.

2. Make sure that the component requests the focus when appropriate. For
custom components, you'll probably need to implement a MouseListener
that calls the requestFocus method when the component is clicked.

3. If you're writing a custom component, implement the component's


isFocusTraversable method so that it returns true. This lets the user tab to
your component.

Key Event Methods


The KeyListener interface contain three methods:

void keyTyped(KeyEvent)

Called by the AWT just after the user types a Unicode character into the listened-
to component.

void keyPressed(KeyEvent)

Called by the AWT just afterthe user presses a key on the keyboard.
void keyReleased(KeyEvent)

Called by the AWT just after the user releases a key on the keyboard

Example For KeyEvent Handling


The following example demonstrates key events. It consists of a text field that you can
type into, followed by a text area that displays a message every time the text field fires a
key event. A button at the bottom of the applet lets you clear both the text field and text
area.

importjava.applet.Applet;
import java.awt.*;
import java.awt.event. *;
/*<applet code-'KeyEventDemo" height-'100" width="300"></applet>*/
public class KeyEventDemo extends Applet implements KeyListener, ActionListener
TextArea display Area;
TextField typingArea;
String newline;
public void init()
{
Button button = new Button("Clear"); button.addActionListener(this);

Training Cycle 9 *a%


Wintech Computers IAVA

typingArea =new TextField(20); typingArea.addKeyListener(this);


displayArea =new TextArea(5, 20); displayArea setEditable(false)';
setLayout(new BorderLayout());
add("Center", displayArea);
addfNorth", typingArea);
add("South", button);
newline = System getProperty(''line. separator");

/** Handle the key typed event from the text field. */

public void keyTyped(KeyEvent e)


{
displayInfo(e, "KEY TYPED ")
}

/** Handle the key pressed event from the text field. */

public void keyPressed(KeyEvent e)


{
displayInfo(e, "KEY PRESSED: ");
}

/** Handle the key released event from the text field. */

public void keyReleased(KeyEvent e)


{
displaylnfo(e, "KEY RELEASED: ");
}

/** Handle the button click. */

public void actionPerformed(ActionEvent e)


{
//Clear the text components.

displayArea.setText("");
typingArea. setText("");
//Return the focus to the typing area.
typingArea.requestFocus();
}

protected void displayInfo(KeyEvent e, String s)


{
String charString, keyCodeString, modString, tmpString; char c =
e.getKeyCharQ,

Training Cycle 9 144


IAVA 2
Wintech Computers

int keyCode = e.getKeyCode().


int modifiers = e getModifiers().
if(Character.isISOControKc))

charString = "key character - (an unprintable control character)";


} else
{
charString = "key character = '" + c + ,
}

keyCodeString = "key code = " + keyCode + " (" +


KeyEvent.getKeyText(keyCode) + ")",
modString = "modifiers = " + modifiers,
tmpString = KeyEvent.getKeyModifiersText(modifiers).

if(tmpString.length()>0)
{
modString += " (" + tmpString + ")"; }
else
{
modString +--- " (no modifiers)".
i
i

displayArea.append(s + newline + " " +charString + newline + " "


+ keyCodeString + newline + " " + modString + newline);
}

The KeyEvent Class


Each key event method has a single parameter: a KeyEvent object The KeyEvent class
defines the following useful methods:

int getKeyChar()

void setKeyChar(char)

Get or set the Unicode character associated with this event

int getKeyCode()

void setKeyCode(int)

Get or set the key code associated with this event. The key code identifies the
particular key on the keyboard that the user pressed or released The KeyEvent class
defines many key code constants for commonly seen keys For example, VKA
specifies the key labeled A, and VK ESCAPE specifies the ESCAPE key
void setModifiers(int)

Training Cycle 9 145


Wintech Computers

Sets the state of the modifiet keys for this event Also see the InputEvent getModifiers
method

Other potentially useful methods in KeyEvent include methods that generate localizable
text descriptions ofkey codes and modifier keys.
The KeyEvent class extends InputEvent, which extends ComponentEvent
ComponentEvent provides the handy getComponent method. InputEvent provides the
following useful methods

int getWhen()

Returns the timestamp of when this event occurred. The higher the timestamp the
more recently the event occurred [CHECK!]
boolean isAltDownQ
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()

Convenient methods giving you the state of the modifier keys when the event was
generated

int getModifiers()

Returns a flag indicating the state of all the modifier keys when the event was
generated

Writing a Mouse Listener

Mouse events tell you when the user uses the mouse (or similar input device) to
interact with a component Mouse events occur when the cursor enters or exits a
component's on-screen area and when the user presses or releases the mouse button.
Because tracking the cursor's motion involves significantly more system overhead
than tracking other mouse events, mouse motion events are separated into a separate
listener type

Mouse Event Methods

The Mousel.istener interface contains three methods:

void mouseCIicked(MouseEvent)

Called by the AWT just after the user clicks the listened-to component.
void mouseEntered(MouseEvent)

Called by the AWT just after the cursor enters the bounds of the listened-to
component

void mouseExited(MouseEvent)

Training Cycle 9 146


Wintech Computers JAVA 2

Called by the AWT just after the cursor leaves the bounds of the listened-to
component.

void mousePressedfMouseEvent)

Called by the AWTjust after the user presses a mouse button while the cursor is
over the listened-to component.

void mouseReleased(MouseEvent)

Called by the AWT just after the user releases a mouse button after a mouse press
over the listened-to component.

One complication affects mouse-entered, mouse-exited, and mouse-released events.


When the user drags (presses and holds the mouse button and then moves the mouse),
then the component that the cursor was over when the drag started is the one that receives
all subsequent mouse and mouse-motion events up to and including the mouse button
release. That means that no other component will receive a single mouse event - not
even a mouse-released event while the drag is occurring.

Examples of Handling Mouse Events


Below is a code block which shows how to get thenumber of times the mouse clicked.

component. addMouseListener(new MyMouseListener());

public class MyMouseListener extends MouseAdapter {


public void mouseClicked(MouseEvent evt) {
if (evt.getClickCountO = 3) (
// triple-click
}else if (evt.getClickCountO = 2) {
// double-click
}
}
}

The MouseEvent Class

Each mouse event method has a single parameter: a MouseEvent object. The
MouseEvent class defines the following useful methods:
int getClickCount()

Returns the number ofquick, consecutive clicks the user has made (including
this event).
int getX()

int getYQ

Training Cycle 9
Wintech Computers JAVA 2

Point getPoint()
Return the (x,y) position at which the event occurred, relative to the component over
which the event occurred.

boolean isPopupTrigger()
Returns true if the mouse event should cause a popup menu to appear. Because popup
triggers are platform dependent, if your program uses popup menus, you" should call
isPopupTrigger for both mouse down and mouse up events.
The MouseEvent class extends InputEvent, which extends ComponentEvent.
ComponentEvent provides the handy getComponent method. InputEvent provides the
following useful methods.
int getWhen()
Returns the timestamp ofwhen this event occurred. The higher the timestamp, the more
recently the event occurred
boolean isAltDown()
boolean isControlDown()
boolean isMetaDown()
boolean isShiftDown()

Convenient methods giving you the state of the modifier keys when the event was
generated.
int getModifiers()
Returns aflag indicating the state of all the modifiers when the event was generated.
Besides the modifier keys, this flag indicates which mouse button was pressed. For
example, the following expression is true ifthe right button was pressed:

(mouseEvent.gefModifiersO &InputEvent. BUTTON3MASK)


== InputEvent.BUTTON3_MASK

Example for Mouse Event:


Below is code block which shows you how to get which buttons ofthe mouse is clicked.
component.addMouseListener(newMyMouseListener());
public class MyMouseListener extends MouseAdapter (
public void mouseClicked(MouseEvent evt) (
if ((evt.getModifiers() &InputEvent.BUTTONl_MASK) != 0) {
processLeft(evt.getPoint()); }
if ((evt.getModifiers() &InputEvent.BUTTON2_MASK) != 0) {
processMiddle(evt.getPoint()); }
if((evt.getModifiers() &InputEvent.BUTTON3_MASK) != 0) {
processRight(evt.getPoint()); }

148
Training Cycle 9
Wintech Computers J*v*

Writing a Mouse Motion Listener


Mouse motion events tell you when the user uses the mouse (or a similar input device) to
move the onscreen cursor

Mouse Motion Event Methods


The MouseMotionListener inteiface contain two methods:
void mouseDragged(MouseEvent)
Called by the AWT in response to the user moving the mouse while holding a mouse
button down This event is fired by the component that fired the preceding mouse-pressed
event, even if the cursor is no longer over that component
void mouseMoved(MouseEvent)

Called by the AWT in response to the user moving the mouse with no mouse buttons
pressed. This event is fired by the component that's currently under the cursor.

Examples of Handling Mouse Motion Events


Below- is a program which demonstrates the use MouseMotionEvents.

import 3ava.applet.*;
import java.awt.*;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;
/*<applet code="MouseMotionEventDemo" height="200"
width="300"></applet>*/
public class MouseMotionEventDemo extends Applet
implements MouseMotionListener
{
TextField textfi;
TextArea textArea;
static final int maxlnt = java.lang.Integer.MAX_VALUE;
String newline;

public void init() {


GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);

c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1.0;
c.weighty = 1.0;

Training Cycle 9 149


Wintech Computers JAVA

c.insets = new Insets(l, 1, 1, i);


textfi= new TextField(12);
gridbag.setConstraints(textfi, c);
add(textfi);

c.insets = new Insets(0, 0, 0, 0);


textArea = new TextArea(5, 20);
textArea.setEditable(false);
gridbag.setConstraints(textArea, c);
add(textArea);

//Register for mouse events on Textzfield and applet(panel).


Textfi.addMouseMotionListener(this) ;
addMouseMotionListener(this);

newline = System.getProperty("line.separator");
1

public void mouseMoved(MouseEvent e) {


msg="Mouse moved";
repaint();
}

public void mouseDragged(MouseEvent e) {


msg="Mouse Dragged";
repaint();

public void paint(Graphics g;


g.drawString(msg,100,200);

Event Methods Used by Mouse-Motion Listeners


Each mouse motion event method has a single parameter -- and it's not called
MouseMotionEvent' Instead, mouse motion event methods use MouseEvent objects

Writing a Text Listener


Text events are generated after the text in a text component has changed somehow. The
1.2 AWT components that generate text events are text fields and text areas. To get
earlier notification of text changes - for example, to intercept incorrect characters - you
should write a key listener

Text Event Methods


The TextListener interface has just one method, so it has no corresponding adapter class.
Here's the method:

Training Cycle 9 150


Wintech Computers JAVA 2

void textValueChanged(TextEvent)
Called bv the AWT just after the text in the listened-to component changes

The TextEvent Class


Each text event method has a single parameter: a TextEvent object The TextEvent class
defines no generally useful methods Using the getSource method that TextEvent inherits
from F.ventObject, you can get the text component that generated the event and then send
messages to it

Writing a Window Listener

Window events are generated by a Window just after the window is opened, closed,
iconified, deiconified, activated, or deactivated Window events also notify the listener
when the window has received a request that it close Opening a window means showing
it for the first time, closing it means disposing of the window Icomfying it means
substituting a small icon on the desktop for the window, deiconifying means the opposite
A window is activated if it or a component it contains has the keyboard focus,
deactivation occurs when the window and all of its contents lose the keyboard focus

The most common use of window listeners is closing windows If a program doesn't
handle window-closing events, then nothing happens when the user attempts to close a
window An application that features a single window might react to window-closing
events from that window by exiting Other programs usually react to window-closing
events by disposing of the window or making it invisible
Another common use of window listeners is to stop threads and release resources when a
window is iconified, and to start up again when the window is deiconified This way, you
can avoid unnecessarily using the processor or other resources For example, when a
window that contains animation is iconified, it should stop its animation thread and free
any large buffers When the window is deiconified, it can start the thread again and
recreate the buffers

If you want to be notified when a window is made visible or hidden, then you should
register a componentlistener on the window

Trahvng Cycle 9 .5.


Wintech Computers
JAVA 2

Window Event Methods

The WindowListener interface contain these methods:


void windowOpened(WindowEvent)
Called by the AWT just after the listened-to window has been shown for the first
time

void windowClosing(WindowEvent)
Called by the AWT in response to a user request that the listened-to window be closed
To actually close the window, the listener should invoke the window's dispose or
setVisible(false) method.

void windowClosed(WindowEvent)
Called by the AWT just after the listened-to window has closed.
void windowlconified(WindowEvent)
void windowDeiconified(WindowEvent)
Called by the AWT just after the listened-to window is iconified or deiconified,
respectively

void windowActivated(WindowEvent)
void windowDeactivated(WindowEvent)
Called by the AWT just after the listened-to window is activated or deactivated,
respectively

Examples of Handling Window Events


Below is the code that demonstrates a Window Events in Java.

import java.applet Applet,


import java.awt.*;
import java awt event.ActionListener;
import java awt event ActionEvent,
import java awt event WindowEvent;
import java awt event. WindowListener;
/*<applet code="WindowEventDemo" width="200" height-'100"></applet>*/
public class WindowEventDemo extends Applet
implements WindowListener,
ActionListener {

TextArea display,
Frame window,
Button bl, b2,
static final String SHOW = "show",

Training Cycle 9 152


Wintech Computers JAVA 2

static final String CLEAR = "clear";


String newline;

public void init() {


bl = new Button("Click to bring up a window.");
bl setActionCommand(SHOW);
bl addActionListener(this);

b2 = new Button("Click to clear the display.");


b2. set ActionCommand(CLEAR);
b2 addActionListener(this);

display = new TextArea(5, 20);


display.setEditable(false),

setLayout(new BorderLayout());
add("North", bl);
add("Center", display);
add("South", b2);

//Create but don't show window.


window = new Frame("Window Event Window");
window.addWindowListener(this);
window.add("Center",
new Label("The applet listens to this window for window events."));
window. pack();

newline = System getProperty("line.separator"),


}

public void stop() {


window, setVisible(false);
}

public void windowClosing(WindowEvent e) {


window setVisible(false),
displayMessage("Window closing", e);
}

public void windowClosed(WindowEvent e) {


displayMessage("Window closed", e)
}

public void windowOpened(WindowEvent e) {


displayMessage("Window opened" e)
}

Training Cycle 9
Wintech Computers JAVA 2

public void windowIconified(WindowEvent e) {


displayMessage("Window iconified", e);
}

public void windowDeiconified(WindowEvent e) {


displayMessage("Window deiconified", e);
}

public void windowActivated(WindowEvent e) {


displayMessage("Window activated", e);
}

public void windowDeactivated(WindowEvent e) {


displayMessage("Window deactivated", e);
}

void displayMessage(String prefix, WindowEvent e) {


display.append(prefix
1 H . II

+ e.getWindow()
+ newline);
}

public void actionPerformed(ActionEvent e) {


if (e getActionCommand() == SHOW) {
window. pack();
window setVisible(true),
} else {
display.setTextC'");
}
}
}

The WindowEvent Class

Each window event method has a single parameter: a WindowEvent object The
WindowEvent class defines one useful method, getWindow, which returns the Window
that generated the window event.

Training Cycle 9 154


Wintech Computers JAVA 2

9.25 More on Layout Mangers

Above are pictures of two programs, each of which displays five buttons. The Java code
for both programs is almost identical. So why do they look so different9 Because they use
different layout managers to control the layout of the buttons
A layout manager is an object that controls the size and position of components in a
container. Layout managers adhere to the LayoutManager interface By default, every
Container object has a LayoutManager object that controls its layout For Panel objects,
the default layout manager is an instance of the FlowLayout class For Window objects,
the default layout manager is an instance of the BorderLayout class

Using Layout Mangers


Every Container, by default, has a layout manager ~ an object that implements the
LayoutManager interface If a Container's default layout manager doesn't suit your needs,
you can easily replace it with another one. The AWT supplies layout managers that range
from the very simple (FlowLayout and GridLayout) to the special purpose (BorderLayout
and CardLayout) to the ultra-flexible (GridBagLayout)
This lesson gives you some general rules for using layout managers, gives you an
overview of the layout managers the AWT provides, and then tells you how to use each
of the AWT layout managers

General Rules for Using Layout Managers


Unless you explicitly tell a Container not to use a layout manager, it is associated with its
very own instance of a layout manager This layout manager is automatically consulted
every time the Container might need to change its appearance Most layout managers
don't require programs to directly call their methods.

How to Choose a Layout Manager


The AWT-provided layout managers have different strengths and weaknesses This
section discusses some common layout scenarios and which AWT layout managers might
work for each scenario If none of the AWT layout managers is right for your situation,
you should feel free to use layout managers contributed to the net, such as PackerLayout.

Scenario:
You need to display a component in as much space as it can get Consider using
BorderLayout or GridBagLayout If you use BorderLayout, you'll need tc put the space-
hungry component in the center With GndBagLayout, you'll need to set the constraints
for the component so that fill=GridBagConstraints BOTH Or, if you don't mind every
other component in the same container being just as large as your space-hungry
component, you can use a GridLayout

Training Cycle 9 155


Wintech Computers JAVA 2

Scenario:

You need to display a few components in a compact row at their natural size.
Consider using a Panel to hold the components and using the Panel's default
FlowLayout manager

Scenario:

You need to display a few same-sized components in rows and/or columns


GridLayout is perfect for this

How to Create a Layout Manager and Associate It with a Container


Every container has a default layout manager associated with it All Panels (including
Applets) are initialized to use a FlowLayout All Windows (except special-purpose ones
like FileDialog) are initialized to use a BorderLayout

Ifyou want to use aContainer's default layout manager, you don't have to do athing. The
constructor for each Container creates a layout manager instance and initializes the
Container to use it

To use a non-default layout manager, you need to create an instance ofthe desired layout
manager class and tell the Container to use it. Below is some typical code that does this.
This code creates a CardLayout manager and sets it up as the layout manager for a
Container
^Container.setLayout(new CardLayout());

Rules of Thumb for Using Layout Managers


The Container methods that result in calls to the Container's layout manager are add(),
remove(). removeAll(), layout(), preferredSizeQ, and minimumSize() The add(),
remove(), and removeAll() methods add and remove Components from a Container; you
can call them at any time The layout() method, which is called as the result of any paint
request to a Container, requests that the Container place and size itself and the
Components it contains, you don't usually call it directly. The preferredSize() and
minimumSizeO methods return the Container's ideal size and minimum size,
respectively The values returned are just hints; they have no effect unless your program
enforces these sizes

Flow Layout Manger

java awt FlowLayout

Public Flowl.ayout( int align):


Constructs anew FlowLayout with specified align either LEFT, CENTER or
RIGHT The components are aligned left center or right as specified in case of no
space it will be add components to second line

Training Cycle 9 156


Wintech Computers JAVA 2

Example, toolbar.setLayout( new FlowLayout( FlowLayout.LEFT);

Then you add items into the container. When you re-size, the components
automatically get realigned.

Border Layout Manger


This is the default layout for frames and windows and so need not be mentioned for
these. This layout divides the area into the areas given below.

North

West Center East

South

import java.awt *

public class MyBorderLayout extends Frame


{
public MyBorderLayout ()
{
setTitle("My Border 1ayout");
Panel p = new Panel ();
p.setLayout(new FlowLayout(FlowLayout. LEFT));
p.add(new ButtonfLeft"));
p.add(new Button("Right"V);
p.add(new Button("up"));
p.add(new Button("Down"));
p.add(new Button("Close"));
add("North",p);
addf'East". new Scrollbar(Scrollbar VERTICAL));
addC'South", new Scrollbar(Scrollbar.HORIZONTAL));
}

public static void main(String args[])


{
Frame f = new MyBorderLayout(),
f resize ( 300, 300);

Training Cycle 9 157


Wintech Computers JAVA 2

fshow();

Card Layout Manager


In this layout, the objects ( components ) are placed behind each other, unlike in other
layouts, where they are placed side by side. This means that when you click on one
component ( for examnle a button ) that particular object shows up. These objects are
placed in a panel, and an area (usually rest of the area) is where the objects are managed.
The objects are called cards and can be accessed by the tab key. These cards are grouped
onto individual "index cards" Cards are similar to MDI frames except that they cannot be
tiled

java.awt.CardLayout

public void show(Container parent, String name)


This changes to a card of the card layout.

parent The container with the card layout.


Name: name of card.
Public void first( Container parent): Goes to the first card of the container.
parent: The container with the card layout
Public void next(Container parent): Changes to the next card.
parent The container with the card layout
public void previous(Container parent):
Changes to previous card.
Public void last(Container parent): Changes to the last card
parent : The container with the card layout.

Sample Program
Below is an example for card Layout.

import java applet *,


import java awt *,
import java awt event *
/*<applet code^CardLavoutPxample"' width= '200" height-M00"'*</applet>*/
public class CardLayoutExample extends Applet {
public void init() {
// Create a layout manager, and save a reference to it for future use.
// This CardLayout leaves 10 pixels margins around the component.
final CardLayout cardlayout = new CardLayout(10, 10);

Training Cycle 9 158


Wintech Computers JAVA 2

// Specify the layout manager for the applet


this setLayout(cardlayout);
for(inti= l;i<=9;i++) {
Button b = new Button("Button #" + i);
ActionListener listener = new ActionListener() {
public void actionPerformed( ActionEvent e) { // When button is clicked
cardlayout next(CardLayoutExample this); // display the next one
>

b.addActionListener(listener),
this.add("Button" + i, b); // Specify a name for each component
}
}
}

Grid Layout Manager

When you want to arrange all components in rows and columns as in a calculator, you
use this manger
Example:
Panel p = new Panel ( ); p setLayout ( newGridLayout ( 4, 4 )),

This sets up a grid with four rows and four columns You can then add buttons in the
following manner
p idd ( new Button ( "a" > >.
p add ( new Button ( "b")),

Sample Program

import java applet Applet;


import java.awt.*;
public class Grid extends Applet
{
private Button buttonl, button2, button3, button4, button5;

public void init()


{
buttonl = new Buttonf'one").
button2 = new
Button,'"two"), button3 =
new Button("three"), button4
= new Button("four"),
button5 = new
Button("five"),

Training Cycle 9 159


Wintech Computers JAVA 2

setLayout(new
GridLayout(2,3));

//order is important

add(buttonl) // row 1 col 1


add(button2) // row 1 col 2
add(button3) // row 1 col 3
add(button4) // row 2 col 1
add(button5); // row 2 col 2

Training Cycle 9
Training
Cycle: 10
Wintech Computers JAVA 2

10. JAVA APPLETS

10.1 Introduction

Java basically supports two kinds of applications.

1) Applets
2) Stand alone Applications

Applets are Java programs that run within the confines of a Web browser. Unlike stand
alone applications, applets do not have main functionality. We have by now an idea of
how to develop simple standalone applications. In this Chapter we shall study applets.
The growth and popularity of Java to a significant extent has been due to applets. Before
Java, there is no single programming language with which one can develop applets and
applications for the Internet. Applets can run in a Java enabled web browser or in an
Applet Viewer.

10.1.1 Applet Viewer

Applet Viewer is a standalone program that you can use to test your applets. The Sun
JDK provides this feature which is executed with appletviewer command.

Example: appletviewer MyApplet.html

Testing your applets on a viewer is fast, but does not give the text features outside of the
applet Besides it does not provide the security features of a Web browser and its real life
feel. Applets are meant for theJava enabled browser such as a Netscape Navigator.

To see (load) your applets on the browser or in a appletviewer, you need to create a
separate HTML file with a html extension The executable file with the class extension
should be included in the applet code tag We shall see how this is done with a simple
applet program

Sample Program 10.1 A simple applet program

import java.awt. Graphics;


public class HelloWorld extends java.applet.Applet
(
public void iriit( )
(
setSize ( 100, 50 );

Training Cycle 10 160


Wintech Computers JAVA 2

public void paint ( Graphics g )


{

g.drawString ( "Hello, World ", 50, 30 );


}
}

Save this file and compile it

Creating the HTML file

<HTML>
<HEAD>

<TITLE> My First Applet </TITLE>


<BODY> Say Hi To everyone.
<APPLET> ALIGN = center CODE = "HelloWorld.class" WIDTH=100
HEIGHT=100>
</APPLET>
</BODY>
</HTML>

Save this code with html extension HelloWorld html

How to view the applet?

Method 1
In case you have Sun's appletviewer then enter appletviewer HelloWorld html at
command line.

Method 2:
Go to Netscape and load the html file either from the VRL or selection File/Open
location

If you view the applet in the browser, you can see it is surrounded by text This is useful
to provide additional information about the applet.

10.2 Applet Basics

Applets bring live content to static Web pages. They can be loaded from across the net or
from the local disk and are executed locally. Security is of importance especially when
you load applets from a remote site.

1) Applets can never run any local executable program.


2) Applets cannot communicate with any other host but the originating host
3) Applets cannot get any information about the local computer
4) In Netscape, applets cannot read or write to the local file system

Training Cycle 111 161


Wintech Computers JAVA 2

These features ensure security to both the applets and the local machine

10.2.1 Hierarchy

Any Java based graphical application can easily be converted into an applet This is
because both Frame and Applet are extended from the container class So you can use
same methods for both.

Object

Com >onent

Container

Window Panel

Frame Applet

The life cycle of an Applet


There are four methods that give the frame work to build an applet.
init( )

start( )

stop( ) and

destroy! )

init(): Used for initial setup such as defining layout, passing parameters and other
initializations

start( ):This is called immediately after init Start () is called each time a user returns to
the page or when the page is deiconified Unlike start, init is called once only.

stop( ):This method is called when user moves off the page on which the Applet sits or
when it is iconified If Applet is not doing time-consuming activities like performing
animation, this need not be implemented

destroy(): This method is called when the browser shuts down It is used to re-claim
resources

Training Cycle 10 162


Wintech Computers JAVA 2

Example 10.2.2

import java.applet.*;
import java.awt.Graphics;
public class Simple extends Applet
{
String Buffer buffer;
public void init()
{
buffer= new StringBuffer();
}

public void start( )


{
addltem( "starting...");
}

public void stop( )


{
additem( "stopping...");
}

public void destroy( )


{
additem( "preparing for unloading...");

void additem(String newWord)


{
System.out.println(newWord);
buffer.append(newWord);
repaint( );
}

public void paint( Graphics g)


(
//Draw a rectangle around the applet's display area
g.drawRect(0, 0, size( ).width -1, size( ).height -1);

//Draw the current string inside the rectangle


g.drawString(buffer.toString( ), 5, 15);
}
}

10.3 Methods for Drawing and Event Handling

class Simple extends Applet

163
Training Cycle 10
Wintech Computers JAVA 2

pubic void paint (Graphics g) { .}

The Simple apples defines its onscreen appearance by overriding the paintQ method. The
paintQ method is one of two display methods that applets can override:

Paint()
The basic display method litany applets implement the paint() method to draw the
applet's representation within a browser page

update ()
A method you can use along with paint () to improve drawing performance.

10.4 Methods for Adding Ul Components

The Simple applet's display code (implemented in its paint () method) is flawed: It
doesn't support scrolling. Once the text it displays reaches the end of the display
rectangle, you can't see any new text Here's an example of the problem:

The simplest cure for this problem is to use a pre-made user interface (Ul) component
that has the right behavior

10.5 Methods for Using Ul Components in Applet

Because the Applet class inherits from the AWT Container class, it's easy to add
components to applets and to use layout managers to control the components' onscreen
positions. Here are some of the Container methods an applet can use

add()
Adds the specified Component

remove ()
Removes the specified Component.

setLayout ()
Sets the layout manager.

Training Cycle 10 154


Wintech Computers
1 JAVA 2

10.6 Threads in Applets

Every applet can run in multiple threads. Applet drawing methods (paint () and update Q)
are always called from the ART drawing and event handling thread. The threads that the
major milestone methods - init(), start(), stop ( ), and destroy() - are called from depends
on the application that's running the applet. But no application ever calls them from the
AWT drawing and event handling thread
10.6.1 What Applets Can and Can't Do

Security Restrictions
Every browser implements security policies to keep applets from doing damage The
security policies that current browsers adhere to are described here. However, the
implementation of the security policies differs from browser to browser Also, security
policies are subject to change For example, if a browser is developed for use only in
trusted environments, then its security policies will likely be very much more lax than
those described here

Current browsers impose the following restrictions on any applet that's loaded over the
network

Ai , pplet can't load libraries or define native methods


It cant ordinarily read or write files on the host that's executing it
It can't make network connections except to the host that it came from
It can't start any program on the host that's executing it
It can't read certain system properties
Windows that an applet brings up look different from windows that an
application brings up

Each browser has a Security Manager object that implements its security policies. When
a Security Manager detects a violation, it throws a SecurityException. Your applet can
catch this SecurityException and react appropriately
Applet Capabilities
The Java applet package provides an API that gives applets some capabilities that
applications don't have For example, applets can play sounds, which other programs
can't do yet

Here are some other things that applets can do that you might not expect:
Applets can make network connections to the host they came from.

Applets running within a Web browser can easily cause HTML


documents io be displayed

Training Cycle IO 165


Wintech Computers JAVA 2

Applets can invoke public methods of other applets on the same page.

Applets that are loaded from the local file system(from a


directory in the user's CLASSPATH) have none of the
restrictions that applets loaded over the network do.

Although most applets stop running once you leave their page, they don't
have to.

10.6.2 Adding an Applet to an HTML Page

Once you've written some code for your applet, you'll want to run your applet to test it.
To run an applet in a browser or in the JDK Applet Viewer, the applet needs to be added
to an HTML page, using the <APPLET> tag. You then specify the URL of the HTML
page to your browser or the Applet Viewer.

The Simplest Possible ~APPLET> Tag

Here's the simplest from of the <APPLET> tag:

<APPLET CODE = AppletSubclass.class WIDTH = anlnt HEIGHT = anlnt>


</APPLET>

The above tag tells the browser or applet viewer to load the applet whose Applet
subclass, named AppletSubclass, is in a class file in the same directory as the HTML
document that contains the tag. The above tag also specifies the width and height in
pixels of the applet.

When a browser encounters the tag, it reserves a display area of the specified width and
height for the applet, loads the bytecodes for the specified Applet subclass, creates an
instance of the subclass, and then calls the instance's init () and start () methods.

10.6.3 Specifying the Applet Directory with CODEBASE

Here's a slightly more complex applet tag. It adds a CODEBASE attribute to tell the
browser/viewer which directory the Applet subclass bytecodes are in.
<APPLET CODE =AppletSubclass class CODEBASE=aURL WIDTH = anlnt
HEIGHT = anlnt > </APPLET>

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

Training Cycle 10 166


Wintech Computers JAVA 2

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


</applet>

10.6.4 Specifying Parameters with the <Param> tag


Parameters can be passed to an Applet from HTML.

Sample Program 10.4: Using the PARAM tag

import java.applet.*;
import java.awt.*;
/*
<applet code=Param.class width=300 height=300>
<param name="sl" value="300" >
<param name="s2" value="250"> </applet>*/
public class Param extends Applet
{
int w,h;
public void init()
{
try{
if(getParameter("si")!=null)
w=lnteger.parselnt((getParameter("si"))) ;
else w=500;
if(getParameter("s2")!=null)
h=lnteger.parselnt((getParameter("s2")));
else
h=300;
resize(w,h);
)
catch(Exception e){
System.out.println(e.toString());
}
}

public void paint(Graphics g)


{
g.drawString("Testing for parameters",100, 100) ;
g.drawString(String.valueOf(w),150,150);
g.drawString(String.valueOf(h),200,200);

}
)

10.6.5 Interaction with the browser and other applets:

Applets can interact with the browser and other applets running in the same web page.
For example, you can get information from an applet, process it and pass it to another

Training Cycle 10 167


Wintech Computers JAVA 2

applet for display. Or you might want to tell the browser to display another web page or
load an audioClip. The 'AppletContext' interface contains methods for the above
purposes.

Methods of AppletContext:

Method Function

Gets an applet named name. If not found,


Applet getApplet(String name); null is returned

AudioClip getAudioClipflJRL) Gets an audio clip

Enumeration getAppletQ Lists the applets available in the current


context.
Image getlmage(URL) gets an image

Public void showDocument(URL, String Shows a new document in a target window


target) or frame. Accepts target strings:
selfshow in current frame, parenV.show
in parent frame, top.show in new unnamed
top-level window, and <other>:show
in new top-level window named <other>.
Void showDocument(URL) Tells the browser to show a document of
the url
Void showStatus(String) Shows the string in the status bar of the
browser

Example:
Suppose you want to tell the browser to load another document contained at a
given URL
URL aurl = new URL("http://abc.def.com/-ghijkl/m.html");
getAppletContext.showDocument(aurl);

10.6.6 Converting an applet to a stand alone application:


Follow these steps.
I Change the class froni extending the Applet class to extending Frame class
2. Write 'main' method.
3. Call init(), start(), stop() and destroy() methods in proper sequence to get
required functionality.
In the program below we view an applet in a frame.
import Java.applet.*;
import java.awt.*;

Training Cycle 10
168
Wintech Computers JAVA 2

/* <applet code="StandaloneScribble" width=300 height=300>


</applet> */
public class StandaloneScribble
{
publiq static void mainfString arg[])
{

Applet applet = new Scribbled;


Frame frame=new AppletFrame("Scribble",applet,300,300);
)
class AppletFrame extends Frame
{
public AppletFrame(String title, Applet applet, int width,int height)
{
super(title);
MenuBar menubar = new MenuBarO;
Menu file= new Menu("File",true);
menubar.add(file);
setMenuBar(menubar);
add("Center", applet);
setSize(width, height);
show();
)
public boolean action(Event e. Object erg) (
if (e.target instanceof Menultem) {
String label=(String)erg;
if (label.equals("Quit"))
System.exit(0);
)
return false;
1
)
class Scribble extends Applet
U

One more example below to view an applet in a frame.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="AppletFrame" width=300 height=300x/applet> */
class SampleFrame extends Frame

SampleFrame(String title)
{
super(title);
MyWindowAdapter adapter=new MyWindowAdapter(this);
addWindowListener(adapter) ;
)
public void paint(Graphics g)
(
g.drawString("This is Frame Window",150,130);
)
}

Training Cycle 10 169


Wintech Computers JAVA 2

class MyWindowAdapter extends WindowAdapter


{
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame)
1
this.sampleFrame=sampleFrame;
)
public void windowClosing(WindowEvent we)
(
sampleFrame.setVisible(false);
I
)
public class AppletFrame extends Applet
1
Frame f;
public void init()
{
f=new SampleFrame("A Frame Window");
f.setSize(250,250);
f.setVisible(true);
)
public void start ()
(
f.setVisible(true);
)
public void stop ()
(
f.setVisibleif^lsei;
)
public void paint(Graphics g)
(
g.drawString("This is an Applet window",10,20)

10.7 Animation

Animation is an illusion of movement created by rapid succession of images with slight


changes in content The human eye can be tricked into perceiving movement with as low
value as 10 frames/second (fps) Motion pictures use 24 fps and still achieve good
animation
Most java-based animations are frame-based, because of its simplicity The cast-based
animation is popular in games, where the image moves independent of the background

10.7.1 Java support for Image handling


Java allows images to be imported and displayed It supports GIF and JPEG formats
Image anlmage, //creates an instance

Training Cycle 50
170
V\ intech Computers JAVA 2

^inlmage=getImage (getDocumentBase ( ) , "dike.gif"; ; //gets an image


qetGraphics ( ) . drawlmage (anlmage, 1000, this); - draws the image at
10,20

Example: Basic image handling

import java awt.*,


import java.applet.*;
/*<applet code="BasicImageHandling" width=300 height=300></applet>*/
public class BasiclmageHandling extends Applet
{
private Image I;
public void init()
{
l=getlmage(getDocumentBase(),"hiin034 gif);
}
public void paint(Graohics u)
{
g.drawlmage(l, 10,20,this);
}
}

Ensure that hnn034 gif file should be in your directory

Example: Frame-based Animation in java


import java.applet.*,
import java awt *:

/*<applet code="Animatel" width=400 height=300 - /applet -*

public class Animate! extends Applet implements Runnable


{
Image img[],
int i,j,
int b=4,
int a=4,
Thread t;

public void init()


{
img=new Image[4],
J=0.
fot(i=0,i<4,i-t +)
{img[i]=getlmage(getCodeBase()."juggler"+j " gif),

Training Cycle 10
Wintech Computers JAVA 2

i=0;}
public void startO
{t= new Thread(this);
t.startO;
}
public void paint(Graphics g)
{g.drawlmage(img[i],a,b,this);
}
public void run()
(while(true)
(i++;
ifti=4)
i=0;
repaint();
setSize(200,200); }
}
public void stopO
{ t=null; }
}

Training Cycle 10
172
Training
Cycle: 11
JAVA 2
Wintech Computers

The UML

Introduction

The UML emerged from the unification that occurred in the 1990s following the "method wars"
ofthe 1970s and 1980s. Even though the UML evolved primarily from various second-generation
object-oriented methods (at the notation level), the UML is not simply athird-generation object-
oriented modeling language. Its scope extends its usability far beyond its predecessors. And it is
experience, experimentation, and gradual adoption of the standard that will reveal its true
potential and enable organizations to realize its benefits.

What is UML
The UML is a modeling language for specifying, visualizing, constructing, and documenting the
artifacts of a system-intensive process.
Within a system-intensive process, a method is applied as a process, to derive or evolve a
system.
As a language, it is used for communication. That is, a means to capture knowledge
(semantics) about a subject and express knowledge (syntax) regarding the subject for the
purpose ofcommunication. The subject is the system under discussion.
As a modeling language, it focuses on understanding a subject via the formulation ofa model
ofthe subject (and its related context). The model embodies knowledge regarding the subject,
and the appropriate application ofthis knowledge constitutes intelligence
Regarding unification, it unifies the information systems and technology industry's best
engineering practices across types ofsystems (software and non-software), domains (business
versus software), and life-cycle processes
As it applies to specifying systems, it can be used to communicate "what" is required ofa
system, and "how" a system may be realized.
As it applies to visualizing systems, it can be used to visually depict a system before it is
realized.
As it applies to constructing systems, it can be used to guide the realization of a system
similar to a "blueprint"
As it applies to documenting systems, it can be used for capturing knowledge about a system
throughout its life-cycle.
The UML is not:
A visual programming language, but a visual modeling language.
A tool or repository specification, buta modeling language specification.
A process, but enables processes.
Fundamentally, the UML is concerned with capturing, communicating, and levering knowledge.

Whv We Model

Training Cycle 11 173


Wintech Computers
JAVA 2

Developing a model for an industrial-strength software system prior to its construction or


renovation is as essential as having a blueprint for large building Good models are essential for
communication among project teams and to assure architectural soundness We build models of
complex systems because we cannot comprehend any such system in its entirety As the
complexity of systems increase, so docs the importance of good modeling techniques There are
main additional factors of a projects success, but having a rigorous modeling language standard
is one essential factor A modeling language must include:
Model elements fundamental modeling concepts and semantics
Notation visual rendering of model elements
Guidelines - idioms of usage within the trade
In the face ofincreasingly complex systems, visualization and modeling become essential. The
UML is a well-defined and widely accepted response to that need. It is the visual modeling
language ofchoice for building object-oriented and component-based systems

GOALS OF THE UML


The primary goals in the design of the UML were as follow.
1) Provide users a ready-to-use, expressive visual modeling language so they can develop
and exchange meaningful models.
2) Provide extensibility and specialization mechanisms to extend the core concepts.
3) Be independent of particular programming languages and development processes.
4) Provide a formal basis for understanding the modeling language
5) Encourage the growth of the 00 tools market
6) Support higher-level development concepts such as collaborations, franieworks.pattems, and
components
7) Integrate best practices

These goals are discussed, below

Provide users a ready-to-use. expressive visual modeling language so they can develop and
exchange meaningful models It is important that the OOAD standard support a modeling
language that can be used "out of the box" to do normal general-purpose modeling tasks. Ifthe
standard merely provides a meta-meta-desenption that requires tailoring to a particular setof
modeling concepts, then it will not achieve the purpose of allowing users to exchange models
without losing information or without imposing excessive work to map their models to a very
abstract form The UML consolidates a set of core modeling concepts that are generally
accepted across many current methods and modeling tools. These concepts are needed in many
or most large applications, although not every concept is needed in every partof every
application Specifying a meta-meta-level format for the concepts is not sufficient for model
users because the concepts must be made concrete for real modeling to occur If the concepts in
different application areas were substantially different, then such an approach might work, but
the core concepts needed by most application areas are similar and should therefore be supported
directly by he standard without the need for another layer.
Provide extensibility and specialization mechanisms to extend the core concepts. We expect
that the UML will be tailored as new needs are discovered and for specific domains. At the same
time, we do not want to force the common core concepts to be redefined or re-implemented for
each tailored area Therefore we believe that the extension mechanisms should support
deviations from the common case, rather than being required to implement the core OOA&D
concepts themselves The core concepts should not be changed more than necessary Users need
to be able to
1) build models using core concepts without using extension mechanisms for most

Training Cycle II *''*


I AVA 2
Wintech Computers JrtVA L

normal applications;
2) add new concepts and notations for issues not covered by the core;
3)choose among variant interpretations of existing concepts, when there is no clear consensus;
4) specialize the concepts, notations, and constraints for particular application domains.
Be independent ofparticular programming languages and development processes The UML
must and can support all reasonable programming languages. Italso must and can support
various methods and processes ofbuilding models. The UML can support multiple programming
languages and development methods without excessive difficulty.
Provide a formal basis for understanding the modeling language. Because users will use
formality to help understand the language, itmust be both precise and approachable; a lack of
either dimension damages its usefulness. The formalisms must not require excessive levels of
indirection or layering, use of low-level mathematical notations distant from the modeling
domain, such as set-theoretic notation, or operational definitions that are equivalent to
programming an implementation. The UML provides a formal definition ofthe static format of
the model using a metamodel expressed in UML class diagrams. This is a popular and widely
accepted formal approach for specifying the format ofa model and directly leads tothe
implementation ofinterchange formats. UML expresses well-formedness constraints in precise
natural language plus Object Constraint Language expressions. UML expresses the operational
meaning of most constructs inprecise natural language. The fully formal approach taken to
specify languages such as Algol-68 was not approachable enough for most practical usage.
Encourage the growth of the OO tools market By enabling vendors to support a standard
modeling language used by most users and tools, the industry benefits. While vendors still can
add value in their tool implementations, enabling interoperability is essential Interoperability
requires that models can be exchanged among users and tools without loss of information. This
can only occur if the tools agree on the format and meaning of all of the relevant concepts. Using
a higher meta-level is no solution unless the mapping to the user-level concepts is included inthe
standard.
Support higher-level development concepts such as collaborations, frameworks, patterns, and
components Clearly defined semantics of these concepts is essential to reap the full benefit of
OO and reuse. Defining these within the holistic context of a modeling language is a unique
contribution of the UML.
Integrate best practices. A key motivation behind the development of the UML has been to
integrate the best practices in the industry, encompassing widely varying views based on levels
of abstraction, domains, architectures, life cycle stages, implementation technologies, etc. The
UML is indeed such an integration of best practices.

COMPARING UML TO OTHER MODELING LANGUAGES

The seemingly simple expression 1+2 requires awareness of the following constructs in order
to be understood:
The symbols 1, 2, and +.
The concepts one, two, and addition that the symbols depict.
The rules that govern the concepts and symbols.
The body of knowledge encompassing these constructs is the calculus commonly known as
arithmetic. A calculus is a collection of rule-governed symbols that facilitate reasoning about
something. Arithmetic defines the Arabic numerals with the addition, subtraction, multiplication,
and division symbols, and associated rules to facilitate reasoning about problems and solutions
involving numeric values.

Training Cycle 11 '75


Wintech Computers JAVA 2

Aformal language is an uninterpreted calculus where the mechanical application of rules to a


symbolic representation of a problem yields the appropriate solution.
An uninterpreted calculus involves the application of rules without knowing why the solution is
derived or grasping the semantics or rational of the symbols themselves.
An artificial language is an interpreted calculus where the symbols are interpreted via the
concepts they represent. An interpreted calculus involves die application ofrules by knowing why
the solution is derived and grasping the semantics or rational of the symbols themselves A
natural language is an ordinary human language such as English, Arabic, Russian, etc

Fundamentally, a language consists of a collection of concepts (semantics) with a


notation (syntax) and rules (guidelines) governing the concepts and notation Underlying a
language and the methods that utilize a language is a foundation consisting of fundamental
principles (axioms). These fundamental principles involve essential and "universally" accepted
elements or constituents that define the constructs upon which a language is established (means)
and facilitate some goals and scope to which the language applies (ends). That is. a language is
created for a reason or purpose

Example

1. Money is thefoundation underlying our economic reality.


2. Money facilitates the exchange and attainment of goods and services (ends).
3. Money defines physical articles that are a medium of exchange and measure of value (means)
4. Conclusively, money is the means for pursing various ends within an economic reality

Natural Language UML Definition and Significance


Alphabet Symbol Fragment or String The primitive parts of a language
Character (letters, characters, signs,
marks).
Word Symbol (Node or Path) or The fundamental unit of meaning.
String
Sentence Diagram Fragment Grammatical unit of meaning
containing a subject and a
Predicate (proposition).
Paragraph Diagram Unit of thought containing
grammatical units of meaning about
a subject (or related subjects).
Section Architectural View Organized units of thought.
Document Model Organized knowledge.

Object Orientation
Object orientation is a concept-centric paradigm encompassing the following pillars (first
principles), abstraction, encapsulation, inheritance, and polymorphism. Because the object-
oriented paradigm is derived from the convergence of other fundamental paradigms, it is
reducible to the other paradigms as required by its application via a language or method.
Therefore, because the UML is based on the object-oriented paradigm, it is flexible enough to
facilitate and express artifacts within approaches based on other paradigms (functional, data,
responsibility, etc )

176
Training Cycle 11
Wintech Computers JAVA 2

Architectural Views
Architectural views organize models and knowledge around specific sets of concerns
(architectural focus) The UML provides the following architectural views regarding models of
problems and solutions:
The user modelview encompasses a problem and solution as understood by those individuals
whose problem the solution addresses This view is also known as the use case or scenario
view

The structural model view encompasses the structural dimension of a problem and solution
This view is also known as the static or logical view.
The behavioral model view encompasses the behavioral dimension of a problem and solution.
This view is also known as the dynamic, process, concurrent, or collaborative view
The implementation model view encompasses the structural and behavioral dimensions of the
solution's realization This view is also known as the component or development view
The environment model view encompasses the structural and behavioral dimensions of the
domain m which the solution is realized This view is also known as the deployment or
physical view
Other model views may be defined and used as necessary An architectural focus is defined
by a set ofconcerns (particular to stakeholders) An architectural view is defined by the set of
elements from a model that address an architectural focus For example, security issues may
define an architectural focus. A security architectural view includes the set of elements from a
model that addiess security issues.

The Architecture of the UML

To understand the architecture of the UML. consider how computer programs and programming
languages are related There are many different programming languages (C, C++, Java, Smalltalk,
etc ), and each particular program is developed using a specific programming language All of
these languages support various declarative constructs for declaring data, and procedural
constructs for defining the logic that manipulates data Because a model is an abstraction, each of
these concepts may be captured in set of related models. Programming language concepts are
defined in a model called a metamodel Each particular programming language is defined in a
model that utilizes and specializes the concepts within the metamodel. Each program
implemented in a programming language may be defined in a model called a user model that
utilizes and instanteates the concepts within the model ofthe appropriate language This scheme
of a metamodel representing computer programming constructs, models representing computer
programming languages, and user models representing computer programs exemplifies the
architecture of the UML
The UML is defined within a conceptual framework for modeling (Figure 1) that consists ofthe
following four
distinct layers or levels of abstraction:
The meta-metamodel layer consists ofthe most basic elements on which the UML is based -
the concept of
a "Thing", representing anything that may be defined. This level of abstraction is used to
formalize the notion
ofa concept and define a language for specifying metamodels
The metamodel layer consist of those elements that constitute the UML, including concepts
from the

Training Cycle 11 177


Wintech Computers JAVA 2

object-oriented and component-oriented paradigms. Each concept within this level is an instance
(via
classification by stereotyping) of the nieta-metamodel concept "Thing". This level of abstraction
is used to
formalize paradigm concepts and define a language for specifying models.
The model layer consists of UML models This is the level at which modeling of problems,
solutions, or systems occur. Each concept within triis level is an instance (via classification
b\ stereotyping) of a concept within the metamodel layer. This level of abstraction is used to
formalize concepts and define a language for communicating expressions regarding a give
subject Models in this layer are often called class or type models.
The user model layer consists of those elements that exemplify UML models. Each concept
within this level is an instance (via classification/classifying) of a concept within the model
layer and an instance (\ia classification by stereotyping) of a concept within the metamodel
layer This level of abstraction is used to formalize specific expressions regarding a give
subject. Models in this layer are often called object or instance models
Within this framework, the "meta" notion is used to signify a relationship between a set of non-
metai-oncepts and their metaconcept. The "meta" notion is not a property of a model, but ofthe
role a model plays in relation to another model: a meta-metamodel relates to a metamodel the
same way that a metamodel relates to a model and the same way that a model relates to a user
model. Abstraction (or abstracting) involves formulating metaconcepts by focusing
on similarities and differences among a set of non-metaconcepts to extract intrinsic essential
characteristics (relevant common features) and avoid extrinsic incidental characteristics
(irrelevant distinguishing features) in order to define metaconcepts having those characteristics
that are relevant to defining every non-metaconcept in the set
Manifestation (or manifesting) involves exemplifying metaconcepts to define a set of non-
metaconcepts having intrinsic essential characteristics (relevant common features) without any
extrinsic incidental characters (irrelevant distinguishing features) from a set of metaconcepts.
Fundamentally, a metaconcept is a abstraction ofa set ofnon-metaconcepts and the set of non-
metaconcepts are manifestations of the metaconcept, where abstraction involves the formulation
of metaconcepts and manifestation involves the exemplification (or instanteation) of
metaconcepts Instanteation involves classifying, stereotyping, and extending
(generalization/specialization/inhentance) concepts within the various layers of the conceptual
framework for modeling Classifying involves instanteating a user model layer element by
associating it with a model layer element Stereotyping involves instanteating a user model layer
element by associating it with a metamodel layer element Within the fundamental UML notation,
concepts (and metaconcepts) are depicted as symbols and relationships among concepts (and
metaconcepts) are depicted as paths (lines) connecting svmbols

L-;-
:H

vn: "~
3

H. n ^ - i - l e J.

j/ f''/M>*i W.V* /*.v*- ,\#*.^/*-//lXV

178
Training C>cle 11
Wintech Computers JAVA 2

Extension Mechanisms
Extension mechanisms are the means for customizing and extending the UML. The UML defines
properties for each model element and a means for adding new types of model elements
(metamodel elements)and modify the properties
of existing model elements:
Stereotypes (Figure 2) are used for classifying or marking model elements and introducing new
types ofmodel elements. Each stereotype defines a set ofproperties that are received by elements
of that stereotype and well-formedness rules that must be satisfied by elements of that stereotype.
Stereotypes are used to introduce metamodel elements. Stereotypes are depicted as strings
enclosed in guillemets (or double angle brackets) preceding the name of an element. Stereotypes
may also have an associated graphic icon or marker.

Stereotype
Neire
{Properties}

Figure 2: Stereotypes
Properties (Figure 3) are characteristics of a model element. Properties are depicted as strings
consisting ofacomma-separated list of substrings (property strings) enclosed in curly braces.
<<Stereotype
Name
(Property-String, .

Figure 3: Property Strings


Constraints (Figure 4) are properties for specifying semantics or conditions that must be
maintained as true for model elements. Constraints are depicted as strings within property strings
Tagged values (Figure 4) are properties for specifying keyword-value pairs of model elements
where keywords are characteristics or attributes. Tagged values are depicted as keyword-value
pairs within property stings.

Stereotype
Name
(Constraint-String, Keyword-Value, ...}
Figure 4: Ctuutmutt String* ami tfr/wwtf-Voter Cain

^V^cd,efmeS thC fo,,owing ru,es governing the use of extension mechanisms


fol^'i
forms the baseTntnS 3,Tedmetaclasses.
for all modeling abstract,on drawn from *system being modeled. This concept
fnl^r^
forms the basisV
for ^classes,ElCment thatinterfaces,
data types, deSCnbeS etc.
behavioral "d stctural
in the model layer f*ures. This concept
^
obtctlTthCee ^"MOdd E,emem ^ hM PeratlnS md a** ms Conc^ forms ** basis for
user model layer.

Training Cycle 11
179
Wintech Computers JAVA 2

Model-Element-Stereotype Rule
AModel Element may be associated with zero or one stereotype
A stereotype may be associated with zero or more Model Elements
Classifier-Instance Rule (for classifying)
An Instance may be associated with one or more Classifiers.
A Classifier may be associated with zero or more Instances.
Classifier-Instance-Stereotype Rule (for stereotyping)
An Instance must have the same stereotype as its Classifier.
An Instance need not render its stereotype.
Classifying-Notation Rule
An Instance (object) ofa Classifier concept (class) depicted asa symbol:
May have a name or identifier string that represents the name of the instance The name must
be underlined.
May have a colon followed by a comma-separated classifier list that indicates the classifiers
of the instance. The colon and classifier list must be underlined.
An Instance (link) of a Classifier relationship (association) depicted as a path (line):
May not have a name or identifier string that represents the name of the instance
May have the classifier name rendered. The name must be underlined
Stereotyping-Notation Rule
The stereotype of a concept (object or class) is depicted as a symbol with a string enclosed in
guillemets (or double angle brackets) preceding the name of the concept.
The stereotype of a relationship (link or association) among concepts (object or class) is
depicted as a path (line) with a string enclosed in guillemets (or double angle brackets) preceding
the name of the relationship.
Using extension mechanisms, the UML metamodel may be extended. A UML extension is a set
of extensions (stereotypes, tagged values, and constraints) that extend, customize, or tailor the
UML for a specific domain or process. A UML variant is a semantically well-defined language
(expressed as a metamodel) built on top of the UML metamodel; it specializes but does not
change the UML terms or redefine their meanings The UML standard registers a process-specific
extension, the UML Extension for the Objectory Process for Software Engineering, and a
domain-specific extension, the UML Extension for Business Modeling. Because the UML
metamodel is quite involved, a simplified version is utilized to explore extension mechanisms and
the rules governing their use in applying and extending the language

The Object-Oriented Paradigm

Problem solving involves understanding or conceptualize a problem, solving the problem, and
implementing or realizing the solution Conceptualizing a problem involves representing the
problem using representational constructs (mental notions or ideas). Solving the problem
involves manipulating representational constructs from the problem domain and the solution
domain to derive a representation of the desired solution. Realizing a solution involves mapping
those representational constructs of the solution unto the solution world, that is, constructing the
solution The use of representational constructs is a very natural process that often occurs subtly
and sometimes unconsciously in problem solving. Underlying this scheme is the use of a
paradigm in determining the possible types of representations utilized in problem-solving efforts.
The object-orientated paradigm is derived from the convergence of other fundamental paradigms,
and is reducible to the other paradigms as required by its application via a language or method.

Training Cycle U ,80


IAVA 2
Wintech Computers JAVA L

The flexibility provided by utilizing this paradigm can be best understood by examining the roots
ofthe paradigm itself within Plato's theory ofForms.

The Obiect-Orientated Paradigm

The object-oriented paradigm focuses on the behavioral and structural characteristics of entities
as complete units. It is concept-centric (holistic) in that it focuses on all the types of features that
constitute any given concept. The paradigm encompasses and supports the following pillars (first
principles):
Abstraction involves the formulation of representations by focusing on similarities and
differences among a set ofentities to extract intrinsic essential characteristics (relevant common
features) and avoid extrinsic incidental characteristics (irrelevant distinguishing features) in order
to define a single representation having those characteristics that are relevant to defining every
element in the set.
Encapsulation involves the packaging of representations by focusing on the hiding of details to
facilitate abstraction, where specifications are used to describe what an entity is and what an
entity does and implementations are used to describe how an entity is realized.
Inheritance involves the relating and reusing of existing representations to define new
representations.
Polymorphism involves the ability ofnew representations to be defined as variations ofexisting
representations, where new implementations are introduced but specifications remain the same
such that a specification has many implementations. These pillars are used to facilitates
communication, increase productivity and consistency, and enable the management ofchange and
complexity within problem-solving efforts.

Objects and Classes

Objects and classes abstract entities.

Objects are representational constructs of entities. Objects encapsulate structural characteristics


known as attributes and behavioral characteristics known as operations. Attributes are
representational constructs of structural characteristics of entities and determine the possible
states of an object. Operations are representational constructs of behavioral characteristics of
entities and determine the possible behaviors of an object as invoked in response to receiving a
message. Objects have identity and are instances of classes. Fundamentally, objects are abstracted
entities that encapsulate state and behavior.

Classes are descriptions of objects with a common implementation. Classes are concerned with
the implementation of uniform structural characteristics and behavioral characteristics.
Fundamentally, classes are descriptions of objects with common attributes, operation
implementations, semantics, associations, and interactions.

Types are descriptions of objects with a common specification. Types are concerned with the
specification of uniform structural characteristics and behavioral characteristics. Types may be
explicitly related to classes, where a class receives an interface from a type and provides an
implementation for the interface, or types may be implicitly related to classes, where a class
defines an interface and provides an implementation. Fundamentally, types are descriptions
of objects with common attributes, operation interfaces, semantics, associations, and interactions.

TrainingCycle 11 181
Wintech Computers
JAVA Z

Links and Associations


Links and associations abstract relationships among entities.
Links are representational constructs of entities that relate other entities. Links are instances of
associations. Fundamentally, links are abstracted relationships among objects.
Associations are descriptions of links with a common implementation Aggregations are
associations that specify a whole-part relationship among an aggregate and component parts
Compositions are aggregations with strong ownership and coincident lifetime constraints among
a composite and component parts. Generalizations are associations specifying a taxonomic
relationships that relate more general representational constnicts and more specific
representational constructs. The more specific representational constructs are derived from
existing more general representational constructs and acquire the characteristics of the more
general representational constructs via inheritance. The more specific representational constructs
may override characteristics received via inheritance and introduce new characteristics. Because
the more specific representational constructs receive the characteristic of the more general
representational constructs, instances of the more specific representational constmcts may be
substituted for instances of the more general representational constructs. Polymorphism enables
the same message (operation interface) to invoke the appropriate method (operation
implementation) based on the class ofthe receiver when a more specific instance is substituted
for a more general instance. Fundamentally, associations are descriptions oflinks with common
attributes, operation implementations, semantics, associations, and interactions.

Scenarios and Interactions

Scenarios and interactions abstract occurrences among entities.

Scenarios are representational constructs of entities that are conduits for a sequence ofmessage
exchanges among other entities. Scenarios are instances ofinteractions. Fundamentally, scenarios
are abstracted message exchanges among objects.

Interactions are descriptions of scenarios with a common implementation. Message exchanges


involve a sender who is said to apply an operation on a receiver by sending a message (operation
interface) that invokes a method (operation implementation) within the receiver. Fundamentally,
interactions are descriptions ofscenarios with common message exchange sequences, classes, and
associations.

Reuse and the Unified Modeling Language

In today's a highly volatile environment involving a global, vigorously competitive, and


unpredictable market filled with opportunities and risks resulting from constant change and ever-
increasing complexity, businesses can only succeed by addressing market challenges and

Training Cycle 11 182


Wintech Computers JAVA 2

competitively achieving business goals. Competitiveness (or having a competitive advantage)


involves the ability of an organization to proactively minimize risks and capitalize on
opportunities while, not simply sustaining, but thriving in a highly volatile environment and
adding value by increasing quality, reducing costs, and reducing time-to-market. Fundamentally,
productively delivering quality in a timely and cost-effective manner.

These challenges are best addressed by applying the fundamental engineering principle ofreuse -
do not reinvent, but adapt existing proven quality elements, and construct new quality elements
only as necessary - and the fundamental natural principle ofevolution - do not simply adapt, but
develop from adapting via a process of adapting and cultivating the ability to better adapt by
addressing immediate needs and continuously maturing to anticipate and be better positioned to
address immanent needs.

Reuse Culture

Reuse is the promised holy grail of object orientation that enables us to improve value by
increasing quality, reducing costs, and reducing time-to-market. Technology and processes enable
people to practice reuse; however, enabling reuse does not ensure that reuse will occur. An
organizational culture is required to promote reuse. Such a culture encompasses the following:
A standardized language for communication - the UML.
A paradigm optimized for the conceptualization and specification phases of problem solving -
object orientation.
A paradigm optimized for the specification and realization phases of problem solving -
component-based development.
Otherparadigms supporting higher-level concepts (frameworks, patterns, etc.).
Processes, people, and tools that establish a cohesive reuse strategy.

Reuse Strategy

While a reuse culture establishes the foundation for reuse, a reuse strategy encompassing the
following is required to actualize the benefits of reuse:
A vision supported by an infrastructure..
A repository for housing and managing assets (reusable artifacts).
Reuse champions, mentors, and evangelists chartered to promote and be catalysts for reuse.
A standard for defining assets.
A quality system for evaluating the quality of assets.
A metric system for evaluating asset reuse.
An incentive system encouraging the realization of reusable artifacts and asset reuse.
Processes and methods focusing on reuse throughout the system development life cycle.
Tools that enable execution of the strategy.

Applying the Unified Modeling Language

Organizations compete in a global market that is characterized by opportunities and risks where
ongoing business and technological change fuel ever-increasing competition. Organizations must
not only manage change and the complexity that results from adapting to change, but capitalize
on the lessons learned, best practices, and knowledge gained through this evolutionary process.

Training Cycle 11 183


Wintech Computers JAVA 2

The importance and criticality of knowledge has given way to the Knowledge Revolution. This
revolution can be characterized by the radical and fundamental paradigm shift that is occurring
within the business and technology industries where an organization's application of knowledge
defines its competitive advantage. Organizations can no longer only rely on physical muscle and
size, but must harness intellectual capital and creativity to be successful. Knowledge takes on
many forms, however, its value is demonstrated through its application and the realization of
solutions to problems.

Therefore, it is very conceivable that a common language, such as the Unified Modeling
Language (UML), that unifies the many threads and incarnations ofthe Knowledge Revolution is
the most viable means for organizations to best realize a competitive advantage via capturing,
communicating, and leveraging knowledge.

Problems. Solutions, and Problem Solving

Organizations produce and deliver products and services that address customer needs and
requirements Requirements may be characterized as problems (often referred to as as-is
situations). Products and services that address requirements are characterized as solutions (often
referred to as to-be situations). To deliver valued solutions, organizations must apply knowledge
in problem-solving efforts; therefore, knowledge and the ability to apply it is the determining
factor of success.
Projects are problem-solving efforts that involve stakeholders and deliverables or work
products in order to
formalize the "work hard and hope for the best" approach to problem solving.
Programs are collections of problem-solving efforts
Methods specify how to conduct problem-solving efforts.
Processes are realizations of methods.
Methodologies are taxonomies, or well-organized collections, of related methods.

Problems and Solutions

Problems and solutions occur within a context (domain or space). The problem (system) must be
understood in order to be solved. The solution (system) to a problem must be understood in order
to be constructed and used The solution must be organized (architecture) in order to facilitate its
realization and adhere to the various constraints of the context in which it will be realized. To
solve the problem, appropriate knowledge about the problem and solution must be captured
(models), organized around decisions regarding the problem and solution (architectural views),
and depicted (diagrams) using some language that enables it to be communicated and leveraged
in the problem-solving process.
Therefore, the following concepts are critical to problems and solutions: domains or spaces,
systems, architectures, models, architectural views, diagrams, and languages.

Problem Solving

Problem-solving approaches are organized (life cycles) to offer a management perspective and a
development perspective. The two perspectives enablethe effort to be managed and performed.
Problem solving requires being able to view the problem (paradigm) for the purpose of
understanding it, and being able to view the solution (paradigm) for the purpose of realizing it.

Training Cycle 11 184


Wintech Computers JAVA2

The problem-solving process involves leveraging knowledge to derive the solution (artifacts) to
the problem through a series of(possibly concurrent) steps (activities) in which knowledge and
rules ofthumb (heuristics) gained from other problem-solving efforts may be used. Therefore, the
following concepts are critical to problems solving: paradigms, artifacts, activities, and
heuristics.

The role of the UML is to enable and facilitate the following:


Specifying, visualizing, understanding, and documenting problems.
Capturing, communicating, and levering knowledge inproblem solving.
Specifying, visualizing, constructing, and documenting solutions.

However, the UML does not prescribe any particular problem-solving approach, but is very
flexible and customizable to fit any approach. It enables and promotes (but does not require nor
mandate) a use-case-driven, architecture-centric, iterative, and incremental process that is object
oriented and component based.

Way To Apply

Applying the UML involves instanteating the metamodel at the model or user model layer.

Figure 5 shows how model elements are fully specified at each layerof the conceptual framework
for modeling
A mm-Concept is an instance of Thing (stereotyping) and correlates to the UML Classifier
concept (or one
of its derivatives).
A mm-Concept-Instance is an instance of Thing (stereotyping) and correlates to the UML
Instance concept
(or one of its derivatives).
A mm-Concept and a mm-Concept-Instance are associated.
A m-Concept is an instance of a mm-Concept (stereotyping).
A urn-Concept is an instance of a m-Concept (classifying) and a mm-Concept-Instance
(stereotyping).
Figure 6 shows the minimal notation required to depict Figure 5.

Training Cycle 11 185


Wintech Computers JAVA 2

Thing

Meta-metamodtl
Metamodel

Thing TMng
mm-Cor.cept no-Concept-Instance

Metamodel
Model"

mn-Concept
M-Concept

Model
Uei Model

KU-Concept-I&stance
uai Concept i m Concept

#%*ry 5. Ctmtqtmtt FMue*t#lkfr ***#** - V*Qf SpttifM Modtt nw

Thing

Meta-metamodtl
Metamodel

mm-Cor.cept inn-Concept-Instance

Metamodel
Model'

m-Concept

Model
User Model

um-Concept : m-Concept

Flgtwt 6:ConctfUMMt rmmwarti.for MoMtatg ~ Mmimtttf$p*t$*4 AMtt Etmmi*

Training Cycle 11 186


Wintech Computers JAVA 2

Figure 7 shows a simple fully specified example:

Class is an instance of Thing (stereotyping).

Object is an instance of Thing (stereotyping).

Class and Object are associated.

Association is an instance of Thing (stereotyping).

Link is an instance of Thing (stereotyping).

Association and Link are associated.

Person is a class: Person is an instance of Class (stereotyping).

Team is a class: Team is an instance of Class (stereotyping).


*

Aperson may be a member ofa team, and a team may have various members: Member Ofis an
instance of Association (stereotyping).

Si is a person: Si is an instance of Person (classifying) and Object (stereotyping).

Tl is a team: Tl is an instance of Team (classifying).and Object (stereotyping)

Si is a member of Tl: Member Of is an instance of Member Of (classifying) and Link


(stereotyping). Figure 8 shows the minimal notation required to depict Figure 7. This example,
which is consistent with the conceptual framework for modeling, demonstrates the following
regarding the rules that the UML defines governing the use of extension mechanisms:

The Classifier-Instance-Stereotype rule is problematic. As stipulated by this rule:

Si would have to be an instance of Person (classifying) and Class (stereotyping) when Si is an


instance of Person (classifying) and Object (stereotyping).

Tl would have to be an instance of Team (classifying) and Class (stereotyping) when Tl is an


instance of Team (classifying) and Object (stereotyping).

Member Of would have to be an instance of Member Of (classifying) and Association


(stereotyping) when Member Of is an instance of Member Of (classifying) and Link
(stereotyping) Therefore. Class and Association are instanteated (stereotyping), but Object and
Link may never be instanteated (stereotyping)

The Classify ing-Notation rule and the Stereotyping-Notation rule are inconsistent. The
stereotype of a concept (Person and Team) and the stereotype of a relationship (Member Of)
among concepts are depicted in exactly the same manner, however, the classification of a concept

Training Cycle 11 187


Wintech Computers JAVA 2

(Si and Tl) and the classification of a relationship (Member OO among concepts are depicted
differently

Thing

Meta-metamodel
Metarn odel

xThing>> <<Thing>> <<Thing>> Thing>>


Class Object Link Association

Metamodel
Model
<<Associat:on>>

Hember Of
<<Class>> <<Class
Person Team

Model
Uset Model
<<Link

Hember Of
<<Object>> <<Object
Si : Tcroon Tl : Team

I'igurt ? Simple Hxample mill I nth Specified MocGr/ Mtmeitt*

Thina

Meta-metamodel
Metamodel

Class Object Link Association

Metam odel
Model

Hember Of
Person Team

Model
User Model

Hember Of
Si : Person Tl Team

rigmt:Simple Kxampk *ith lUiuimatfy $i*'fit4\fo4<et titmtm

188
Training Cycle 11
Winteth Computers JAVA2

Figure 9 shows a more complex fully specified example:

Class is an instance of Thing (stereotyping).


Object is an instance of Thing (stereotyping).
Class and Object are associated.
Association is an instance of Thing (stereotyping).
Link is an instance of Thing (stereotyping).
Association and Link are associated.
Person is a class: Person is an instance of Class (stereotyping).
Team is a class: Team is an instance of Class (stereotyping).
A person may be a member of a team, and a team may have various members: Member Of is an
instance of Association (stereotyping).
Permanent is a class: Permanent is an instance of Class (stereotyping).
Temporary is a class: Temporary is an instance of Class (stereotyping).
People and teams may be categorized as permanent or temporary.
Si is a permanent person: Si is an instance of Person (classifying), Permanent (classifying), and
Object (stereotyping).* Tl is a temporary team: Tl is an instance of Team (classifying),
Temporary (classifying), and Object (stereotyping).
Si is a member of Tl: Member Of is an instance of Member Of (classifying) and Link
(stereotyping).
Figure 10 shows the minimal notation required to depict Figure 9. This example, which is
consistent with the
conceptual framework for modeling, demonstrates the following regarding the rules that the UML
defines governing
the use of extension mechanisms:
The Classifier-Instance-Stereotype rule is problematic. As stipulated by this rule:
Si would have to be an instance of Person (classifying), Permanent (classifying), and Class
(stereotyping) when Si is an instance of Person (classifying), Permanent (classifying), and Object
(stereotyping)
Tl would have to be an instance of Team (classifying), Temporary (classifying), and Class
(stereotyping) when Tl is an instance of Team (classifying), Temporary (classifying), and Object
(stereotyping).
Member Of would have to be an instance of Member Of (classifying) and Association
(stereotyping)
when Member Of is an instance of Member Of(classifying) and Link (stereotyping).
Therefore, Class and Association are instanteated (stereotyping), but Object and Link may never
be instanteated (stereotyping).
The Classifying-Notation rule and the Stereotyping-Notation rule are inconsistent. The
stereotype of a concept (Person and Team) and the stereotype of a relationship (Member OO
among concepts are depicted in exactly the same manner, however, the classification ofa concept
(Si and Tl) and the classification of a relationship (Member OO among concepts are depicted
differently.

Training Cycle 11 189


Wintech Computers JAVA 2

Meta-metamodel
Metamodel

:<Thing Thing Thmg Thing


Class Object Link Association

Metamodel
As90ciation-
Model
Member 01

:<Class>> Class <<Class Class


Person Team Permanent Temporary

Model
User Model
Link
Hember Of
<<Object>> <<Object
Si Tcraon, rcrroancnt Tl : Team Temporary

f iiw* '>. M<t (<>mpkx Exwplt** lulh Sprrifitd W*WXtmtim

Meta-m etam odel


Metamodel

Metamodel
Model
Member Of

Person Team Permanent Temporary

Model
User Model

Hember Of
Si Person, Permanent Tl Team. Temporary

/ iguee 10: Mure (ompkx twupte with MimmUy Specifird WoA/ Ktemtnti

190
Training Cycle 11
JAVA 2
Wintech Computers

Extending the UML

Extending the UML involves defining aUML extension, aset of extensions (stereotypes, tagged
values, and constraints), or a UML variant, a semantically well-defined language (expressed as a
metamodel) built on top of the UML metamodel.
Figure 11 shows how model elements are fully specified at each layer of the conceptual
framework for modeling when extending the UML

Amm-Concept is an instance of Thing (stereotyping) and correlates to the UML Classifier


concept (or oneof its derivatives).
Amm-Concept-Instance is an instance of Thing (stereotyping) and correlates to the UML
Instance concept (orone of its derivatives).
Amm-Concept and a mm-Concept-Instance are associated.
Ae-mm-Concept is derived from a mm-Concept and is an instance of Thing (stereotyping) It
correlates to a new Classifier concept and is stereotyped using the keyword stereotype to indicate
that it is part ofan extended metamodel that extends the UML metamodel
Ae-mm-Concept-lnstance is derived from amm-Concept-Instance and is an instance of Thing
(stereotyping). It correlates to a new Instance concept and is stereotyped using the keyword
stereotype to indicate that it is part of an extended metamodel that extends the UML metamodel
Ae-mm-Concept and a e-mm-Concept-Instance are associated

A m-Concept-1 is an instance ofa mm-Concept (stereotyping)


Am-Concept-2 is an instance ofa e-mm-Concept (stereotyping)
A um-Concept-1 is an instance of a m-Concept-1 (classifying) and a mm-Concept-Instance
(stereotyping).
Aum-Concept-2 is an instance ofa m-Concept-2 (classifying) and a e-mm-Concept-Instance
(stereotyping)

Figure 12 shows the minimal notation required todepict Figure 11

Training Cycle 11 ,91


Wintech Computers
JAVA 2

Metunehmodtl
Metamodel

Thing Thing
mm-Concept ram-Concept-Instance

I J
Extended Metamodel

<<stereotype stereotype
e-mm-Concept e-mm-Concept-Instance

Extended Metamodel
''" " " ' !> , II tin./
Model

mm-Co.icept e-mro-Cpncept
m-Concept-1 m-Concept-2

Model
User Model

mm-Concept-Ir.stance e-mm-Concept-Insta3ce
um-Concept-1 : m-Concept-1 um-Concept-2 : m-Concept-2

m if;fMn^ftmrirai

Training Cycle 11 192


Wintech Computers JAVA 2

Mt-mtmod*l
Metamodel

mm-Concept mm-Concept-Instance

Metamodel L L\
Extended Metamodel

stereotype stereotype
e-mm-Concept e-mm-Concept-Instance

Ex tended Metamodel
Model

<<e-mm-Concept>>
m-Concept-1
m-Concept-2

Model
User Model

um-Concept-1 : ra-Coneept-1 um-Concept-2 : m-Concept-2

hxtrn 12: luwqHuat ftamtvotk fmMaMmf with Kxminl HttamM - Minimally Specified VfWW tltmcm

Defining (or registering) a UML extension involves describing the extension and its purpose or
basis in a document ("UML Extension for . ") havingthe following content:
Description
Prerequisite Extensions
Stereotype
Name
Metamodel Class (that the stereotype extends)
Semantics
Syntax (Notation) Icon
Constraint Property
String
Semantics
Tagged Value Property
Key word
Semantics

Training Cycle 11 193


Wintech Computers JAVA 2

Well-formedness Rules
Generalization
Association
Comments

The following defines (or registers) a UML Extension for Human Resource Modeling:

Description
This defines a DMI Extension for Human Resource Modeling It describes stereotypes that may be used to tailor the
use of the
language tor working with human resource systems This is not meant to beacomplete definition of these concepts and
how to applv
them, but it serves the purpose of registering this extension and its icons
Prerequisite Extensions
This extension requires no other extension to the language for its definition
Stereotype
Name I'ervm
Metamodel Class: Class
Semantics A class that represents an abstraction of a human relevant to ahuman resources system.
Syntax (Notation) Icon: None
Constraint Property: None
Tagged Value Property: None
Stereotype
Name I earn
Metamodel Class: Class
Semantic*: A classthat represents an abstraction of an organizational unit relevant to a human resources system.
The
organizational unit contains people
Syntax (Notation) Icon: None
Constraint Property: None
Tagged Value Property: None
Stereotype
Name Status
Metamodel Class: Class
Semantics A class that represents an abstraction of the status of an organizational unit or a human relevant to a
human
resouiccs s\ sieni The status may represent any condition or categorization relevant to a human resources system.
Syntax (Notation) Icon None
Constraint Property: None
Tagged Value Property None
Stereotype
Name Member Of
Metamodel Class: Association
Semantics An association between a human and an organizational unit used to indicate
that the human belongs to the organizational unit
Syntax (Notation) Icon: None
Constraint Property None
Tagged Value Property None
Well-formedness Rules

194
Training Cycle 11
IAVA 1
Wintech Computers JftVA'

. Generalization: All of the modeling elements in a generalization must be of the same


stereotype.
Association. Apart from the standard UML combinations, the following combinations are
allowed for each stereotype:
Member Of: From Teamto Person, and from Person to Team.
Comments
This extension does not introduce any new tagged values.
This extension does not introduce any new constraints, other than those associated with the well-
formedness semantics of the
stereotypes introduced.
Figure 13 shows a simple fully specified example using the UML Extension for Human Resource
Modeling:
Class is an instance of Thing (stereotyping).
Object is an instance of Thing (stereotyping).
Class and Object are associated.
Association is an instance of Thing (stereotyping).
Link is an instance of Thing (stereotyping).
Association and Link are associated.
Employee is a person class: Employee is an instance ofPerson (stereotyping).
Requirements is a team class: Requirements is an instance ofTeam (stereotyping).
An employee (who is a person) may be a member of a requirements team exclusively, and a
requirements team may have various employees (who are people) as members exclusively:
Exclusively is an instance of Member Of (stereotyping).
Si is an employee: Si is an instance of Employee (classifying) and Object (stereotyping).
Tl is a requirements team: Tl is an instance of Requirements (classifying) and Object
(stereotyping).
Si is a an exclusive member of Tl: Exclusively is an instance of Exclusively (classifying) and
Link (stereotyping).
Figure 14 shows the minimal notation required to depict Figure 13. This example, which is
consistent with the conceptual framework for modeling, demonstrates the following regarding the
rules that the UML defines governing the use of extension mechanisms:
The Classifier-Instance-Stereotype rule is problematic. As stipulated by this rule:
Si would have to be an instance of Employee (classifying) and Person (stereotyping) when Si is
an instance of Employee (classifying) and Object (stereotyping).
Tl would have to be an instance of Requirements (classifying) and Team (stereotyping) when
Tl is an instance of Requirements (classifying) and Object (stereotyping).
Exclusively would have to be an instance of Exclusively (classifying) and Member Of
(stereotyping) when Exclusively is an instance of Exclusively (classifying) and Link
(stereotyping) Therefore. Class and Association are instanteated (stereotyping), but Object and
Link may never be instanteated (stereotyping) Furthermore, the following results:
Employee is an instance of Person (stereotyping) and Si is an instance of Object (stereotyping).
Person and Object are not at the same semantic level of abstraction: Class and Object are
associated, but Person and Object are not; however, because Person is a subclass of Class, it
inherits the relationship to Object
Requirements is an instance of Team (stereotyping) and Tl is an instance of Object
(stereotyping), Team and Object are not at the same semantic level of abstraction: Class and
Object are associated, but Team and Object are not. however, because Team is a subclass of
Class, it inherits the relationship to Object Therefore, the user model layer elements (Si,

Training Cycle 11 '^


Wintech Computers JAVA 2

Exclusively, and Tl) are more generic instances (stereotyping) than the model layer elements
(Employee, Exclusively, and Requirements) they instanteate (classifying).
The Classifying-Notation rule and the Stereotyping-Notation rule are inconsistent. The
stereotype of a concept (Employee and Requirements) and the stereotype of a relationship
(Exclusively) among concepts are depicted in exactly the same manner, however, the
classification of a concept (Si andTl) and the classification of a relationship (Exclusively) among
concepts are depicted differently.

Thing

Meta-m etam odtl


Metamodel

<<Thing Thing Thing <<Thing


Class Object Link: Association

Metamodel
Model
Hember or

Exclusively
<<Person Teaw
Employee Requirements

Model
U ser Model
Link
Exclusively
<<Object <<Object
Si i Employee Tl i Rcquircmcnto

Ptg*n I); Smptt lixftmpir with Fuiff SpeclfM M*<t*i Kttmtm tmd the Wt, Hxttnvlm fiv Httmau Ktmnrce Modeling

Thing

Meta-m etam odel


Metamodel

Class Object Link: Association

Metamodel
Model
Hemfaer 0
Exclusively
<<Person <<Team

Employee Requirements

Model
U ear Model

Exclusively
Si ; Employee Tl : Recuirements

196
Training Cycle 11
Wintech Computers JAVA 2

Figure 14. Simple Example with MinimaUy Specified Model Elements and the UML Extension for Human
Resource Modeling
Figure 15 shows a more complex fully specified example using the UML Extension tor Human
Resource Modeling.
Class is an instance of Thing (stereotyping).
Object is an instance of Thing (stereotyping).
Class and Object are associated.
Association is an instance of Thing (stereotyping)
Link is an instance of Thing (stereotyping).
Association and Link are associated.
Employee is a person class: Employee is an instance ofPerson (stereotyping).
Requirements is a team class: Requirements is an instance ofTeam (stereotyping).
An employee (who is a person) may be a member of a requirements team exclusively, and a
requirements team may have various employees (who are people) as members exclusively:
Exclusively is an instance of Member Of (stereotyping).
Permanent is a status class: Permanent is an instance of Class (stereotyping).
Temporary is a status class: Temporary isaninstance of Class (stereotyping).
Employees and requirements teams may be categorized as permanent or temporary.
Si is an permanent employee: Si is an instance of Employee (classifying), Permanent
(classifying), and Object (stereotyping).
Tl is a temporary requirements team: Tl is an instance of Requirements (classifying),
Temporary (classifying), and Object (stereotyping).
Si is a an exclusive member of Tl: Exclusively is an instance of Exclusively (classifying) and
Link (stereotyping).
Figure 16 shows the minimal notation required to depict Figure 15. This example, which is
consistent with the conceptual framework for modeling, demonstrates the following regarding the
rules that the UML defines governing the use of extension mechanisms:
The Classifier-Instance-Stereotype rule is problematic. As stipulated by this rule:
Si would have to be an instance of Employee (classifying), Permanent (classifying), Person
(stereotyping), and Status (stereotyping) when Si is an instance of Employee (classifying),
Permanent (classifying), and Object (stereotyping).
Tl would have to be an instance of Requirements (classifying), Temporary (classifying), Team
(stereotyping) and Status (stereotyping) when Tl is an instance of Requirements (classifying),
Temporary (classifying), and Object (stereotyping).
Exclusively would have to be an instance of Exclusively (classifying) and Member Of
(stereotyping) when Exclusively is an instance of Exclusively (classifying) and Link
(stereotyping). Therefore, Class and Association are instanteated (stereotyping), but Object and
Link may never be instanteated (stereotyping).
Furthermore, the following results:
Employee is an instance of Person (stereotyping) and Si is an instance of Object (stereotyping),
Person and Object are not at the same semantic level of abstraction: Class and Object are
associated, but Person and Object are not; however, because Person is a subclass of Class, it
inherits the relationship to Object.
Requirements is an instance of Team (stereotyping) and Tl is an instance of Object
(stereotyping), Team and Object are not at the same semantic level of abstraction: Class and
Object are associated, but Team and Object are not; however, because Team is a subclass of

Training Cycle 11 197


Wintech Computers
JAVA 2

Class, it inherits the relationship to Object. Therefore, the user model layer elements (Si
Exclusively, and Tl) are more generic instances (stereotyping) than the model layer elements
(Employee, Exclusively, and Requirements) they instanteate (classifying).
The Classifying-Notation rule and the Stereotyping-Notation rule are inconsistent The
stereotype ofaconcept (Employee, Requirements, Permanent, and Temporary) and the stereotype
of a relationship (Exclusively) among concepts are depicted in exactly the same manner
however, the classification of a concept (Si and Tl) and the classification of a relationship
(Exclusively) among concepts are depicted differently.

Thing

Meta-m etun odel


MUtnodl

Thing>> Thlng>> Thlng>> TMng


Class Object Link Association

Metamodel
<-Member >>
Model'
Exclua ively
<<Person <<Teeun <<3tatuo>> <<Status
Employee Requirements Permanent Temporary

MM . <<Link
User Model
e Exclusively

<<Object <<Object
31 Employee, Permanent Tl : Requirements, Tenporary

fIff IS: Man Complex t.xemfit. with rulfy SpYeffUd M4fi tiltmemt tuti the (.'/. Kaewion jar Human Krsmtrc \Mehag

Thing

Meta-m etam odel


M*Umod*l

Class Object Link Association

Metamodel
Hember *>> -
Model
Exclusively

<<Person>> <<Teara>> <<3t ar.us <<3tatus>>


Employee Requirements Permanent Temporary

Model
U er Model Exclusively

31 : Employee, Permanent T: : Requlreroenr.3, Tenporary

figure It: Mm* t'ompttx Kxumpk with Minimally Specified Modtt fitment* md tht /'* X Lmrnioa fur tinmen tam Modeting

Training Cycle 11 198


Wintech Computers JAVA 2

Brief Description of UML with JAVA.


CLASSES
b>age)| |echema|

das*
reference

class entity dees reference Java API class


(lesources)
INTERFACES
{pe^r""*"|chBma'l
V N V standard
interface
Java API
Interface reference
Interface
b A K
b_ X
interface ent*y interface reference J ava API interlace
(lesources]
JAVACOMPONENTS
\oomponmt {treetntt ittuotw) ?JP*B*r *""Tscnsma}"
Java
Java component
component reference

lavabean entity javabean reference


classes and interfaces
with compartments
PRIMITIVE DATATYPES WRAPPED
1
Int Integer
i...............j package
simple data type wrapped Integer -object
entity Ml (Java API date ret.) package entity
(use colours)
RELATIONSHIPS
EXTENDING IMPLEMENTING
(reference to anothet objejct) (inherilance) ('virtual" inheritance!
twheert[4| V
Wheel
Car
weight
float 1
mark
r string ] ^E^,
owner
Person
/pointer V

-he-?-j WI Kr~H
relationship* implementing
(o another entity of ntorleSCM interlaces

-RELATIONSHIP TYPES RELATIONSHIP OPTIONS -ARRAYS

attt
any (of below) w absolute (normal)
mundefSlzeArrtJ
alti
"property" ^..?f.... optional rray|nHm|
attr
port-or %yjtl.H *-wey ("strong")
HNVianrt rone*n*mbu4'l
USF OF CLASS

ant /'Seivice caHI"/


"connection"
TrSS-ttr"? P1ional,wo^ay
DYNAMIC DATA STRUCTURES JAVA KEYWORDS COMMENTS

'note'
FinatClast
la< b)
/* comment text V
^
ABS

<c ""> r WWIHMHM


AbttractClat*
// comment texthne

/" kne description"/


(final and abstract classes)

Training Cycle 11 199


Exercise
Wintech Computers JAVA 2

12. Exercise

Objective Questionsfor Java

70 Questions

Question 1) What will happen when you attempt to compile and run this code''

abstract class Base{


abstract public void myfunc();
public void another(){
System.out.println(" Another method");
>
}
public class Abs extends Base{
public static void main(String argv[]){
Abs a = new Abs();
a amethod(),
}
public void myfunc(){
System.out.println("My func");
}
public void amethod(){
myfunc();

1) The code will compile and run, printing out the words "My Func"
2) The compiler will complain that the Base class has non abstract methods
3) The code will compile but complain at run time that the Base class has non abstract methods
4) The compiler will complain that the method myfunc in the base class has no body, nobody at
all to looove it

Question 2)
What will happen when you attempt to compile and run this code9

public class MyMain{


public static void main(String argv){
System out printlnfHello cruel world");
}
}

1)The compiler will complain that main is a reserved word and cannot be used for a class
2) The code will compile and when run will print out "Hello cruel world"

Exercise 201)
Wintech Computers JAVA 2

3) The code will compile but will complain at run time that no constructor is defined
4) The code will compile but will complain at run time that main is not correctly defined

Question 3)
Which of the following are Java modifiers?

l)public
2) private
3) friendly
4) transient
4) vagrant

Question 4)
What will happen when you attempt to compile and run this code?
class Base{
abstract public void myfunc();
public void another(){
System out.println("Another method");
}
>
public class Abs extends Base{
public static void main(String argv[]){
Abs a = new Abs();
a amethod(),
}
public void myfunc(){
System.out.println("My func"),
>
public void amethod(){
myfuncQ;

1) The code will compile and run, printing out the words "My Func"
2) The compiler will complain that the Base class is not declared as abstract.
3) The code will compile but complain at run time that the Base class has non abstract methods
4) The compiler will complain that the method myfunc in the base class has no body, nobody at
all to looove it

Question 5)
Why might you define a method as native?
1) To get to access hardware that Java does not know about
2) To define anew data type such as an unsigned integer

201
Exercise
Wintech Computers JAVA 2

3) To write optimised code for performance in a language such as C/C++


4) To overcome the limitation of the private scope of a method

Question 6)
What will happen when you attempt to compile and run this code?
class Base{
public final void amethod(){
System.out.println("amethod");
}
}
public class Fin extends Base{
public static void main(String argv[]){
Base b = new Base();
b.amethod();
}
}

1) Compile time error indicating that a class with any final methods must be declared final itself
2) Compile time error indicating that you cannot inherit from a class with final methods
3) Run time error indicating that Base is not defined as final
4) Success in compilation and output of "amethod" at run time.

7) What will happen when you attempt to compile and run this code?
public class Mod{
public static void main(String argv[]){
}
public static native void amethod();
}
1) Error at compilation: native method cannot be static
2) Error at compilation native method must return value
3)Compilation but error atrun time unless you have made code containing native amethod
available
4) Compilation and execution without error

8) What will happen when you attempt to compile and run this code?
private class Base{}
public class Vis{
transient int iVal;
public static void main(String elephant[]){
}
}
l)Compile time error: Base cannot be private
2)Compile time error indicating that an integer cannot betransient

Exercise 202
Wintech Computers JAVA 2

3)Compile time error transient not a data type


4)Compile time error malformed main method

9) What happens when you attempt to compile and run these two files in the same directory?
//File PI java
package MyPackage,
class PI {
void afancymethod(){
System out println("What a fancy method");
>
}
//File P2.java
public class P2 extends PI {
afancymethod();
}
1) Both compile and P2 outputs "What a fancy method" when run
2) Neither will compile
3) Both compile but P2 has an error at run time
4) PI compiles cleanly but P2 has an error at compile time

10) You want to find out the value of the last element of an array. You write the following code
What will happen when you compile and run it ?
public class MyAr{
public static void main(String argv[]){
int[] i = new int[5],
System out println(i[5]),
}
}
1) An error at compile time
2) An error at run time
3) The value 0 will be output
4) The string "null" will be output

11) You want to loop thiough an array and stop when you come to the last element Being a good
java programmer and forgetting everything you ever knew about C/C++ you know that arrays
contain information about their size Which of the following can you use9

l)myarray length(),
2)myarray length,
3)myarray size
4)myarray size().

Question 12)

203
Exercise
Wintech Computers JAVA 2

What best describes the appearance of an applet with the following code?
import java.awt.*;
import java.applet.*;
public class FlowAp extends Frame{

public static void main(String argv[]){


FlowAp fa=new FlowAp();
fa.setSize(400,300);
fa.setVisible(true);
}
FlowAp(){
add(new Button("One"));
add(new ButtonfTwo"));
add(new Button("Three"));
add(new Button("Four"));
}//End of constructor

}//End of Application
1) AFrame with buttons marked One to Four placed oneach edge.
2) AFrame with buutons marked One to four running from the top to bottom
3) A Frame with one large button marked Four in the Centre
4) An Error at run time indicating you have not set a LayoutManager

Question 13)
How do you indicate where a component will be positioned using Flowlayout?
1) North, Southeast,West
2) Assign a row/column grid reference
3) Pass a X/Y percentage parameter to the add method
4) Do nothing, the FlowLayout will position the component

Question 14)
How do you change the current layout manager for a container
1) Use the setLayout method
2) Once created you cannot change the current layout manager ofacomponent
3) Use the setLayoutManager method
4) Use the updateLayout method

Question 15)
7) Which ofthe following are fields ofthe GridBagConstraints class?
1) ipadx
2) fill

Exercise 204
Wintech Computers JAVA 2

3) insets
4) width

Question 16)
What most closely matches the appearance when this code runs?
import java awt.*;

public class CompLay extends Frame{


public static void main(String argv[]){
CompLay cl = new CompLayO;
}

CompLayO{
Panel p = new Panel(),
p setBackground(Color.pink);
p.add(new Button("One"));
p.add(new Button("Two"));
p.add(new Button("Three"));
add("South",p),
setLayout(new FlowLayout());
setSize(300,300);
setVisible(true);
}

1) The buttons will run from left to right along the bottom ofthe Frame
2) The buttons will run from left to right along the top ofthe frame
3) The buttons will not be displayed
4) Only button three will show occupying all ofthe frame

Question 17)
Which statements are correct about the anchor field?
1) It is afield ofthe GridBagLayout manager for controlling component placement
2) It is afield of the GridBagConstraints class for controlling component placement
3) Avalid setting for the anchor field is GridBagConstraints.NORTH
4) The anchor field controls the height of components added to acontainer
Question iM
What will happen when you attempt to compile and run the following code?
public class Bground extends Thread{
public static void main(String argv[]){
Bground b = new Bground();
b run();

205
Exercise
Wintech Computers JAVA 2

}
public void startO{
for(inti = 0;i<10;i++){
System.out.println("Value of i = " + i);
}
}

1) Acompile time error indicating that no run method is defined for the Thread class
2) Arun time error indicating that no run method is defined for the Thread class
3) Clean compile and at run time thevalues 0 to 9 are printed out
4) Clean compile but no output at runtime

Question 19)
When using the GridBagLayout manager, each new component requires a new instance of the
GridBagConstraints class. Is this statement
l)true
2) false

Question 20)
Which most closely matches a description of a Java Map?
1) A vector of arrays for a 2D geographic representation
2) A class for containing unique array elements
3) A class for containing unique vector elements
4) An interface that ensures that implementing classes cannot contain duplicates

Question 21)
How does the set collection deal with duplicate elements?
1) An exception is thrown if you attempt to add an element with a duplicate value
2) The add method returns false if you attempt to add an element with a duplicate value
3) A set may contain elements that return duplicate values from a call to the equals method
4) Duplicate values will cause an error at compile time

Question 22)
What can cause a thread to stop executing?
1) The program exits via a call to exit(0);
2) The priority of another thread is increased
3) A call to the stop method of the Thread class
4) A call to the halt method of the Thread class

Question 23)

Exercise 206
Wintech Computers JAVA 1

For aclass defined inside amethod, what rule governs access to the variables of the enclosing
method?
1) The class can access any variable
2) The class can only access static variables
3) The class can only access transient variables
4) The class can only access final variables

Question 24)
Under what circumstances might you use the yield method of the Thread class
1) To call from the currently running thread to allow another thread ofthe same priority to run
2) To call on a waiting thread to allow it to run
3) To allow a thread of higher priority to run
4) To call from the currently running thread with a parameter designating which thread should be
allowed to run

Question 25)
What will happen when you attempt to compile and run the following code
public class Hope{
public static void main(String argv[]){
Hope h = new Hope();
}
protected Hope(){
for(inti=0;i<10;i++){
System.out.println(i);
}
}
}
1) Compilation error: Constructors cannot be declared protected
2) Run time error: Constructors cannot be declared protected
3) Compilation and running with output 0 to 10
4) Compilation and running with output 0 to 9

Question 26)
What will happen when you attempt to compile and run the following code
public class MySwitch{

public static void main(String argv[]){


MySwitch ms= new MySwitch();
ms.amethodO;
}

Exercise 207
Wintech Computers JAVA 2

public void amethod(){

int k=10;
switch(k){
default: //Put the default at the bottom, not here
System.out.println("This is the default output");
break;
case 10:
System, out. println("ten");
case 20:
System.out.println("twenty");
break;
}
}
}
1) None of these options
2) Compile time errror target of switch must be an integral type
3) Compile and run with output "This is the default output"
4) Compile and run with output "ten"

Question 27)
Which cf the following is the correct syntax for suggesting that the JVM performs garbage
collection
1) System free(),
2) System setGarbageCollection();
3) System out gc();
4) System gc();

Question 28)
What will happen when you attempt to compile and run the following code
public class As{
int i = 10;
int j;
char z= 1,
boolean b,
public static void main(String argv[]){
As a = new As(),
a.amethod();
}
public void amethod0{
System, out. printlmj);
System.out.println(b);
}
}

Exercise 208
Wintech Computers JAVA 2

1) Compilation succeeds and at run time an output of 0 and false


2) Compilation succeeds and at run time an output of 0 and true
3) Compile time error b is not initialised
4) Compile time error z must be assigned a char value

Question 29)
What will happen when you attempt to compile and run the following code with the command
line "hello there11
public class Arg{
String[] MyArg,
public static void main(String argv[]){
MyArg=argv,
}
public void amethod(){
System.out.println(argv[1]);
}
}
1) Compile time error
2) Compilation and output of "hello"
3) Compilation and output of "there"
4) None of the above

Question 30)
What will happen when you attempt to compile and run the following code
public class StrEqj

public static void main(Stnng argv[]){


StrF.q s = new StrEq(),
>
private StrEq(){
String s = "Marcus",
String s2 = new StnngC'Marcus");
ifls==s2){
System out println("we have a match");
}else{
System out println("Not equal"),

}
1) Compile time error caused by private constructor
2) Output of "we have a match"

209
Exercise
Wintech Computers JAVA 2

3) Output of "Not equal"


4) Compile time error by attempting to compare strings using =

Question 31)
1) What will happen when you attempt to compile and run the following code
importjava.io.*;

class Base{
public static void amethod()throws FileNotFoundException{}
}

public class ExcepDemo extends Base{


public static void main(String argv[]){
ExcepDemo e = new ExcepDemo();
}
public static void amethod(){}

protected ExcepDemo(){
try{
DatalnputStream din = new DatalnputStream(System.in);
System.out.println("Pausing");
din.readChar();
System.out.println("Continuing");
this.amethod();
}catch(IOException ioe) {}
}

}
l)Compile time error caused by protected constructor
2) Compile time error caused by amethod not declaring Exception
3) Runtime error caused by amethod not declaring Exception
4) Compile and run with output of "Pausing" and "Continuing" after a key is hit

Question 32)
What will happen when you attempt to compile and run this program
public class Outer{
public String name = "Outer";
public static void main(String argv[]){
Inner i = new Inner();
i.showName();
}//End of main

private class Inner{

Exercise 210
Wintech Computers JAVA 2

String name =new String("Inner");


void showName(){
System, out.println(name);
}
}//End of Inner class

}
1) Compile and run with output of "Outer"
2) Compile and run with output of "Inner"
3) Compile time error because Inner isdeclared as private
4) Compile time error because ofthe line creating the instance ofInner

Question 33)
What will happen when you attempt to compile and run this code
//Demonstration of event handling

import java awt event.*;


import java awt.*;

public class MyWc extends Frame implements WindowListener{


public static void main(String argv[]){
MyWc mwc = new MyWc();

public void windowClosing(WindowEvent we){


System exit(O),
}//End of windowClosing

public void MyWc(){


setSize(300,300),
setVisible(true),
}
}//End of class

1) Error at compile time


2) Visible Frame created that that can be closed
3) Compilation but no output at run time
4) Error at compile time because ofcomment before import statements

Question 34)
What will happen when you attempt to compile and run the following code
public class MyAr{
public static void main(String argv[]) {
MyAr ni = new MyAr(),
m.amethod();

211
Exercise
Wintech Computers JAVA 2

}
public void amethod(){
static int i;
System out.println(i);
}
}
1) Compilation and output of the value 0
2)Compile time error because i has not been initialized
3) Compilation and output of null
4) Compile time error

Question 35)
Which of the following will compile correctly
1) short myshort = 99S;
2) String name = 'Excellent tutorial Mr Green';
3) char c= 17c;
4)intz = 015;

Question 36)
Which of the following are Java key words
1)double
2)Switch
3)then
4)instanceof

Question 37
What will be output by the following line?
System out println(Math.floor(-2.1));
l)-2
2)2.0
3)-3
4)-3.0

Question 38)
Given the following main method in a class called Cycle and a command line of
java Cycle one two
what will be output?
Class Abe
{
public static void main(String bicycle[]){
System.out println(bicycle[0]);
}

Exercise 212
Wintech Computers JAVA 2

1) None of these options


2) cycle
3) one
4) two

Question 39)
Which of the following statements are true?
1) At the root of the collection hierarchy is a class called Collection
2) The collection interface contains a method called enumerator
3) The interator method returns an instance of the Vector class
4) The set interface is designed for unique elements

Question 40)
Which of the following statements are correct?
1) If multiple listeners are addedto a component only events for the last listener added will be
processed
2) If multiple listeners are added to a component the events will be processed for all but with no
guarantee in the order
3) Adding multiple listeners to a comnponent will cause a compile time error
4) You may remove as well add listeners to a component.

Question 41)
Given the following code
class Base{}

public class MyCast extends Base{


static boolean bl=false;
static int i = -1;
static double d = 10.1;

public static void main(String argv[]){


MyCast m = new MyCast();
Base b = new Base();
//Here
}
}
Which of the following, if inserted at the comment //Here will allow the code to compile and run
without error

l)b=m,
2) m=b;

Exercise
Wintech Computers JAVA 2

3)d=i;
4)bl =

Question42)

Which of the following statements aboutthreading are true


1) You can only obtain a mutually exclusive lock on methods in a class that extends Thread or
implements runnable
2) You can obtain a mutually exclusive lock on any object
3)Athread can obtain a mutex lock ona method declared with the keyword synchronized
4) Thread scheduling algorithms are platform dependent

Question 43)
Your chiefSoftware designer has shown you a sketch of the new Computer parts system she is
about to create. At the top of the hierarchy is a Class called Computer and under this are two
child classes One is called LinuxPC and one is called WindowsPC. The main difference
between the two is that one runs the Linux operating System and the other runs the Windows
System (of course another difference is that one needs constant re-booting and the other runs
reliably). Under the WindowsPC are two Sub classes one called Serverand one Called
Workstation. How might you appraise your designers work?

1) Give the goahead for further design using the current scheme
2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than
Class type
3) Ask for the option of WindowsPC to be removed as it will soon be obsolete
4) Change the hierarchy to remove the need for the superfluous Computer Class.

Question 44)
Objective 4.1)
Which of the following statements are true
1) An inner class may be defined as static
2) An inner class may NOT be define as private
3) An anonymous class may have only one constructor
4) An inner class may extend another class

Question 45)
What will happen when you attempt to compile and run the following code
Class Output
{
public static void main(String arg[])
{

Exercise 214
Wintech Computers JAVA 2

int Output=10,
boolean bl = false;
if((bl==true) && ((Output+=10)==20)){
System.out.println("We are equal "+Output);
}else
{
System.out.println("Not equal! "+Output);
}
}
}
1) Compile error, attempting to peform binary comparison on logical data type
2) Compilation and output of "We are equal 10"
3) Compilation and output of "Not equal! 20"
4) Compilation and output of "Not equal! 10"

Question 46)
Given the following variables which of the following lines will compile without error?
String s = "Hello";
long 1= 99;
double d= 1.11;
int i = 1;
int j = 0;
l)j=is;
2)j=ij;
3)j=id;
4)j=i;

Question 47)
What will be output by the following line of code?
System out.println(010|4);
1) 14
2)2.2
3)6
4)2

Question 48)
Given the following variables
char c = 'c';
int i = 10;
double d= 10;
long 1=1;
String s = "Hello";
Which of the following will compile without error?

Exercise
JAVA 2
Wintech Computers

l)c=c+i;
2)s+=i,
3)i+=s;
4)c+=s;

Question 49)
Which of the following will compile with error?
1) File f = new File(7","autoexec bat");
2) DatalnputStream d = new DataInputStream(System in);
3) OutputStreamWriter o = new OutputStreamWriter(System out);
4) RandomAccessFile r = new RandomAccessFilefOutFile");

Question 50)
Given the folowing classes which of the following will compile without error9
interface IFace{}
class CFace implements IFace{}
class Base{}

public class ObRefextends Base{


public static void main(String argv[]){
ObRef ob = new ObRefO;
Base b = new Base();
Object o 1 = new Object();
IFace o2 = new CFace();

l)ol=o2;
2)b=ob,
3)ob=b;
4)o l=b;

Question 51)
Given the following code what will be the output?
class ValHold{
public int i = 10;
}
public class ObParm{
public static void main(String argv[]){
ObParm o = new ObParm();
oamethod(),
}
public void amethod(){
int i = 99,

Exercise 216
Wintech Computers JAVA 2

ValHold v = new ValHold();


v.i=30;
another(v.i);
System.out.println(v.i);

}//End of amethod

public void another(ValHold v, int i){


i=0,
v.i = 20;
ValHold vh = new ValHold();
v= vh;
System.out.println(v.i+". "+i);
}//End of another
}
1) 10,0, 30
2) 20,0,30
3) 20,99,30
4) 10,0,20

Question 52)
Given the following class definition, which of the following methods could be legally placed
after the comment
//Here
public class Rid{
public void amethod(int i, String s){}
//Here
}
l)public void amethod(String s, int i){}
2)public int amethod(int i, String s){}
3)public void amethod(int i, String mystring)!}
4) public void Amethod(int i, String s) {}

Question 53)
Given the following class definition which of the following can be legally placed after the
comment line
//Here ?
class Base{
public Base(int i){}
}

public class MyOver extends Base{


public static void main(String arg[]){
MyOver m = new MyOver(lO);

Exercise
Wintech Computers JAVA 2

}
MyOver(int i){
super(i);
}
MyOver(String s, int i){
this(i);
//Here

}
}
l)MyOver m = new MyOver();
2)super();
3)this("Hello",10);
4)Base b = new Base(lO),

Question 54)

What output result when the main method of the class sub is run?
class Base {
public void method( int i) {
System.out.println("value is : "+i);
}
}

public class Sub extends Base {


public void method (int j) {
System.out.println("This Value is : "+j);
}
public void method (String s) {
System out.println("l was Passed : "+s);
}
public static void main (String args[]) {
Base bl=new Base();
Base b2= new Sub();
bl.method(5);
b2.method(6);
}
}

1) value is 5 value is 6;
2) This value is 5 This value is 6;
3) value is 5 This value is 6;
4) This value is 5 value is 6;
5) I was passed 5 I was passed 6;

Exercise 218
Wintech Computers JAVA 2

Question 55)
Which of the following are methods of the Thread class?
l)yield()
2) sleep(long msec)
3) go()
4) stop()

Question 56)
Which ofthe following methods are members ofthe Vector class and allow you to input a new
element
1) addElement
2) insert
3)append
4) additem

Question 57)
Which of the following statements are true?
1) Adding more classes via import statements will cause aperformance overhead, only import
classes you actually use.
2) Aclass cannot be defined with the private modifier
3) Ainner class can be defined with the protected modifier
4) An interface cannot be instantiated

Question 58)
Which ofthe following are correct event handling methods

1) mousePressed(MouseEvent e){}
2) MousePressed(MouseClick e){}
3) functionKey(KeyPress k){}
4) componentAdded(ContainerEvent e){}

Question 59)
Which ofthe following are methods ofthe Collection interface?
1) iterator
2) isEmpty
3) toArray
4) setText

Question 60)

219
Exercise
Wintech Computers JAVA 2

Which of the following best describes the use of the synhronized keyword?
1) Allows two process to run in paralell but to communicate with each other
2) Ensures only one thread at a time may access a class or object
3) Ensures that two or more processes will start and end at the same time
4) Ensuies that two or more Threads will start and end at the same time
Q61) Consider the following line of code:
Int x[] = new int [25];
After execution , which statement or statement are true9
1) x[24]iso.
2) x[24] is undefined.
3) x[25]is0
4) x[0] is null
5) x length is 25

Qb2) A Java mpnitor musi cither extend Thread or implement Runnable

1) True
2) False

Q63) Which one of the following statements is true?

1) An abstract class may not have any final methods.


2) A final class may not have abstract methods.

Q64) A thread wants to make a second thread ineligible for execution To do this, the first
thread can call the suspend() method on second thread
1) True
2) False

Q65) Ifa frame uses its default layout manager and does not contain any panels, then all the
components within the frame are same width and height
1) True
2) False

Q66) How would you set the color ofagraphics context called g to cyan?
1) g.set(Color cyan);
2) g.setCurrentColor(cyan);
3) g.setColor("cyan");

Q67) Which of the statements below are true?


1) UTF character are all 8 bits
2) Unicode character are all 8 bits.
3) Unicode character are all 16 bits.

Q68)lt is possibale to use the file class to list the contents of the current working directory
1) True

Exercise 220
Wintech Computers JAVA 2

2) False

Q69) Reader have methods that can read and return floats and doubles
1) True
2) False

Q70) Thread wants to make a second thread ineligible for execution To do this, the first thread
can call the yeild( ) method on the second thread
1) True
2) False

Answers

Answer 1)
I) The code will compile and run, printing out the words "My Func"
A class that contains an abstract method must be declared abstract itself but may contain non
abstract methods

Answer 2)
4) The code will compile but will complain at run time that main is not correctly defined

Answer 3)

1) public
2) private
4) transient
The keyword transient is easy to forget as is not frequently used Although a method may be
considered to be friendly like in C++ it is not a Java keyword.

Answer 4)

2) The compiler will complain that the Base class is not declared as abstract.
If a class contains abstract methods it must itself be declared as abstract

Exercise
.. u^ .
Wintech Computers
JAVA 2

Answer 5)

1) To get to access hardware that Java does not know about


3) To write optimised code for performance in a language such as C/C++
Answer 6)
4) Success in compilation and output of"amethod" at run time.
Afinal method cannot be owerriden in a sub class, but apart from that it does not cause any
other restrictions

Answer 7)
4) Compilation and execution without error
It would cause a run time error if you had a call to amethod though.

Answer 8)
l)Compile time error: Base cannot be private
Atop leve (non nested) class cannot beprivate.

Answer 9)
4) PI compiles cleanly but P2 has an error at compile time
The package statement in PI.java is the equivalent ofplacing the file in a different directory to
the file P2.java and thus when the compiler tries to compile P2 an error occurs indicating that
superclass PI cannot be found.

Answer 10)
2) An error at run time
This code will compile, but at run-time you will get an ArraylndexOutOfBounds exception. This
becuase counting in Java starts from 0 and so the 5th element of this array would be i[4]
Remember that arrays will always be initialized to default values wherever they are created.

Answer 11)
2)myarray. length;
The String class has a length() method to return the number of characters. I have sometimes
become confused between the two.

Answer 12)
3) A Frame with one large button marked Four in the Centre
The default layout manager for a Frame is the BorderLayout manager This Layout manager
defaults to placing components in the centre if no constraint is passed with the call to the add
method

Answer 13)
4) Do nothing, the FlowLayout will position the component

Answer 14)
1) Use the setLayout method

Exercise 222
Wintech Computers IAVA

Answer 15)
1) ipadx
2) fill
3) insets

Answer 16)
2) The buttons will run from left to right along the top of the frame

The call to the setLayout(new FlowLayout()) resets the Layout manager for the entire frame and
so the buttons end up at the top rather than the bottom

Answer 17)
2) It is a field ofthe GridBagConstraints class for controlling component placement
3) A valid settting for the anchor field is GridBagConstraints.NORTH

Answer 18)
4) Clean compile but no output at runtime

This is a bit ofa sneaky one us I have swapped around the names ofthe methods you need to
define and call when running a thread If thefor loop were defined in a method called
public void run()
and the call in the main method had been to b start()
The list of values from 0 to 9 would have been output

Answer 19)
2) false

You can re-use the same instance of the GridBagConstraints when added successive
components

Answer 20)
4) An interface that ensures that implementing classes cannot contain duplicates

Answer 21)
2) The add method returns false if you attempt to add an element with a duplicate value
I find it a surprise that you do not get an exception

Answer 22)
1) The program exits via a call to exit(0);
2) The priority of another thread is increased
3) A call to the stop method of the Thread class

Java threads are somewhat platform dependent and you should be carefull when making

Exercise 22^
. L Computers
Wintech ^ . JAVA 2

assumptions about Thread priorities. On some platforms you may find that aThread with higher
priorities gets to "hog" the processor.

Answer 23)
4)The class can only access final variables

Answer 24)

1) To call from the currently running thread to allow another thread ofthe same priority to run
Answer 25)

4) Compilation and running with output 0 to 9

Answer 26)
1) None of these options

Because ofthe lack ofa break statement after the break 10; statement the actual output will be

"ten" followed by "twenty"

Answer 27)
4) System.gc();

Answer 28)
1) Compilation succeeds and at run time an output of0 and false
The default value for a boolean declared at class level is false, and integer is 0;

Answer 29)
1) Compile time error
You will get an error saying something like "Cant make a static reference to a non static
variable" Note that the main method is static

Answer 30)
3) Output of "Not equal"
Despite the actual character strings matching, using the = operator will simply compare
memory location Because the one string was created with the new operator it will be in a
different location in memory to the other string.

Answer 31)
4) Compile and run with output of "Pausing" and "Continuing" after a key is hit
An overriden method in a sub class must not throw Exceptions not thrown in the base class In
the case of the method amethod it throws no exceptions and will thus compile without complain.
There is no reason that a constructor cannot be protected

Answer 32)

Exercise
Wintech Computers
JAVA 2

4) Compile time error because ofthe line creating the instance ofInner
This looks like aquestion about inner classes but it is also areference to the fact that the main
method is static and thus you cannot directly access anon static method. The line causing the
error could be fixed by changing it to say
Inner i = new Outer() new Inner();
Then the code would compile and run producing the output "Inner"
Answer 33)
1) Error at compile time
If you implement an interface you must create bodies for all methods in that interface This code
will produce an error saying that MyWc must be declared abstract because it does not define all
ofthe methods in WindowListener. Option 1is nonsense as comments can appear anywhere
Option 3suggesting that it might compile but not produce output is ment to mislead on the basis
that what looks like aconstructor is actually an ordinary method as it has areturn type.
Answer 34)
4) Compile time error
An error will be caused by attempting to define an integer as static within a method. The lifetime
ofafield within a method is the duration ofthe running ofthe method Astatic field exists once
only for the class. An approach like this does work with Visual Basic

Answer 35)
4)intz = 015,
The letters c and s do not exist as literal indicators and a String must be enclosed with double
quotes, not single as in this case

Answer 36)
l)double
4)instanceof

Note the upper case Son switch means it is not a keyword and the word then is part ofVisual
Basic but not Java. Also, instanceof looks like a method but is actually a keyword,
Answer 37)
4)-3 0

Answer 38)
3) one
Command line parameters start from 0 and fromt he first parameter after the name ofthe compile
(normally Java)

Answer 39)
4) The set is designed for unique elements
Collection is an interface, not a class. The Collection interface includes a method called iterator
This returns an instance of the Iterator class which has some similarities with Enumerators

Exercise 225
Wintech Computers JAVA 2

The name set should give away the purpose ofthe Set interface as it isanalogous to the Set
concept in relational databases which implies uniquness.

Answer 40)
2) Ifmultiple listeners are added to a component the events will be processed for all but with no
guarantee in the order
4) You may remove as well add listeners to a component.
Itought to be fairly intuitive that a component ought to be able to have multiple listeners. After
all, a textfield might want to respond to boththemouse andkeyboard

Answer 41)
1) b=m;
3)d=i;
You can assign up the inheritance tree from a child to a parent but not the other way without an
explicit casting A boolean can only ever be assigned a boolean value.

Answer 42)
2) You can obtain a mutually exclusive lock on any object
3) A thread can obtain a mutex lock on a method declared withthe keyword synchronized
4) Thread scheduling algorithms are platform dependent
Yes that says dependent and not independent.

Answer 43)
2) Ask for a re-design of the hierarchy with changing the Operating System to a field rather than
Class type
Of course there are as many ways to design an object hierarchy as ways to pronounce Bjarne
Strousjoup, but this is the sort of answer that Sun will proabably be looking for in the exam.

Answer 44)
1) An inner class may be defined as static
4) An inner class may extend another class
How could an anonymous class have a constructor?. Remember a constructor is a method with
no return type and the same name as the class. Inner classes may be defined as private

Answer 45)
4) Compilation and output of "Not equal! 10"
The output will be "Not equal 10". This illustrates that the Output +=10 calculation was never
performed because processing stopped after the first operand was evaluated to be false. If you
change the value of bl to true processing occurs as you would expect and the output is "We are
equal 20";.

Answer 46)
2)j= ij;
4)j=il;

Answer 47)
4)2

Exercise 226
Wintech Computers JAVA 2

As well as the binary OR objective this questions requires you to understand the octal notaction
which means that the leading letter zero (not the letter O)) means that the first 1 indicates the
number contains one eight and nothing else. Thus this calculation in decimal mean
8|4
To convert this to binary means
1000
0100

1100

Which is 12 in decimal
The | bitwise operator means that for each position where there is a 1, results in a 1 in the same
position in the answer

Answer 48)
2)s+=i;
Only a String acts as if the + operator were overloaded

Answer 49)
Although the objectives do not specifically mention the need to understand the I/O Classes,
feedback from people who have taken the exam indicate that you will get questions on this topic.
As you will probably need to know this in the real world of Java programming, get familiar with
the basics I have assigned these questions to Objective 10.1 as that is a fairly vague objective.
1) File f = new File(7","autoexec bat");
2) DatalnputStream d = new DatalnputStream(System.in);
3) OutputStreamWriter o = new OutputStreamWriter(System.out);
Option 4, with the RandomAccess file will not compile because the constructor must also be
passed a mode parameter which must be either "r" or "rw"

Answer 50)
l)ol=o2;
2)b=ob.
4)ol=b;

Answer 51)
4) 10,0,20

Answer 52)
1) public void amethod(String s, int i){}
4) public void Amethod(int i, String s) {}
Overloaded methods are differentiated only on the number, type and order of parameters, not on
the return type of the method or the names of the parameters.

Answer 53)

4)Base b = new Base(10);

227
Exercise
Wintech Computers JAVA 2

Any call to this or super must be the first line in a constructor. As the method already has a call
to this, no more can be inserted.

Answer 54)
3) is correct. The first method is produce by Base class when bl.method(5) is called and is
therefore value is 5. Despitevariable b2 declare as being if the Base class the behavior that result
when method() is invoked upon it isthe behavior associated with class ofthe actual object, not
with the type of variable, since the object is of class Sub not of, class Base the result is this value
is 6.

Answer 55)
l)yield()
2) sleep
4) stop()
Note, the methods stop and suspend have been deprecated with the Java2 release, and you may
get questions on the exam that expect you to know this. Check out the Java2 Docs for an
explanation

Answer 56)
l)addElement

Answer 57)
The import statement allows you to use a class directly instead offully qualifying it with the full
package name, adding more classess with the import statement does not cause a runtime
performance overhad. An inner class can be defined with the private modifier
3) An inner class can be defined with the protected modifier
4) An interface cannot be instantiated

Answer 58)
1) mousePressed(MouseEvent e){}
4) componentAdded(ContainerEvent e){}
Answer 59)
1) iterator
2) isEmpty
3) toArray

Answer 60)
2) Ensures only one thread at a time may access a class orobject
A-61)
1 and 2 are true. The array has 25 elements, indexed from 0 throught 24.A11 element are
initialized to zero

A-62)
False. Amonitor is an instance ofany class that has syncronized code.

Exercise 22g
Wintech Computers JAVA 2

A-63) 2nd is true: A final class may not have any abstract methods. Any class with abstract
methods must itself be abstract, and class may not be both abstract and final

A-64) True

A-65) False. The default layout manager is Border

A-66) 1. is correct. The 13 pre defined color are static variables in class Color, so you access
them via class name

A-67) 3 - is correct UTF character are as big as they need to be.

A-68) True

A-69) False. Readers and Writers only deals with charcter I/O

A-70) False The yield() method is static and always causes the current thread to yield.

229
Exercise
Wintech Computers JAVA 2

Subjective Questions

Questions
1) Write a program to generate Fibonacci series.
2) Write a Echo program which prints out to screen whatever you are typing.
3) Write a program which reverses whatever you types into console
4) Write a class which is having a method which returns the factorial ofa number.
5) Write a program to demonstrate how to sort numbers using a simple algorithm
6) Write aclass Rectangle which is having methods for calculating all the properties of a
Rectangle.
7) Use Graphics class to write a class which display a Rectangle.
8) Write a program to generate Pseudo Random Numbers.
9) Write a class to find average oftwo Numbers passed to it
10) Use Applet to draw a String " Wintech Computers"
11) Write a Scribble program using Java Applet
12) Write a program to demonstrate Flow Layout
13) Write a program to demonstrate GridLayout.
14) Write a program to demonstrate BorderLayout.
15) Write a program to demonstrate CardLayout.
16) Write a program to demonstrate YesNo Dialog using Dialog class.
17) Write a multiline displayer using Canvas class
18) Write a program from which we can make cut and paste of Strings in a TextArea
19) Write a program which deletes a given file ( Command line)
20) Write a program which copies one file into another( The files will be given through
command line)
21) Write a program which displays containts ofa file in a textarea using FileDialog
22) What is UML9

Exercise 2^
Wintech Computers JAVA 2

Answers

1) Write a program to generate Fibonacci series.

public class Fibonacci


{
public static void main(String[] args)
{
int current, prev = 1, prevprev = 0;
for(int i = 0; i < 20; i++)
{
current = prev + prevprev;
prevprev=prev;
prev = current;
System.out.print(current + " ");
}
System.out.println();
}
}

2) Write aEcho program which prints out to screen whatever you are typing.
public class Echo
{
public static void main(String[] args)
{
int i = 0;
while(i < args.length)
{
System.out.print(args[i] + " ");
i++;
}
System.out.println() ;
}
}

3) Write a program which reverses whatever you types into console

public class Reverse {


public static void main(String[] args) {

for(int i = args.length-1; i >= 0; i) {

for(int j=args[i].length()-1; j>=0; j) {

System.out.print(args[i].charAt(j));
}

Exercise 231
Wintech Computers JAVA 2

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

4) Write a class, which is having a method, which returns the factorial ofa number.

class Factorial
{
int fact(int n)
{
int result;
if(n= =1)
return 1;
result=fact(n-1)*n;
return result;
}
}
class Recursion
{
public static void main(String arg[]) throws lOException
{
int i=lnteger.parselnt(arg[0]);
Factorial f=new Factorial();
System.out.println("Factorial oa no: "+f.fact(i));
}
}

5) Write a program to demonstrate how to sort numbers using a simple algorithm.

public class SortNumbers {

public static void sort(double[] nums) {


for(int i = 0; i < nums.length; i++) {
int min = i; // holds the index of the smallest element
// find the smallest one between i and the end of the array
for(int j = i; j < nums.length; j++) {
if (numsfj] < nums[min]) min = j;
}
// Now swap the smallest one with element i.
// This leaves all elements between 0 and i sorted,
double tmp;
tmp = nums[i];
nums[i] = nums[min];
nums [min] = tmp;
}

Exercise 232
Wintech Computer* JAVA 2

/** This is a simple test program for the algorithm above */


public static void main(String[] args) {
doublet] nums = new double[10]; // Create an array to
hold numbers
for(int i = 0; i < nums.length; i++) // Generate random
numbers
nums[i] = Math.random() * 100;
sort(nums); // sort them
for (int i = 0; i < nums.length; i++) // Print them out
System.out.println(nums[i]);

6) Write a class Rectangle which is having methods for

public class Rect (


// These are the data fields of the class
public int xl, yl, x2, y2;

/* +

* The is the main constructor for the class. It simply uses


its arguments
* to initialize each of the fields of the new object. Note
that it has
* the same name as the class, and that it has no return value
declared in
* its signature.

public Rect(int xl, int yl, int x2, int y2) {


this.xl = xl;
this.yl = yl;
this.x2 = x2;
this.y2 = y2;
}

/* *

* This is another constructor. It defines itself in terms of


the one above

public Rect(int width, int height) { this(0, 0, width, height);

/** This is yet another constructor. */


public Rect() ( this(0, 0, 0, 0); }

/** Move the rectangle by the specified amounts */


public void move(int deltax, int deltay) {
xl += deltax; x2 += deltax;

Exercise 233
Wintech Computers JAVA 2

yl += deltay; y2 += deltay;

/** Test whether the specified point is inside the rectangle */


public boolean islnside(int x, int y) {
return ((x >= xl) && (x <= x2) && (y >= yl) && (y <= y2));
)

/**

* Return the union of this rectangle with another. I.e.


return the
* smallest rectangle that includes them both.
**/
public Rect union(Rect r) {
return new Rect((this.xl < r.xl) ? this.xl r.xl,
(this.yl < r.yl) ? this.yl r.yl,
(this.x2 > r.x2) ? this.x2 r.x2,
(this.y2 > r.y2) ? this.y2 r.y2);
}

* Return the intersection of this rectangle with another.


* I.e. return their overlap.
** /

public Rect intersection(Rect r) {


Rect result = new Rect((this.xl > r.xl) ? this.xl : r.xl,
(this.yl > r.yl) ? this.yl : r.yl,
(this.x2 < r.x2) ? this.x2 : r.x2,
(this.y2 < r..y2) ? this.y2 : r.y2);
if (result.xl > result.x2) { result.xl = result.x2 = 0; )
if (result.yl > result.y2) { result.yl = result.y2 = 0; }
return result;
}

/**

* This is a method of our superclass, Object. We override it


so that

* Rect objects can be meaningfully converted to strings, can


be

* concatenated to strings with the + operator, and can be


passed to
*
methods like System.out.println()

public String toString() {


return "[" + xl + "," + yl + "; " + x2 + "," + y2 + "]";

}
/** This class demonstrates how you might use the Rect class */
public class RectTest {
public static void main(String[] args) {
Rect rl = new Rect(l, 1, 4, 4); // Create Rect objects
Rect r2 = new Rect(2, 3, 5, 6);

Exercise 234
Wintech Computers JAVA 2

Rect u = rl.union(r2); // invoke Rect methods


Rect i = r2.intersection(rl);

if (u.islnside(r2.xl, r2.yl)) // Use Rect fields and


invoke a method
System.out.println("(" + r2.xl + "," + r2.yl + ") is inside
the union");

// These string concatenations implicitly call the


Rect.toString() method
System.out.println(rl + " union " + r2 + " = " + u);
System.out.println(rl + " intersect " + r2 + " = " + i);
}
}

7) Use Graphics class to write a class which display a Rectangle.

import java.awt.*;
import java.applet.*;

/* - .
<applet code="Rectangles" width=300 height=300>
</applet>
V
public class Rectangles extends Applet
{
public void paint(Graphics g)
{
g.drawRect(10,10,60,50);
g.fillRect(100,10,60,50);
g.drawRoundRect(190,10,60,50,15,15);
g.fillRoundRect(70,50,140,100,30,40);
}
}

8) Write a program to generate Pseudo Random Numbers.

class Randomizer (
// Carefully chosen constants from the book "Numerical Recipes
in C".
// All "static final" fields are constants.
static final int m = 233280;
static final int a = 9301;
static final int c = 4 92 97;

// The state variable maintained by each Randomizer instance


long seed = 1;

Exercise
Wintech Computers JAVA 2

/* *

* The constructor for the Randomizer (.) class. It must be


passed some
* arbitrary initial value or "seed" for its pseudo-randomness.
**/

public Randomizer(long seed) ( this.seed = seed; }


/* *

* This method computes a pseudo-random number between 0 and 1


using a very
* simple algorithm. Math.random() and java.util.Random are
actually a lot
* better at computing randomness.
** /

public float randomFloat() {


seed = (seed * a + c) % m;
return (float)seed/(float)m;
}

/**

* This method computes a pseudo-random integer between 0 and


specified
* maximum. It uses randomFloat() above.
* */
public int randomlnt(int max) {
return Math.round(max * randomFloat());
}

/*

* This nested class is a simple test program: it prints 10


random integers.
* Note how the Randomizer object is seeded using the current
time.
** /

)
class Test2 (
public static void main(String[] args) (
Randomizer r = new Randomizer(new
java.util.Date().getTime());
for(int i = 0; i < 10; i++)
System.out.println(r.randomlnt(100));
}
)
9) Write a class to find average of Numbers passed to it.

class Averager {

double sum;
double n;

Exercise 236
Wintech Computers JAVA 2

public void addDatum(String x) {


int u;
u=lnteger.parselnt(x);
n++;
sum += u;
}

/** This method returns the average of all numbers passed to


addDatum() */
public double getAverage() { return sum / n; }

public double getNum() { return n; }

/** This method returns the sum of all numbers passed to


addDatum() */
public double getSum() { return sum; )

class Testl (
public static void main(String args[]) {
Averager a - new Averager(); '

if (args.length<l){
System.out.println("you should pass the parameter");
System.exit(0);
}
for(int i - 0; i < args.length-1; i++)
a.addDatum(args[i]);
System.out.println("Average: " + a.getAverage());
System.out.printIn("N: " + a.getNum());
System, out.println ("Sum: " + a.getSumO);

)
)
10) Use Applet to draw a String" Wintech Computers".

import java.applet.*; // Don't forget this import statement I


import java.awt.*; // Or this one for the graphics!

/** This applet just says "Wintech Computers */


public class FirstApplet extends Applet (
// This method displays the applet.
// The Graphics class is how you do all drawing in Java.

Exercise
*AVA 2
Wintech Computers

public void paint(Graphics g) {


g.drawString("Wintech Computers", 25, 50);
}
}

11) Write aScribble program using Java Applet


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/** A simple applet that uses the Java 1.1 event handling model
*/
public class Scribble2 extends Applet
implements MouseListener,
MouseMotionListener {
private int last_x, last_y;

public void init() {


// Tell this applet what MouseListener and
MouseMotionListener
// objects to notify when mouse and mouse motipn events
occur.
// Since we implement the interfaces ourself, our own methods
are called.
this.addMouseListener(this);
this.addMouseMotionListener(this);
}

// A method from the MouseListener interface. Invoked when the


// user presses a mouse button.
public void mousePressed(MouseEvent e) {
last_x = e.getX();
last_y = e.getY ();
}

// A method from the MouseMotionListener interface. Invoked


when the
// user drags the mouse with a button pressed,
public void mouseDragged(MouseEvent e) {
Graphics g = this.getGraphics();
int x = e.getXO, y = e.getY();
g.drawLine(last_x, last_y, x, y);
last_x = x; last_y = y;
}

// The other, unused methods of the MouseListener interface,


public void mouseReleased(MouseEvent e) {;}
public void mouseClicked(MouseEvent e) {;}
public void mouseEntered(MouseEvent e) {;}
public void mouseExited(MouseEvent e) {;}

Exercise 238
Wintech Computers JAVA 2

// The other method of the MouseMotionListener interface,


public void mouseMoved(MouseEvent e) {;)
}

12) Write a program to demonstrate Flow Layout.

import java.awt.*;
import java.awt.event.*;
public class MyButtons extends Frame implements ActionListener
{
public MyButtons ( )
{
setTitle ( "My Buttons " ); // Title of the window.
setLayout ( new FlowLayout ( )); // Sets the layout
//using layout manager
add( new Button ( "Yellow")); //Creating buttons with
//respective labels
add( new Button ( "Blue"));
add( new Button ( "Orange"));
add( new Button ( "Cyan"));
add( new Button ( "Pink"));
add( new Button ( "Red"));
Button b= new Button("Green");
add(b);
b.addActionListener(this);
addWindowListener(new Mywindowadap());
}
public void actionPerformed(ActionEvent e)
(
System.out.println(" Button Green is Pressed");
}
public static void main(String args[]){
Frame f = new MyButtons();
f.setSize(300,300);
f.setVisible(true);
1
}
class Mywindowadap extends WindowAdapter(
public void windowClosing(WindowEvent we){
System.exit(0);
}
}

13) Write a program to demonstrate GridLayout

import java.applet.Applet,
import java.awt.*;

239
Exercise
Wintech Computers JAVA 2

/*<applet code="Gridl" height="100" width="200"X/applet>*/

public class Gridl extends Applet

private Button buttonl, button2, button3, button4,


button5;

public void init()


{
buttonl = new
Button("one");
button2 =
newButton("two");

button3=newButton("th
ree"); button4 =
newButton("four");
button5 =
newButton("five");
setLayout(newGridLayo
ut(2,3));

//order is important

add(buttonl); // row 1
col 1
add(button2); // row 1
col 2
add(button3); // row 1
col 3

add(button4) ; // row 2
col 1
add(button5) ; // row 2
col 2
}
}

14) Write a program to demonstrate BorderLayout.

import java.applet.*;
import java.awt.*;
import Java.awt.event.*;

/*<applet code="Beeper" height="100"


width="200"x/applet>*/

public class Beeper extends Applet implement:


ActionListener

Exercise
240
Wintech Computers JAVA 2

{
Button button;
public void init( )
{
setLayout(new BorderLayout() );
button = new ButtonC'Click Me");
add("Center", button);
button.addActionListener(this) ;
}
public void actionPerformed(ActionEvent e)
<
Toolkit.getDefaultToolkit().beep();
}
}

15) Write a program to demonstrate CardLayout.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/*<applet code="CardLayoutExample" width="200"


height="100"></applet>*/

public class CardLayoutExample extends Applet {


public void init () {
// Create a layout manager, and save a reference to it for
future use.
// This CardLayout leaves 10 pixels margins around the
component.
final CardLayout cardlayout = new CardLayout(10, 10);
// Specify the layout manager for the applet
this.setLayout(cardlayout);
for(int i = 1; i <= 9; i++) (
Button b = new Button("Button #" + i);
ActionListener listener = new ActionListener(
public void actionPerformed(ActionEvent e) // When
button is clicked
cardlayout.next(CardLayoutExample.this); // display
the next one.

b.addActionListener(listener);
this.add("Button" + i, b); // Specify a name for each
component
}
}
)
16) Write a program to demonstrate YesNo Dialog using Dialog class.

241
Exercise
Wintech Computers JAVA 2

import java.awt.*;
import java.awt.event.*;

public class YesNoDialog extends Dialog


{
public YesNoDialog(Frame parent, String title, String message,
String yes_label, String no_label, String
cancel_label)
{
// Create a modal dialog with the specified title and parent
super(parent, title, true);

this.setLayout(new BorderLayout(15, 15));

later in the chapter


this.add("Center", new TextArea(message, 20, 20));'

// Create an action listener for use by the buttons of the


dialog.
// When a button is pressed, this listener first closes the
dialog box.
// Then, it passes the event on to the listeners registered
for the
// dialog box, after changing the event source from the
individual button
// to the dialog box itself. Since events are immutable, it
must create
// a new ActionEvent object in order to change the source.
It passes
// this new event to the listeners by calling
actionPerformed() on the
// AWTEventMulticaster object stored in the listeners field
(see below).
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
YesNoDialog.this.dispose(); // pop down dialog
if (listeners != null) // notify all registered
listeners
listeners.actionPerformed(new
ActionEvent(YesNoDialog.this,
e.getID() ,

e.getActionCommand() ));
}
};

// Create a panel for the dialog buttons and put it at the


bottom

Exercise 242
Wintech Computers JAVA 2

// of the dialog. Specify a FlowLayout layout manager for


it.
Panel buttonbox = new Panel();
buttonbox.setLayout(new FlowLayout(FlowLayout.CENTER, 25,
15));
this.add("South", buttonbox);

// Create each specified button, specifying the action


listener
// and action command for each, and adding them to the
buttonbox
if (yes_label != null) { // if a label was
specified.
Button yes = new Button(yes_label); // create button
yes.setActionCommand("yes"); // set action
command
yes.addActionListener(listener); // set listener
buttonbox.add(yes); // add button to
the panel
}
if (no_label != null) {
Button no = new Button(no_label);
no.setActionCommand("no") ;
no.addActionListener(listener);
buttonbox.add(no) ;
}
if (cancel_label != null) {
Button cancel = new Button(cancel_label);
cancel.setActionCommand("cancel");
cancel.addActionListener(listener);
.buttonbox.add(cancel);
}

// Finally, set the dialog to its preferred size,


this.pack();
}

/** This field will hold a list of registered ActionListeners,


thanks
* to the magic of AWTEventMulticaster */
protected ActionListener listeners = null;

/** Register an action listener to be notified when a button is


pressed
* AWTEventMulticaster makes this easy. */
public void addActionListener(ActionListener 1) {
listeners = AWTEventMulticaster.add(listeners, 1);
}

/** Remove an action listener from our list of interested


listeners */
public void removeActionListener(ActionListener 1) {

243
Exercise
Wintech Computers JAVA 2

listeners = AWTEventMulticaster.remove(listeners, 1);


}

* A main method that demonstrates how to use this class, and


allows testing
*/
public static void main(String[] args) {
// Create, size, and show a frame because dialogs require a
frame parent.
Frame f = new Frame("InfoDialog Test");
f.setSize(100, 100);
f.show();

// Create an instance of InfoDialog, with title and message


specified
YesNoDialog d =
new YesNoDialog(f, "YesNoDialog Test",
"There are unsaved files.\n" +
"Do you want to save them before
quitting?",
"Yes, save and quit",
"No, quit without saving",
"Cancel; don't quit");

// Register an action listener for the dialog. This one just


prints
// the results out to the console,
d.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.out.println("The user pressed: " +
e.getActionCommand()
);
}
}
);

// Now pop the dialog up. It will pop itself down


automatically,
d.show();
}
}

17) Write a multiline displayer using Canvas class.

import java.awt.*;
import java.util.*;

public class MultiLmeLabel extends Canvas {

Exercise 244
Wintech Computers JAVA 2

// User-specified attributes
protected String label; // The label, not broken
into lines
protected int margin_width; // Left and right margins
protected int margin_height; // Top and bottom margins
protected int alignment; // The alignment of the
text.
public static final int LEFT = 0, CENTER = 1, RIGHT = 2; //
alignment values
// Computed state values
protected int num_lines; // The number of lines
protected String[] lines; // The label, broken into
lines
protected int[] line_widths; // How wide each line is
protected int max_width; // The width of the widest
line
protected int line_height; // Total height of the font
protected int line_ascent; // Font height above
baseline
protected boolean measured = false; // Have the lines been
measured?

// Here are five versions of the constructor


public MultiLineLabel(String label, int margin_width,
int margin_height, int alignment) {
this.label = label; // Remember all the
properties
this.margin_width = margin_width;
this.margin_height = margin_height;
this.alignment = alignment;
newLabel(); // Break the label up
into lines
}
public MultiLineLabel(String label, int margin_width, int
margin_height! (
this(label, margin_width, margin_height, LEFT);
}
public MultiLineLabel(String label, int alignment) {
this(label, 10, 10, alignment);
}
public MultiLineLabel(String label)
{
thisdabel, 10, 10, LEFT) ;
}
public MultiLineLabel()
{
this ("") ;

// Methods to set and query the various attributes of the


component

245
Exercise
JAVA 2
Wintech Computers

// Note that some query methods are inherited from the


superclass.
public void setLabel(String label)
(
this.label = label;
newLabeK); // Break the label into lines
measured = false; // Note that we need to measure
lines
repaint(); // Request a redraw
}
public void setFont(Font f)
super.setFont(f); // tell our superclass about the
neW measured = false; // Note that we need to remeasure
lines
repaint(); // Request a redraw
}
public void setForeground(Color c)
super.setForeground(c); // tell our superclass about the
new color
repaint(); // Request a redraw (size is
unchanged)

public void setAlignment(int a) { alignment = a; repaint(); }


public void setMarginWidth(int mw) { margin_width = mw;
repaint(); }
public void setMarginHeight(int mh) { margin_height = mh;
repaint(); }
public String getLabel() { return label; }
public int getAlignment() { return alignment; }
public int getMarginWidth() { return margin_width; }
public int getMarginHeight() { return margin_height; }

* This method is called by a layout manager when it wants to


* know how big we'd like to be. In Java 1.1,
getPreferredSize () is
* the preferred version of this method. We use this
deprecated version
* so that this component can interoperate with 1.0 components.
*/
public Dimension preferredSize () {
if ([measured) measure();
return new Dimension(max_width + 2*margin_width,
num_lines * line_height +
2*margin_height);
}

* This method is called when the layout manager wants to know

Exercise 24
Wintech Computers JAVA 2

* the bare minimum amount of space we need to get by.


* For Java 1.1, we'd use getMinimumSize().
*/
public Dimension minimumSize() { return preferredsize(); }
/* *

* This method draws the label (same method that applets use).
* Note that it handles the margins and the alignment, but that
* it doesn't have to worry about the color or fontthe
superclass
* takes care of setting those in the Graphics object we're
passed.
*/
public void paint(Graphics g) {
int x, y;
Dimension size = this.size(); // use getsize() in Java 1.1
if (!measured) measure();
y = line_ascent + (size.height - num_lines * line_height)/2;
for(int i = 0; i < num_lines; i++, y += line_height) {
switch(alignment) {
default:
case LEFT: x = margin_width; break;
case CENTER: x = (size.width - line_widths[i])/2; break;
case RIGHT: x = size.width - margin_width -
line_widths[i]; break;
}
g.drawString(lines[i], x, y);

/** This internal method breaks a specified label up into an


array of lines.
* It uses the StringTokenizer utility class. */

protected synchronized void newLabel()


{
StringTokenizer t = new StringTokenizer(label, "\n");
num lines = t.countTokens();
lines = new String[num_lines];
line_widths = new int[numlines];
for(int i = 0; i < num_lines; i++) lines[i] = t. nextToken () ;
}

/** This internal method figures out how the font is, and how
wide each
* line of the label is, and how wide the widest line is. */

protected synchronized void measure()


(
FontMetrics fm =
this.getTool kit() .getFontMetrics(this.get Font()) ;
line height = fm.getHeight() ;

247
Exercise
IAVA 2
Wintech Computers

line_ascent = fm.getAscent();
max_width = 0;
for(int i = 0; i < num_lines; i++)

line_widths[i] = fm.stringWidth(lines[i]) ;
if (line widths[i] > max_width) max_width = line_widths[i];
)
measured = true;
)
public static void main(String args[]){
Canvas cv = new MultiLineLabel("wintech",200,200,2);
cv.setSize(300,300);
cv.show();
}
}

18) Write a program from which we can make cut and paste ofStrings in a TextArea.

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;

/* +

* This program demonstrates how to add string cut-and-paste


capabilities
* to an application.
* * /

public class StringCutAndPaste extends Frame implements


ActionListener

/* *

* The main method creates a frame, arranges to handle its


closing,
* packs it and pops it up.

public static void main(String[] args)


{
Frame f = new StringCutAndPasteO;
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0);
}
}
);
f.pack();

Exercise 248
Wintech Computers JAVA 2

f.show();
}

/** The text field that holds the text that is cut or pasted */
TextField field;

/**

* The constructor builds a very simple test GUI, and registers


this object
* as the ActionListener for the buttons
** /

public StringCutAndPaste()
(
this.setFont(new Font("SansSerif", Font.PLAIN, 14)); // Use
a nice font

// Set up the Cut button


Button cut = new Button("Cut");
cut.addActionListener(this) ;
cut.setActionCommand("cut");
this.add(cut, "West");

// Set up the Paste button


Button paste = new Button("Paste");
paste.addActionListener(this) ;
paste.setActionCommand("paste") ;
this.add(paste, "East");

// Set up the text field that they both operate on


field = new TextField();
this.add(field, "North");
}

/* *

* Clicking on one of the buttons invokes this method, which in


turn

* invokes either the cut() or the paste() method

public void actionPerformed(ActionEvent e)


{
String cmd = e.getActionCommand();
if (cmd.equals("cut")) cut();
else if (cmd.equals("paste")) paste();
}

/* *

* This method takes the current contents of the text field,


creates a
* StringSelection object to represent that string, and puts
the
* StringSelection onto the clipboard

Exercise 2<*9
Wintech Computers JAVA 2

public void cut()


{
// Get the currently displayed value
String s = field.getText();
int l=s.length();
String sl= field.getSelectedText();
int ls=sl.length();
int in = s.indexOf(si);
int tl=ls+in;
if (ls==l) field.setText("");
if (tl==l |tl>l){
s=s.substring(0,in);
field.setText(s);
}

if(tl<l)
{
String sh=s.substring(0,in);
String so=s.substring(tl,1);
s=sh+so;
field.setText(s);
}
// Create a StringSelection object to represent it.
// This is a big convenience, because StringSelection
implements both
// the Transferable interface and the ClipboardOwner. We
don't have
// to deal with either of them.
// StringSelection ss = new StringSelection(s);
// Now set the StringSelection object -as the contents of the
clipboard
// Also set it as the owner of the clipboard.
/* this.getToolkit()-getSystemClipboard().setContents(ss,
ss);*/
}

/*

* This method does the reverse. It gets the contents of the


clipboard,
* then asks for them to be converted to a string, then
displays the
* string.

public vdid pasted


{
// Get the clipboard
Clipboard c = this.getToolkit().getSystemClipboard();
// Get the contents of the clipboard, as a Transferable
object
Transferable t = c.getContents(this);

Exercise 250
Wintech Computers JAVA 2

// Ask for the transferable data in string form, using the


predefined
// string DataFlavor. Then display that string in the field.
try {
String s = (String)
t.getTransferData(DataFlavor.stringFlavor);
field.setText(s);

// If anything goes wrong with the transfer, just beep and do


nothing.
catch (Exception e)
{
this.getToolkit().beep();
return;

}
}

19) Write aprogram which deletes agiven file (Command line).

import java.io.*;

/* +

* This class is a static method delete() and a standalone


program that
* deletes a specified file or directory.
** /

public class Delete


{

* This is the main() method of the standalone program. After


checking ,_._,.. ^
* it arguments, it invokes the Delete.delete() method to do
the deletion

public static void main(String[] args)


{
if (args..length != 1)
{ '// Check command-line arguments
System.err.println("Usage: Java Delete <file or
directory>");
System.exit(0) ;

// Call delete() and display any error messages it throws,


try { delete(args[0]); }

251
Exercise
Wintech Computers JAVA 2

catch (IllegalArgumentException e) {
System.err.println(e.getMessage()); )
}

/* *

* The static method that does the deletion. Invoked by


main(), and designed
* for use by other programs as well. It first makes sure that
the

* specified file or directory is deleteable before attempting


to delete it.
* If there is a problem, it throws an
IllegalArgumentException.
*/

public static void delete(String filename)


{
// Create a File object to represent the filename
File, f = new File(filename);
// Make sure the file or directory exists and isn't write
protected
if (!f,exists()) fail("Delete: no such file or directory: " +
filename);
if (!f .canWriteO ) fail ("Delete: write protected: " +
filename);
// If it is a directory, make sure it is empty
if (f.isDirectory()) (
String[] files = f.list();
if (files.length > 0) fail("Delete: directory not empty: "
+ filename);
}
// If we passed all the tests, then attempt to delete it
boolean success = f.delete();
// And throw an exception if it didn't work for some
(unknown) reason.
// For example, because of a bug with Java 1.2 on Linux,
// directory deletion always fails
if (Isuccess) fail("Delete: deletion failed");

/** A convenience method to throw an exception-*/


protected static void fail(String msg) throws
IllegalArgumentException {
throw new IllegalArgumentException(msg);

20) Write aprogram which copies one file into another( The files will be given through
command line)

Exercise ,-,
Wintech Computers JAVA 2

import java.io.*;

/**

* This class is a standalone program to copy a file, and also


defines a
* static copy() method that other programs can use to copy
files.

public class FileCopy


{
/** The main() method of the standalone program. Calls copy().
*/

public static void main(String[] args)


{
if (args. length != 2) // Check arguments
System.err.println("Usage: java FileCopy <source file>
<destination>");
else
{
// Call copy() to do the copy, and display any error
messages it throws.
try { copy(args[0], args[l]); }
catch (lOException e) { System.err.println(e.getMessage());
>
}
}

/* *

* The static method that actually performs the file copy.


* Before copying the file, however, it performs a lot of tests
to make
* sure everything is as it should be.

public static void copy(String from_name, String toname)


throws lOException{
File from_file - new File(from_name); // Get File objects
from Strings
File to_file = new File(to_name);
// First make sure the source file exists, is a file, and is
readable.
if (!from_file.exists())
abort("FileCopy: no such source file: " + from_name);
if (!from_file.isFile())
abort("FileCopy: can't copy directory: " + from_name);
if (!from_file.canRead())
abort("FileCopy: source file is unreadable: " + from_name);

253
Exercise
Wintech Computers JAVA 2

// If the destination is a directory, use the source file


name

//as the destination file name


if (to_file.isDirectory() )
to file = new File(to_file, from_file.getName());

// If the destination exists, make sure it is a writeable


file
// and ask before overwriting it. If the destination doesn't
// exist, make sure the directory exists and is writeable.
if (to_file.exists ())
{
if (!to_file.canWrite())
abort("FileCopy: destination file is unwriteable: " +
to_name);
/./ Ask whether to overwrite it
System.out.print("Overwrite existing file " + to_name + "?
(Y/N): ");
System.out.flush();
// Get the user's response.
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in));
String response = in.readLine();
// Check the response. If not a Yes, abort the copy.
if (!response.equals("Y") && !response.equals("y"))
abort("FileCopy: existing file was not overwritten.");
}
else
(
// if file doesn't exist, check if directory exists and is
writeable.
// If getParent() returns null, then the directory is the
current dir.
// so look up the user.dir system property to find out what
that is.
String parent = to_file.getParent(); // Get the
destination directory
if (parent == null) parent =
System.getProperty("user.dir"); // or CWD
File dir = new File(parent); // Convert it to a
file.
if (!dir.exists ())
abort("FileCopy: destination directory doesn't exist: " +
parent);
if (dir.isFile())
abort("FileCopy: destination is not a directory: " +
parent);
if (!dir.canWrite())
abort("FileCopy: destination directory is unwriteable: "
+ parent);

Exercise 254
Wintech Computers JAVA 2

// If we've gotten this far, then everything is okay.


// So we copy the file, a buffer of bytes at a time.
FilelnputStream from = null; // Stream to read from source
FileOutputStream to = null; // Stream to write to
destination
try {
from = new FilelnputStream(from_file); // Create input
stream

to = new FileOutputStream(to_file); // Create output


stream

byte[] buffer = new byte[4096]; // a buffer to hold


file contents
int bytes_read; // How many bytes
in buffer
// Read a chunk of bytes into the buffer, then write them
out,
// looping until we reach the end of the file (when read()
returns -1) .
// Note the combination of assignment and comparison in
this while
// loop. This is a common I/O programming idiom.
while((bytes_read = from.read(buffer)) != -1) // Read bytes
until EOF
to.write(buffer, 0, bytes_read); // write
bytes
}'
// Always close the streams, even if exceptions were thrown
finally {
if (from != null) try { from.close(); } catch (lOException
e) { ; }
if (to != null) try { to.closeO; } -catch (lOException e) {
; }
}
}

/** A convenience method to throw an exception */


private static void abort(String msg) throws lOException {
throw new lOException(msg);
}

21) Write a program which displays containts of a file in a textarea using FileDialog.

import java.awt.*;
import java.awt.event.*;

class framel extends Frame


{
framel( )

Exercise 255
Wintech Computers JAVA 2

{
super("file dialog");
mywadapter adapter = new mywadapter( );
addWindowListener(adapter) ;
}
}

class mywadapter extends WindowAdapter


{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

class filedemo
{

public static void main(String args[])


{
Frame f = new framel( );
f .setSize(200,200);
f.setVisible(true) ;
FileDialog fd = new FileDialog(f,"file
dialog",FileDialog.Load) ;
Fd.setVisible(true);
}
}

22) The UML is a modeling language for specifying, visualizing, constructing, and
documenting the artifacts ofa system-intensive process.

Within a system-intensive process, a method is applied as a process to derive or


evolve a system.
As a language, it is used for communication. That is, a means to capture knowledge
(semantics) about a subject and express knowledge (syntax) regarding the subject for
the purpose of communication. The subject isthe system under discussion.
As a modeling language, it focuses on understanding a subject via the formulation of
a model of the subject (and its related context). The model embodies knowledge
regarding the subject, and the appropriate application ofthis knowledge constitutes
intelligence.
Regarding unification, it unifies the information systems and technology industry's
best engineering practices across types of systems (software and non-software),
domains (business versus software), and life-cycle processes.

Exercise 256
Wintech Computers JAVA 2

As it applies to specifying systems, it can be used to communicate "what" is required


of a system, and "how" a system may be realized.

As it applies to visualizing systems, it can be used to visually depict a system before it


is realized.
As it applies to constructing systems, it can be used to guide the realization of a
system similar to a "blueprint"

As it applies to documenting systems, it can be used for capturing knowledge about a


system throughout its life-cycle

r 257
Exercise
Wintech Computers JAVA 2

APPENDIX

Java Virtual Machine

The easiest and cleanest way to describe Java virtual machine is to compare Java run-time
environment Java requires a Velcro effect type mechanism This mechanism is provided by
Java executable or class file and Java run-time environment

Java run-time environment acts as a receptor in Java executable - Java run-time


environment bond. Java run-time environment binds itself to the specific native platform and
provides a shield against any platform specific issues by eliminating machine -specific issues.
This shielding is known as a layer of indirection for the Java executable

At the time the executable is handed to the Java run-time environment for execution in
the JVM, the application can assume a certain set of predefined functionality It is up to the
JVM to shield the application from any platform-specific dependencies. As long as the platform
has a JVM affixed to it, all Java executables are able to run. In this way, the Java application
binds to the JVM ,in turn, binds to the specific platform. It means that Java application can run
on any platform that has an accessible Java runtime environment

The JVM provides Java executables with the machine architecture to be executed on
and the runtime provides basic operating functionalies. JVM emulates 'Java chip' which only
knows how to execute the Java machine instruction set The support classes required by Java
executables like Java, lang package resides in run-time environment and are fetched by JVM as
needed. Because of this reason the class file of Jdkl.O can't run in Jdkl.2

Following is the block diagram of Java virtual machine

JAVA VIRTUAL
Byte code
MACHINE
Class Loader Verifier

Security Manager

Appendix
258
Wintech Computers JAVA 2

The JVM is a virtual machine, it is not an interpreter but rather an emulator. To call
JVM as a interpreter, interpreting Java compiled byte code into actual native machine code is
partly true. It actually executes theclass file byemulating.

JVM actually consists of five funtional block for executing class file which is its
primary task are as follows :-

1. Stack
2. Garbage Collection Heap
3. Method Area
4. Registers
5. Instructions Set

According to the figure given above the class loader has a very important role to play. It
loads classes into the JVM. It is internally divided into five unites and do the function of
retrival of class file when called by JVM, verifies the code of the called file for security
reasons, supplies the supporting files to the class file needed for its execution and initializes
the Java Virtual Machine. Its stops the loaded class to access other classes except standard
Java libraries. After class loader the class file goesto byte code verifier. It checks that the class
file is not disturbing pointers or not converting object illegally. It also checks its format of the
class file and after being satisfied passes to security manager. The Security manager stops the
class file from accessing native machines file such as Harddisk and allows access to the
following only-
Networking
Protected Information
Operating System Level Programs and processes
The Class Loader and Java class library.

259
Appendix

Вам также может понравиться