Sie sind auf Seite 1von 120

COALESCE

Java Programming

COALESCE Technologies Pvt. Ltd


1

COALESCE
Table of Contents
Chapter
1.

Java as a OOP Language ................................................................................. 6

1.4.

Goals of Java Programming Language ....................................................................6

1.5.

Concept of Bytecode ...............................................................................................7

1.6.

The Key features of Java..........................................................................................7

1.4.

Platform Independence...........................................................................................7

1.5.

Simplicity................................................................................................................7

1.6.

Object-oriented .......................................................................................................7

1.7.

Robustness..............................................................................................................7

1.8.

Multithreaded..........................................................................................................8

1.9.

Interpreted and High Performance..........................................................................8

1.10.

Distributed .............................................................................................................8

1.11.

Dynamic .................................................................................................................8

1.12.

Review Questions ...................................................................................................8

Object-Oriented Programming ..................................................................... 9

2.
2.1.

OOPS vs. Procedural Programming........................................................................9

2.2.

Data Abstraction & Encapsulation ....................................................................... 11

2.3.

Inheritance........................................................................................................... 12

2.4.

Polymorphism ...................................................................................................... 12

The Java Architecture.......................................................................................13

3.
3.1.

The Java Virtual Machine...................................................................................... 13

3.2.

Garbage Collection................................................................................................ 13

3.3.

Code Security ....................................................................................................... 14

3.4.

The JVM Runtime Environment........................................................................... 14

3.5.

Class Loader ......................................................................................................... 14

3.6.

Verification Process.............................................................................................. 15

3.7.

Review Quastions ................................................................................................. 15

Creating a program in Java ............................................................................16

4.
4.1.

The source file layout ............................................................................................ 16

4.2.

Compiling & Running a Program......................................................................... 17

4.3.

Java Classes & Packages....................................................................................... 17

4.4.

Java Keywords ...................................................................................................... 18

COALESCE
4.5.

Wrapper Classes................................................................................................... 18

4.6.

Primitive Data Type Wrapper Class..................................................................... 19

4.7.

Variables.............................................................................................................. 19

4.8.

Member & Automatic variables............................................................................ 19

4.9.

Object Reference Variables ..................................................................................20

4.10.

Type Conversion and Casting...............................................................................20

4.11.

Widening conversions permitted in Java............................................................... 21

4.12.

Narrowing Conversions allowed........................................................................... 21

4.13.

Operators and Assignments ................................................................................. 21

4.14.

The Bitwise operators ..........................................................................................22

4.15.

Relational Operators ............................................................................................22

4.16.

Boolean Logical operators....................................................................................23

4.17.

The ternary operator.............................................................................................23

4.18.

Classes in Java......................................................................................................24

4.19.

Methods in Java ...................................................................................................24

4.20.

'this keyword .......................................................................................................25

4.21.

Overloading .........................................................................................................25

4.22.

Overriding ...........................................................................................................27

4.23.

Passing arguments using Call by value & using Call by reference........................27

4.24.

Access control-using Modifiers............................................................................28

4.25.

Other Modifiers ...................................................................................................28

4.26.

Abstract: ............................................................................................................ 299

4.27.

Static....................................................................................................................29

4.28.

Native..................................................................................................................30

4.29.

Nested and inner classes...................................................................................... 31

4.30.

Classes Defined Inside Methods..........................................................................32

4.31.

Anonymous classes ............................................................................................ 322

4.32.

Additional Features of Anonymous Inner Classes ................................................33

4.33.

Properties of Inner classes ...................................................................................33

4.34.

Collection API .....................................................................................................33

4.35.

The Vector Class..................................................................................................33

4.36.

Review Quastions ................................................................................................35

Reflection API ................................................................................................... 36

5.
5.1.

Object class.........................................................................................................36

5.2.

Abstract Classes...................................................................................................37

COALESCE
6.

Packages.............................................................................................................. 38

6.1.

Package DefaultPackage;.....................................................................................38

6.2.

Classpath.............................................................................................................38

6.3.

Protection of Access ............................................................................................39

7.

Importing of Packages ....................................................................................41

7.1.

Classes versus Abstract class versus Interface ...................................................... 41

7.2.

Interfaces............................................................................................................. 41

8.

Accessing implementations Through Interface References.............. 43

8.1.

Extending Interfaces............................................................................................43

8.2.

Review Questions................................................................................................44

9.

Input/Output in Java ...................................................................................... 45

9.1.

What Are Streams?...............................................................................................45

9.2.

Byte-Oriented Streams.........................................................................................45

9.3.

Character Oriented Streams.................................................................................45

9.4.

Character Stream Classes and Interfaces..............................................................47

9.5.

Reading and Writing from and to a File...............................................................48

9.6.

Review Question..................................................................................................50

10. APPLETS.............................................................................................................51
10.1.

The steps involved in running an Applet.............................................................. 51

10.2.

AppletViewer.......................................................................................................53

11.

The HTML APPLET Tags .......................................................................... 54

11.1.

Applet Architecture..............................................................................................55

11.2.

An Applet Skeleton...............................................................................................55

11.3.

Applet Display......................................................................................................56

11.4.

Applet Initialization and Termination ..................................................................56

11.5.

The Applet Class ..................................................................................................57

11.6.

paint(Graphics g) ................................................................................................58

11.7.

repaint() ..............................................................................................................58

11.8.

To set Background and Foreground colors..........................................................58

11.9.

Requesting Repainting........................................................................................59

11.10.

The Status Window.............................................................................................59

11.11.

Passing Parameters to Applets............................................................................60

11.12.

Difference between Applications and Applets..................................................... 61

11.13.

Review Questions ...............................................................................................62

COALESCE
12. Fundamentals of Exception Handling ..................................................... 63
12.1.

Exception Types...................................................................................................64

12.2.

try and catch.........................................................................................................65

12.3.

Multiple Exceptions .............................................................................................65

12.4.

Throw...................................................................................................................66

12.5.

Throws.................................................................................................................67

12.6.

finally...................................................................................................................68

12.7.

Javas Built in Exceptions....................................................................................68

12.8.

Javas Unchecked RuntimeException Subclasses: ...............................................69

12.9.

Javas checked exceptions defined in java.lang ....................................................69

12.10.

User defined Exception Subclasses:.....................................................................69

12.11.

Review Questions................................................................................................70

13. Event Handling..................................................................................................71


13.1. Event Handling Mechanisms ................................................................................ 71
13.2. Outward rippling model or Hierarchical Event Model........................................... 71
13.3.

Delegation event model ........................................................................................ 71

13.4.

Event Sources.......................................................................................................72

13.5.

EventListeners......................................................................................................72

13.6.

EventClasses ........................................................................................................72

13.7.

Methods ...............................................................................................................72

13.8.

Hierarchy of Event Classes in java.awt.event ........................................................73

13.9.

Main Event Classes in java.awt.event....................................................................73

13.10. The Classes, Methods and Interfaces used by AWT..............................................74


13.11.

The WindowEvent Class ......................................................................................78

13.12.

Using the delegation event model ........................................................................79

13.13. Adapter Classes....................................................................................................79


13.14.

Inner Classes........................................................................................................80

13.15. Anonymous Inner Classes....................................................................................80


13.16.

Review Questions ................................................................................................ 81

14. AWT Controls .................................................................................................... 82


14.1.

Window Fundamentals.........................................................................................83

14.2.

The class hierarchy for panel and frame................................................................84

14.3.

Component...........................................................................................................84

14.4.

Container..............................................................................................................84

14.5.

Panel ....................................................................................................................84

COALESCE
14.6.

Frame...................................................................................................................84

14.7.

Handling Events in a Frame Window...................................................................85

15. Adding & Removing Controls...................................................................... 87


15.1.

Labels...................................................................................................................87

15.2.

Buttons.................................................................................................................87

15.3.

Check Box............................................................................................................88

15.4.

Choice Controls....................................................................................................90

15.5.

Lists..................................................................................................................... 91

15.6.

ScrollPane.............................................................................................................93

15.7.

Scrollbar ...............................................................................................................93

15.8.

TextField & TextArea...........................................................................................94

15.9.

TextArea...............................................................................................................96

15.10.

Radio Buttons......................................................................................................97

15.11.

Review Questions.................................................................................................98

16. Layout Managers .............................................................................................. 99


16.1.

Identifying GUI requirements...............................................................................99

16.2.

Selection of the Components................................................................................99

16.3.

Sketching the GUI.............................................................................................. 100

16.4.

Using Layout Managers...................................................................................... 100

16.5.

Containers and Components............................................................................... 100

16.6.

Common subclasses of java.awt.Container ..........................................................101

16.7.

Component Size and Position..............................................................................101

16.8.

Layout Managers................................................................................................ 102

16.9.

FlowLayout Manager.......................................................................................... 102

16.10.

BorderLayout Manager...................................................................................... 103

16.11. GridLayout Manager.......................................................................................... 105


16.12.

CardLayout Manager ......................................................................................... 107

16.13. GridBagLayout Manager.....................................................................................110


16.14.

anchor constraint .................................................................................................111

16.15. fill constraint .......................................................................................................112


16.16.

Insets..................................................................................................................113

16.17. Null Layout Manager..........................................................................................116


16.18.

Choosing Layout Managers ................................................................................117

16.19.

Review Questions ...............................................................................................117

17. Index .................................................................................................................... 119


5

COALESCE

1.

Java as a OOP Language

Java was conceived by a team of engineers in Sun Microsystems in 1991 as a part of a


research project, which was led by James Gosling and Patrick Naughton. It took 18 months
to develop the first working version. This language was initially called Oak but was
renamed as Java in 1995.
Modeled after C++, the Java language was designed to be small, simple, and portable across
platforms and operating systems, both at the source and at the binary level, which means
that Java programs (applets and applications) can run on any machine that has the Java
virtual machine installed.
1.1. Goals of Java Programming Language
JAVA language is an effective programming language for it

Is object-oriented; and helps the programmer visualize the program in real-life terms.

Eliminates pointer arithmetic and memory management that affect code robustness.
An interpreted environment resulting the following two benefits:

Speed of development.

Code portability enables the operating system to make system level calls on
behalf of the runtime environment.

A way for programs to run more than one unit of execution called a thread of activity.

A means to change programs dynamically during their runtime life by allowing them to
download code modules.

Security
Java is a secured programming language because it provides the user with a Virtual Firewall
between the networked applications and the computer thus ensuring that the data in the
users system is protected by any possible Infectious contents. This is achieved by confining
the Java program within the Java Runtime Environment.

Portability
Java can be easily ported on any type of system and irrespective of the operating system
being used. Java achieves this portability due to its feature of Implementation Independency.
6

COALESCE
1.2. Concept of Bytecode
The Security and the portability concerns of the user was solved by the Java Programming
language, because the out put of a Java program is not a executable piece of code, instead it
is Bytecode which is the output of the Java Compiler. This Bytecode is understood by, the
Java Virtual Machine (JVM), which is the interpreter for Bytecode. The JVM s are different
for different operating systems.
1.3. The Key features of Java
The factors that have played an important role in moulding the final form of Java language
are:

1.4 Platform Independence


Platform independence-that is, the ability of a program to move easily from one computer
system to another-is one of the most significant advantages that Java has over other
programming languages, particularly if your software needs to run on many different
platforms. If you're writing software for the World Wide Web, being able to run the same
program on many different systems is crucial to that program's success. Java is platform
independent at both the source and the binary level.
1.5 Simplicity
Java was designed to be easy for the professional programmer to learn and use effectively.
Being simple means Being small also. Java achieves this by enabling the programmer to build
a- software that can be run stand-alone even on small machines.
A system, which functions independently without the help of any network resources, is
known as a stand-alone system.
1.6 Object-oriented
Object-Oriented design is a technique of programming, which mainly focuses on the Object
and its Interfaces. To make a comparison, an object-oriented mechanic would be bothered
only about repairing the vehicle, and secondarily on the tools that he is going to use. A nonobject-oriented mechanic would primarily be concerned of his tools rather than the vehicle.
The object-oriented features of Java are very much of C++ itself.
1.7 Robustness
The multi-platform environment places extraordinary demands on a program, because the
program must execute reliably in a variety of systems. Java emphasizes a lot on early
checking for problems, later dynamic or runtime checking, thus eliminating error-prone
situations.

COALESCE
1.8 Multithreaded
Multithreading is a concept, where different process, run simultaneously. Java supports
multithreaded programming because of its better interactive responsiveness and real time
behavior.
1.9 Interpreted and High Performance
The code can be easily interpreted on any system that provides a Java Virtual Machine. The
conversion of the Interpreted code into the machine code at Run Time for the particular
CPU on which the application is running is called High Performance.
The compilation of code in an interpreted environment is done line by line & hence the
debugging of the code becomes very easy, as the interpreter points exactly to the line where
the error ocurs.
1.10 Distributed
It is designed for the distributed environment of the Internet, as it handles TCP/IP
protocols. Java allows objects on two different computers to execute procedures remotely.
Java has revived these interfaces in a package called Remote Method Invocation (RMI) .
1.11 Dynamic
Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve access to objects at run time. This makes it possible to dynamically link
code in a safe manner.
1.12

Review Questions

1. What are Bytecodes?


2. What do we mean by saying Java is Interpreted?
3. If Java is platform independent, why doesnt it run on all platforms?

COALESCE
2. Object-Oriented Programming
OOP is the dominant programming paradigm these days, having replaced the Structured
mode of programming techniques that were developed in the early 70s. Java is an objectoriented programming language like C++, Ada, Simula, Small-talk.
The key to being most productive in OOP is to make each object responsible for carrying
out a set of related tasks. If an object relies on a task that isnt its responsibility, it needs to
have access to an object whose responsibilities include that task. The first object then asks
the second object to carry out the task. This is done with a more generalized version of the
function call that you are familiar with in procedural programming. In java we call this as
method calls. In particular an object should never directly manipulate the internal data of
another object. All communication should be via messages that is, method calls. By
designing your objects to handle all appropriate messages & manipulate their data internally,
you maximize reusability, reduce data dependency & minimize debugging time.
2.1. OOPS vs. Procedural Programming
In procedure oriented programming, you identify the tasks to be performed and then:
Break the task to be performed into sub-tasks and those into smaller subtasks, until
the subtasks are simple enough to be implemented directly.
Write procedures to solve simple tasks & combine them into more sophisticated
procedures, until you have the functionality achieved.
Most programmers use a mixture of the top-down & bottom-up strategies to solve a
programming problem. The important difference is that in OOP you first isolate the classes
in the project only then you look for the methods of the class. And there is another
important difference between traditional procedures & OOP methods: each method is
associated with the class that is responsible for carrying out the operation.
For small problems the breakdown into procedures works very well. But for larger
problems, classes & methods have two advantages. Classes provide a convenient clustering
mechanism for methods. A simple web browser may require 1000 functions for its
implementation or it may require 100 classes with an average of 10 methods per class. The
latter structure is much easier to grasp by the programmer or to handle by teams of
programmers. The Encapsulation built into classes helps you here as well: classes hide their
data representations from all code except their own methods.

COALESCE
Procedural Programming.
FUNCTION

GLOBAL DATA

FUNCTION

FUNCTION

Object Oriented Programming


method

OBJECT DATA

method

method
OBJECT DATA

method

method

OBJECT DATA

The above figure shows that if a programming bug messes up the data it is easier to
search for the culprit among the methods that had access to that data item among those
procedures.

10

COALESCE
There is a more serious problem, while classes are factories for multiple objects with the
same behavior, you cannot get multiple copies of a useful module. Suppose you have a
module encapsulating a collection of orders, together with a balanced binary tree module
to access them quickly. Now it turns out that you actually need two such collections, one
for the pending orders & one for the completed orders. You cannot simply link the
order tree twice. And you dont really want to make a copy & rename all the procedures
in order for the linker to work.
Classes do not have this limitation. Once a class has been defined it is easy to construct
any number of instances of that class type, where as a module can have only one
instance.

Classes
The Class is a container that holds both data & code together in a single unit. It is a template
for objects. Classes are user defined data types and behave like built in da ta types of a
programming language. Once a class has been defined, we can create any number of objects
belonging to that class.
Ex: Fruit Grape, Fruit Water melon and Fruit Pine Apple.

Here the class Fruit has different instances with the same properties but different values.

Objects
Objects are the basic run-time entities in an object-oriented system.
Ex: Person, Bank Account, Table of data or any item that the program must handle.

They contain data and code to manipulate that data. When a program is executed, the
objects can interact with each other without knowing the details of each others data or code.
Ex: A Customer Object requesting the Account Object for the Bank balance.

2.2.Data Abstraction & Encapsulation


is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse. The data is not accessible to the
outside world and only those functions that are wrapped in the class can access it. These
functions provide the interface between the objects data and the program. The insulation of
the data from the direct access by the program is called data hiding.
Encapsulation

11

COALESCE
2.3.Inheritance
Inheritance is the process by which one object acquires the properties of another object. This
is important because it supports the concept of hierarchical classification. Inheritance
interacts with encapsulation as well. Inheritance provides the idea of reusability of code and
each sub class defines only those features that are unique to it.
Flora
Plants
Rose

Trees
Tomato

Oak

Coconut

2.4.Polymorphism
Polymorphism is a feature that allows one interface to be used for a general class of actions.
An operation may exhibit different behavior in different instances. The behavior depends
on the types of data used in the operation. It plays an important role in allowing objects
having different internal structures to share the same external interface. Polymorphism is
extensively used in implementing inheritance.
Ex:

add(int a, int b) add(int a, float b, int c) add(int a, int b, float c, double d)

Here different datatypes are being added using the same interface.

12

COALESCE
3. The Java Architecture
Java essentially uses the following features to fulfill its goals:

The Java Virtual Machine

The Garbage Collector

Code security

3.1. The Java Virtual Machine


Java achieves the concept of platform-independence by inventing an abstract computer of its
own and running on that. This virtual machine, as it is called runs a special set of instructions,
called bytecodes that are simply a stream of formatted bytes, each of which has a precise
specification of exactly what each byte code does to this virtual machine. The virtual
machine is also responsible for certain fundamental capabilities of Java, such as object
creation and garbage collection.
The JVM is defined as An abstract machine that is implemented by emulating it in software on a
real machine.

The JVM provides the hardware platform specifications to which all java technology code is
compiled. This specification enables java software to be platform independent because the
compilation is done for a generic machine known as Java Virtual Machine (JVM). This
generic machine can be emulated into software to run on various existing computer systems
or implemented in hardware.
The compiler takes the java application source code and generates bytecodes. Every java
interpreter, regardless of whether it is a java technology development tool or a web browser
that can run applets, has an implementation of JVM. The Java virtual machine specification
consists of the following:

The byte code syntax, including opcode and operand sizes, values, and types, and
their alignment.
The values of any identifiers (for example, type identifiers) in bytecodes or in
supporting structures
The layout of the supporting structures that appear in compiled Java code
The Java .class file format

3.2.Garbage Collection
In the Java programming language, the dynamic allocation of objects is achieved using the
new operator. An object once created uses some memory and the memory remains allocated
till there are references for the use of the object. When there are no references for an object,
it is assumed to be no longer needed and the memory occupied by the object can be
reclaimed. There is no explicit need to destroy an object as java handles the de-allocation
automatically. The technique that accomplishes this is known as Garbage Collection.
13

COALESCE
Programs that do not de-allocate memory can eventually crash when there is no memory left
on the system to allocate. These programs are said to have memory leaks.
Garbage collection happens automatically during the lifetime of a java technology program,
eliminating the need to de-allocate memory and avoiding memory leaks. Such processes are
called background processes.
There are methods, System.gc() and Runtime.gc() that look as if they run the garbage
collector but even these methods do not have any control on the Garbage Collection
Process.
3.3. Code Security
Source File

Class Loader
Byte Code Verifier

javac Hello.java

Network

Interpreter

JIT Code
Generator

Hello.class

Runtime
Hardware

3.4.The JVM Runtime Environment


