Java Second Wintech Computers
Java Second Wintech Computers
Wintech Computers
Table Of Contents
Training Cycle 1
Training Cycle 2
2. Fundamentals of Java
2.1 Introduction 8
2.5 Expressions 12
Training Cycle 3
Training Cycle 4
4.6 Packages 57
4.7 Interfaces 57
Training Cycle 5
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
1. Introduction to Java
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.
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.
ActiveX technology of Microsoft is also used to write programs for Internet, mainly for client
side applications.
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.
Training Cycle 1
JAVA 2
Wintech Computers
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 .
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 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.
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++.
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.
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
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.
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.
Visual Cafe (from Symantec Inc.): As above plus advanced GUI design features.
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.
Training Cycle 1
Wintech Computers JAVA 2
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.
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.
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
javac ExampleProgram.java
]ava ExampleProgram
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
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.
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
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
Training Cycle 2 11
JAVA 2
Wintech Computers
Bitwise Operators
Abitwise operator allows you to perform bit manipulation on data. This table summarizes the
bitwise and logical operators available inthe Java language.
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
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.
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) {
}
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:
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
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
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.
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
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.
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
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.
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:
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
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.
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.
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
Training Cycle 3 22
Training
Cycle: 4
Wintech Computers JAVA 2
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.
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.
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
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
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()
public Rectangle(Point p)
origin = p;
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:
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
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
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
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));
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.
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:
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:
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:
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:
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
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:
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.
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 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:
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.
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
Methods
m>>jtw
ff'{tjriiis.&tt()' * *)- , -
- return false;
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.
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.
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
Training Cycle 4
Wintech Computers JAVA 2
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
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.
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.
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;
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");
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
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.
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:
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()
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 /
The method body is where all the action takes place. It contains the Java instructions that
implement the method.
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.
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.
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 )
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.
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
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
Training Cycle 4
Wintech Computers JAVA 2
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):
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
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;
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.
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
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.
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;
Training Cycle 4 51
Wintech Computers JAVA 2
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
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
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
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:
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:
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;
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.
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
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.
Examp]e:
interface Collection
(
public static final int MAX=500;
public abstract void add ( Obiect ob);
public abstract int Current) );
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.
// 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
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.
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.
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 ']').
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];
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.
Training Cycle 5 ,,
Wintech Computers JAVA 2
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.
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.
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:
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.
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
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
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
catch(ArithmeticException e)
{
System.out.println("Exception: " + e);
A=0;
}
Output
Exception: Java.lang.ArithmeticException
Training CycJe 6 69
Wintech Computers JAVA 2
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.
Training Cycle 6
Wintech Computers JAVA 2
throw Throwablelnstance
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;
Ouput
C:\JCODE>java ThrowDemo
Caught inside demoproc.
Training Cycle 6 71
Wintech Computers JAVA 2
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.
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 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
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
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.
}
\
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 ( );
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
)
Java.lang.Thread
Training Cycle 7 76
Wintech Computers JAVA 2
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.
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
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 ( );
)
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();
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.
Training Cycle 7 80
Wintech Computers JAVA 2
Java.lang.Thread
Training Cycle 7 81
Wintech Computers JAVA 2
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
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
Training Cycle 7 g2
Wintech Computers JAVA 2
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,
java.langThread
83
Training Cycle 7
JAVA 2
Wintech Computers
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.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.
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.
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
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
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 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
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);'
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
import java.io.
<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
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
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
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
Buffered Writer
CharArray Writer
Filter Writer
Piped Writer
Print Writer
Siring Writer
OutputStream Writer
FileWriter
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.
import java.io.*;
if (args.length!= 2)
{
System.out.println("Usage: Java CopyProgram
<Source> <destination>");
System.exit(0) ;
}
while((c=rd.read())!= -1)
{
wr.write (c);
}
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.
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
93
Training Cycle 8
JAVA 2
Wintech Computers
Java, io.DataOutputStream
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
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.
Java.io.File
95
Training Cycle 8
Wintech Computers JAVA 2
import java.io.*;
class Filelnfo
(
public static void main(String args[])
{
char c;
File file=new File("ras.txt") ;
if (file.exists() )
(
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
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
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
java.io.BuffredlnputStream
Java.io.BufferedOutputStream
java.io.LineNumberlnputStream
Training Cycle 8
98
Training
Cycle: 9
Wintech Computers JAVA 2
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
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.
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
102
Training Cycle 9
IAVA 2
Wintech Computers
import java.awt.*;
import java.awt.event.*;
import Java.applet.*;
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
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 ");
}
}
TrainingCycle 9 104
JAVA 2
Wintech Computers
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
ContainerEve wEvent
KeyEvent MouseEvent
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
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:
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[])
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.
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);
9.6 Fonts
Text can displayed in various Styles, Fonts and Font Types. Font is an object in
Java
Example:
Here we have an instance of Font class that is set to the parameters as given in the
brackets.
import java.awt.*;
import java.awt.event.*;
class MyWindow3 extends Frame
}
}
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:
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
import java.awt.*;
import java.awt.event.*;
class Mywindow extends Frame
{
Mywindow()
{
super("FontMetrics Example");
setSize(150, 75);
show();
if(e.id==Event.WINDOW_DESTROY)
System.exit(0);
return super.handleEvent(e);
java.awt.Graphics
9.7 Colors
Standard Colors
Syntax:
public final static Color color
Example. Color.darkGray,
Java.awt.Color
Java. awt.Graphics
public abstract void setColor ( Color c): Changes the current color
C: new color object
java.awt.Graphics
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 )
System.exit(0) ;
return super.handleEvent (e);
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.
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
import java.awt.*;
import java.awt.event.*;
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
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
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.
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 Image createlmage (int w , int h): This method creates an off
screen buffer.
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
Java.awt.Component
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
118
Training Cycle 9
Wintech Computers JAVA 2
Adding Buttons
java.awt. Button
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.
java.awt. Container
public void setLayout ( LayoutManager mgr ): Sets layout manager for the
container.
Training Cycle 9
119
Wintech Computers JAVA 2
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)
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
Example:
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
North
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.
Example:
{
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
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
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
import java.awt.*;
import java.applet.*;
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.
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.
java.awt.TextArea
MytextArea = new TextArea (10, 60) //10 hn.es of60 colum~rs each
import java.awt.*;
You can select portions ofthe text in the text area using the methods given below.
java.awt.TextComponent
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.
import java.awt.*;
import java.awt.event.*;
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.
java.awt.Label
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:
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).
Training Cycle 9
129
Wintech Computers JAVA 2
public Checkbox( String label) Creates a check box with a label on it.
public void setstate ( boolean Sets the check box to a new state, either
state )
true or false.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
checkBold=new Checkbox("Bold");
checkltalic=new Checkbox("Italic");
f=new Font("TimesRoman", Font. PLAIN, 14);
t.setFont(f);
add(t);
add(checkBold);
add(checkltalic);
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.
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
Training Cycle 9
131
Wintech Computers JAVA 2
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()
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.
Example
132
Training Cycle 9
JAVA 2
Wintech Computers
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;
add(choiceButton);
add(t);
java.awt.List
public String getltem (int index ) Gets an item from the list indicated
by index.
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.
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);
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.
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.
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.
This table lists the kinds of events that each 1.2 AWT component can generate.
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
TextArea IX X xxx X
TextComponent X X XXX
TextField X X X xxx X
Window
xxx
iArfrttt XX X X
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.
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.
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
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)
Called by the AWT after the listened-to component becomes visible as the result
of the setVisible method being called
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.
Each container event method has a single parameter: a ContainerEvent object. The
ContainerEvent class defines two useful methods:
Component getChild()
140
Training Cycle 9
Wintech Computers JAVA 2
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.
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.
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.
void itemStateChanged(ItemEvent)
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()
int getStateChangeQ
Returns the new state of the item. The ItemEvent class defines two states:
SELECTED and DESELECTED
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
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.
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
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);
/** Handle the key typed event from the text field. */
/** Handle the key pressed event from the text field. */
/** Handle the key released event from the text field. */
displayArea.setText("");
typingArea. setText("");
//Return the focus to the typing area.
typingArea.requestFocus();
}
if(tmpString.length()>0)
{
modString += " (" + tmpString + ")"; }
else
{
modString +--- " (no modifiers)".
i
i
int getKeyChar()
void setKeyChar(char)
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)
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
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
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)
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.
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:
148
Training Cycle 9
Wintech Computers J*v*
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.
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;
c.fill = GridBagConstraints.BOTH;
c.gridwidth = GridBagConstraints.REMAINDER;
c.weightx = 1.0;
c.weighty = 1.0;
newline = System.getProperty("line.separator");
1
void textValueChanged(TextEvent)
Called bv the AWT just after the text in the listened-to component changes
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
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
TextArea display,
Frame window,
Button bl, b2,
static final String SHOW = "show",
setLayout(new BorderLayout());
add("North", bl);
add("Center", display);
add("South", b2);
Training Cycle 9
Wintech Computers JAVA 2
+ e.getWindow()
+ newline);
}
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.
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
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
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:
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());
Then you add items into the container. When you re-size, the components
automatically get realigned.
North
South
import java.awt *
fshow();
java.awt.CardLayout
Sample Program
Below is an example for card Layout.
b.addActionListener(listener),
this.add("Button" + i, b); // Specify a name for each component
}
}
}
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
setLayout(new
GridLayout(2,3));
//order is important
Training Cycle 9
Training
Cycle: 10
Wintech Computers JAVA 2
10.1 Introduction
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.
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.
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
<HTML>
<HEAD>
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.
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.
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
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
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();
}
163
Training Cycle 10
Wintech Computers JAVA 2
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.
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
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.
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
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 can invoke public methods of other applets on the same page.
Although most applets stop running once you leave their page, they don't
have to.
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 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.
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
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());
}
}
}
)
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
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
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);
Training Cycle 10
168
Wintech Computers JAVA 2
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);
)
}
10.7 Animation
Training Cycle 50
170
V\ intech Computers JAVA 2
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
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
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.
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.
Example
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.
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
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.
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, .
Stereotype
Name
(Constraint-String, Keyword-Value, ...}
Figure 4: Ctuutmutt String* ami tfr/wwtf-Voter Cain
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
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.
The flexibility provided by utilizing this paradigm can be best understood by examining the roots
ofthe paradigm itself within Plato's theory ofForms.
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.
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
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.
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.
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.
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.
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 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.
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.
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.
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
Thing
Meta-metamodtl
Metamodel
mm-Cor.cept inn-Concept-Instance
Metamodel
Model'
m-Concept
Model
User Model
um-Concept : m-Concept
Aperson may be a member ofa team, and a team may have various members: Member Ofis an
instance of Association (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
(Si and Tl) and the classification of a relationship (Member OO among concepts are depicted
differently
Thing
Meta-metamodel
Metarn odel
Metamodel
Model
<<Associat:on>>
Hember Of
<<Class>> <<Class
Person Team
Model
Uset Model
<<Link
Hember Of
<<Object>> <<Object
Si : Tcroon Tl : Team
Thina
Meta-metamodel
Metamodel
Metam odel
Model
Hember Of
Person Team
Model
User Model
Hember Of
Si : Person Tl Team
188
Training Cycle 11
Winteth Computers JAVA2
Meta-metamodel
Metamodel
Metamodel
As90ciation-
Model
Member 01
Model
User Model
Link
Hember Of
<<Object>> <<Object
Si Tcraon, rcrroancnt Tl : Team Temporary
Metamodel
Model
Member Of
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 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
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
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
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
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'
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
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
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
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
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
Metamodel
Hember *>> -
Model
Exclusively
Model
U er Model Exclusively
figure It: Mm* t'ompttx Kxumpk with Minimally Specified Modtt fitment* md tht /'* X Lmrnioa fur tinmen tam Modeting
das*
reference
-he-?-j WI Kr~H
relationship* implementing
(o another entity of ntorleSCM interlaces
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
'note'
FinatClast
la< b)
/* comment text V
^
ABS
12. Exercise
70 Questions
Question 1) What will happen when you attempt to compile and run this code''
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
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
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
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{
}//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.*;
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{
Exercise 207
Wintech Computers JAVA 2
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
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
}
1) Compile time error caused by private constructor
2) Output of "we have a match"
209
Exercise
Wintech Computers JAVA 2
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{}
}
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
Exercise 210
Wintech Computers JAVA 2
}
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
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
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{}
l)b=m,
2) m=b;
Exercise
Wintech Computers JAVA 2
3)d=i;
4)bl =
Question42)
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{}
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
}//End of amethod
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){}
}
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);
}
}
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
1) True
2) False
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");
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)
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)
Answer 26)
1) None of these options
Because ofthe lack ofa break statement after the break 10; statement the actual output will be
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)
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-66) 1. is correct. The 13 pre defined color are static variables in class Color, so you access
them via class name
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
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() ;
}
}
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));
}
}
Exercise 232
Wintech Computer* JAVA 2
/* +
/* *
Exercise 233
Wintech Computers JAVA 2
yl += deltay; y2 += deltay;
/**
/**
}
/** 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
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);
}
}
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;
Exercise
Wintech Computers JAVA 2
/* *
/**
/*
)
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
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".
Exercise
*AVA 2
Wintech Computers
Exercise 238
Wintech Computers JAVA 2
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);
}
}
import java.applet.Applet,
import java.awt.*;
239
Exercise
Wintech Computers JAVA 2
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
}
}
import java.applet.*;
import java.awt.*;
import Java.awt.event.*;
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();
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
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.*;
e.getActionCommand() ));
}
};
Exercise 242
Wintech Computers JAVA 2
243
Exercise
Wintech Computers JAVA 2
import java.awt.*;
import java.util.*;
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?
245
Exercise
JAVA 2
Wintech Computers
Exercise 24
Wintech Computers JAVA 2
* 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 figures out how the font is, and how
wide each
* line of the label is, and how wide the widest line is. */
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.*;
/* +
/* *
Exercise 248
Wintech Computers JAVA 2
f.show();
}
/** The text field that holds the text that is cut or pasted */
TextField field;
/**
public StringCutAndPaste()
(
this.setFont(new Font("SansSerif", Font.PLAIN, 14)); // Use
a nice font
/* *
/* *
Exercise 2<*9
Wintech Computers JAVA 2
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);*/
}
/*
Exercise 250
Wintech Computers JAVA 2
}
}
import java.io.*;
/* +
251
Exercise
Wintech Computers JAVA 2
catch (IllegalArgumentException e) {
System.err.println(e.getMessage()); )
}
/* *
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.*;
/**
/* *
253
Exercise
Wintech Computers JAVA 2
Exercise 254
Wintech Computers JAVA 2
21) Write a program which displays containts of a file in a textarea using FileDialog.
import java.awt.*;
import java.awt.event.*;
Exercise 255
Wintech Computers JAVA 2
{
super("file dialog");
mywadapter adapter = new mywadapter( );
addWindowListener(adapter) ;
}
}
class filedemo
{
22) The UML is a modeling language for specifying, visualizing, constructing, and
documenting the artifacts ofa system-intensive process.
Exercise 256
Wintech Computers JAVA 2
r 257
Exercise
Wintech Computers JAVA 2
APPENDIX
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
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
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