The byte codes are stored in class files. At runtime, the bytecodes that make up a java
software program are loaded, checked, and run in an interpreter. In the case of applets the
bytecodes can be downloaded and then interpreted by the JVM built into the browser. The
interpreter has two functions: it executes bytecodes, and makes the appropriate calls to the
underlying hardware.
A Java technology runtime environment runs code compiled for a JVM and performs three
main tasks:

Loads Code

Verifies Code -

Performed by the byte code verifier

Executes Code -

Performed by the runtime interpreter

Performed by the class loader

3.5.Class Loader
The class loader loads all classes needed for the execution of a program. The class loader
adds security by separating the namespaces for the classes of the local file system from those
imported from network sources.
14

COALESCE
Once all the classes have been loaded, the memory layout of the executable file is
determined. At this point specific memory addresses are assigned to symbolic references
and the lookup table is created. Because memory layout occurs at runtime, the java
technology interpreter adds protection against unauthorized access into the restricted areas
of code.
Java software code passes several tests before actually running on your machine. The JVM
puts the code through a byte code verifier that tests the format of code fragments and
checks code fragments for illegal code code that forges pointers, violates access rights on
objects, or attempts to change object type.
3.6.Verification Process
The byte code verifier makes four passes on the code in a program. It ensures that the code
follows the JVM specifications and does not violate system integrity. If the verifier
completes all four passes without returning an error message, then the following is ensured.
The classes follow the class file format of the JVM specification

There are no access restriction violations

The code causes no operand stack overflows or underflows

The types of parameters for all operational codes are known to always be
correct.

No illegal data conversions, such as converting integers to object references, have occurred.

3.7.Review Questions
1. What kind of Garbage Collection does the Java Virtual Machine use?

15

COALESCE
4. Creating a program in Java
A Java program file is an ordinary text file with . java extension. Java source files are
created in a plain text editor, or in an editor that can save files in plain ASCII without any
formatting characters. It contains one or more class definitions. In Java all code must reside
inside a class. Generally the class name written in the .java file will be the name for the .java
file too.

4.1. The source file layout


There are three top-level elements that may appear in a file. None of these elements is
required. If they are present, they must appear in the following order:

Package Declaration (optional only one)

Import Statements (optional any number)

Class Definitions (Any number only one public class)

SimpleExample.java
// A SAMPLE PROGRAM IN JAVA
import java.io.*;
public class SimpleExample
{

public static void main(String args[])


{ System.out.println("Hey I am successful in writing my prog");
}

}
What does this whole program has to say..?

The program is a java application, since it has main() method. Now let us understand the
signature of the main() method:
The main() method is:
public:

so that it can be accessed by anything, including the java technology interpreter.

Tells the compiler that the main() method is usable in the context of the class
SimpleExample and should be run before the program does anything else.
static:

void: Indicates that it does not return anything.


String args[ ]:

parameter.

Contains command line arguments. args[0] stores the first command line

Object creation: In

java, objects are created by explicitly calling the constructor of the class for
which it holds the reference.
Java programs do not directly deal with objects. Rather it deals with the reference of the
object, which the constructor returns.

16

COALESCE
4.2.Compiling & Running a Program
To compile the SimpleExample program, execute the compiler, javac, specifying the name of
the source file on the command line, as shown here:
C:\>javac SimpleExample.java

The javac compiler creates a file called SimpleExample.class. This .class file is nothing but the
bytecode for the program. The bytecode is the intermediate representation of your program
that contains instructions the Java interpreter will execute. Thus, the output of javac is not
the code that can be directly executed.
To actually run the program, you must use the Java interpreter, called java. To do so, pass the
class name SimpleExample at the command-line:
C:\>java SimpleExample

When the program is run, the following output is displayed:


Hey I am successful in writing my prog.

4.3.Java Classes & Packages


A class is a term for a template that provides data and the functionality, which will work on that
data.
The Java Development Kit comes with a standard set of class (Java Class Library) that
implements most of the basic behaviors needed - not only for programming tasks, but also
for graphics and networking database etc.
A Package is a group of related classes. The class library is organized in to many packages,
each containing several classes. The following packages are prominent:
java.lang: contains classes that form the core of the language, such as String, Math,
Integer and thread. It is automatically imported by default into all the user defined
Source files.
java.awt: contains classes that make up the Abstract Window Toolkit (AWT). This
package is used for constructing and managing the graphical user interface of the
application.
java.net: Contains classes for performing network related operations and dealing with
sockets and uniform resource locators (URLs).
java.io: Contains classes that deal with file Input/Output.

java.util: Contains utility classes for tasks, such as random number generation,
defining system properties, and using date and calendar related functions.

17

COALESCE
4.4.Java Keywords
There are 52 reserved keywords defined in the Java language. These keywords, combined
with the syntax of the operators and separators, form the definition of the Java language.
Keywords in Java Language:
Abstract

Const

Finally

Implements

Public

This

Boolean

Continue

For

Instanceof

Throw

Transient

Break

Float

If

Null

Short

Void

Byte

Default

Import

Int

Super

Volatile

Case

Do

False

Return

Switch

While

Catch

Double

Interface

Package

Synchronized

Char

Else

Long

Private

Static

Class

Extends

Goto

Protected

Try

True

Final

New

Native

Throws

Data Types
Type

In bits

Range

Byte

-27 to 27-1

Short

16

-215 to 215-1

Int

32

--231 to 231-1

Long

64

-263 to 263-1

Float

32

3.4e-038 to 3.4e+038

Double

64

1.7e-308 to 1.7e+308

Boolean

True/False

Char

16

0 to 65,636 (216-1)

4.5.Wrapper Classes
Java deals with two different types of entities: Primitive types and true objects. Although Java is
truly object-oriented, it does not use most primitive types for the usual reason: performance.
Manipulating primitive type without any object-oriented overhead is quite a bit more
efficient. Java contains many subsystems that can work only with objects. By wrapping the
primitive types in some object sugar coating the programmer can easily create a class whose
sole purpose is encapsulation. The net effect would be to obtain an object giving the
programmer the universality and power that come with dealing with only objects.
Ex:

Class Integer for primitive type int.


Class Short for primitive type short.

18

COALESCE
The following table shows the primitive types & the wrapper classes present in the java.lang
package.
Many Java Classes prefer to work with objects rather that the primitive data types. Thus the
Wrapper classes come as help. They provide object versions of the data type. They also
provide methods to convert strings to various data types.
4.6.Primitive Data Type

Wrapper Class

Data type

Wrapper Class

Data type

boolean

Boolean

char

Character

Short

Short

Long

Long

Int

Integer

Float

Float

Double

Double

byte

Wrapper Class

Byte

Wrapper class is constructed by passing the value to be wrapped into the appropriate
constructor.
int pint=500;

Integer wint=new Integer(pint); int p2=wint.intValue();

4.7.Variables
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. The variables have a scope,
which defines their visibility and lifetime. The variable name is a name given to the memory
location in a computer and not for the value present in it.
In Java all variables must be declared before they can be used.
Type identifier [=value], identifier [=value];
int i,j,k; int a=2,b=4,c=6;

float pi=3.14f; double do=20.22d; char a=v

Java allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
RightAngledTriangle.java
// DYNAMIC INITIALIZATION
class RightAngledTriangle
{

public static void main(String args[])


{

double a=6.0, b=7.0;


double c=Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse of the right angled triangle is "+c);

}
}

4.8.Member & Automatic variables


Java supports variables of two different lifetimes:
19

COALESCE
A member variable of a class is created when the instance is created, and is accessible
from any method in the class.
An automatic variable also called the local variable of a method is created on entry to
the method, exists only during execution of the method. Every automatic variable must
be explicitly initialized before being used.

4.9.Object Reference Variables


Java programs do not directly deal with objects. When an object is constructed, the
constructor returns a value a bit pattern that uniquely identifies the object. This value is
known as a reference to the object.
Button ok;
ok=new Button(Ok);

In the above example the Button constructor returns a reference to the just-constructed
button not the actual button object or a copy of the button object. This reference is
stored in the variable ok.

4.10. Type Conversion and Casting


A variable of one type can receive the value of another type. There are situations in which
the system implicitly changes the type of an expression without your explicitly performing a
cast. You can explicitly change the type of a value by casting. Casting means assigning a
value of one type to a variable of another type. Automatic, non-explicit type changing is
known as Conversion.
If the two types are compatible, then java will perform the conversion automatically else, the
cast operator has to be explicitly used to convert the data between incompatible types.
Ex: An int value can be assigned to a long variable but there is no conversion defined from
float to byte.
CastingExample.java
// TYPE CASTING
class CastingExample
{

public static void main(String args[])


{

byte x;
int a=270;
double b =128.128;
System.out.println("\n int converted to byte");
x=(byte) a;
System.out.println("a and x "+ a +" "+x);
System.out.println("\n double converted to int");
a=(int) b;
System.out.println("b and a "+ b +" "+a);

20

COALESCE
System.out.println("\n double converted to byte");
x=(byte) b;
System.out.println("b and x "+b +" "+x);
}
}

4.11.

Widening conversions permitted in Java


From a byte to a short, an int, a long, a float, or a double

From a short to an int, a long, a float, or a double

From an int to a long, a float, or a double

From a long to a float, or a double

From a float to a double


Char
Int

Byte

long

float

double

Short

4.12. Narrowing Conversions allowed


From a byte to a char

From a short to a byte or a char

From a char to a byte or a short

From an int to a byte, a short, or a char

From a long to a byte, a short, a char, or an int

From a float to a byte, a short, a char, an int, or a long

From a double to a byte, a short, a char an int, a long, or a float

4.13. Operators and Assignments


Java provides a fully featured set of operators. All operators are evaluated left to right. For
assignments associativity is right-to-left.
OPERATOR

RESULT

Addition

Subtraction

*
/

Multiplication
Division
21

COALESCE
%

Modulus

++

Increment (Unary)

+=

Addition assignment

-=

Subtraction assignment

*=

Multiplication assignment

/=

Division assignment

%=

Modulus assignment

--

Decrement

4.14. The Bitwise operators


The Bit wise operators defined in java can be applied to the integer types, long, int, short, char
and byte.
OPERATOR

RESULT

Bit wise Unary NOT

&

Bit wise AND

Bit wise OR

Bit wise exclusive OR

>>

Shift right (Performs a signed shift)

>>>

Shift right zero fill (Performs a unsigned shift)

<<

Shift left

&=

Bit wise AND assignment

|=

Bit wise OR assignment

^=

Bit wise exclusive OR assignment

>>=

Shift right assignment

>>>=

Shift right zero fill assignment

<<=

Shift left assignment

The bitwise AND works on bit values and returns 1 only if both the operands are one, else it
returns 0.
4.15. Relational Operators
OPERATOR
RESULT
==

Equal to

!=

Not Equal to
22

COALESCE
>

Greater than

<

Lesser than

>=

Greater than or equal to

<=

Less than or equal to

The outcome of relational operators is a boolean value. The relational operators are most
frequently used in the expressions that control the, if statement and the various loop
statements.
4.16. Boolean Logical operators
They operate only on boolean operands. They combine two boolean values to form a
resultant boolean value.
OPEARTOR

RESULT

&

Logical AND

Logical OR

Logical XOR (exclusive OR)

||

Short-circuit OR

&&

Short-circuit AND

Logical unary NOT

&=

AND assignment

|=

OR assignment

^=

XOR assignment

==

Equal to

!=

Not equal to

?:

Ternary if-then-else

The logical AND checks the condition of the first operand and also the second operand. But
the short-circuit AND checks the second operand only if the first operand returns true, else
it returns false.
4.17. The ternary operator
Java includes a special ternary (three way) operator that can replace certain types of if-thenelse statements.
expression1?expression2:expression3;

Expression1 can be any expression that evaluates a boolean value. If expression1 is true, then
expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is
that of the expression evaluated. Both expression2 and expression3 are required to return the
same type, which can be void.
23

COALESCE
4.18. Classes in Java
The class defines a new data type and this data type is used to create objects of that type.
class is an template for an object.

Following is the general from of the class:


class MyClass
{

variable1;
variable2;

Method1()
{

// Body of Method1.

}
Method2(parameters)
{

//Body of Method2.

}
}

4.19. Methods in Java


A method contains code to operate on the data present in a class. A method does not
operate on the data; rather, the data operates on itself.
<modifiers><return type>< name>([parameter list])[throws exception]
{
body of the method;
}

Constructors
They are used to initialize the data members of a class, immediately after an object is created.
It has the same name as the class, in which it resides and is syntactically similar to a method.
Once defined, the constructor is automatically called immediately after the object is created.
Constructors do not have a return type. This is because the implicit return type of a class
constructor is the class type itself.
The reason why the parentheses are needed after the
class name while initializing an object is, to call the constructor for the class being defined.
class Cube
{

int length;
int volume;
//Default constructor which takes no parameters.
public Cube() {
}//Overloaded parameterized constructor.
public Cube(int x){
length = x;

24

COALESCE
}

public int calVolume(){


volume = length*length*length;
return volume;

public static void main(String args[])

int volumeReturn;
// creating the object of the class Cube using the new operator with the constructor.
Cube c=new Cube(3);
volumeReturn=c.calVolume();

}
}

The class Cube is used for calculating the volume of a cube. The constructor receives the
length of the cube as a parameter and initializes the instance variable length with the supplied
value. The method calVolume calculates the Volume of the cube.
Using the keyword new in the constructor causes the following:

First the space for the new object is allocated and initialized to the zero form or
null.

Second, any explicit initialization is performed.

Third, a constructor, which is a special method, is executed. Arguments passed in


the parentheses to the new are passed to the constructor.

The final stage of a new object is to call a method called a constructor.

It is also possible to pass parameters to the constructors and they are known as parameterized
constructors.

4.20. this keyword


It is used in any method to refer to the current object or class instance. That is, this is always a
reference to the object on which the method was invoked.
fruit(mango m, apple a, grape g)
{

this.green=m;
this.red=a;
this.black=g;

4.21. Overloading
Reusing the same method name with different types and/or number of arguments and
perhaps a different return type is known as overloading.

25

COALESCE
Using the same method name with identical arguments and return type is known as
overriding. Method overriding forms the basis for one of Javas most powerful concept,
dynamic method dispatch. Dynamic method Dispatch is the mechanism by which, a call to an
overridden function is resolved at run time rather than compile time. Dynamic method
dispatch is important because this is how java implements run-time polymorphism.
A superclass reference variable can refer to a subclass object. Java uses this fact to resolve
calls to overridden methods at run time. Here is how. When an overridden method is called
through a superclass reference, java determines which version of that method to execute
based upon the type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time. When different types of objects are referred to, different
version of an overridden method will be called. In other words, it is the type of the object
being referred to (not the type of there reference variable) that determines which version of
an overridden method will be executed. Therefore, if a super class contains a method that is
overridden by a subclass, then when different types of objects are referred to through a
super class reference variable, different versions of the method are executed.
is used while creating several methods that perform closely related functions
under different conditions within a class. The compiler will treat each of these methods as
different method.
A method name can be reused anywhere, if it follows the following:
Overloading

In an unrelated class, no special conditions apply and the two methods are not
considered related in any way.
In the class that defines the original method, or a subclass of that class, the method
name can be reused if the argument list differs in terms of the type of at least one
argument.

OverLoadingExample.java
class OverLoading{
void plan() {
System.out.println(Default Constructor);
}
//overloading the method plan with a parameter of type int.
void plan(int x) {
System.out.println(The value of x is :+x);
}
}
class OverLoadingExample
{
public static void main(String args[])
{
OverLoading ol= new OverLoading();
//calling all the forms of the method plan.
ol.plan();
ol.plan(5);
}
}

In the above program plan() is overloaded twice. The first time is without a parameter,
which prints Default Constructor and the second is with a parameter of type int. Whenever a
method, which is overloaded is called, a match between the arguments used to call the
method and the methods parameters is searched by Java.
26

COALESCE
4.22. Overriding
In a strict subclass of the class that defines the original method, the method name can be
reused with identical argument types and order and with identical return type. This is
overriding.

In this case, additional restrictions apply to the accessibility of, and exceptions that may be
thrown by, the method.
When an overloaded method is called, java looks for a match between the arguments used to
call the method and the methods parameters. However, this match need not always be
exact. In some cases Javas automatic type conversion can play role in overload resolution.
Java will employ its automatic type conversions only if no exact match is found.
The key differences between overloading and overriding are
OverLoading
It is the relationship between the methods
available in the same class.
It does not block inheritance from the
superclass.
In overloading separate methods share the
same name.
It follows different method signatures.
It may have different return types.
It may have different declared exceptions.

OverRiding
It is the relationship between a superclass
method and a subclass method.
It blocks inheritance from the superclass.
In overriding subclass method replaces the
superclass method.
It follows same method signature.
It must have matching return types.
It must have compatible declared exceptions.

OverridingExample.java
abstract class Base
{ abstract public void call();
} class Derived extends Base
{ public void call()
{ System.out.println(Hello Everybody);
}
}class OverridingExample
{public static void main(String args[])
{

Base b;
Derived d= new Derived();
b=d;
b.call();

}
}

4.23. Passing arguments using Call by value & using Call by reference
An argument to a sub routine can be passed in two ways.
27

COALESCE
1.
2.

call by value.
call by reference.

In call by value, the method receives a copy of the original data and therefore, changes in
the method have no effect on the original value.
In call by reference, a reference of a variable is passed as a parameter to the method. Since a
reference is passed to the method changes to it are affected at all places where the variable
(object) will be used.
4.24. Access control-using Modifiers
Modifiers are

Java keywords that give the compiler information about the nature & scope of
code, data or classes. Modifiers specify, that a particular class or variable or a method is
static, or final, or transient. With these access modifiers encapsulation is worked out
according to the need of the program.
A member access level is determined by the access specifier, that modifies its declaration.
Javas access specifiers are public, private and protected. Java also defines a default access
level.
It is the most generous access modifier. A public class, variable, or method may be
used in any java program without restriction.
public:

The least generous access modifier is private. Top level classes may not be declared
private.
private:

A protected access specifier defines that only the members of the class and its sub
class in which it is defined can access that feature.
protected:

When no access specifier is used, then by default the member of a class is public within its
own package, but cannot be accessed outside the package.
4.25. Other Modifiers
The final modifier applies to classes, methods, and variables. The meaning of final
varies from context to context, but the essential idea is the same.
A final class may not be sub classed.
If applied to a variable it means to say that the value is constant.
A final object reference variable may not be changed but the data owned by the object
that is referred as final can be changed.
final:

A final method may not be overridden. This is done for security reasons and these methods
are used for optimization.

28

COALESCE
4.26. abstract:
The abstract modifier can be applied to classes and methods. A class that is abstract cannot
be instantiated. Abstract classes provide way to defer implementation to sub classes.
A class must be declared abstract if any of the following conditions is true:
The class has one or more abstract methods.
The class inherits one or more abstract methods (from an abstract parent) for which it
does not provide implementations.
The class declares that it implements an interface but does not provide implementations
for every method of that interface.
4.27. Static
The static modifier can be applied to class variables, methods, and even a code that is not a
part of method. It cannot be assigned to a top-level class definition but it can be assigned to
an inner class level definition.
A static class member can be accessed directly by the class name and doesnt need any
object. A single copy of a static member is maintained through out the program regardless
of, the number of objects created.
Static variables are initialized only once and at the start of the execution during the lifetime
of a class. These variables will be initialized first before the initialization of any instance
variables.
Methods declared as static (class methods) have several restrictions:
They can only call other static methods.
They must only access static data. Attempt to access non-static data causes a compiler
error.
Non-static methods can access static data and methods.
They cannot refer to this or super in anyway.
These methods can be accessed using the class name rather than a object reference.
main() is static because it must be accessible for an application to run, before any
instantiation takes place.
When main() begins, no objects are created, so if you have a member data, you must
create an object to access it.
StaticExample.java
// STATIC INITIALIZERS
class StaticExample
{
static int x =8;
static float y;
double z;
void display()
{
System.out.println("Infosys");
}
static void inf(int i)
{
System.out.println("i = "+i);
System.out.println("x = "+x);
System.out.println("y = "+y);
}
static

29

COALESCE
{

System.out.println("Initialising the Static Block");


y=x*2;

}
public static void main(String args[])
{
StaticExample se=new StaticExample();
inf(25);
se.display();
}
}

4.28. Native
The native modifier can refer only to methods. A method declared as native says that the
body of the method i.e, the code is outside the JVM in a library.
Native code is written in a non-java language, typically in C or C++, and compiled for a
single target machine type. It is mainly used for GUI components, network communication,
and a broad range other platform-specific functionality.
When a native method is invoked, the library that contains the native code ought to be
loaded and available to the java virtual machine; if it is not loaded, there will be a delay. The
library is loaded by calling System.loadLibrary(Library name);.
The following gives the code snippet:
Class NativeExample
{
// Native method declaration
native void doSomethingLocal(int i);
static
{
System.loadLibrary(Mynativelib);
}
}

Callers of native methods do not have to know that the method is native. The call is made
in exactly the same way as if it were non-native.
NativeExample natex;
Natex=new NativeExample();
Ne.doSomethingLoacal(5);

The synchronized modifier is used to control access to critical code in


multithreaded programs. We will look into it when we learn Multithreading
synchronized:

volatile variables are of interest in multiprocessor environments. Declaring a


variable volatile says that it might be modified asynchronously, so the compiler takes special
precautions.
Volatile:

30

COALESCE
MODIFIER

CLASS

public
protected
Friendly
private
no
final
abstract
static
native
transient
synchronized

yes
no
yes
yes
yes
yes
no
no
no

VARIABLE

yes

METHOD/CONSTRUCTOR

yes
yes
yes
yes
yes
yes
yes
no
yes
no

yes
yes
yes
yes
yes
yes
yes
no
yes

4.29. Nested and inner classes


A class written within another class is known as nested class. Inner classes are a useful
feature because they allow you to group classes that logically belong together and to control
the visibility of one within another. The scope of the nested class is bounded by the scope
of its enclosing class. A nested class has access to the members, including private members,
of the class in which it is nested. However, the enclosing class does not have access to the
members of the nested class. The access to the enclosing classs scope is possible because
the inner class actually has a hidden reference to the outer class context.
There are two types of nested classes static and non-static. If a inner class is static, it must
access the members of its enclosing class through an object. That is, it cannot refer to
members of its enclosing class directly.
The most important type of nested class is the non-static inner class. It has access to all of the
variables and methods of its outer class and may refer to them directly in the same way that
other non-static members of the outer class do. Thus an inner class is fully within the scope
of its enclosing class.
InnerClassExample.java
// DEMONSTRATING NESTED CLASSES
class InnerClass
{
int far_x=45;
void plan()
{
Inner inner=new Inner();
inner.display();
} class Inner
{ void display()
{
System.out.println("Displaying : far_x : "+far_x);
}
}
} class InnerClassExample
{
public static void main(String args[])
{
InnerClass ic=new InnerClass();
ic.plan();
}
}

31

COALESCE
4.30. Classes Defined Inside Methods
Java allows a class to be defined inside a method. Any variable, either a local variable or a
formal parameter, can be accessed by methods within an inner class, provided that variable is
marked final . An object created inside a method is likely to outlive the method invocation.
Since local variables and method arguments are conventionally destroyed with their method
exits, these variables would be invalid for access by inner class methods after the enclosing
method exits. By allowing access only to final variables, it becomes possible to copy the
values of those variables into the object itself, thereby extending their lifetime.
MOuter.java
// CLASSES DEFINED INSIDE METHODS
public class MOuter
{
private int i=10;
final int j=20;
public static void main(String args[])
{
MOuter that=new MOuter();
that.go((int)(Math.random()*100),(int)(Math.random() * 100));
}
public void go(int x, final int y)
{
int a=x+y;
final int b=x-y;
class MInner
{
public void method()
{
// System.out.println(("X : "+x); // Illegal
System.out.println("Y : "+y);
// System.out.println("a : "+a); // Illegal
System.out.println("b : "+b);
System.out.println("i : "+i);
//accessible
System.out.println("j : "+j);
// accessible
}
} MInner that=new MInner();
that.method();
}
}

4.31. Anonymous classes


Some classes that you define inside a method do not need a name. A class defined in this
way without a name is an anonymous class. In fact, they are defined in the place they are
constructed.
public void amethod()
{
theButton.addActionListener(new ActionLIstener()
{
public void actionPerformed(ActionEvent ae)
{ System.out.println(Action performed);
}
}
);
}

An anonymous class cannot have a constructor. Since you do not specify a name for the
class, you cannot use the name to specify a constructor.

32

COALESCE
4.32. Additional Features of Anonymous Inner Classes
An anonymous class can be a subclass of another explicit class, or it can implement a single
explicit interface. An anonymous class cannot be both an explicit subclass and implement
an interface.
4.33. Properties of Inner classes

The class name can be used only within the defined scope.
The inner class can also be defined inside a method generally known as anonymous class.
The inner class can use both static and instance variables of enclosing classes and final
local variables of enclosing blocks.
An inner class can act as an interface implemented by another inner class.
Inner classes that are declared static automatically become top-level classes.
Inner classes cannot declare any static members; only top-level classes can declare static
members.
Public, private, static are all legal access modifiers for this inner class.
Inner classes can extend any class or interface
They can access all static, final and instance variables.

4.34. Collection API


A collection is a single object representing a group of objects, known as its elements.
The java programming language supports collection classes Vector, Bits, Stack, Hashtable,
BitSet, LinkedList, and so on. For example, Stack implements a last-in-first-out (LIFO)
sequence and Hashtable provides an associative array of objects.
Collections maintain references to objects of type Object. This allows any object to be
stored in the collection. It also necessitates the use of correct casting before you can use the
object, after retrieving it from the collection.
The collection API typically consists of interfaces that maintain objects.
Collection: A group of objects with no specific ordering.
Set: A group of objects with no duplication.
List: A group of ordered objects; duplicates are permitted.
The API also contains classes, such as HashSet, and ArrayList, which implement these
interfaces. The API also provides methods supporting some algorithms, such as sorting,
binary searching, evaluating the minimum and maximum out of lists, and collections.
4.35. The Vector Class
The vector class provides methods for working with dynamic arrays of varied element types.
Java.lang.Object

Java.util.AbstractCollection
33

COALESCE
Java.util.AbstractList
Java.util.Vector
Public class Vector extends AbstractList

Implements List, Cloneable, Serializable

Each vector maintains a capacity and a capacityIncrement. As elements are added to a


vector, storage for the vector increases, in chunks to the size of the capacityIncrement
variable. The capacity of a vector is always at least as large the size of the vector (It is usually
larger).
Constructors:

Variables: The

public Vector()
public Vector(int initialCapacity)
public Vector(int initialCapacity, int capacityIncrement)

vector class contains the following instance variables.

The size of the increment. (If 0, the size of the buffer is


doubled every time it needs to grow).
Protected int elementCount The number of elements in the buffer.
Protected Object elementData[] The buffer where elements are stored.
Protected int capacityIncrement

Methods:

The following are some of the methods in the Vector class.

Returns the number of elements in the Vector. (This is not the same as the
Vector capacity)
public boolean contains(Object elem) Returns true if the specified object is a value of the
collection.
public int indexOf(Object elem) Searches for the specified object starting from the first
position, and returns an index to it (or 1 if the element is not found). It uses the objects
equals() method, so if this object does not override Objects equals() method, it compares
only object references, not object contents.
public synchronized Object elementAt(int index) Returns the element at the specified index. It
throws ArrayIndexOutOfBoundsException if index is invalid.
public synchronized void setElementAt(int index) Replaces the element at the specified index
with the specified object. It throws ArrayIndexOutOfBoundsException if index is invalid.
public synchronized void removeElementAt(int index) Deletes the element at the specified
index. It throws ArrayIndexOutOfBoundsException if index is invalid.
public synchronized void addElementAt(int index) Adds the specified object as the last
element of the vector.
public synchronized void insertElementAt(int index) Inserts the specified object as an element
at the specified index, shifting up all elements with equal or greater index. It throws
ArrayIndexOutOfBoundsException if index is invalid.
public int size()

MyVector.java
// DEMONSTRATING VECTORS
import java.util.*;
public class MyVector extends Vector

34

COALESCE
{

public MyVector()
{
// STORAGE CAPACITY AND CAPACITY INCREMENT
super(1,1);
}
public void addInt(int i)
{
// addElement requires object argument
addElement(new Integer(i));
}
public void addFloat(float f)
{
addElement(new Float(f));
}
public void addString(String s)
{
addElement(s);
}
public void addCharArray(char a[])
{
addElement(a);
}
public void printVector()
{
Object o;
// compare with capacity
int length=size();
System.out.println("Number of vector elements is : "+
length+" and they are ");
for(int i=0;i<length;i++)
{ o=elementAt(i);
if(o instanceof char[])
{
// AN ARRAY'S toString() method will not
// PRINT THE REQUIRED OUTPUT
System.out.println(String.copyValueOf((char[]) o));
} else
{
System.out.println(o.toString());
}
}
}
public static void main(String args[])
{
MyVector mv=new MyVector();
int digit=5;
float real=3.14f;
char letters[]={'i','n','f','y'};
String s=new String("Infosys City");
mv.addInt(digit);
mv.addFloat(real);
mv.addCharArray(letters);
mv.addString(s);
mv.printVector();
}

4.36. Review Quastions


1
2
3
4
5

What is a Package?
What do you understand by wrapper class
What is a Constructor?
Differentiate between overloading & overriding
What are the different modifiers available in Java

35

COALESCE
5. Reflection API
The reflection API is a safe secure API, which can be used for object introspection. We can
find out which class the object extends and what are the methods and variables etc. The API
can be used to:

Construct new class instances and new arrays.


Access and modify fields of objects and classes.
Invoke methods ob objects and classes.
Access and modify elements of arrays.

These operations are possible only if the security policy permits them. The Reflection API is
useful in situations where you need to retrieve and manipulate information at runtime.
The following are some of the core Reflection API, which defines classes and methods:
The class java.lang.Class provides methods that provide information about a class and its
fields, constructors and methods
The class java.lang.reflect.Field provides methods that set and get information about the
fields in the class.
The class java.lang.reflect.Method provides methods that access and call methods in the
class, and get their signatures.
The class java.lang.reflect.Array enables an introspection of an array object.
The class java.lang.reflect.Constructor provides reflection access to constructors.
The Java Security Manager controls access to the core Reflection API on class-by-class basis.
Standard Java programming language access control is enforced when:

A Field is used to get or set a field value.


A Method is used to invoke a method.
A Constructor is used to create and initialize a new instance of a class.

5.1. Object class


This is one special class, called Object, defined by java. All other classes are subclasses of
object. That is, object is a superclass of all other classes. This means that a reference variable
of type object can refer to an object of any other class. Also, since arrays are implemented as
classes, a variable of type object can also refer to any array.
Object defines the following methods:
METHOD

PURPOSE

Object clone()

Creates a new object that is the same as the object being


cloned.

Boolean equals(Object object)

Determines whether one object is equal to another.


36

COALESCE
Void finalize()

Called before an unused object is recycled.

Class getClass()

Obtains the class an object at run time.

Int hashCode()

Returns the hash code associated with the invoking object.

Void notify()

Resumes execution of a thread waiting on the invoking


object.

Void notifyAll()

Resumes execution of all threads waiting on the invoking


object.

String toString()

Returns a string that describes the object.

Void wait()

Waits on another thread for execution.

void wait(long milliseconds)


void wait(long milliseconds,
int nanoseconds)
The methods getClass(), notify(), notifyAll(), and wait() are declared as final.
The other methods can be overridden. equals() methods compares the contents of two
objects. The toString() method returns a string that contains a description of the object on
which it was called. Also, this method is automatically called when an object is output using
println(). Many classes override this method.
5.2. Abstract Classes
Any class containing one or many abstract methods should also be declared abstract. The
keyword abstract is used before the keyword class to declare a class as abstract. The abstract
class cannot have objects of its own, i.e, it cannot be directly instantiated using the new
operator. Abstract constructors and abstract static methods also cannot be declared in a
abstract class. Any subclass of an abstract class must either implement all the abstract
methods in the superclass, or it should be declared abstract.
abstract class One
{

abstract void mine();


void mineonly()
{
System.out.println("A Concrete method");
}

}
class Two extends One
{
void mine()
{
System.out.println("Implementation of mine by Two");
}
}
class AbstractExample
{
public static void main(String args[])
{
Two t = new Two();
t.mine();
t.mineonly();
}
}

37

COALESCE
6. Packages
A package is a collection of related classes. Packages are containers for classes that are used
to keep the class name space compartmentalized. Using interface, you can specify a set of
methods, which can be implemented by one or more classes. The interface, itself, does not
actually define any implementation.
The package declaration, if any, must be at the beginning of the source file. You must
precede it with white space and comments, but nothing else. Only one package declaration
is permitted and it governs the entire source file.
Packages and Interfaces are two of the basic components of a java program. A java program
can contain any of the following four parts.
A single package statement (optional)
Any number of import statements (optional)
A single public class declaration (required)
Any number of classes private to the package (optional)
The package statement defines a namespace in which classes are stored. It is nothing but a
directory, in which a class is defined. When the package name is omitted, it is put into the
default package, which has no name.
6.1. Package DefaultPackage;
Java uses file system directories to store packages. Any classes you declare to be part of
DefaultPackage must be stored in a directory called DefaultPackage. The case is significant,
and the directory name must match the package name exactly. More than one file can include the
same package statement. The package statement simply specifies to which package the
classes define belong.
6.2. Classpath
It is a environmental variable, which contains the path for the default-working directory(.).
The specific location that java compiler will consider, as the root of any package hierarchy is,
controlled by Classpath.
To define a class called MyPackage in a package called, Package the class MyPackage
is defined in a directory called pack. When this program is compiled, the MyPackage.class
created is stored under the pack directory but it cannot be run from the same directory path,
as it is no longer referred as MyPackage.
Enumerating its package hierarchy, separating the packages with dots must refer the class. It
is because; the classpath is at the top of the class hierarchy. So, the file has to be run by
changing the current directory up by one level (parent directory), or add the top of your
development class hierarchy to the class path environmental variable. Then it is possible to
use java.Package.MyPackage from any directory.
If the source code is in the directory called c:\Infosys, then the classpath setting
should be
38

COALESCE
...;c:\Infosys;c:\java\classes;.

An inherited file cannot be compiled from the same directory. When a Subclass creates an
object for a superclass present in some other program file then, the Subclass cannot be
compiled from the same directory as the compiler tries to access the class for which the
object is being created in its child directory.
PackageDemonstration.java
// PACKAGES DEMONSTRATION
package abc;
class Requirement
{
String name;
double balance;
Requirement(String x, double y)
{
name=x;
balance=y;
}
void show()
{
if(balance<0)
System.out.println("--->");
System.out.println(name+" : Rupees."+balance);
}
}
class PackageDemonstration
{
public static void main(String args[])
{
Requirement rq[]=new Requirement[3];
rq[0]=new Requirement("Patty",2000);
rq[1]=new Requirement("Sharon",1000);
rq[2]=new Requirement("Cheryl",1500);
for(int i=0;i<3;i++) rq[i].show();
}
}

After naming this file as PackageDemonstration.java and storing it in a directory called abc
we need to compile this file. Finally after checking that the PackageDemonstration.class file
is in the abc directory, we can execute the program from the command line by calling :
java abc.PackageDemonstration

6.3.Protection of Access
Packages add another dimension to access control. Encapsulation and containing the namespace
and scope of variables and methods are through the means of Classes and Packages. Packages
contain classes and other subordinate packages. The Classes contain data and code. The class is
Javas smallest unit of abstraction.
The three access specifiers are private, public, and protected, which provide a variety of ways
to produce the many levels of access required.
Private
Same class

Yes

No modifier
Yes

39

Protected
Yes

Public
Yes

COALESCE
Same package
Subclass

No

Yes

Yes

Yes

Same package
non subclass

No

Yes

Yes

Yes

Different
package
subclass

No

Yes

Yes

Yes

Different
Package
non-subclass

No

No

No

Yes

A class has only two possible access levels: default and public. When a class is
declared as public, it is accessible by any other code. If a class has default access, then it can
only be accessed by other code within its same package.

40

COALESCE
7. Importing of Packages
To use the functionality of a class A present in a package, by a class B present in some other
package, the class A has to be imported by class B.
There are no Java classes in the unnamed default package; all of the standard classes are
stored in some named package. Since classes within packages must be fully qualified with
their package name or names, it could become tedious to type in the long dot-separated
package path name for every class you want to use. In Java the import statement is utilized to
bring certain classes.
Ex:

import java.util.*;
import java.awt.event.* ;
import javax.servlet.* ;
import javax.swing.* ;

In the second example, AWT is the top-level package & the event is the sub-ordinate
package inside the AWT package. While importing the packages each sub-ordinate package
is separated from its base package by a dot operator.
7.1. Classes versus Abstract class versus Interface
CLASS
ABSTRACT CLASS
Specifies the full set of Specifies the full set of
methods for an object.
methods for an object.
Implements all of its Implements none, some or
methods.
all of its methods.
Can have instances.
Cannot have instances.
Can have subclasses
Useless without subclasses. It
must have subclasses.

INTERFACE
Specifies a subset of
methods for an object.
Implements none of its
methods.
Cannot have instances.
Cannot have subclasses,
must have classes that
implement it. It is useless
without them.

7.2.Interfaces
An interface is a set of predefined methods to be implemented by one or more classes in
future. An Interface will just give what the method should do, but it will not give the
implementation for it. This helps the programmer to write his own logic in his class, which
implements the particular interface. The methods in an interface will have no body and it
just mention the method signature.
Interfaces are very similar to classes syntactically. Interfaces do not have any instance
variables. Any variable declared in an interface is automatically taken as public, static and
final. To implement an interface, a class must implement the complete set of methods
declared by the interface.
It is through interfaces that Java achieves multiple inheritance. By providing the interface
keyword, Java allows to fully utilize the one interface, multiple methods aspect of
polymorphism. Interfaces are designed to support dynamic method resolution at run time.
41

COALESCE
The general form of declaring an interface is as follows:
access class classname[extends superclass] implements interface[interface]
{
// body
}

Implementing Interfaces
By including the implements clause in a class definition, we implement an interface.
public class classname2 [extends classname1]
[implements interface] {
}

The methods that implement an interface must be declared public. Also, the type signature of
the implementing method must match exactly the type signature specified in the definition
of the interface.
An interface is defined in the following way.
Math.java
public interface Math
{
public int Add(int a, int b);
}

Save the above defined interface as Math.java and compile the same.
TestInterface.java
//Class implementing the interface Math.
public class TestInterface implements Math
{
public int Add(int a, int b)
{
return(a+b);
}
public static void main(String args[])
{
int result;
TestInterface ob = new TestInterface();
result = ob.Add(20,22);
System.out.println("The sum of 20 & 22 is :" + result);
}
}

The above TestInterface class is implementing the interface Math by defining the method
Add() with parameters a and b of type int. The object defined for the class TestInterface ob
calls the Add() method which has the values 20 and 22 respectively which is stored in the
result which is also of the type int. The result is then called inside the println() to display the
answer.

42

COALESCE
8. Accessing implementations Through Interface
References
Interfaces can be used as a type of reference variable. The usual dynamic binding takes
effect. References can be cast to and from interface types. The instanceof operator is used
to determine if an objects class implements an interface.
Any instance of any class that implements the declared interface can be stored in a variable
which is an object reference. When a method is called through one of these references, the
correct version will be called based on the actual instance of the interface being referred to.
The method to be executed is looked up dynamically at run time, allowing classes to be
created later than the code, which calls methods on them.
Class TestInterface
{
public static void main(String args[])
{
Callback C = new Client();
C.callback(42);
}
}

In the above example, the variable C is declared to be of the interface type Callback, yet it
was assigned to an instance of Client class. Although C can be used to access the callback()
method, it cannot access any other members of the Client class. An interface reference
variable only has knowledge of the methods declared by its interface declaration.
8.1. Extending Interfaces
One interface can inherit another by use of the keyword extends. When a class implements
an interface that inherits another interface, it must provide implementations for all methods
defined within the interface inheritance chains. Any class that implements an interface must
implement all methods defined by that interface, including any that are inherited form other
interfaces.
interface one
{
void method1();
void method2();
}
interface two extends one
{
void method3();
}
class MyInterest implements two
{
public void method1()
{
System.out.println(This is Implementing method 1.);
}
public void method2()
{
System.out.println(This is Implementing method 2.);
}
public void method3()
{
System.out.println(This is Implementing method 3.);
}
}

43

COALESCE
class MyFavourite
{
public static void main(String args[])
{
MyInterest mi = new MyInterest();
mi.method1();
mi.method2();
mi.method3();
}
}

8.2.Review Questions
What is an object?
What is a class?
What is a method?
What is the difference between instance method and a class method?
What is the difference between an instance variable and a class variable?
What is inheritance?
What is an overloaded method?
What does it mean to override a method?
What is the super Key word used for?
10. What is an interface?
11. What is the instanceof keyword and what does it do?
12. What are packages, and what are they used for?
13. What does protected access mean?
14. Why do I have to put an f after a floating- point constant?
15. What is the difference between Integer and int in Java?
1.
2.
3.
4.
5.
6.
7.
8.
9.

44

COALESCE
9. Input/Output in Java
9.1. What Are Streams?
A stream is a path of communication between the source of some information and its
destination. The source and the destination can be a file, the computer's memory, or even
from the Internet. For example, an input stream allows you to read data from a source, and
an output stream allows you to write data to a destination.
The foundations of this stream framework in the Java class hierarchy are the two abstract
classes, InputStream and OutputStream. All the I/O classes are in the io package. Since the
Streams are abstract, the same I/O classes and methods can be applied to any type of I/O
devices.
Java works with two types of I/O streams:
1. Byte-Oriented streams
2. Character Oriented streams.
But at the low-level everything is byte oriented.
9.2.Byte-Oriented Streams
A general stream, which receives and sends information as bytes, is called a byte-oriented
stream. At the top of the hierarchy are the two abstract classes: InputStream and OutputStream
for input and output respectively. These classes define many important methods for
handling the streams. The read() and write() methods in the InputStream and OutputStream
are used for reading and writing to and from streams respectively. Both these methods are
abstract and are implemented by all the classes derived from these Inputstream and
OutputStream Classes
9.3.Character Oriented Streams
Streams, which receive and send information as characters are called character oriented
streams. The abstract classes Reader and Writer are the base classes for all the characteroriented streams. Two of the most important methods are, read() and write(), which read and
write characters of data, respectively. These methods are overridden by derived stream
classes.

45

COALESCE
Here is a list of classes in the io package.
Byte Stream Classes and Interfaces
Stream Class
BufferedInputStream

Meaning

Buffered input stream

BufferedOutputStream

Buffered output stream

ByteArrayInputStream

Input stream that reads from a byte a rray

ByteArrayOutputStream

Output stream that writes to a byte array

DataInputStream
FileInputStream

An output stream that contains methods for writing the Java


Standard data types.
Input stream that reads bytes from a file.

FileOutputStream

Output stream that writes bytes to a file

FilterInputStream

Implements InputStream

FilterOutputStream

Implements OutputStream

InputStream

Abstract class that describes stream input

OutputStream

Abstract class that describes stream output

PipedInputStream

Input pipe

PipedOutputStream

Output pipe

PrintStream

Output stream that contains print( ) and println( )

PushbackInputStream
RandomAccessFile
SequenceInputStream

Input stream that supports one-byte unget, which returns a


byte to the input stream
Supports random access file I/O
Input stream that is a combination of two or more input streams
that will be read sequentially, one after the other

46

COALESCE
9.4.Character Stream Classes and Interfaces
BufferedReader
BufferedWriter

Buffered input character stream


Buffered output character stream

CharArrayReader

Input stream that reads from a character array

CharArrayWriter

Output stream that writes to a character array

FileReader

Input stream that reads from a file

FileWriter

Output stream that writes to a file

FilterReader

Filtered reader

FilterWriter

Filtered writer

InputStreamReader

Input stream that translates bytes to characters

LineNumberReader

Input stream that counts lines

OutputStreamWriter

Output stream that translates characters to bytes

PipedReader

Input pipe

PipedWriter

Output pipe

PrintWriter

Output stream that contains print( ) and println( )

PushbackReader

Input stream that allows characters to be returned to the input


Stream

Reader

Abstract class that describes character stream input

StringReader

Input stream that reads from a string

StringWriter

Output stream that writes to a string

Writer

Abstract class that describes character stream output

We will be studying only the FileInputStream and FileOutputStream here. Rest will be
covered in the Advanced JAVA part.
47

COALESCE
9.5.Reading and Writing from and to a File

The File Class


The File class object represents an abstract representation of file and directory path-names.
It provides various methods to access the file and retrieve the information of the file.
The constructors to create an object of File class are:
File(String path);

File(String path, String name);


File(File dir,String name);

The first constructor takes the full path of the file to be accessed: (c:\mydir\filename).
The second creates an object from a separate path a given a filename
The third creates an object with a different path given by another File Object and the
filename.
The File Class provides various methods to retrieve information about the file like the
filename, The parent directory, the path of the file. It also provides methods which tell
whether the file is a file or a directory. The list(), list down all the files in the current
directory.

The FileInputStream class


To read from a file the FileInputStream object is used. It is derived from InputStream. It
overrides all the methods of inputstream.
Constructors:
FileInputStream(String name) throws FileNotFoundException

Requires the path of the file to be opened.

FileInputStream(File file) throws FileNotFoundException

Requires the File object, which refers to a file.


FileInputStreamExample

import java.io.*;
class FileExample
{
public static void main(String args[])
{
byte buffer[] = new byte[2056];
try
{
FileInputStream fis = new FileInputStream(fileexample.java);
int bytes = fis.read(buffer,0,2056);
try
{
String s = new String(buffer,0,bytes,by default);
System.out.println(s);
}catch(UnsupportedEncodingException ex)
{
System.out.println(The encoding\By Default\ not found: +ex);
}
} catch(Exception ex)

48

COALESCE
{ String e = ex.toString();
System.out.println(e);
}
}
}

The FileOutputStream class


To write to a file the FileOutputStream object is used. It is derived from the Outputstream. It
overrides all the methods of OutputStream.
Constructors:
FileOutputStream(String name) throws FileNotFoundException

Requires the path of the file to be opened.

FileOutputStream(File file) throws FileNotFoundException

Requires the File object, which refers to a file.


FileOutputStream Example.

import java.io.*;
class FileExample2
{
public static void main(String args[])
{
byte buffer[] = new byte[80];
try
{
System.out.println(\n Enter a line to save to the disk:);
int bytes = System.in.read(buffer);
FileOutputStream fos = new FileOutputStream(line.txt);
fos.write(buffer,0,bytes);
}
catch(Exception ex)
{
String e = ex.toString();
System.out.println(e);
}
}
}

Once the program is executed the file line.txt is saved in the directory from which you are
executing your java programs. If you execute the program twice the first file is overrided by
the second file since both the files will be saved as line.txt. If you want the values to be
appended in to the same file use the following piece of code:
FileOutputStream fos = new FileOutputStream(line.txt, true);

49

COALESCE
PrintWriter class
In the above program we had used the println() method, but any guess where do we get it
from..?
The System class derives the out object it uses to give the output from the class PrintWriter.
PrintWriter is one of the character-based classes. Using a character based class for console
output makes it easier to internationalize your program. It has the various versions of the
println() method.

9.6.Review Question
1. How do I read input from the user analogous to using standard input and output in c
and c++?

50

COALESCE
10. APPLETS
Unlike a Java application which executes from the command window, a Java Applet is a
program that is run using the Appletviewer, which is a test utility for applets included with the
J2SDK(Java2 Software Development Kit) or applets can be viewed in a World wide web
browser also. The appletviewer is a tool provided by the sun microsystems to view applets. It
is present in the bin directory after the JDK is installed in the programmers machine.
The Appletviewer or the browser executes an applet when a Hypertext Markup
Language(HTML) document containing the applet is opened in the Appletviewer or the
browser.

Web Server
FirstFile.ht

<html>
<body>
<applet code=FirstFile.class width=50
height=50>
Response

Web

Reque

The above diagram shows how exactly an Applet is executed in a browser. When a request is
made by the client to get the FirstFile.html , the web server handles the request, and a
response is sent back to the client. When the browser gets the html file the applet present in
the html file is executed. The FirstFile.class when interacts with the browser, executes thus
executing the applet inside the browser. Applet is always in the form of bytecode and not in an
executable format.

10.1.

The steps involved in running an Applet

Applets are small applications that are accessed on an Internet server, transported over the
Internet, automatically installed, and run as a part of a Web document. After an applet
arrives on the client, it has limited access to resources, so that it can produce an arbitrary
multimedia user interface and run complex computations without introducing the risk of
viruses or breaching data integrity.
SimpleApplet.java

51

COALESCE
// TO RUN A SIMPLE APPLET
/*
<applet code="SimpleApplet" width=150 height=100>
</applet>
*/
import java.applet.*;
import java.awt.*;
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to the programming with Applets",20,20);
}
}

Applet and AWT class hierarchy


Java.lang.Object
Java.awt.Component
Java.awt.Container
Java.awt.Window
Java.awt.Frame

java.awt.Panel
java.applet.Applet

Applets must also import java.awt. AWT stands for the Abstract Window Toolkit. The AWT
contains support for a window based graphical interface. Since all applets run in a window, it is
necessary to include support for that window. The console-based Java run-time interpreter does not
execute applets. Rather, a Web browser or an Appletviewer executes them.

52

COALESCE
10.2. AppletViewer
The Appletviewer is a Java application that enables the user to run applets without using a Web
browser. It resembles a minimum browser.
The Appletviewer takes, as a command-line argument, a URL to an HTML file containing an applet
reference. This applet reference is an HTML tag that specifies the code that the Appletviewer loads; for
ex:
<applet code=SimpleApplet.class width=150 height=100>
</applet>

The general format of this tag is the same as any other HTML, using the < and > symbols to
delimit the instructions. All the parts shown here are required. You must have both
<applet> and </applet>. The applets should be treated as being of fixed size and use the
size specified in the <applet> tag.
Appletviewer [-debug] URLs
EX:

javac SimpleApplet.java
Appletviewer SimpleApplet.java

Once an applet has been compiled, it is included in an HTML file using the APPLET tag.
The applet will be compiled by a Java enabled web browser when it encounters the APPLET
tag within the HTML file. To view and test an applet more conveniently, simply include a
comment at the head of your Java source code file that contains the APPLET tag.
/*
<applet code=SimpleApplet width=150 height=100>
</applet>
*/

This comment contains an APPLET tag that will run an applet called SimpleApplet in a window that is
200 pixels wide and 60 pixels high. Since the inclusion of an APPLET command makes testing applets
easier.
To execute an applet in applet viewer use the following command.
C:\appletviewer SimpleApplet.java

53

COALESCE
11. The HTML APPLET Tags
The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer. An applet viewer will execute each APPLET tag that it finds in a separate
window, while web browsers will allow many applets on a single page.
<applet
[archive=archiveList]
code=appletFile.class
width=pixels height=pixels
[codebase=codebaseURL]
[alt=alternateText]
[name=appletInstanceName]
[align=alignment]
[vspace=pixels] [hspace=pixels]
[<param name=appletAttribute1 value=value>]
[<param name=appletAttribute2 value=value>]
:
:
[alternate HTML Tags]
</applet>

This optional attribute describes one or more archives containing classes and
other resources that are preloaded. The classes are loaded using an instance of an
AppletClassLoader with the given codebase. The archives in the archive list are separated by
comma (,).
Note: The Archive (JAR) is a special file format, which enables you to bundle multiple files into a single
ARCHIVE:

archive file. Typically a JAR file will contain the class files and auxiliary resources associated with applets and
applications.

CODE is a required attribute that gives the name of the file containing your applets
compiled class file. This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in or the directory indicated by CODEBASE if set. This
can also be in the format package.appletFile.class.
CODE:

WIDTH and HEIGHT are required attributes that give the size (in
pixels) of the applet display area, not including any windows or Dialogs that the applet
displays.
WIDTH AND HEIGHT:

CODEBASE is an optional attribute that specifies the base URL of the applet
code, which is the directory that will be searched for the applets executable class file
(specified by the CODE tag). The HTML documents URL (Uniform Resource Locator)
directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does
not have to be on the host from which the HTML document was read.
CODEBASE:

The ALT tag is an optional attribute used to specify a short text message that should be
displayed if the browser understands the APPLET tag but cant currently run Java applets.
This is distinct from the alternate HTML you provide for browsers that dont support
applets.
ALT:

54

COALESCE
NAME is an optional attribute used to specify a name for the applet instance.
Applets must be named in order for other applets on the same page to find them by name
and communicate with them. To obtain an applet by name, use getApplet(), which is defined
by the AppletContext interface.
NAME:

ALIGN is an optional attribute that specifies the alignment of the applet. This
attributes is treated the same as the HTML IMG tag with these possible values: LEFT,
RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and
ABSBOTTOM.
ALIGN:

These attributes are optional. VSPACE(vertical space) specifies the


space, in pixels, above and below the applet. HSPACE(horizontal space) specifies the space,
in pixels, on each side of the applet. Theyre treated the same as the IMG tags VSPACE and
HSPACE attributes.
VSPACE AND HSPACE:

The PARAM tag allows you to specify applet specific


arguments in an HTML page. Applets access their attributes with the getParameter() method.
PARAM NAME AND VALUE:

11.1. Applet Architecture


An applet is a window-based program. As such, its architecture is different from the socalled normal, console-based programs.
First, applets are event driven. An applet waits until an event occurs. The AWT notifies the
applet about an event by calling an event handler that has been provided by the applet. Once
this happens, the applet must take appropriate action and then quickly return control to the
AWT. This is a crucial point. For the most part, the applet should not enter a mode of
operation in which it maintains control for a extended period. Instead, it must perform
specific actions in response to events and then return control to the AWT run-time system.
Second, the user initiates interaction with an applet. The user interacts with the applet, as he
or she wants, when he or she wants. These interactions are sent to the applet as events to
which the applet responds. For example, when the user clicks a mouse inside the applets
window, a mouse-clicked event is generated.
11.2. An Applet Skeleton
Applets override a set of methods that provides the basic mechanism by which the browser
or applet viewer interfaces to the applet and controls its execution. The init(), start(), stop(),
and destroy() are defined by the, Applet class. paint(), is defined by the AWT Component
class. Default implementations for all of these methods are provided. Applets do not need to
override those methods they do not use.
init()

start()

55
stop()

paint()

COALESCE

Diagram showing the Life-cycle of an Applet


11.3.

Applet Display

Applets are graphical in nature, although you can issue System.out.println() calls, you do not
normally do so. Instead, you create your display in a graphical environment.
You can draw on an applets panel by using the paint() method. The browser environment
calls the paint() method whenever the applet is to be refreshed.
The paint() methods takes an argument that is an instance of the java.awt.Graphics class. The
argument is always the graphics context of the panel that makes up the applet. This context
can be used to draw or write into the applet.
To display a string in an applet, use drawString(), which is a member of the Graphics class.
Typically, it is called from within earlier update() or paint().
void drawString(String message, int x, int y)

The drawstring() method takes the X and Y co-ordinates of the Applet as parameters to place
a string inside it. It depends on the programmer to calculate properly the X and Y coordinates to draw the strings.
11.4.

Applet Initialization and Termination

When an applet starts executing, the following methods are called as they are in this
sequence:

init()
start()
paint()

When an applet is terminated, the following sequence of method calls takes place:

stop()
destroy()

This method is the first method to be called. This is used to initialize variables. This
method is called only once during the life- time of the applet.
init()

56

COALESCE
This method is called after init(). It is also called to restart an applet after it has been
stopped. start() is called each time an applets content is displayed onscreen. So, if a user
leaves a web page and comes back, the applet starts executing at start().
start()

This method has one parameter of type Graphics. This parameter will contain the
graphics context, which describes the graphics environment in which the applet is running.
This context is used whenever output to the applet is required.
paint()

This method is called to stop the applet from running. This method is called when a
HTML page containing a applet is not in use any more by the user. Thus the stop method
ensures that, threads involved in enabling the applet to run do not execute anymore. Thus
saving CPU storage amount & time.
stop()

This method is called when the environment determines that your applet needs to
be removed completely from memory. The stop() method is always called before destroy().
destroy()

11.5.

The Applet Class

The Applet class defines the methods shown in the table below. Applet extends the AWT
class Panel. In turn, Panel extends Container , which extends Component. These classes provide
support for Javas window-based, graphical interface. Thus, Applet provides all of the
necessary support for window-based activities.
Method
void destroy()
AppletContext getAppletContext()
String getAppletInfo()
URL getCodeBase()
URL getDocumentBase()
Image getImage(URL url,
String imageName)
Locale getLocale()
String getParameter(String Parameter
Name)
String[][] getParameterinfo()

void init()
Boolean isActive()
void resize(Dimension dim)

Description
Method called by the browser before destroying
the applet.
Returns the context of the applet.
Returns a string that gives description of the applet.
Gets the URL associated with the applet.
Returns the URL of the HTML document which
invokes the applet
Returns an Image object that encapsulates the
Image found at the location specified by url
And having name specified by image name
Returns a Locale object that is used by various
Locale-sensitive classes and methods.
Gets the parameter associated.
Returns a String table that describes the
Parameters recognized by the applet.

Called to Initialize the applet.


Used to check whether the applet is started or not.
Resizes the applet according to the dimensions
57

COALESCE
void resize(int width, int height)
void showStatus(String str)
void start()
void stop()

11.6.

Specified by dim.
Resizes the applet according to the dimensions
Specified by width and height
Displays str in the status window of the browser
Or applet viewer.
Called by the browser when an applet should
Start (or resume) execution.
Called by the browser to suspend the execution
Of the applet.

paint(Graphics g)

Exposure handling occurs automatically and results in a call to the paint() method. A facility
of the Graphics class, called a clip rectangle, is used to optimize the paint() method so that
updates are not made over the entire area of the graphics unless necessary. Ra ther, these
updates are restricted to the region that has been damaged. Override the paint() method to
control what is painted on your applet.
11.7. repaint()
a call to the repaint() method notifies the system that you want to change the display.
update(Graphics g)
The repaint() method actually causes the AWT thread to call another method, update().
The update method usually clears the current display and calls paint(). This method is called
when the applet has requested that a portion of its window be redrawn.

11.8.

To set Background and Foreground colors

The background color for an applet is set using the setBackground() method, and to set the
foreground color, we use setForeground(). These methods are defined by Component and
they have the following general forms
void setBackground(Color newColor)
void serForeground(Color newColor)

The newColor specifies the color, which replaces the previous set color.
Ex: Color.red, Color.green

The default foreground color is black. The default background color is light gray.
ColorExample.java
// CHANGING BACKGROUND AND FOREGROUND COLORS
/*
<applet code="ColorExample" width=250 height=50>
</applet>
*/
import java.awt.*;
import java.applet.*;
public class ColorExample extends Applet

58

COALESCE
{

String msg;
// set background and foreground colors
public void init()
{ setBackground(Color.blue);
setForeground(Color.yellow);
msg="Inside init() --";
} public void start()
{ msg+="Inside start() --";
} public void paint(Graphics g)
{ msg+="Inside paint() --";
g.drawString(msg,20,15);
} public void stop()
{ System.out.println("Applet is Stopped");
repaint();
} public void destroy()
{ System.out.println("Applet is Destroyed");
} public void update(Graphics g)
{ setBackground(Color.gray);
setForeground(Color.black);
}
}

11.9. Requesting Repainting


The repaint() method is defined by the AWT. It causes the AWT run-time system to execute
a call to your applets update() method, which, in its default implementation, calls paint().
Thus, for another part of your applet to output to its window, simply store the output and
then call repaint(). The AWT will then execute a call to paint().
The repaint() method can be presented in the following ways:void repaint()

This style enables the entire window to be repainted.


The following style specifies a region to be replaced:
void repaint(int left, int top, int width, int height)

The dimensions left, top, width and height are specified in pixel measurements.
One solution to this problem is to use the following styles
void repaint(long maxDelay)
void repaint(long maxDelay, int x, int y, int width, int height)

maxDelay

called.

specifies the maximum number of milliseconds that can elapse before update() is

11.10. The Status Window


An applet can also output a message to the status window of the browser or applet viewer
on which it is running. To do so, we use showStatus().
StatusMessage.java
// USING THE STATUS WINDOW
/*
<applet code="StatusMessage" width=300 height=50>
</applet>
*/
import java.applet.*;

59

COALESCE
import java.awt.*;
public class StatusMessage extends Applet
{
public void init()
{
setBackground(Color.blue);
setForeground(Color.white);
}
public void paint(Graphics g)
{
g.drawString("You are inside the Applet Window",15,20);
showStatus("Applets status window");
}
}

11.11. Passing Parameters to Applets


The APPLET tag in HTML allows you to pass parameters to your applet. The <PARAM> tag in an
<APPLET> context can pass configuration information to the applet. The getParameter() method is
used to retrieve a parameter in the applet. If no parameter name is found in any <param> tag inside the
<applet></applet> pair, then the getParameter() returns null.
AppletBanner.java
// A PARAMETERIZED BANNER
/*
<applet code="AppletBanner" width=250 height=100>
<param name=message value="A Banner inside an Applet ">
</applet>
*/
import java.applet.*;
import java.awt.*;
public class AppletBanner extends Applet implements Runnable
{
String msg;
Thread t=null;
int state;
boolean stopflag;
public void init()
{
setBackground(Color.blue);
setForeground(Color.white);
}
public void start()
{
msg=getParameter("message");
if(msg==null)
msg="No Message";
msg=" "+msg;
t=new Thread(this);
stopflag=false;
t.start();
}
public void run()
{
char ch;
for( ; ; )
{
try
{
repaint();
Thread.sleep(175);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
if(stopflag)
break;
}catch(InterruptedException e)
{
}
}

60

COALESCE
} public void stop()
{ stopflag=true;
t=null;
} public void paint(Graphics g)
{ g.drawString(msg,25,50);
}
}

11.12. Difference between Applications and Applets


JAVA APPLICATION
It must be installed on a local Machine.

JAVA APPLET
It does not need a explicit installation on a
local machine.
It must be run explicitly in a Java-compatible It loads and runs itself automatically in a
virtual machine.
Java-enabled web browser.
It can run with or without a Graphical user It must run with a Graphical user interface.
interface.
It starts executing from its main().
It starts executing from its init().
After being started once, it manages its own It has its flow of execution determined partly
flow of execution.
by its browser.
It has no inherent security features apart It has significant security controls to prevent
from the Java language security features.
malicious or poorly written applets from
harming the users system.

61

COALESCE
11.13. Review Questions
1.
2.
3.
4.
5.
6.
7.
8.

What is an Applet?
How do Applets differ from Applications?
Can I put more than one Applet in a single web page?
Where can I put my applets class files, and how do I indicate their location using the
Applet tag?
How do I determine the width and height of my applet?
How can my applet tell when a user leaves or returns to the web page containing my
applet?
How can I arrange for different applets on a web page to communicate with each other?
Do I need any special server software or setup to deliver applets?

62

COALESCE
12. Fundamentals of Exception Handling
An exception is a run-time error. Exception Handler is a set of instructions that handles an
exception. Default handler, provided by the Java run time system handles a few exceptions.
Exceptions can occur when

You try to open a non-existing file.

Disturbed network connection.

Operands being manipulated are out of prescribed ranges

Class file missing which was supposed to be loaded.

A few objectives can be pursued when dealing with processing in a program.

Determine if modifying the existing code will eliminate the problem.

Inform the User.

Save the data whenever possible.

Offer the user a choice of subsequent action.

A Java exception is an object that describes an exceptional (that is, error) condition, that has
occurred in a piece of code. When an exceptional condition arises, an object representing
that exception is created and thrown in the method that caused the error. That method may
choose to handle the exception itself, or pass it on. Either way, at some point, the exception
is caught and processed. Exceptions can be generated by the Java run-time system, or they
can be manually generated by your code. Exceptions thrown by Java relate to fundamental
errors that violate the rules of the Java language or the constraints of the Java execution
environment. Manually generated exceptions are typically used to report some error
condition to the caller of a method.
Java exception handling is managed via try, catch, throw, throws, and finally. Program
statements that you want to monitor for exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown. Your code can catch these exceptions
that are automatically thrown by the Java run-time system. To manually throw an exception
we use the keyword throw. Any exception that is thrown out of a method must be specified
by a throws clause. Any code that absolutely must be executed before a method returns is
put in a finally block.

63

COALESCE
12.1.

Exception Types
Throwable
Error

Exception

VirtualMachineError

OutOfMemory
Error

AWTError

StackOverFlow
Error

IOException

RuntimeException

EOF
FileNot
Arithmetic
Exception Found Exception Exception

Null
Array Index out of
Pointer Exception bounds Exception.

There is an important subclass of Exception, called RuntimeException. Exceptions of this type


are automatically defined for the programs that you write and include things such as division
by zero and invalid array indexing. They define type violations and other faults that cannot
be trapped at compile time, such as NullPointerException.
The other branch is topped by Error, which defines exceptions that are not expected to be
caught under normal circumstances by your program. Exceptions of type Error are used by
the Java run-time system to indicate errors having to do with the run-time environment,
itself.
Uncaught Exceptions
Class Exception()
{
public static void main(String argv[])
{
int n=0;
int e=16/n;
}
}

A new exception object is thrown by the Java run-time system when it detects the attempt
to divide by zero. This exception is constructed by the Java run-time system itself. Thus the
execution of Exception() is stopped abruptly because if an exception is thrown, the Java runtime system requires it to be caught in order to run the program.
An exception generated by the system is given below:
Java.lang.ArithmeticException: / by Zero at Exception.main(Exception.java:4)
Exception
main
Exception.java
Java:4
ArithmeticException

:
:

:
The class name
:
The method name
The filename
:
Line number
It is a subclass of Exception, which describes the
type of the error happened.

64

COALESCE
12.2.

try and catch

To guard against and handle a run-time error, simply enclose the code that you suspect of an
exception being thrown, inside a try block. Immediately following the try block, include a
catch clause that specifies the exception type that is to be caught.
ExceptionExample.java
// EXCEPTION HANDLING
class ExceptionExample
{
public static void main(String argx[])
{
int n,i;
try
{
i=0;
n=12/i;
System.out.println("This line will not be printed");
} catch(ArithmeticException e)
{ System.out.println("Division by zero" + e);
} System.out.println("After catch statement");
}
}

Once an exception is thrown, program control is passed out of the try block into the catch
block. Once the catch statement has executed, program control continues with the next line
of the program following the try/catch signature.
A try and catch statement work in tandom or together. A try block is always followed by a
catch block, which handles or catches the exception. A catch block always monitors the
preceding try block. The catch block is not executed if no exception is thrown.
12.3. Multiple Exceptions
If there are multiple exception classes that might arise in the try block, then several catch
blocks are allowed to handle them separately, each handling different exception type. After
one catch statement executes, the others are bypassed, and execution continues after the
try/catch block.
MultipleCatchExample.java
// MULTIPLE CATCH STATEMENTS
// PASS ONE ARGUMENT IN COMMAND LINE TO
// EXECUTE THE SECOND CATCH
public class MultipleCatchExample
{
public static void main(String argx[])
{
try
{
int e=argx.length;
int f=20/e;
int g[]={1};
g[20]=81;
} catch(ArithmeticException ae)
{ System.out.println("Divided by zero"+ae);
} catch(ArrayIndexOutOfBoundsException oe)
{ System.out.println("Array index out of bound"+oe);
} System.out.println("After Try and Catch blocks");
}

65

COALESCE
}

The try statements can be nested. Each time a try statement does not have a catch handler
for a particular exception, the stack is unwound and the next try statements catch handlers
are inspected for a match. If no catch statement matches, then an error is generated.
NestedTryExample.java
// NESTING TRY STATEMENTS
// TRY PASSING 1 AND 2 COMMAND LINE ARGUMENTS
class NestedTryExample
{
public static void main(String argx[])
{
try
{
int a=argx.length;
int b=20/a;
System.out.println("a= "+a);
try
{
if(a==1)
{ a=a/(a-a);
}
if(a==2)
{
int c[]={1};
c[22]=99;
}
}catch(ArrayIndexOutOfBoundsException oe)
{ System.out.println("Array index out of bounds");
}
}catch(ArithmeticException ae)
{ System.out.println("Divide by 0");
}
}
}

12.4.

Throw
throw statement is used explicitly to throw an exception.
throw ThrowableInstance;

ThrowableInstance must be an object of type Throwable or a subclass of Throwable. There


are two ways of obtaining a Throwable object; using a parameter into a catch clause, or
creating one with the new operator.
There is an important reason why the throw statement and the construction of the exception
are normally combined. The exception builds information about the point at which it was
created, and that information is shown in the stack trace when the exception is reported. It
is convenient if the line reported as the origin of the exception is the same line as the throw
statement, so it is a good idea to combine the two parts, and throw new exception() becomes
the norm.
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.
ThrowExample.java
// THROWING AN EXCEPTION
class ThrowExample
{
static void demoex()

66

COALESCE
{

try
{ throw new NullPointerException("Null pointer Exception");
}catch(NullPointerException ne)
{
System.out.println("Caught inside the demoex"+ne);
throw ne;
}

}
public static void main(String argx[])
{
try
{ demoex();
}catch(NullPointerException ne)
{ System.out.println("Exception Recaught : "+ne);
}
}
}

12.5. Throws
A throws clause lists the types of exceptions that a method might throw. It is a general rule
that any method that might throw an exception must declare the fact. This is a form of
enforced documentation.
This is necessary for all exceptions, except those of type Error or RuntimeException, or any of
their subclasses. All other exceptions that a method can throw must be declared in the
throws clause. If they are not, a compile-time error will result .
ThrowsExample.java
// THROWS EXAMPLE
class ThrowsExample
{ static void throwingone() throws IllegalAccessException
{
System.out.println("Inside throwing one");
throw new IllegalAccessException("Exception");
}
public static void main(String argx[])
{
try
{ throwingone();
}catch(IllegalAccessException ie)
{ System.out.println("Caught : "+ie);
}
}
}

67

COALESCE
12.6. finally
It defines a block of code that always executes, regardless of whether an exception was
caught. When an exception is raised, finally executes the code present in it before the control
moves out of the method. A try can have both catch followed by finally.
The code in
the finally block will be executed whatever the circumstances well, nearly definitely. If an
exception arises with a matching catch block, then the finally block is executed after the catch
block. If no exception arises, the finally block is executed after the try block.
The circumstances that prevent execution of the code in a finally block are:
The death of a Thread
Using of the System.exit() method.
Turning off the CPU
Due to an exception arising in the finally block.
An exception in the finally block, exactly behaves like any other exception.
FinallyExample.java
// FINALLY EXAMPLE
class FinallyExample
{ static void active()
{ try
{
System.out.println("Inside active");
throw new RuntimeException("EX");
}finally
{
System.out.println("active finally");
}
}
static void activeb()
{
try
{ System.out.println("Inside activeB");
return;
}finally
{ System.out.println("activeB finally");
}
}
static void activec()
{
try
{ System.out.println("Inside activeC");
}finally
{ System.out.println("activec finally");
}
}
public static void main(String args[])
{
try
{ active();
}catch(Exception ex)
{ System.out.println("Exception caught");
} activeb();
activec();
}
}

12.7. Javas Built in Exceptions


Java defines several exception classes in the standard package java.lang.
Most of the exceptions are subclasses of the RuntimeException. Since java.lang is implicitly
imported into all java programs most exceptions derived from RuntimeException are
automatically available and they need not be included in any methods throws list. These are
68

COALESCE
known as unchecked exceptions because the compiler does not check to see if a method
handles or throws these exceptions. A few exceptions defined by java.lang must be included
in a methods throws list if that method can generate one of these exceptions and does not
handle itself. These are called checked exceptions.
12.8.

Javas Unchecked RuntimeException Subclasses:

EXCEPTION
ArithmeticException
ArrayIndexOutOfBoundsExcepti
on
ArrayStoreException
ClassCastException
IllegalArgumentsException
IndexOutOfBoundsException
NullPointerException
NumberFormatException
StringIndexOutOfBounds

12.9.

MEANING
Arithmetic errors.
Array index is out-of-bounds
Assignment to an array element of an
incompatible type
Invalid cast
Illegal argument used to invoke a method
Some type of index is out-of-bounds
Invalid use of a null reference
Invalid conversion of a string to a numeric
format
Attempt to index outside the bounds of a
string

Javas checked exceptions defined in java.lang

EXCEPTION
ClassNotFoundException
IllegalAccessException
NoSuchMethodException

MEANING
Class not found
Access to a class is denied
A requested method does not exist

12.10. User defined Exception Subclasses:


To create an exception subclass, define a subclass of Exception(which is a subclass of
Throwable). There is no need to implement anything and their existence in the type system
that allows it to be used as exceptions.
The Exception class does not define any methods of its own instead, it inherits the methods
provided by Throwable. Thus, all the exceptions, including the user created ones, have the
methods defined by Throwable available to them.

69

COALESCE
Methods defined by Throwable
Method
Throwable fillInStackTrace()
String getLocalizedMessage()
String getMessage()
Void printStackTrace()
Void printStackTrace(PrintStream
stream)
Void printStackTrace(PrintWriter
stream)
String toString()

Description
Returns a Throwable object that
contains a completed stack trace. This
object can be re-thrown
Returns a localized description of the
exception
Returns a description of the exception
Displays the stack trace
Sends the stack trace to the specified
stream
Sends the stack trace to the specified
stream
Returns a String object containing a
description of the exception. This
method is called by println() when
outputting a Throwable object

12.11. Review Questions


1. What is an Exception?
2. Why do methods have to declare exceptions, which could be thrown by them?
3. What is the difference between a run-time exception and a normal exception?

70

COALESCE
13. Event Handling
An Action performed at an Instance is called an Event. When an event occurs, the underlying
Operating System recognizes the event and notifies the respective application. Events are
generated by user interaction with the GUI, like a button pressed and they may also occur
without user interaction like, when a timer expires, a counter exceeds a value, when a
software or hardware failure occurs, or an operation is completed. In Java, all events are
supported by java.awt.event package.
13.1. Event Handling Mechanisms
Javas original outward rippling or hierarchical event model proved to have some
shortcomings. A new event delegation model was introduced in release 1.1 of the JDK.
Both models are supported in JDK 2, but eventually the old model will disappear.

13.2. Outward rippling model or Hierarchical Event Model


The major problem was that an event could only be handled by the component that
originated the event or by one of the containers that contained the originating component.
This restriction violated one of the fundamental principles of object-oriented programming:
The Functionality should reside in the most appropriate class.
Another drawback of the original model was that a large number of CPU cycles were wasted
on uninteresting events. An event in which a program had no interest would propagate all
the way through the containment hierarchy before eventually being discarded.
13.3. Delegation event model
The modern approach to handling events is based on the delegation event model, Its
concept is quite simple: a source generates an event and sends it to one or more Listeners. In
this scheme, the listener simply waits until it receives an event. Once received, the listener
processes the event and then returns. The advantage of this design is that the application
logic that processes events is cleanly separated from the user interface logic that generates
those events. A user interface element is able to delegate the processing of an event to a
separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an
event notification. This provides an important benefit: notifications are sent only to listeners
that want to receive them.
The Delegation event model is based on four concepts:
Event Classes
Event Listeners
Explicit event enabling
Adapters

71

COALESCE
13.4. Event Sources
An object that generates an event is called a Source. A source must register listeners in order
for the listeners to receive notification about a specific type of event. Each type of event has
its own registration method.
public void addTypeListener(TypeListener tl);
Type

is the name of the event el is the event listener.


Ex:

addMouseListener(this);

When an event occurs, all registered listeners are notified and receive a copy of the event
object. This is known as multicasting the event. In all cases, notifications are sent only to
listeners that register to receive them.
A source must also provide a method that allows a listener to un-register an interest in a
specific type of event. The methods that add or remove the listeners are provided by the
source that generates events.
public void removeTypeListener(TypeListener tl);
RemoveKeyListener();

13.5. EventListeners
An object that is notified when an event occurs is a Listener . It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about
specific types of events. Second, methods should be implemented to receive and process the
notifications
13.6. EventClasses
The classes that represent events are at the core of Javas event handling mechanism.
Most of the event classes reside in java.awt.event package.
java.util.EventObject. is the top most super class of all the new event classes.
EventObject(Object src)

13.7.

Methods

Object getSource()

returns the object that originated the event.

returns the ID of the event. An events ID is an int that specifies the exact nature
of the event.
Int getID()

72

COALESCE
13.8.

Hierarchy of Event Classes in java.awt.event


EventObject

Java.awt.AWTEvent
ActionEvent AdjustmentEvent
ContainerEvent

ComponentEvent

FocusEvent InputEvent
KeyEvent

ItemEvent

PaintEvent

TextEvent

WindowEvent

MouseEvent

All Classes belong to java.awt.event package unless otherwise noted

13.9.

Main Event Classes in java.awt.event

EVENT CLASS
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
InputEvent
ItemEvent
KeyEvent
MouseEvent
TextEvent
WindowEvent

DESCRIPTION
Generated when a button is pressed.
Generated when a scroll bar is used.
Generated when a component is
used.
Generated when a component is
added or removed from the
container.
Generated when a component gains
or loses keyboard focus
Abstract
superclass
for
all
component input event classes.
Generated when a check box or list
item is clicked or used.
Generated when input is received
from the keyboard.
Generated when the mouse is
dragged, clicked, or released
Generated when the value of a text
area or text field is changed.
Generated when a window is
activated,
closed,
deactivated,
deiconified, iconified, opened, or
quit.

LISTENER
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener

ItemListener
KeyListener
MouseListener
TextListener
WindowListener

The above listed events in the table, if expected in your program should implement the
corresponding listeners and respective methods in-order to handle the events.
73

COALESCE
13.10. The Classes, Methods and Interfaces used by AWT

The ActionEvent class


An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a
menu item is selected.
Constructors
ActionEvent(Object src, int type, String comd)
ActionEvent(Object src, int type, String comd, int modifiers)

src
type comd -

refers to the object that generated the event.


type of the event
command string

Methods
String getActionCommand()

object.
Int getModifiers()
Interface

returns the command name for the invoking ActionEvent

returns a value that indicates which modifier keys were pressed.

ActionListener interface

Void actionPerformed(ActionEvent acev)

It is invoked when an action event occurs.

The AdjustmentEvent Class


The scrollbar generates the Adjustment Event.
Integer constants

BLOCK_DECREMENT, BLOCK_INCREMENT: when user clicks inside the scroll bar


area to increase or decrease its value.
TRACK: Slider was dragged.
UNIT_INCREMENT, UNIT_DECREMENT: When the button at the end of the scroll
bar is clicked.
Constructor
AdjustmentEvent(Adjustable src, int id, int type, int data)

Id: ADJUSTMENT_VALUE_CHANGED

data: data

Methods
Adjustable getAdjustable() returns the object that generated the event.
int getAdjustmentType() returns the type of the adjustment event.
int getValue() returns the amount of adjustment made or was done.

74

COALESCE
Interface

AdjustmentListener interface

void adjustmentValueChanged(AdjustmentEvent adev)

It is invoked when an adjustment occurs.

The ComponentEvent Class


The ComponentEvent is generated when the size, position, or visibility of a component is
changed. It is a superclass of ContainerEvent, FocusEvent, KeyEvent, MouseEvent and
WindowEvent.

COMPONENT_HIDDEN, COMPONENT_MOVED,
COMPONENT_RESIZED, COMPONENT_SHOWN

Integer constants

Constructors

ComponentEvent(Component src, int type)

Methods
component getComponent()

returns the component that generated the event.

ComponentListener interface
These methods are invoked when a component is resized, moved, shown, or hidden.
Interface

void componentResized(ComponentEvent coev)


void componentMoved(ComponentEvent coev)
void componentShown(ComponentEvent coev)
void componentHidden(ComponentEvent coev)

The ContainerEvent Class


A ContainerEvent is generated when a component is added or removed from a container.
Integer constants

COMPONENT_ADDED, COMPONENT_REMOVED

Constructors
ContainerEvent(Component src, int type, Component cmp)

comp: returns the component that has been added or removed from the container.
Methods
Container getContainer() returns a reference to
Component getChild() returns a reference to

from the container.

the container that generated this event.


the component that was added or removed

ContainerListener interface
These methods are invoked when a component is added or removed from a container.
Interface

void componentAdded(ContainerEvent cnev)


void componentRemoved(ContainerEvent cnev)

The FocusEvent Class


75

COALESCE
The FocusEvent is generated when a component gains or loses focus.
Integer constants

FOCUS_GAINED, FOCUS_LOST.

Constructors
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean temporaryflag)

The argument is set to true if the focus event is temporary. Otherwise, it is set to false. (A
temporary focus event occurs as a result of another user interface operation. Ex: When the
focus is in a text field and the user moves the mouse to use the tool bar).
Methods
boolean isTemporary() It returns true if the focus change is temporary.

FocusListener interface
These methods are invoked when a component gains or loses the keyboard focus.
Interface

void focusGained(FocusEvent foev)


void focusLost(FocusEvent foev)

The InputEvent class


This is an abstract class and is a subclass of ComponentEvent and is the superclass for
component input events. Its subclasses are KeyEvent and MouseEvent.
Methods
These methods check the modifiers that were pressed at the time when the event was
generated.
boolean isAltDown(),
boolean isAltGraphDown(),
boolean isMetaDown(), booleanisShiftDown()

boolean isControlDown()

ItemListener interface
This method is invoked when the state of an item changes.
Interface

void itemStateChanged(ItemEvent itev)

The KeyEvent Class


A KeyEvent is generated when keyboard input occurs.
Constructors
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)

When
Modifier
Code

specifies which key was pressed


indicates which modifiers were pressed
indicates virtual key code (VK_A, VK_B)
76

COALESCE
Ch

returns the character equivalent of virtual key code.

Methods
:
returns the character that was entered from the keyboard.
:
returns the key code (ASCII value)
If no valid character is entered, getKeyChar() returns CHAR_UNDEFINED and
getKeyCode() returns VK_UNDEFINED.
getKeyChar()
getKeyCode()

Interface
KeyListener interface

These methods are executed when a key is pressed and released and when a character has
been entered respectively.
Sequence: When a key is pressed, key pressed, typed and released are executed in a
sequence.
void keyPressed(KeyEvent keev)
void keyReleased(KeyEvent keev)
void keyTyped(KeyEvent keev)

The MouseEvent Class


A MouseEvent is generated when the user interacts with the application using the Mouse.
Integer constants

MOUSE_PRESSED, MOUSE_CLICKED,MOUSE_DRAGGED, MOUSE_EXITED,


MOUSE_MOVED, MOUSE_RELEASED, MOUSE_ENTERED.
Constructors
MouseEvent(component src, int type, long when, int modifiers,
int X, int Y, int clicks, boolean triggerspopup)

X&Y
Clicks
Triggerspopup -

Co-ordinates of the mouse


The click count is passed in clicks
indicates if an event causes popup menu to appear on this platform.

Methods
int getX() & int getY()

occurred.
alternate method to obtain the co-ordinates of the mouse.

Point getPoint():
me.getPoint()

: returns the X & Y co-ordinates of the mouse when the event

atjava.awt.point[X=100,Y=100]

void translatePoint(int X, int Y): changes the location of the event.


Int getClickCount(): obtains the number of mouse clicks for the event to be generated.
boolean isPopupTrigger() : tests if this event causes a popup menu to appear on this platform.
Interfaces

77

COALESCE
MouseListener and MouseMotionListener interfaces. These methods are invoked with
respective mouse actions.
MouseListener interface
void mouseClicked(MouseEvent moev)
void mouseEntered(MouseEvent moev)
void mouseExited(MouseEvent moev)
void mousePressed(MouseEvent moev)
void mouseReleased(MouseEvent moev)

MouseMotionListener interfaces
void mouseDragged(MouseEvent muev)
void mouseMoved(MouseEvent muev)

The TextEvent Class

Text fields and text areas generate the TextEvent, when users or programs enter characters.
Integer constants

TEXT_VALUE_CHANGED
Constructors
TextEvent(Object src, int type)

The text event does not include the characters currently in the text component that
generated the event. Instead, the program should use other methods associated with the text
component to retrieve the information.
TextListener interface
This method is invoked when a change occurs in a text area or text field.
Interface

void textChanged(TextEvent teev)

13.11. The WindowEvent Class


The WindowEvent is triggered when an action is performed with respect to a window.
Integer constants
WINDOW_ACTIVATED,
WINDOW_CLOSED,
WINDOW_CLOSING,
WINDOW_DEACTIVATED, WINDOW_DEICONIFIED, WINDOW_ICONIFIED,
WINDOW_OPENED.
Constructor

WindowEvent(Window src, int type)

Methods
Window getWindow(): returns

the window object that generates the event.


78

COALESCE
Interface
WindowListener interface
These methods are invoked with respective window actions.
void windowActivated(WindowEvent wiev)
void windowClosed(WindowEvent wiev)
void windowClosing(WindowEvent wiev)
void windowDeactivated(WindowEvent wiev)
void windowDeiconified(WindowEvent wiev)
void windowIconified(WindowEvent wiev)
void windowOpened(WindowEvent wiev)

13.12. Using the delegation event model


In programming using Delegation Event model, Implementation of the appropriate interface
in the listener will help receive the type of event desired. Implement
13.13. Adapter Classes
Adapter classes are useful when you want to receive and process only some of the events
that are handled by a particular event listener. They are used to simplify the creation of
event handlers.
Listener Interfaces implemented by Adapter classes
Adapter Class
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter

Listener Interface
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
WindowListener

13.14. Inner Classes


A class defined within a class is called an Inner class. These inner classes can be used to
simplify the code when using event adapter classes.
In the following example, InnerClassExample is a top-level class that extends Applet.
MyMouseAdatper is defined within the scope of InnerClassExample. It has access to all of
the variables and methods within the scope of that class. There fore, the mousePressed()
method can call the showStatus() method directly. It no longer needs to do this via a stored
reference to the applet. Thus, it is no longer necessary to pass MyMouseAdatper() a
reference to the invoking object.
InnerClassExample
// DEMONSTRATING THE INNER CLASSES
import java.applet.*;

79

COALESCE
import java.awt.event.*;
/*
<applet code="InnerClassExample" width=150 height=200>
</applet>
*/
public class InnerClassExample extends Applet
{ public void init()
{
addMouseListener(new MyMouseAdapter());
}
//THIS IS INNER CLASS
class MyMouseAdapter extends MouseAdapter
{
public void mousePressed(MouseEvent moev)
{ showStatus("you are pressing the mouse");
}
}
}

13.15. Anonymous Inner Classes


A inner class, which is not assigned a name, is called an Anonymous Inner class. It can
facilitate the writing of event handlers. In the following example, there is one top-level class
AnonymousInnerClassExample. The init() method calls the addMouseListener() method.
Its argument is an expression that defines and instantiates an anonymous inner class. It has
access to all of the variables and methods within the scope of
AnonymousInnerClassExample class. Therefore, it can call showStatus() method.

ANONYMOUSINNERCLASS EXAMPLE
import java.applet.*;
import java.awt.event.*;
/*
<applet code="AnonymousInnerClassExample" width=300 height=150>
</applet>
*/
public class AnonymousInnerClassExample extends Applet
{

public void init()


{

addMouseListener(new MouseAdapter()
{

public void mousePressed(MouseEvent moev)


{

showStatus("You have Pressed the Mouse");

}
});
}

80

COALESCE
}

13.16. Review Questions


1.
2.
3.
4.
5.
6.

What is an action event?


How is my program notified when a menu item is selected?
When should I use an event adapter class?
Will the code written for the Hierarchical event model still run in the JDK 1.1?
How to handle action events in the JDK1.1?
Is there any event to signal when a window is resized?

81

COALESCE
14. AWT Controls
The main purpose of the AWT is to support applet windows; it can also be used to create
stand-alone windows that run in a GUI environment. Javas components are implemented
by the many subclasses of the java.awt.Component and java.awt.MenuComponent
superclasses. The frequently used AWT classes contained in the java.awt package are
CLASS
AWTEvent
BorderLayout
Button
Canvas
CardLayout
Checkbox
CheckboxGroup
CheckboxMenuItem
Choice
Color
Component
Container
FileDialog
FlowLayout
Font
FontMetrics
Frame
GridBagConstraints
GridBagLayout
Image
Insets
Label
List
Menu
MenuBar
MenuComponent
MenuItem
Panel
PopupMenu
Rectangle
Scrollbar
ScrollPane
TextArea
TextComponent
TextField
Window

DESCRIPTION
Encapsulates the AWT events
The border layout manager.
Creates a Button
A blank window
The card layout manager.
Creates a check box.
Creates a group of check box.
Creates an on/off menu item
Creates a pop-up list
Manages color in a portable, platform-independent fashion
An abstract superclass for AWT components
A subclass of Component that can hold other components
Creates a window from which a file can be selected
The flow layout manager.
Encapsulates a font type.
Encapsulates various information related to a font.
Creates a standard window that has a title bar, resize corners, and a
menu bar
Defines various constraints relating to the GridBagLayout class
The grid bag layout manager.
Encapsulates graphical images
Encapsulates the borders of a container
Creates a label
Creates a list from which the user can choose.
Creates a Pull Down Menu
Creates a Menu bar
An abstract class implemented by various menu classes.
Creates a menu item
The concrete subclass of container
Encapsulates a pop-up menu
Encapsulates a rectangle
Creates a scroll bar
A container that provides horizontal and vertical scroll bars
Creates a multilane edit control
A super class for TextArea and TextField
Creates a single line edit control
Creates a window with no frame, no menu bar, and no title

There are several methods that are implemented by all the visual and container components,
by inheriting from the java.awt.Component.
82

COALESCE
It returns the size of the component. The return type is Dimension, which has
public data members height and width each specified in pixels.
getSize()

This method determines the font that a component will use for rendering any text
that it needs to display.
setFont()

setEnabled()

component.

It takes a single argument of boolean type and is used to enable or disable a


//To disable a Button
yes.setEnabled(false);

The setSize() method takes two arguments; width and height in


pixels. The setBounds() method takes four arguments; x, y, width and height which are also
specified in pixels.These two methods are used extensively while we are working with layout
managers.
setSize() and setBounds()

This method is used to hide or display a component inside a container. This


method takes a BOOLEAN argument.
setVisible()

// To hide a button

maybe.setVisible(false);

14.1. Window Fundamentals


The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level. The two most common windows are those derived from Panel ,
which is used by applets, and those derived from a Frame, which creates a standard window.
Much of the functionality of these windows is derived from their parent classes.

83

COALESCE
14.2.

The class hierarchy for panel and frame


Component

Container

MenuContainer
Interface

Window

Panel

Frame

Applet

14.3. Component
Component is an abstract class that encapsulates all the attributes of a visual component. All
user interface elements that are displayed on the screen and that interact with the user are
subclasses of Component.
14.4. Container
The Container class is a subclass of Component. It has methods that allow other component
objects to be placed in it. Other Container objects can be stored inside a Container, which
makes it a multileveled containment system.
14.5. Panel
The Panel class is a subclass of Container. It doesnt add any new methods, it just implements,
the Container. It is a Screen component. It is a window that does not contain a title bar,
menu bar, or border. That is why, it is not seen when an applet is run inside a browser.
When an applet is run using applet viewer, it provides the title and border. Panel is the
superclass for Applet. Panel is Abstract.
To add components to a Panel, we use the add() method present in Panel, inherited by
Container.
14.6. Frame
It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. A
warning message is generated when a Frame object is created in an applet.

84

COALESCE
14.7. Handling Events in a Frame Window
Since Frame is a subclass of Component, it inherits all its properties. This means that you can
use and manage a frame window that you create just like you manage your applets main
window. Whenever an event occurs in a window, the event handlers defined by that window
will be called.
WindowMouseEvents.java
// HANDLING MOUSE EVENTS
/*
<applet code="WindowMouseEvents" width=150 height=150>
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
class WindowMouseEvents extends Frame
implements MouseListener,MouseMotionListener
{
String msg="";
int mouseX=15,mouseY=30;
int movX=0,movY=0;
SimpleFrame(String title)
{
super(title);
addMouseListener(this);
addMouseMotionListener(this);
MyWindowAdapter adapter=new MyWindowAdapter(this);
addWindowListener(adapter);
} public void mouseClicked(MouseEvent moev)
{
}
public void mouseEntered(MouseEvent evtObj)
{
mouseX=18;
mouseY=50;
msg="Mouse in the child window";
repaint();
}
public void mouseExited(MouseEvent me)
{
mouseX=18;
mouseY=50;
msg="mouse left child window";
repaint();
}
public void mousePressed(MouseEvent moev)
{
mouseX=moev.getX();
mouseY=moev.getY();
msg="Down";
repaint();
} public void mouseReleased(MouseEvent moev)
{
mouseX=moev.getX();
mouseY=moev.getY();
msg="up";
repaint();
} public void mouseDragged(MouseEvent moev)
{
mouseX=moev.getX();
mouseY=moev.getY();
movX=moev.getX();
movY=moev.getY();
msg="*";
repaint();
} public void mouseMoved(MouseEvent moev)

85

COALESCE
{
}
{

movX=moev.getX();
movY=moev.getY();
repaint(0,0,128,80);
public void paint(Graphics g)
g.drawString(msg,mouseX,mouseY);
g.drawString("Mouse is at "+movX+", "+movY,15,50);

}
}class MyWindowAdapter extends WindowAdapter
{
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame)
{
this.sampleFrame=sampleFrame;
} public void windowClosing(WindowEvent wiev)
{
sampleFrame.setVisible(false);
}
}public class WindowMouseEvents extends Applet
implements MouseListener, MouseMotionListener
{
SampleFrame f;
String msg="";
int mouseX=0,mouseY=10;
int movX=0,movY=0;
public void init()
{
f=new SampleFrame("Handling Mouse Events");
f.setSize(150,150);
f.setVisible(true);
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.pink );
}
public void start()
{ f.setVisible(true);
}
public void stop()
{ f.setVisible(false);
}

86

COALESCE
15. Adding & Removing Controls
To include a control into the window, the instance of the desired control should be created
first & then added to the window using the add() method.
Component add(Component compobj);

To remove a control from the window, we use remove() defined by the Container().
Void remove(Component compobj);

15.1. Labels
Labels are controls, containing a string, which the component displays. A label is an object
of type Label. They do not support any interaction with the user.
Label(); Label(String str);

Label(String str, int how);

The values of how are: left, right and center.by default it is left.
The text present in a label can be set and obtained using:
void setText(String str)

String getText()

The text is aligned using:


void setAlignment(int how)
To obtain the current alignment we use the method: int getAlignment()
AWTLabel.java
// DEMONSTRATE LABELS
/*
<applet code="AWTLabel" width=150 height=150>
</applet>
*/
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class AWTLabel extends Applet
{
public void init()
{
Label one=new Label(Infosys);
Label two=new Label("Infosys-BTM");
Label three=new Label("Towers",Label.RIGHT);
add(one);
add(two);
add(three);
}
public void paint(Graphics g)
{
g.drawString("Labels are Being Added",100,100);
}
}

15.2. Buttons
The most frequently used control is the button. A button is a component that contains a label
and it generates an event when it is pressed. Buttons are objects of type Button.
Each time a button is pressed, an action or event is generated. This is sent to a previously
registered Listener. Each listener implements the ActionListener interface. The interface
defines the actionPerformed() method, which is called when an event occurs.
87

COALESCE
AWTButton.java
// DEMONSTRATE BUTTONS
/*
<applet code="AWTButton" width=150 height=150>
</applet>
*/
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AWTButton extends Applet implements ActionListener
{
String msg="";
Button yes, no, maybe;
public void init()
{
yes=new Button(" INFOSYS ");
no=new Button("BTM");
maybe=new Button("TOWERS");
//To disable a Button
yes.setEnabled(true);
// To set background & foreground
// colors for an applet
setBackground(Color.blue);
setForeground(Color.white);
// To set background & foreground
// colors for a control
no.setBackground(Color.white);
no.setForeground(Color.black);
// To hide a button
maybe.setVisible(true);
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
}
public void actionPerformed(ActionEvent acev)
{
String str=acev.getActionCommand();
str=str.trim();
if(str.equals("INFOSYS"))
{ msg="You have Pressed Infosys";
}
else if(str.equals("BTM"))
{ msg="You have Pressed BTM";
}
else
{ msg="You have Pressed Towers";
}
repaint();
}
public void paint(Graphics g)
{ g.drawString(msg,25,100);
}
}

15.3. Check Box


The check box gives the user two states, Checked and unchecked. Check boxes can be used
individually or groups. When used in groups the user can check more than one check box.
88

COALESCE
CheckBox(),
CheckBox(String str), CheckBox(String str, boolean on)
CheckBox(String str, boolean on, CheckBoxGroup cbGroup)
CheckBox(String str, CheckBoxGroup cbGroup, boolean on)
boolean getState():

or not.

returns the current state of the check box, whether checked

void setState(boolean on):


sets the current state of the check box.
String getLabel():
returns the current label of the check box.
void setLabel(String str): sets the label to the check box.

Each time a check box is selected or deselected, an item event is generated. This is sent to
the listener that was registered previously, which implements the ItemListener interface and
which defines the itemStateChanged() method.
AWTCheckBox.java
// DEMONSTRATING CHECK BOXES
/*
<Applet code="AWTCheckBox" width=150 height=150>
</Applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AWTCheckBox extends Applet implements ItemListener
{
String msg=" ";
Checkbox keonics,thomson,samsung,toshiba;
public void init()
{
keonics=new Checkbox("Keonics",null,true);
thomson=new Checkbox("Thomson");
samsung=new Checkbox("Samsung");
toshiba=new Checkbox("Toshiba");
add(keonics);
add(thomson);
add(samsung);
add(toshiba);
keonics.addItemListener(this);
thomson.addItemListener(this);
samsung.addItemListener(this);
toshiba.addItemListener(this);
} public void itemStateChanged(ItemEvent itev)
{ repaint();
}
public void update()
{
setBackground(Color.blue);
setForeground(Color.white);
} public void paint(Graphics g)
{
msg="Current Status :";
g.drawString(msg,10,60);
msg="Keonics "+keonics.getState();
g.drawString(msg,10,80);
msg="Thomson "+thomson.getState();
g.drawString(msg,10,100);
msg="Samsung "+samsung.getState();
g.drawString(msg,10,120);
msg="Toshiba "+toshiba.getState();
g.drawString(msg,10,140);

89

COALESCE
}
}

15.4.

Choice Controls

A choice is a drop-down list from which the user may choose the item he wants to. A
choice is also known as Combo box. Choice only defines a default constructor, which creates
an empty list.
To add data to the list:
void addItem(String name)
or
void add(String name)
Items are added to the list in the order in which the user calls the add() or addItem() methods.
String getSelectedItem(): gets a string which has the name of the selected item.
Int getSelectedIndex(): gets the index value of the item selected.

gets the number of items in the list.

Int getItemCount():
void select(int index):

sets the currently selected item using the index value.

void select(String name): sets the currently selected item using the name.
String getItem(int index):

gets the name associated with the item for which the index
is specified.

Each time a choice is selected an ItemEvent is generated. This is sent to the registered
listener, which implements the ItemListener interface.
The interface has an
itemStateChanged() event, which has an ItemEvent object as an argument.
AWTChoice.java
// DEMONSTRATE CHOICE LISTS
/*
<applet code="AWTChoice" width=150 height=150>
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AWTChoice extends Applet implements ItemListener
{

Choice country, captain;


String msg=" ";
public void init()
{

country=new Choice();
captain =new Choice();
country.add("India");
country.add("Australia");
country.add("England");

90

COALESCE
country.add("South Africa");
captain.add("Ganguly");
captain.add("Steve");
captain.add("Hussain");
captain.add("Shaun");
captain.select("Ganguly");
add(country);
add(captain);
country.addItemListener(this);
captain.addItemListener(this);
} public void itemStateChanged(ItemEvent itev)
{

repaint();

} public void paint(Graphics g)


{

msg="Current Country : ";


msg+=country.getSelectedItem();
g.drawString(msg,5,100);
msg="Current Captain : ";
msg+=captain.getSelectedItem();
g.drawString(msg,10,150);

}
}

15.5. Lists
The List class provides the user multiple-selection list. A list object can be constructed to
display any number of choices in the visible window.
List(),

List(int numRows),

numRows

List(int numRows, boolean multipleSelect)

specifies the number of entries to be displayed in the List.

multipleSelect

specifies whether the user can make multiple selections from the list.

To add a selection to the list:


or

void add(String name),


index

void add(String name, int index)

specifies the position of the index where the data has to be added.

gets the string which has the name of the selected item, when only a
single selection is allowed by the list.
String getSelectedItem()
int getSelectedIndex()

gets the index value of the selected item.

String[] getSelectedItems()
int[] getSelectedIndexes()

list.

gets an array containing the names of all the selected items.


gets an array containing the indexes of all the selected items in the
91

COALESCE
int getItemCount()

gets the count of the items present in the list.

void select(int index)

using the index value sets the currently selected item.

String getItem(int index)


int getRows()

gets the item with the specified index.

gets the number of rows visible in the list.

each time an item is selected or deselected by a click , an ItemEvent object is generated. Its
getStateChange() method is used to determine whether a selection or deselection triggered
this event.
AWTList.java
// DEMONSTRATING LISTS
/*
<applet code="AWTList" width=150 height=150>
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AWTList extends Applet implements ActionListener
{

List country,captain;
String msg=" ";
public void init()
{

country=new List(4,false);
captain =new List(4,false);
country.add("India");
country.add("Australia");
country.add("England");
country.add("Pakistan");
captain.add("Sourav");
captain.add("Steve");
captain.add("Nasser");
captain.add("Moin");
captain.select(1);
add(country);
add(captain);
country.addActionListener(this);
captain.addActionListener(this);

}
{
}

public void actionPerformed(ActionEvent acev)


repaint();
public void paint(Graphics g)

92

COALESCE
{

int idx[];
msg="Current Country : ";
idx=country.getSelectedIndexes();
for(int i=0;i<=idx.length;i++)
{

msg+=country.getItem(idx[i])+" ";
g.drawString(msg,10,120);
msg="Current Captain : ";
msg+=captain.getSelectedItem();
g.drawString(msg,10,140);

}
}
}

15.6. ScrollPane
A scroll pane can contain a single component, which may be taller or wider than the scroll
pane itself. If the contained component is larger than the scroll pane, then the default
behavior of the scroll pane is to acquire horizontal and/or vertical scroll bars as needed.
ScrollPane()

ScrollPane(int scrollbarpolicy)

Scrollbarpolicy: ScrollPane.SCROLLBARS_AS_NEEDED
ScrollPane.SCROLLBARS_ALWAYS
ScrollPane.SCROLLBARS_NEVER

15.7. Scrollbar
Scrollbars are used to select continuous values between specified ranges. They may be
organised horizontally and vertically. The user can drag the slider box to a new position.
The scroll bar will then reflect these values.
Scrollbar()

Scrollbar(int style)

Scrollbar(int style, int initialvalue, int thumbsize, int min, int max)

The first form creates a vertical scroll bar but its style is specified as follows:
Height of the thumb in units is passed in
thumbsize and min & max values are passed by min & max.
Scrollbar.VERTICAL, Scrollbar.HORIZONTAL.
int getValue():

gets the current value of the Scrollbar.

void setValue(int newvalue):

sets the current value for the scroll bar.

int getMinimum() & int getMaximum():

gets the minimum & maximum values of the scroll

bar.
Unit Increment: This

occurs when the user clicks on the buttons present on the scrollbar.

Block Increment: This

occurs when the user clicks on the scroll area in the slider box.

The increment values for Unit Increment and Block Increment can be set using:
93

COALESCE
void setUnitIncrement(int newincr)
void setBlockIncrement(in newicr)

15.8.

TextField & TextArea

The TextField and TextArea classes implement, one and two-dimensional components for
text input, display and editing. Both classes extend from TextComponent superclass.

Inheritance of TextField & TextArea


Object

Component

Text Component

TextField

TextArea

The TextField class implements a single-line entry area. They allow the user to enter strings
and to edit the text using the arrow keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.
TextField()

TextField(int numChars)

94

COALESCE
TextField(String str)

TextField(String str, int numChars)

specifies the number of characters which the TextField is supposed to display.


The length of the text in the field is not specified.
numChars:

str: specifies the string, which is to be displayed in the TextField.


String getText(): gets
void setText(): sets

the string in the text field.

a string to the text field.

String getSelectedText():

gets selected part of the text in the field.

void select(int startindex, int endindex):

selects a part of the text in the text field.

boolean isEditable(): determines whether the text present in the text field is editable or not.
void setEditable(boolean canEdit):

used to set the edit property of the text field.

AWTTextField.java
//DEMONSTRATING TEXT FIELD
/*
<applet code="AWTTextField" width=200 height=150>
</applet>
*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AWTTextField extends Applet implements ActionListener
{

TextField name, pass;


public void init()
{

Label namep=new Label(" UserName: ",Label.RIGHT);


Label passp=new Label("Password : ",Label.RIGHT);
name=new TextField(15);
pass=new TextField(10);
pass.setEchoChar('*');
add(namep);
add(name);
add(passp);
add(pass);
name.addActionListener(this);
pass.addActionListener(this);
} public void actionPerformed(ActionEvent acev)

repaint();

} public void paint(Graphics g)


{

g.drawString("UserName : "+name.getText(),10,60);

95

COALESCE
g.drawString("Selected name : "+name.getSelectedText(),10,80);
g.drawString("Password : "+pass.getText(),10,100);
}
}

15.9. TextArea
It is used to accept multiple lines of text input and is also known as multi-line editor.
TextArea()

TextArea(int numLines, int numChars)

TextArea(String str)

TextArea(String str, int numLines, int numChars)

TextArea(String str)

TextArea(String str, int numLines, int numChars, int sBars)

String getText():
void setText():

gets the string present in the text field.

sets a string to the text field.

String getSelectedText():

gets the selected part of the text in the field.

void select(int startindex, int endindex):


boolean isEditable(): determines

whether the text present in the text field is editable or not.

void setEditable(boolean canEdit):


void append(String str):

selects a part of the text in the text field.

used to set the edit property of the text field.

appends the string specified to the end of the text.

void insert(String str, int index):

inserts the string at the specified index.

void replaceRange(String str, int startIndex, int endIndex):

startIndex to endIndex.

It replaces the characters from the

AWTTextArea.java
// DEMONSTRATING TEXT AREA
/*

<applet code="TextArea3" width=150 height=150>

</applet>

*/

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TextArea3 extends Applet
{

public void init()


{

String val="Aim at the moon and shoot"+


"if you miss the moon.\n"+
"you will land\n"+
"among the STARS\n";
TextArea text=new TextArea(val,15,20);
add(text);

96

COALESCE
}

15.10. Radio Buttons


Radio Buttons also called as option buttons, are very much the same like check boxes but the
major difference between the both is we can select multiple check boxes at the same time,
however even though the radio buttons work in a group only one button can be selected at a
time.
To associate radio buttons with each other we use a CheckboxGroup object. When we add
radio buttons to the group, the CheckboxGroup classs internal methods will automatically
make sure that only one button is checked at a time.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class RadioButton extends applet implements ItemListener
{

CheckboxGroup cbg1;
Checkbox checkbox1, checkbox2, checkbox3, checkbox4;
TextField tx1;
public void init()
{

cbg1= new CheckboxGroup();


checkbox1= new Checkbox(Rahul, false, cbg1);
add(checkbox1);
checkbox1.addItemListener(this);
checkbox2 = new CheckBox(Sachin,false, cbg1);
add(checkbox2);
checkbox2.addItemListener(this);
checkbox3= new Checkbox(Saurav, false, cbg1);
add(checkbox3);
checkbox3.addItemListener(this);
checkbox4= new Checkbox(Laxman, false,cbg1);
add(checkbox4);
checkbox4.addItemListener(this);
tx1= new TextField(25);
add(tx1);

}
public void itemStateChanged(ItemEvent e)
{

if(e.getItemSelectable()==checkbox1)
{

tx1.setText(Rahul is selected);

97

COALESCE
}
if(e.getItemSelectable()==checkbox2)
{

tx1.setText(Sachin is selected);

}
if(e.getItemSelectable()==checkbox3)
{

tx1.setText(Saurav is selected);

}
if(e.getItemSelectable()==checkbox4)
{

tx1.setText(Laxman is selected);

}
}
}

15.11. Review Questions


1. What are the Component and Container Classes?
2. Can I add the same component to more than one container?
3. Does AWT allow to control the mouse location from within an application?
4. What fonts are available to an AWT program?

98

COALESCE
16. Layout Managers
A program written in Java might be deployed on more than one platform. If the standard
user interface design techniques were to be used then the user interface might not be
portable. That is the user interface might look and behave differently on a Macintosh rather
than on a Unix or Windows system because standard user interfaces are highly dependent on
the native GUI system. To solve this problem, Java provides a system of portable layout
managers. These layout managers are used to specify rules and constraints for the layout of
the User Interface to make it portable.
Before we discuss Layout Managers in detail we need to have a sound knowledge of the
requirements and the steps involved in designing a good Graphical User Interface.

16.1. Identifying GUI requirements


A Graphical User Interface or GUI has two main requirements. A GUI should:

Be simple to design

Provide a lot of functionality

The professional approach to define a GUI is in four steps as given below:

Selection of the required components.

Sketching the GUI.

Choose the Layout Manager.

Using Layout Managers.

16.2. Selection of the Components


Some general principles should be followed when listing the required components. For
example, the user, to trigger an event, text boxes for input, checkboxes and radio buttons for
choices use buttons.
The programmer has to think in terms of what the end-user would expect to see on the
application. For example in a simple chat application, the user would like to have a text area
to see the messages comming in, a text box to send a message, a text area to list the other
members of the chat and a button to send the message.

99

COALESCE
16.3. Sketching the GUI
It is always advisable that, Once the components have been chosen, the GUI should be
drawn on paper to see how the final GUI would look. For example let us consider, the chat
application itself; the GUI would most probably look like the figure given below.

Text Area for


receiving
messages

Text Area for


listing other
members

TextBox for
sending the
messages

Send

Button

Sketch of the chat application GUI on paper

16.4. Using Layout Managers


AWT uses layout managers because the actual layout is a frequently performed task.
Therefore, according to the principles of object-oriented programming, the functionality of
the layout should be encapsulated into one or more classes to automate the task. To make
the job more simpler, Java provides a set of layout manager classes, which definitely
eliminate a lot of development effort.
The reason for having layout managers is because Java is platform independent. Java
components borrow their behaviour from the operating system of the underlying hardware
on which the Java Virtual Machine is running. Thus an AWT button looks like any other
Motif button, on a Motif platform or it looks like a typical Mac button on a Macintosh
platform.
16.5. Containers and Components
Java GUIs usually reside in applets or in frames. For simple applets, the components are
added to the applet and in simple applications, the components are added to a frame. While
developing complex GUIs, it is convenient to divide the applet or frame into smaller
regions. These smaller regions are commonly implemented using the class Panel.
A Panel is an object of the class java.awt.Panel. It is a container. Like applets and frames, a
panel can contain other components or containers. A panel is always invisible.
A panel is built in the following order:
100

COALESCE

Construction of the panel

Assigning a Layout manager to the panel.

Populating the panel

Adding the panel to its container

While discussing classes, hierarchy refers to the hierarchy of inheritance from superclass to
subclass. While discussing GUIs, hierarchy refers to the containment hierarchy of applets or
frames, which contain components or other containers such as a panel or frame.

Container

Panel

Window

Applet

Frame

ScrollPane

16.6. Common subclasses of java.awt.Container


The container keeps a reference to a particular instance of a layout manager and it invokes
the layout manager to position a component. The same delegation occurs while deciding on
the size of a component also.
16.7. Component Size and Position
The java.awt.Component class has instance variables called X, Y, width and height
specifying the x, y coordinates, the width and the height of the component respectively. The
setBounds() method of the Component class is called when we need to change the size and
position of a component. To set the position and size of the component we pass four
parameters values for the four instance variables X, Y, width and height.
The following example illustrates the setBounds() method
Button B2 = new Button();
B2.setBounds(50,60,70,80);

In the above example, a Button B2 is created and is placed at x, y coordinates 50, 60 and is
of width 70 pixels and height 80 pixels.
It is not advisable to call the method setBounds() on a component, because layout managers
always get the final word. There is every possibility even after we call the setBounds() method
for a button in flow layout, the button is still placed next to the component which was
placed last.
101

COALESCE
A layout manager automatically arranges controls within a window by using some type of
methodology. Layout managers and Containers work as a team and each Container object
has a layout manager associated with it.
The layout manager is set by using the setLayout() method. If no call to setLayout() is made,
then the default layout manager is used for that container. To set the layout manager any one
of the following methods can be used.
void setLayout(new LayoutManager())
void setLayout(layoutobj)

To set the layout to FlowLayout for a panel using the first method is as follows:
Panel panel1 = new Panel();
panel1.setLayout(new FlowLayout());

To set the layout to FlowLayout using the second method we execute the following code:
Panel panel2 = new Panel();
FlowLayout fl = new FlowLayout();
panel2.setLayout(fl);

A null value is passed as a parameter to setLayout() method in order to position and size the
components . To position and size the components manually, we use the setBounds()
method.
The following example illustrates, passing of a null value to the setLayout() method.
Panel panel2 = new Panel();
panel2.setLayout(null);

The layout manager is notified each time a component is added to it. Whenever the
container needs to be resized, the layout manager consults the minimumLayoutSize() and
preferredLayoutSize() methods of the class Container for setting the minimum layout size and
preferred layout size.
16.8. Layout Managers
The Layout Mangers present in the Java programming language are:

FlowLayout

BorderLayout

GridLayout

CardLayout

GridBagLayout

Null Layout

16.9. FlowLayout Manager


Panels a nd applets have this layout manager as their default layout manager. The FlowLayout
manager arranges components in horizontal rows (left to right, top to bottom). When no
more components fit on a line, the next one is placed on the next line. A small space of five
102

COALESCE
pixels default is left between each component, above, below, left and right. The FlowLayout
has the following constructors to help in the creation of the FlowLayout manager.
FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)

where:
how :

Specifies to the FlowLayout Manager whether to start placing the


components from, left, centre or right.

horz and vert:

Represents the horizontal and vertical space in pixels between the


components respectively.

The following example explains how to create a FlowLayout for a frame and adding buttons
to the frame.
Frame f = new Frame();
f.setLayout(new FlowLayout()); /* setLayout() has to be called as
it is not the default layout
for the frame */
Button b1 = new Button();
Button b2 = new Button();
Button b3 = new Button();
f.add(b1);
f.add(b2);
f.add(b3);

The FlowLayout manager does not constrain the size of the components in it, instead it allows
them to have their preferred size. The layout automatically changes when the user resizes the
area.

16.10. BorderLayout Manager


The BorderLayout manager arranges a container's components only in five areas namely
NORTH, SOUTH, EAST, WEST, and CENTER. When a window is stretched
vertically, the EAST, WEST and CENTER regions are stretched. When the window is
stretched horizontally, the NORTH, SOUTH, and CENTER regions are stretched. The
class BorderLayout has the following constructors to help in the creation of the BorderLayout
manager.
BorderLayout()
BorderLayout(int horz, int vert)

The following code explains how to create a BorderLayout manager for a panel using the
constructor without parameters.
Panel panel3 = new Panel();

103

COALESCE
panel3.setLayout(new BorderLayout());

This code creates a BorderLayout manager, which has the default space between the
components.
The following code explains how to create a BorderLayout manager for a panel with a
specified horizontal and vertical gap between components.
Panel panel3 = new Panel();
panel3.setLayout(new BorderLayout(5,6));

A BorderLayout manager is created with a gap of 5 pixels horizontal and 6 pixels vertical
space between the components.
The BorderLayout manager is the default manager for Frame and Dialog. The Border layout is
not affected by the order in which the components are added, because the user specifies the
location for the component as to where it should be placed. By specifying one of the
following constants we can place the components inside a BorderLayout manager:

BorderLayout.NORTH

BorderLayout.SOUTH

BorderLayout.WEST

BorderLayout.EAST

BorderLayout.CENTER.

To add a button to the centre of a frame we use the following syntax


Frame f = new Frame(); // declare a frame
Button b = new Button(); // create a button
f.add(b, BorderLayout.CENTER); // add button to center of frame

The BorderLayout is used to force components to fit into one or more edges of a container,
and to fill up the centre of the container with a component. It is also the layout used to
cause a single component to completely fill its container.
A region in BorderLayout can accommodate only one component. If more than one
component is added, then the first added will be invisible. To overcome this problem we add
components into a container and then add the container to the region.
The example below contains a Frame object f and five Button objects. The Button objects are
placed in the regions namely NORTH, SOUTH, EAST, WEST and CENTER. The
default Layout manager for a Frame is BorderLayout hence, the setLayout() method is not used.
The method go() in the Border class is defined to display the Frame. BLWin is a self
referential object of Border class and is used to invoke the go() method. The method
setSize() is used to set the horizontal and vertical dimensions of the Frame. The method
setVisible() is used to display the Frame .
/* BorderLayoutExample.java */
// DEMONSTRATING BORDER LAYOUT
import java.awt.*;
import java.awt.BorderLayout;

104

COALESCE
public class BorderLayoutExample
{ private Frame f; //declare the frame
private Button bno,bso,bwe,bea,bce; // declare the buttons
public void go()
{ f=new Frame("Border Layout"); // initialise the frame
bno=new Button("North"); // initialise the buttons
bso=new Button("South");
bwe=new Button("West");
bea=new Button("East");
bce=new Button("Center");
f.add(bno,BorderLayout.NORTH); // add buttons to 5 regions
f.add(bso,BorderLayout.SOUTH);
f.add(bwe,BorderLayout.WEST);
f.add(bea,BorderLayout.EAST);
f.add(bce,BorderLayout.CENTER);
f.setSize(200,200); // set initial view size
f.setVisible(true); // set visible to true to view frame
} public static void main(String args[])
{ BorderLayoutExample BLWin=new BorderLayoutExample();
BLWin.go();
}
}

We know that the default layout for frame is BorderLayout, so the method setLayout() is not
called . In case of applets, it can be explicitly specified as:
setLayout(new BorderLayout());
or
setLayout(new BorderLayout(int hpgap, int vgap));
hgap and vgap

specify the horizontal and vertical gap between the components

16.11. GridLayout Manager


The GridLayout lays out components in a two-dimensional grid. The number of rows and
columns are specified when a GridLayout is instantiated and the components will fill up the
cells as defined by the manager. The components are not allowed to be placed in their own
preferred size. The class GridLayout uses the following constructors in the creation of the
GridLayout manager.
GridLayout()
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)

where: horz and vert specify the horizontal and vertical space between the components.
105

COALESCE
The following code explains how to create a GridLayout manager for a panel using the
parameter-less constructor.
Panel panel4 = new Panel();
panel4.setLayout(new GridLayout());

GridLayout manager is created with the default spacing between components.


The following code explains how to create a GridLayout manager for a panel with the
number of rows and columns specified.
Panel panel4 = new Panel();
panel4.setLayout(new GridLayout(5,6));

The above code creates a GridLayout of 5 rows and 6 columns .


To create a GridLayout with specified number of rows and columns and specified horizontal
and vertical gap the following code could be used.
Panel panel4 = new Panel();
panel4.setLayout(new GridLayout(5,6,7,8));

The above code creates a GridLayout with 5 rows and 6 columns, a horizontal gap of 7
pixels and a vertical gap of 8 pixels between components in the GridLayout.
The relative positions of components do not change as the area is resized. Only the sizes of
the components change. The width of each cell is identical and is determined by dividing
the total available width by the number of columns. Similarly, the height of each cell is
determined by dividing the total available height by the number of rows.
The following points should be kept in mind before using a GridLayout manager for a
container.

The order in which the components are added to the grid determines the cell that they
occupy.

Lines of cells are filled from left to right.


All components in the layout are given equal size.
Either the row or the column can be zero but both cannot be zero.

The following program demonstrates how to add five buttons to a GridLayout of 3 rows and
2 columns.
/* GridLayoutExample.java */
import java.awt.*;
import java.awt.GridLayout;
public class GridLayoutExample
{ private Frame f;
private Button b1,b2,b3,b4,b5;
public void go()
{ f=new Frame("Grid Layout");

// initialise frame

106

COALESCE
f.setLayout(new GridLayout(3,2)); // constructor
b1=new Button("Button 1");

// initialise buttons

b2=new Button("Button 2");


b3=new Button("Button 3");
b4=new Button("Button 4");
b5=new Button("Button 5");
f.add(b1); // add buttons to frame
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.setSize(200,200); // set initial view size
f.setVisible(true); /* set visible to true to display frame */
} public static void main(String args[])
{ GridLayoutExample BLWin=new GridLayoutExample();
BLWin.go();
}
}

16.12. CardLayout Manager


The CardLayout places components (usually panels) on top of each other in a stack like a
deck of cards. We are able to see only one card at a time.
The CardLayout is a good layout to use when we need to have different panels containing
different components but in one single Frame.
The state of the controlling component determines which panel the CardLayout displays. For
example in a deck of cards such as a tabbed dialog box, the user makes the choice of the
panel to use by selecting a tab. Here the controlling component is the tab pane. Only the tab
that is selected is displayed and all other tabs are hidden. The class CardLayout has the
following constructors to help in the creation of the CardLayout manager.
CardLayout()
CardLayout(int horz, int vert)

The following code illustrates how to create a CardLayout manager for a panel using the
constructor without parameters.
Panel card_stack = new Panel();
card_stack.setLayout(new CardLayout());

This creates a CardLayout manager with zero cards.


The following code illustrates how to create a CardLayout manager for a panel with a
specified number of rows and columns.
Panel card_stack = new Panel();
card_stack.setLayout(new CardLayout(5,5));

107

COALESCE
The above code creates a CardLayout manager with 5 pixels horizontal and 6 pixels vertical
gap between components. This is like the deck for the cards.
After the deck is created, we create cards to add to the deck. The following example shows
how to add components to a card before adding the card to the deck.
Panel card1 = new Panel(); // initialise first card
card1.setLayout(new FlowLayout()); // set the Layout of the card.
card1.add(new Label("Card 1"));

/* add components to the card */


card1.add(new Button("One"));
card_stack.add("One",card1); //add first card to the card deck

The first card in the above example has the layout set to FlowLayout and has two
components, a Label and Button.
We can add any number of cards each having a different layout manager and its own
components. After the deck is created and the cards have been added to the deck, the
program activates a card by calling one of the following methods defined by CardLayout

void first(Container parent) // move to first card

void last(Container parent) // move to last card

void next(Container parent) // move to next card

void previous(Container parent) // move to previous card

void show(Container parent, String cardName)

The show() need not be explicitly called to display the card. By calling one of the first(), last(),
next(), prev() function the card is displayed. For each of the above functions we need to pass
the object of the container which holds all the cards, in this case we need to pass the
card_stack object to each of the functions.
The following program illustrates the use of the above functions.
/* CardLayoutExample */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code = "ExampleCar" width = 250 height = 250>
</applet> */
public class ExampleCar extends Applet implements ActionListener, MouseListener
{

Checkbox infosys, wipro, siemens, motorola;


Panel panel1;
CardLayout cl;
Button ecity, other;
public void init()

108

COALESCE
{

ecity = new Button("E-City");


other = new Button("Other");
add(ecity);
add(other);
cl = new CardLayout();
panel1 = new Panel();
panel1.setLayout(cl);
infosys = new Checkbox("Infosys",null,true);
wipro = new Checkbox("Wipro");
siemens = new Checkbox("Siemens");
motorola = new Checkbox("Motorola");
Panel p2 = new Panel();
p2.add(infosys);
p2.add(wipro);
Panel p3 = new Panel();
p3.add(siemens);
p3.add(motorola);
panel1. add(p2,"E-City");
panel1.add(p3,"Other");
add(panel1);
ecity.addActionListener(this);
other.addActionListener(this);
addMouseListener(this);

}
public void mousePressed(MouseEvent me)
{

cl.next(panel1);

}
public void mouseClicked(MouseEvent me)
{

public void mouseEntered(MouseEvent me)


{

public void mouseExited(MouseEvent me)


{

public void mouseReleased(MouseEvent me)


{

public void actionPerformed(ActionEvent ae)


{

if(ae.getSource() == ecity)
{

cl.show(panel1,"E-City");

109

COALESCE
}
else
{

cl.show(panel1,"Other");

}
}
}

16.13. GridBagLayout Manager


The GridBagLayout is an extremely flexible and powerful layout that provides more control
than the GridLayout in laying out components in a grid. GridBagLayout positions components
horizontally and vertically on a dynamic rectangular grid. The components do not have to be
the same size, and they can fill up more than one cell.
While GridBagLayout can accommodate a complex grid, it will behave more successfully (and
more predictably) if we organize components into smaller panels, nested inside the
GridBagLayout container. These nested panels can use other layouts, and can contain
additional panels of components if necessary. This is similar to setting the layout for each
card in the CardLayout manager.
This method has two advantages:

It gives the user more precise control over the placement and size of individual
components because he/she can use more appropriate layouts for specific areas, such as
button bars.

It uses fewer cells, simplifying the GridBagLayout and making it much easier to control.

Button bars are a series of buttons grouped together in a panel


GridBagLayout uses GridBagConstraints object to specify the layout information for each
component in a GridBagLayout container. There is a one-to-one relationship between each
component and GridBagConstraints object, we need to customise the GridBagConstraints object
for each of the container's components.
GridBagLayout components have the following constraints:
1.
2.
3.
4.
5.
6.
7.

anchor
fill
gridx, gridy
gridwidth, gridheight
insets
ipadx, ipady
weightx, weighty

GridBagConstraints lets the user control

The position of each component, absolute or relative.


The size of each component, absolute or relative.
The number of cells each component spans.
The mode of filling of an unused display area of a cell.
110

COALESCE

The amount of internal and external padding for each component.


How much weight is assigned to each component to control which components utilize
extra available space. This controls the component's behaviour when resizing the
container.

GridBagConstraints has a constructor that takes all eleven properties of GridBagConstraints. If


one of the values is not passed then the default value is considered. The constructor is given
below
GridBagConstraints();
GridBagConstraints(int gridx, int gridy,
int gridwidth, int gridheight,
double weightx, double weighty,
int anchor,int fill, Insets insets,
int ipadx, int ipady);

The following code example illustrates how to set the GridBagConstraints for a panel.
GridBagConstraints gbc = new GridBagConstraints(0, 3, 1, 1, 0.0,
0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
new Insets(11, 30, 0, 0), 0, 0)
Panel panel2 = new Panel();
panel2.setLayout(new GridBagLayout());
panel2.add(checkbox1, gbc);

The above code adds a CheckBox to a panel with GridBagLayout. We set the GridBagConstraints
for the checkbox by passing a GridBagConstraints object and to the GridBagConstraints
constructor we pass values to all the eleven constraints.
Let us look into more detail of what each constraint means, the valid values and default
values.
16.14. anchor constraint
Description :

When the component is smaller than its display area, use the anchor
constraint to tell the layout manager where to place the component within the area.
The anchor constraint only affects the component within its own display area, depending on
the fill constraint for the component. For example, if the fill constraint value for a
component is GridBagConstraints.BOTH (fill the display area both horizontally and
vertically), the anchor constraint has no effect because the component takes up the entire
available area. For the anchor constraint to have an effect, set the fill constraint value to
GridBagConstraints.NONE,
GridBagConstraints.VERTICAL

GridBagConstraints.HORIZONTAL

Valid values are:


GridBagConstraints.CENTER
GridBagConstraints.NORTH
GridBagConstraints.NORTHEAST
GridBagConstraints.EAST
GridBagConstraints.SOUTHEAST
111

or

COALESCE

GridBagConstraints.SOUTH
GridBagConstraints.SOUTHWEST
GridBagConstraints.WEST
GridBagConstraints.NORTHWEST

Default value is:


GridBagConstraints.CENTER

16.15. fill constraint


When the component's display area is larger than the component's requested
size, use the fill constraint to tell the layout manager which parts of the display area should
be given to the component.
Description:

As with the anchor constraint, the fill constraint only affects the component within its own
display area. The constraint tells the layout manager to expand the component to fill the
whole area it has been given.
Valid values are:

GridBagConstraints.NONE

Do not change the size of the component.

GridBagConstraints.BOTH

GridBagConstraints.HORIZONTAL

Resize the component both horizontally and vertically to fill the area
completely.
Only resize the component to fill the area horizontally.

GridBagConstraints.VERTICAL

Only resize the component to fill the area vertically.


Default value is:
GridBagConstraints.NONE
gridwidth, gridheight

constraint

Use these constraints to specify the number of cells in a row (gridwidth) or


column (gridheight) the component uses. This constraint value is stated in cell numbers,
not in pixels.
Description:

Valid values are:

gridwidth=nn, gridheight=nn

Where nn is an integer representing the number of cell columns or


rows.

GridBagConstraints.RELATIVE(-1)

112

COALESCE
Specifies that this component is the last but one in the row (gridwidth) or
column
(gridheight.)
A
component
with
a
GridBagConstraints.RELATIVE takes all the remaining cells except for
the last one. For example, in a row of six columns, if the component
starts in the third column, a gridwidth of RELATIVE will make it take up
columns three, four, and five.

GridBagConstraints.REMAINDER(0)

Specifies that this component is the last one in the row (gridwidth) or
column (gridheight).
Default value is:
gridwidth=1, gridheight=1
gridx, gridy constraint

Use these constraints to specify the grid cell location for the upper left
corner of component. For example, gridx=0 is the first column on the left, and gridy=0
is the first row at the top. Therefore, a component with the constraints gridx=0 and
gridy=0 is placed in the first cell of the grid (top left).
Description:

GridBagConstraints.RELATIVE specifies that the component be placed relative to the


previous component as follows:

When used with gridx, it specifies that this component be placed immediately to the
right of the last component added.
When used with gridy, it specifies that this component be placed immediately below the
last component added.
Valid values are:

gridx=nn, gridy=nn
GridBagConstraints.RELATIVE (-1)

Default value is:


gridx=1, gridy=1

16.16. insets
Description: Use

insets to specify the minimum amount of external space (padding) in pixels


between the component and the edges of its display area. The inset says that there must
always be the specified gap between the edge of the component and the corresponding edge
of the cell. Therefore, insets work like brakes on the component to keep it away from the
edges of the cell. For example, if we increase the width of a component with left and right
insets to be wider than its cell, the cell will expand to accommodate the component plus its
insets. Because of this, fill and padding constraints never steal any space from insets.
Valid values are:
insets = new Insets(n,n,n,n);

113

COALESCE
Top, left, bottom, right (where each parameter represents the number of pixels between the
display area and one edge of the cell.)
Default values are:
insets = new Insets(0,0,0,0)
ipadx, ipady constraint
Description: These constraints

specify the internal padding for a component:

ipadx specifies the number of pixels to add to the minimum width of the component.
ipady specifies the number of pixels to add to the minimum height of the component.

Use ipadx and ipady to specify the amount of space (in pixels) to add to the minimum size of
the component for internal padding. For example, the width of the component will be at
least its minimum width plus ipadx in pixels. The code only adds it once, splitting it evenly
between both sides of the component. Similarly, the height of the component will be at least
the minimum height plus ipady pixels.
For example:
When added to a component that has a preferred size of 30 pixels wide and 20 pixels high:
If ipadx= 4, the component will be 34 pixels wide.
If ipadx= 2, the component will be 22 pixels high.
Valid values are:
ipadx=nn, ipadx=nn

Default value is:


ipadx=0, ipady=0
weightx, weighty constraint

Use the weight constraints to specify how to distribute a GridBagLayout


container's extra space horizontally (weightx) and vertically (weighty) when the container is
resized. Weights determine what share of the extra space gets allocated to each cell and
component when the container is enlarged beyond its default size.
Description:

Weight values are of type double and are specified numerically in the range 0.0 to 1.0
inclusive. A weight of zero means the component should not receive any of the extra space,
and 1.0 means component gets a full share of the space.
The weight of a row is calculated to be the maximum weightx of all the components in the
row. The weight of a column is calculated to be the maximum weighty of all the components
in the column.
Valid values are:
weightx=n.n, weighty=n.n

Default value is:


weightx=0.0, weighty=0.0

Let us look into an example of GridBagLayout manager using GridBagConstraints.


/* GridBagExample.java */

114

COALESCE
import java.awt.*;
import java.awt.event.*;
public class GridBagExample extends Frame
{ BorderLayout borderLayout1 = new BorderLayout();
Panel panel2 = new Panel();
Checkbox checkbox1 = new Checkbox();
Checkbox checkbox2 = new Checkbox();
Button button1 = new Button();
Button button2 = new Button();
Button button3 = new Button();
Panel panel1 = new Panel();
GridLayout gridLayout1 = new GridLayout();
GridBagLayout gridBagLayout1 = new GridBagLayout();
//Construct the frame
public GridBag()
{ try /* try and catch the exception which might
occur during initialization of components */
{

jbInit();

} catch (Exception e)
{

e.printStackTrace();

}
} //Component initialization
private void jbInit() throws Exception{
this.setLayout(borderLayout1);
this.setSize(new Dimension(323, 285));
this.setTitle("GridBag Layout");
checkbox1.setLabel("Descending");
checkbox2.setLabel("Ascending");
button1.setLabel("OK");
button2.setLabel("Cancel");
button3.setLabel("Help");
gridLayout1.setHgap(6);
gridLayout1.setColumns(3);
panel1.setLayout(gridLayout1);
panel2.setLayout(gridBagLayout1);
this.add(panel2, BorderLayout.CENTER);
panel2.add(checkbox1, new GridBagConstraints(0, 3, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER,

115

COALESCE
GridBagConstraints.NONE, new Insets(11, 30, 0, 0),
0, 0));
panel2.add(checkbox2, new GridBagConstraints(1, 3, 1, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(11, 7, 0, 0),
0, 0));
panel2.add(panel1, new GridBagConstraints(0, 4, 2, 1,
0.0, 0.0, GridBagConstraints.CENTER,
GridBagConstraints.NONE, new Insets(6, 0, 6, 0),
0, 0));
panel1.add(button1, null);
panel1.add(button2, null);
panel1.add(button3, null);
} public static void main(String args[])
{ Card gridBag = new Card();
GridBag.setBounds(50,50,300,400);
GridBag.setVisible(true);
}}

16.17. Null Layout Manager


The Null Layout Manager allows the programmer to place containers or components
anywhere in the Layout. This is generally not used as it causes problems when the window is
resized, and the controls and containers are not repositioned with relative position.
The program below shows us an example of how to use the Null Layout manager.
/* NullLayoutExample.java */
import java.awt.*;
public class NullLayoutExample
{

private Frame f;
private Button b1,b2;
public void go()
{ f=new Frame("Null Layout");
f.setLayout(null); /* by passing null we get the NullLayout manager */
b1=new Button("Button 1");
b1.setBounds(50,50,70,30);/* place the button at the required place */
b2=new Button("Button 2");
b2.setBounds(50,90,70,30);
f.add(b1);
f.add(b2);
f.setSize(200,200);

116

COALESCE
f.setVisible(true);
} public static void main(String args[])
{ NullLayoutExample BLWin=new NullLayoutExample();
BLWin.go();
}
}

As shown above the programmer expects the buttons to be positioned in the center after
window resizing but this does not happen.
16.18. Choosing Layout Managers
To make sure that the programmer has a simple approach to GUI designing several layout
alternatives are chosen. This also allows the programmer to think of

Future enhancements

Changes that might have to be incorporated into the GUI.

There is no rule or methodology in choosing the layout manager but the above two points
would be good to keep in mind when choosing the layout manager. For example, when we
need to develop a calculator, the layout manager to use would be GridLayout. When we need
a GUI, which has tabbed panes, then it is best to use CardLayout.
16.19. Review Questions
1. What is the default layout manager for an applet, frame and panel?
2. If a GridLayout has a frame and no panels, are all the components within the frame of
the same size both height and width?
True / False
3. For the above question if the frame uses its default layout manager, then does the
components have same size?
True / False
4. In Grid Layout manager can the programmer set the width of each component? True /
False
5. Which layout manager arranges components in horizontal rows?
a. FlowLayout
b. GridLayout
c. GridBagLayout
d. Null Layout
6. Which layout manager stores different kind of layouts?
a. FlowLayout
b. GridLayout
c. CardLayout
117

COALESCE
d. Null Layout
7. List the four steps involved in Panel Development?
8. List the two important considerations for choosing the layout manager?
9. List the steps involved in defining GUI requirements?
10. What are the disadvantages of using a Null Layout?

118

COALESCE
17. Index
instanceof................................................................. 43
interface .................................................................... 26
interpreter................................................................... 2

A
abstract ..................................................................... 26
Abstract Window Toolkit ...................................... 13
applet .......................................................................... 9

J
JVM ............................................................................ 2

break ......................................................................... 62
Bytecode..................................................................... 2

new.............................................................................. 8
null............................................................................ 22

catch .......................................................................... 65
class............................................................................. 4
classpath ................................................................... 38
CODEBASE ........................................................... 55
constructor............................................................... 11
container..................................................................... 6

overloading .............................................................. 22
overriding................................................................. 22
P
Package..................................................................... 13
private....................................................................... 25
protected .................................................................. 25
public........................................................................ 25

E
Encapsulation .......................................................... 38
exception.................................................................. 65
extends...................................................................... 24

R
reference................................................................... 43

final ........................................................................... 25
finally ........................................................................ 65

static.......................................................................... 26
subclass..................................................................... 22
super ......................................................................... 32

G
Garbage Collection ................................................... 8

this ............................................................................ 22
throw ........................................................................ 68
Throws ..................................................................... 69
try 70

implements............................................................... 40
import....................................................................... 37
Inheritance ................................................................. 7
instance..................................................................... 16

119

Das könnte Ihnen auch gefallen