You are on page 1of 230

JAVA

Table of Contents:
1. Introduction to JAVA
 History of JAVA
 Features of JAVA
 Introduction to OOPS
 A first program in JAVA
2. Developing a JAVA Programming
 Data Types
 Variables
 Literals
 Expressions
 Operators
 Controls
3. Classes
 General Structure of a class
 Methods
 More about classes
 Constructors
 Finalizer
4. Arrays and Strings
 Declaring Array Variables
 Multidimensional Array
 String Constructors
 String Methods
 Casting and converting
5. Inheritance
 Basics
 Overridding
 Using Final and Abstract Classes
6. Package & Exception Handling
 Packages and Interfaces
 Basics of Exception Handling
 Exception Types
 Creating your own Exception
7. I/O Packages
 Files And Streams
 Methods in Streams
 Types of I/O Streams
 Reader and Writer Classes
 Stream Tokenizer
8. Events and User Interface Components
 Event Handling
 Types of Event Handling
 Containers
 User Interface Component Classes

9. Thread and Multithreading


 Fundamentals of Threads
 Methods of Thread Class
 Multithreading
 More on Threads
 Java’s Interthread Communication
10. Java Lang Package
 Introduction
 Interfaces of java.lang
 Classes of java.lang
11. Util Package
 Interfaces and Collections
 Implementations
 Algorithms
 Legacy Classes and Legacy Interfaces
 String Tokenizer
 Data Comparison
12. Abstract Window Toolkit
 Applet
 Graphics and Images
 Windows in AWT
 Components of AWT
 Animation
13. JFC
 Introduction to JFC
 Swing
 JComponent
 Containers
 Advanced JFC Components
Chapter 1: Introduction to JAVA:
Java is an interpreted language. Java is an Object-Oriented, mutli-threaded
programming language developed by Sun Microsystems in 1991.

History of JAVA:
Java has been around since 1991, developed by a small team of Sun Microsystems
developers in a project originally called the Green project. The intent of the project was
to develop a platform-independent software technology that would be used in the
consumer electronics industry. The language that the team created was originally called
Oak.
In 1994, two Sun developers created the first version of HotJava, and then called
WebRunner, which is a graphical browser for the Web that exists today. The browser was
coded entirely in the Oak language, by this time called Java. Soon after, the Java
compiler was rewritten in the Java language from its original C code, thus proving that
Java could be used effectively as an application language. Sun introduced Java in May
1995 at the SunWorld 95 convention.
Features of JAVA:
Sun describes Java as a "simple, object-oriented, interpreted, robust, secure, architecture-
neutral, portable, high-performance, multithreaded, and dynamic language."

Introduction to OOPS: OOPS stands for Object-Oriented Programming Structure. In


order to manage increasing complexity of the programs, they approach called
Object-Oriented Programming, was introduced. An Object-Oriented Program can
be characterized as data controlling access to code. A real instance of a class is
called an “Object”. Objects communicate with each other with well-defined
interfaces called messages. The object-oriented model is based on three important
concepts namely Encapsulation, Inheritance and Polymorphism.

Encapsulation: Encapsulation is the process of combining elements to create a new


entity. It is a protective wall that prevents the code and data from being randomly
accessed by other code defined outside the wall. For example, a procedure is a type
of encapsulation because it combines a series of computer instructions.

Concept of Encapsulation:

Information Hiding – Ensures that objects cannot change the internal state of other
objects in unexpected ways; only the object’s own internal methods are allowed to
access its state. Each type of object exposes an interface to other objects that
specifies how other objects may interact with it.
Abstraction – The ability for a program to ignore some aspects of the information it is
manipulating.
Inheritance: Inheritance is the process by which one object acquires the properties of
another object. It stands for its concept of hierarchical classification. For example
Maruthi is part of the classification car, which in turn is part of the Transport class.

Polymorphism: Polymorphism is the ability to appear in many forms. It is a feature that


allows one interface to be used for a general class of actions. For example, given a
base class shape, polymorphism enables the programmer to define different area
methods for any number of derived classes, such as circles, rectangles and
triangles. The concept of Polymorphism is expressed by the phrase “one interface,
multiple methods”.

Compiling with JAVA:

The first step is to run the text editor of choice and create the classic HelloWorld
program.

// HelloWorld.java
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!");
}
}

Save the file as HelloWorld.java in the classes’ directory. After saving your source code
with the extension .java, you can compile it using the Java compiler, javac. To run the
javac compiler, execute it with the following syntax.: javac [ options ] filename.java

ex: javac HelloWorld.java

If the code compiles correctly, you will see two files in your classes’ directory:
HelloWorld.java and HelloWorld.class. The .class file has now been converted to
bytecode. To run a java file type

java filename ex: java HelloWorld


Chapter2: Developing a JAVA Programming

The Sun’s Java Development kit (JDK) provides all features to write programs. Java
applications are general programs written in the Java language that do not require a
browser to run.
The Java source file is created in a plain text editor and can also be created in an editor
that saves files in plain ASCII without any formatting characters. A Java program has
two main parts: a class definition that encloses the entire program and a method called
main that contains the body.
Once the program is typed in, it is saved as a file with an extension of .java. Usually java
files have the same name as their class definition. This file is then compiled using javac.
The javac program should be in the execution path for compilation of the java code. Once
completed, a file by the same name, but with the .class extension is created. This is the
java byte code file. The byte code is then run using the java interpreter. In the JDK, the
java interpreter is called java. To execute this, java followed by the filename without the
class extension is typed at the DOS prompt. The above compilation and execution
procedure works only if Sun’s Java compiler is used.

Example:
Open a new file in the editor and type the following script

class Hello {
public static void main (String args[])

{ System.out.pri
ntln("Welcome to DMISS");
}
}

Save the file as Hello.Java.


Compile by trying javac Hello.java on the command line.
On successful compilation execute the program by typing java Hello, on the
command line
The output of the program appears as follows:

Welcome to DMISS

In addition to compilation and execution, both Java compiler and the Java interpreter
check the Java source code and bytecode to make sure that the Java programmer has not
overrun buffers, stack frames etc.
At first class is declared. Every Java application program has a main ( ) method. It is the
first function run when the program is executed. Void keyword preceding main( )
indicates that it does not return any values. Public indicates that the method is global,
static denotes that main( ) is a class method and can be called without creating an object.
The third step indicates the printing a string on to the screen. The curly braces are used to
enclose the class and main function.

DATA TYPES:

Every variable declared should have a name, a type and a value. Java provides different
data types that include character, double, float, integer, string, Boolean etc. These are
primitive types as they are built into the Java language and are not actual objects thus
making it easier to use them. The data types in Java are machine-independent. New types
are declared by a class definition and objects of this class can be created.
Wrapper classes are provided for the primitive type, have the same name as the
primitive type, but the first letter capitalized. The advantage of using wrappers is that
when an object is passed to a method, the method is able to work on the object itself.
Another advantage is that the user can derive his/her own classes from Java’s built-in
wrapper classes.
Integer:
Integers has four types. It include byte, short, int and long, which are for whole-
valued signed numbers. Each holds a different range of values. The values can either be
positive or negative.

Type Size Range


Byte 8 bits -128 to +128
Short 16 bits -32,768 to 32767
Int 32 bits -2,147,483,684 to 2,147,483,647
Long 64 bits -9223372036854775808 to
923372036854775807

Float:
Float is used to store numbers with decimal point. There are two floating point data types
in Java namely the float( 32bits, single-precision ) and the double(64 bits, double
precision).

Character:
It is used for storing individual characters. The char type has 16 bits of precision and it
is unsigned. Java uses Unicode to represent characters. Unicode defines a fully
international characters set that can represent all of the characters in all human languages.
The range of char is 0 to 65,536. There are no negative characters.

Boolean:
Boolean data types hold either a true or a false value. These are not stored as numeric
values and cannot be used as such. This is the type returned by all relational operators,
such as a < b.

Class BoolTest
{
Public static void main(String arg[] )
{
boolean b;
b = false;
System.out.println(“b is “ +b);
b = true;
System.out.println(“b is “ +b);
}
}

This will print……..


b is false
b is true
Variables:
An object stores its state in variables. A variable is an item of data named by an
Identifier. Variables are locations in the memory that can hold values. Before assigning
any value to a variable, it must be declared. Java has three kinds of variables namely
 Instance Variables
 Local Variables
 Class Variables
Instance Variables are used to define attributes or the state of a particular object. These
are used to store information needed by multiple methods in the objects.

Local Variables are used inside blocks as counters or in methods as temporary variables.
Once the block or the method is executed, the variable ceases to exist. The local
Variables are used to store information needed by a single method.

Class Variables are global to a class and to all the instances of the class. They are useful
for communicating between different objects of the same class or for keeping track of
global status.
The keyword static is used to declare a class variable.

DECLARING A VARIABLE:

Syntax: type identifier[=value],[,identifier][=value];


In addition to the name and type that you explicitly give a variable, a variable has scope.
The section of code where the variable’s simple name can be used is the variable’s scope.
The variable’s scope is determined implicitly by the location of the variable declaration,
that is , where the declaration appears in relation to other code elements.
Here are several examples of variable declarations of various types.

Int a, b, c //declares three integers

Variable name:
Variable names in java can start with a letter, an underscore(-), or a dollar sign($)
but cannot begin with a number. The second character onwards can include any letter or
number. Java is case sensitive and also uses the Unicode character set.
Variable types:
Variable types can be any data type that java supports- the eight primitive types, the
name of a class or interface and an array.
Assigning values:
Values are assigned to variables using the assignment operator “equal to”(=).

The following example demonstrates declaration, initialization and display of


variables.
Example:

Open the new file in the editor and type the following script.
1: class Hello (
2: public static void main (String args[]){
3: int x = 90;
4: short y = 4;
5: float z = 10.87f;
6: String name = “Arun”;
7: System.out.println(“the integer value is “+ x);
8: System.out.println (“the short value is “= y);
9: System.out.println (“the float value is “ = z”);
10: System.out.println(“the string value is “ = name);
11: }
12: }

 Save this file as Hello.java and compile using javac Hello.java at DOS
prompt.
 On successful compilation, execute the program using java Hello
 The output is diaplayed as shown
The integer value is 90
The short value is 4
The float value is 10.87
The string value is Arun

Line 3 – 6 depict declaration, initialization and naming of various data types. The
values of the declared variables are printed from lines 7 – 10. The + operator is used here
as a concatenation operator.

LITERALS:
A Literal represents a value of a certain type where the type describes the behaviour
of the value.
There are different types of literals. They are:

 Number literals
 Character literals
 Boolean literals
 String literals

Number:
There are many types of integer literals such as int, long, octal, hexadecimal, etc. 2 is
an example of a decimal integer literal of type int. If a decimal integer literal is larger
than the int, it is declared to be of type long. These integers can also be expressed as octal
or hexadecimal.
Floating point literals have a decimal part and an integer part. Floating point literals result
in floating point numbers of type double. By appending f to a number, it can be changed
as type float. Exponents can be used in floating point literals by using the letter E or e
followed by exponent.

Boolean:
Boolean literals consist of the keywords true or false.

Character:
Character literals are expressed by a single character enclosed within single quotes.
Characters are stored as Unicode characters.

Escape Meaning
\n Newline
\t Tab
\b Backspace
\r Carriage return
\f Form feed
\\ Backslash
\’ Single quote
\” Double quote
\ddd Octal
\xdd Hexadecimal
\udddd Unicode character

Table lists the special codes that represent non-printable characters from Unicode
character set. The letter ‘d ’ in the octal, hex and the Unicode escapes represent a number
or a hexadecimal digit. Java does not include character codes for the bell and the vertical
tab.

String
A string is a combination of characters. String literals are a set of characters that are
enclosed within double quotes. They are real objects, it is possible to concatenate, modify
and test them. For example, “Welcome to DMISS” represents a string. Strings can
contain character constants and Unicode characters.
When a string literal is declared Java automatically creates an instance of the class String
and initializes it with the value specified.

Expressions
Expressions are the simplest form of statements in Java. These statements return a
value that can be assigned to a variable. These statements return a value that can be
assigned to a variable. The following are examples for expressions:
x + 10
total – 1
Operators
Operators are special symbols used in expressions. They include arithmetic operators,
assignment operators, increment and decrement operators, logical operators, bitwise
operators and comparison operators.
Arithmetic Operators
Java has five basic arithmetic operators. Each of these operators takes two operands,
one on either side of the operator.

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus

Modulus operator % returns the remainder of a division operation. It can be applied to


floating-point types as well as integer types.

Example:
Open a new file and type the following script.

public class hello


{
Public static void main ( String args[]))
{
int A = 37;
int B = 42;
double X = 27.475;
double Y = 7.22;
// adding numbers
System.out.println(“ A+B =” +(A+B));
System.out.println(“ X+Y =” +(X+Y));

// subtracting numbers
System.out.println(“ A-B =” +(A-B));
System.out.println(“ X-Y =” +(X-Y));

//multiplying numbers
System.out.println(“ A*B =” +(A*B));
System.out.println(“ X*Y =” +(X*Y));

// dividing numbers
System.out.println(“ A/B =” +(A/B));
System.out.println(“ X/Y =” +(X/Y));
//modulus type
System.out.println(“ A%B =” +(A%B));
System.out.println(“ X%Y =” +(X%Y));

//mixing types
System.out.println(“ B+Y =” +(B+Y));
System.out.println(“ A*X =” +(A*X));
}
}

Save this file as hello.java and compile using javac hello.java at DOS prompt.

The output of the program is:


A+B = 79
X+Y = 34.695

A-B = -5
X-Y = 20.255

A*B = 1554
X*Y = 198.37

A/B = 0
X/Y = 3.8054

A%B = 37
X%Y = 5.815

B+Y = 49.22
A+X = 1016.58

Arithmetic Assignment Operators

Java provides special operators that can be used to combine an arithmetic operation with
an assignment. Assignment operators set the value of a variable or expression to some
new value. The simple = operator sets the left-hand operand to the value of the right-hand
operand. If the operands are object references, then a copy of the reference value will be
assigned and not the object body. The assignment operator is evaluated from right to left,
so a = b = c = 0; would assign 0 to c, then c to b then b to a. A selection of assignment
operators is given.

Expression Meaning
x += y x=x+y
x -= y x=x–y
x *= y x=x*y
x /= y x=x/y
x=y x=y

Increment and Decrement


To increment or decrement a value by one, the ++ operator and – operator are used
respectively. It can be prefixed or postfixed.

Operator Use Description


++ ++op Pre increment operator: Increments op by 1; evaluates to the
value of op after it was incremented.
++ op++ Post increment operator: Increments op by 1; evaluates to the
value of op before it was incremented.
-- --op Pre decrement operator: Decrements op by 1; evaluates to the
value of op after it was decremented.
-- op-- Post decrement operator: Decrements op by 1; evaluates to the
value of op before it was decremented.

Example:
Open a new file and type the following

public class InDe


{
Public static void main (String args[] )
{
int a = 1;
int b = 2;
int c = ++b;
int d = a++;
c++;
System.out.println ( “a=” +a);
System.out.println ( “b=” +b);
System.out.println ( “c=” +c);
System.out.println ( “d=” +d);
}
}

Save this file as InDe.java and compile using javac InDe.java.


Execute the source code using: java InDe
The output is
a=2
b=3
c=4
d=1

Relational and Conditional Operators


A relational operator compares two values and determines the relationship between
them. The expressions would return a Boolean value.

Operator Meaning Example


> Greater than A>7
< Less than A < 15
== Equal A=5
!= Not equal A != 6
<= Less than or equal to A <= 34
>= Greater than or equal to A >= 23

Logical Operators
Logical operators available are AND, OR, XOR and NOT.

AND operator (& or &&) returns true only if both sides in an expression are true. If any
one fails, the operator is false.

OR operator ( | or || ) returns true if any expression is true. Only if all the conditions are
false, the expression is false.

XOR operator ( ^ ), returns true if its operands are different. If both its operands are
similar then it returns false.

NOT operator is negation of the expression.

Bitwise Operators
A shift operator performs bit manipulation on data by shifting the bits of its first operand
right or left. Each operator shifts the bits of the left-hand operand over by the number of
positions indicated by the operator itself. It is used to perform operations on individual
bits in integers.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Left shift
>> Right shift
>>>> Zero fill right shift
~ Bitwise Complement
<<= Left Shift assignment
>>= Right Shift assignment
>>>= Zero fill right shift assignment
x &= y AND assignment
x |= y OR assignment
x ^= y XOR assignment

Example:
Open a new file and type the following script.

Class Bitop
{
public static void main(String args[])
{
int a=1;
int b=2;
int c=3;
a=a /4;
b>>=1;
c<<=1;
a=a^c;
System.out.println(“a=”+a);
System.out.println (“b=” +b);
System.out.println(“c=”+c);
}
}
• Save this file as BitOp.java and compile using javac BitOp.java at the DOS
prompt.
• Execute the source code using: java BitOp
• The output is
a=3
b=1
c=6
Operator precedence
The order which the expressions are evaluated and their overall value is determined by
Operator precedence.
The following table indicates specific precedence of the various operators.

Operator Notes
[],( ), . [] is used for arrays. ( ) group expressions.
Dot is used to access methods and variables
within objects and classes.
++, --, !, - , instance of Returns true or false based on whether the
object is an instance of the named class or
any of that class’s super class.
New( type) expression The new operator is used to create
instances of classes.
*, /, % Multiplication, division, modulus
+, - Addition, subtraction
<<, >> Bitwise left and right shift
<, >, < =,>= Relational comparison tests
= =,!= Equal to and not equal to
& AND
^ XOR
| OR
&& Logical AND
|| Logical OR
?: Ternary operator
=, +=, - =,* =,/=, %=, ^= Assignment

? Ternary operator
Java includes a special ternary operator that can replace certain types of if-then-else
statements. This operator is the ? and it works in Java much like it does in C, C++ and
C#.

expression1 ? expression2 : expression3

When Java evaluates this assignment expression, it first looks at the expression to the left
of the question mark. If it satisfies the condition then expression2 is executed else
expression3 is executed.

Keywords

There are certain sequences of characters, called ‘Keywords’ that have special meaning
in Java. There are around 48 reserved keywords currently defined in Java language, these
keywords, combined with the syntax of the operators and separators, form the definition
of the Java language. These keywords cannot be used as names for a variable, class, or
method.
abstract boolean break byte case cast
catch char class const continue default
do double else extends final finally
float for future if implements import
int interface long native new null
operator package private protected public return
short static super switch synchronized this
throw throws transient try void while

Controls:

A programming language uses control statements to cause the flow of execution, based
on changes to the state of a program. Java’s program control statements can be put into
the following categories: selection, iteration and jump.

The if construct:
The if statement enables your program to selectively execute other statements.

if ( expression)
{
Statement(s) }

To perform a different set of statements if the expression is false? We can use else
statement .
if – else statement:

if ( condition)
body of loop
else
body of loop

Example:
public class grade
{
public static void main(String [] args)
{
int score = 75;
char grade;

if (score >= 90)


{
grade = ‘A’;
} else if (score >=80)
{
grade = ‘B’;
} else if (score >=70)
{
grade = ‘C’;
} else if (score >=60)
{
grade = ‘D’;
} else
{
Grade = ‘F’;
}
System.out.println(“grade =” + grade);
}
}

The output of the program is


Grade = C

Conditional Operator:
The conditional operator is otherwise known as the ternary operator and is considered to
be an alternative to the if else construct. It returns a value and the syntax is:

<test> ? <pass> : <fail>


Where, <test> is the condition to be tested. If the condition returns true then the
statement given in <pass> will be executed. Otherwise, the statement given in <fail> will
be executed.

public class hello{


public static void main (String args[] ) {
int i = 10;
int j = 78;
int z = 0;
z = i < j ? i : j;
System.out.println (“ The value is “ + z);
}
}

Save the file hello.java and compile using javac hello.java.


Execute using java hello
The output is
The value is 10
Iteration Statements:

The while loop

A while statement is used continuously to execute a block of statements while a


condition remains true. The General syntax of the while statement is

While( condition){
< statement>
}
At first while statement evaluates condition, which must return a Boolean value. If the
condition returns true then the while statement executes the statements associated with it.
The while statement test the condition and executes its block until the condition returns
false.

public class while


{
public static void main (String args[]) {
int m = 25;
int p = 0;
int n = 1;
int sum;
while (n <= m)
{
System.out.println ( “ The series is “ + n);
sum = p + n;
p = n;
n = s;
}
}
}
Save the file as while.java and compile using javac while.java
Execute the source code using java while.
The series is 1
The series is 1
The series is 2
The series is 3
The series is 5
The series is 8
The series is 13
The series is 21
do while:
The Java programming language provides another statement that is similar to while
statement—the do-while statement. The general syntax of do-while is

do {
statement(s)
}
while(condition);

Instead of evaluating the expression at the top of the loop, do-while evaluates the
expression at the bottom. Thus the statements associated with a do-while are executed
atleast once.

The for loop


The for statement provides a compact way to iterate over a range of values. The general
form of for statement can be expressed
for (initialization; test; expression){
statement
}
It repeats a set of statements a certain number of times until a condition is matched. In
first part a variable is initialized to a value. The second part consists of a test condition
that returns only a Boolean. The last part is an expression, evaluated every time the loop
is executed.

Example:
public class for{
public static void main (String args[]) {
int i;
for (i = 0;i <10; i = i + 2)
{
if ((i%2) = = 0)
System.out.println(“ + i + is a even number”);
}
}
}

Save the file as for.java and compile using javac for.java


Execute using java for.
The output appears as
0 is an even number
2 is an even number
4 is an even number
6 is an even number
8 is an even number

Nested loop
Like all other programming languages, Java allows loops to be nested. i.e, one loop
may be inside another.

for( initialization; test; expression){


{
for( initialization; test; expression){
statement
}
Statement
}
}
Example:
Class Nested
{
public static void main(String arg[])
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
System.out.println(“.”);
System.out.println();
}
}
}
JUMP STATEMENTS:
The java supports three jump/branching statements:
• The break statement
• The continue statement
• The return statement
BREAK:
The break statement halts the execution of the current loop and forces control out of the
loop. The term break refers to the act of breaking out of a block of code. It tells the
runtime to pick up execution past the end of the named block.

public class break


{
public static void main (String args[]) {
boolean t = true;
a: {
b: {
c: {
System.out.println (“Before the break”);
if (t)
break b;
System.out.println (“This will not execute”);
}
System.out.println (“This will not execute”);
}
System.out.println (“This is after b”);
}
}
}

Save the file as break.java and compile using javac break.java


Execute using java break.
The output appears as
Before the break
This is after b

Break statement has two forms: (i) unlabeled and (ii) labeled.
The unlabeled form of the break statement used to terminate a for, while, or do-while
loop. It encloses switch statement and flow of control transfers to the statement
immediately. The labeled break terminates the statement when the value is found. It does
not transfer the flow of control to be label. The flow of control transfers to the statement
immediately following the labeled (terminated) statement.

Continue:
The continue statement is used to halt the execution of the loop, it starts the next
iteration. The unlabeled form skips to the end of the innermost loop’s body and evaluates
the Boolean expression that controls the loop. The labeled form of the continue statement
skips the current iteration of an outer loop marked with the given label.

public class continue {


public static void main (String args[]) {
for (int i=0; i<10; i++) {
System.out.println (+i+ “ “);
If ( i % 2 ==0)
Continue;
System.out.println ( “ “ );
}
}
}

Save the file as continue.java and compile using javac continue.java


Execute using java continue
The output of the program is
01
23
45
67
89

Return :
The final Java’s branching statement is the return statement. We use return to exit from
the current method. The flow of control returns to the statement that follows the original
method call. The return statement has two forms: one that returns a value and one that
does not. To return a value, simply put the value after the return keyword:

return ++ count;
The data type of the value returned by return must match the type of the method’s
declared return value. When a method is declared void, use the form of return that does
not return a value:
return;

Switch statement:
The switch statement dispatches control to the different parts of the code based on the
value of a single variable or expression. The value of expression is compared with each
of the literal values in the case statements. If they match, the following code sequence is
executed. Otherwise an optional default statement is executed.
General syntax is

switch ( < test >) {


case <value a>:
<result a>;
break;

case<value b>:
<result b>;
break;
default :
<defaultresult>;
}

Example:
class switch {
public static void main (String args[]) {
int month = 8;
switch (month) {
case 1:
System.out.println(“ January”);
break;
case 2:
System.out.println(“ February”);
break;
case 3:
System.out.println(“ March”);
break;
case 4:
System.out.println(“ April”);
break;
case 5:
System.out.println(“ May”);
break;
case 6:
System.out.println(“ June”);
break;
case 7:
System.out.println(“ July”);
break;
case 8:
System.out.println(“ August”);
break;
case 9:
System.out.println(“ September”);
break;
case 10:
System.out.println(“ October”);
break;
case 11:
System.out.println(“ November”);
break;
case 12:
System.out.println(“ December”);
break;
}
}
}

Save the file and compile it


Execute using java switch

The output appears as


August

Summary:
Java is a programming language developed by Sun Microsystems.
Every Java application requires a class declaration and the main( ) method declaration.
Java data types include Boolean, character, double, float, integer, etc. These are called
the primitive types and they are not actual objects.
Variables are locations in the memory that can hold values and they must have a data
type, a name and a value.
A string is a combination of characters and they are real objects, and hence, it is
possible to concatenate, modify and test them.
Operators are special symbols that are used in expression. Java uses many controls
statements.

CLASSES
The basic element of object-oriented programming is a class. A class
definition is a set of plans; the same is true of software objects. In order to create a
software object in Java, it is necessary for someone to first create a plan. In Java, we refer
to that plan as a class. A class is defined by use of the class keyword. A class defines the
shape and behaviour of an object and is a template for multiple objects with similar
features. Any concept represented in a program is encapsulated in a class. When an
application is written, classes of objects are defined.

Syntax:
class <classname> {
<body of the class>
}
A class called Car includes all its features serving as template. Each property is treated as
an attribute of that class. For example, car name, colour, engine, model, number etc are
the attributes.

class car {
String name;
String color;
int number;
}
A class also defines its functional interface known as methods. For instance, car can have
a method that displays the name of the car.
Once a car class is defined, instances of that class can be created and each instance can
have different attributes. When the program runs, instances of the class are created and
discarded as and when required.
An instance of a class can be used to access the variables and methods that form the part
of the class. Each instance of the class has its own copy of instance variables defined in
the class and hence can hold different attributes. The methods in the class operate on
individual instances of the class. The term instance and object are used interchangeably.
The Java environment comes with a library of classes that implement a lot of the basic
behaviour. By creating classes that use the classes provided by Java, highly maintainable
program can be constructed.
Example:
Open a new file and enter the following code:
class one {
public static void main (String args[] ) {
int a = 1;
int b = 2;
int c = 3;
System.out.println (“a = “+ a);
System.out.println (“b = “+ b);
System.out.println (“c = “ +c);
}
}
Save the file as one.java
Compile the file using javac one.java
Run the file using java one

The output of the program is


a=1
b=2
c=3
In this code, at first the class is declared. The main method, entry point to all Java
application programs, is defined. The three variables that are local to the main are
declared. These variables are displayed using println.

Attributes:
Attributes are individual properties that differentiate one object from another and
determines appearance, state and other qualities. Each attribute has a corresponding
instance variable.
Instance Variables:
Data is encapsulated in a class by declaring variables inside the class declaration.
Variables declared in this scope are known as instance variables. Instance variables are
declared in the same way as local variables except that they are declared outside the
scope of any particular method, such as main. For example, a class named point can be
created with instance variables namely a and b. Every object of this class has its own
copy of the instance variable.

class point {
int a, b;
}

Dot Operator
The dot notation is used to obtain the value of the instance variables. It has two
parts namely the object on the left side of the dot and the variable on the right side of the
dot. Dot expressions are evaluated from left to right.
General form:
<objectReference>.<variableName>
where <objectReference> is the name of the object and <variableName> is the instance
variable.
We can store values into instance variables using the dot operator.
p.x = 10;
p.y = 20;
System.out.println (“x=” + p.x + “y=” + p.y)

Declaring Objects:
When you create a class, you are creating a new data type. We can use this type to
declare objects of that type. However, obtaining objects of a class is a two-step process.
At first, we need to declare a variable of the class type. This variable does not define an
object. Second, we must acquire an actual, physical copy of the object and assign it to
that variable. We can do this using new Operator.
The new Operator
The new operator creates a single instance of a named class and returns a reference
to that object. This reference is more or less the address in memory of the object allocated
by new. For example, an instance of a named class and returns a reference to that object.
Object b = new Object( );
Here b is a reference to an instance of object. The reference is then stored in the variable.
There is a critical distinction between how simple types and objects are manipulated in
Java. The variable b is a reference to the object. It does not actually contain it.
When an object is no longer referred to by any variable, Java automatically
reclaims memory used by that object. This is known as garbage collection. When a new
object is created a distinct set of instance variables are obtained. Each object has its own
copy of the instance variables of its class, so changes to the instance variables of one
object have no effect on the instance variables of another. Each object’s instance
variables are separate and distinct from the others.

Class Variables
Class variables are global to a class and to all the instances of the class. They are useful
for communicating between different objects of the same class or for keeping track of
global states. The keyword static is used to declare a class variable. For class variable
there is only one copy of the variable. Every instance of the class has access to that
variable. We have to use the dot notation to access the class variable, and instead of using
the object’s name on the left hand side of the dot operator, the class name can be used.
Thus, class variables can be accessed without creating an object of that class.

Methods
A method’s declaration provides information about the method to the compiler, to the
runtime system and to other classes and objects. Methods are functions that operate on
instances of classes in which they are defined. Objects can communicate with each other
using methods and can call methods in other classes. Instance methods apply and operate
on an instance of the class and instance methods. Instance methods apply and operate on
an instance of the class while class methods operate on the class.

The figure shows the elements of a method declaration:


AccessLevel Access level for this method.
Static This is a class method.
Abstract This method is not implemented.
final Method cannot be overridden.
native Method implemented in another language.
Synchronized Method requires a monitor to run.
returnType methodname The return type and method name.
( paramlist ) The list of arguments.
throws exceptions The exceptions thrown by this method.

Defining Methods
Method definition has four parts. They are:
Name of the method
Type of object
A list of parameters
Body of the method

Method overloading:
Java permits different methods to have the same name as long as the argument list is
different. This is called as method overloading. A basic method definition resembles as

<returntype> <methodname> (<type1> <arg1>, <type2> <arg2>,…..) {


<set of statement>
}

The returntype is the primitive type or class of the value that this method returns. It
should be void if the method does not return a value at all. It is essential to aloe the same
method name to be used with different argument types. And it also must for constructors.
The method’s parameter list is a set of variable declarations. The list is separated by
commas within the parentheses. The parentheses become local variables in the body of
the mehod whose values are passed when the method is called.
Inside the body of the method, statements, expressions and method calls can be present.
If the method has a return type, then a value must be returned using the keyword return.

Calling Methods
Calling a method is similar to calling or referring to an instance variable. The methods
are accessed using the dot notation. The object whose method is called is on the left of
the dot, while the name of the method and its argument are on the right.
Obj.methodname (param1,param2);

Open a new file and enter the code


class Area {
int s1 = 10;
int s2 = 10;
void calc( ) {
int ar = s1 * s2;
System.out.println(“ Area is “ + ar +” sq.cms”);
}
public static void main( String args[]) {
Area a = new Area( );
a.calc( );
}
}

Save the file as Area.java


Compile the file as javac Area.java and execute as java Area

The output appears as


Area is 100 sq.cms

The class Area has two instance variables, s1 and s2, which are initialized when an object
is created. The calc method, which does not return any value, is defined. This method
calculates the area and displays it. In the main method, an instance of the class, Area is
created. The calc method of the class, which calculates and displays the area, is called in
the code.

Class Methods:
Class methods, like class variables, are available to instances of the class and can be
made available to other classes. Class methods can be used anywhere regardless of
whether an instance of the class exists or not. Methods that operate on a particular object
should be defined as instance methods. Methods that provide some general utility but do
not directly affect an instance of the class are declared as class methods.
Syntax of class method:
static <returntype> <methodname> (<type1> <arg1>, <type2> <arg2>,………) {
<set of statements>
}

The static keyword indicates that it is a class method and can be accessed without
creating an object. The class methods, unlike instance methods, are not allowed to use
instance variables, as these methods do not operate on an object.

Passing Argument to Methods


The objects that are passed to the body of the method are passed by reference and the
-basic types are passed by value. This results in a change in original value of the object if
the value is modified in the method.

Open a file and enter the code


class Square {
void calc (int x) {
int sq = x * x;
System.out.println (“ The square of “ + x + “ is “ + sq + “sq.cms”);
}
public static void main ( String args[]) {
Square s = new Square();
s.calc(12);
}
}

Save the file as Square.java


Compile the file as javac Square.java
Execute the file as java Square
The output appears as
The square is 144 sq.cms
The calc method, which takes an integer as argument is defined. This method calculates
the square of the parameter passed and displays it. In the main ( ) method, an object of
this class is created. Then, calc method is invoked with an argument 12. The calc method
calculates the square of the argument passed and displays it.

STATIC MEANING:
The this keyword:
With this keyword, we can understand what it means to make a method Static. It means
that there is no this for that particular method. We cannot call non-static methods from
inside static methods and we can call a static method for the class itself, without any
object. A special reference value called this is included in java. The this keyword is used
inside any instance method to refer to the current object. The value of this refers to the
object on which the current method has been called. The this keyword can be used where
a reference to an object of the current class type is required. Methods declared with the
keyword static( class methods) cannot use this.

Open a new file and enter the following code:


public class point {
int x, y;
void init (int x, int y)
{
this.x = x;
this.y = y;
}
void disp ( )
{
System.out.println (“x=” +x);
System.out.println (“y=” +y);
}
}
class point {
public static void main (String args[]) {
point p = new point ( );
p.init (4,3);
p.disp ( );
}
}

Save the file as point.java


Compile the file using javac point.java
Run the file using java point

The output appears as


x=4
y=3

The final keyword:


The final keyword has slightly different meaning depending on the context, but in
general it says “ this cannot be changed.”
Data, methods and a class, these are the three section where we can use final keyword.
The final keyword is used to indicate that no further alterations can be made.
Final data:
Many programming languages have a way to tell the compiler that a piece of data is
“constant”. A constant is useful for two reasons:
1. It can be a compile-time constant that would not ever change.
2. It can be a value initialized at run-time that you do not want to change.
In Java, the sort of constants must be primitives and are expressed using the final
keyword. A value must be given at the time of definition of such a constant.
A field is that both static and final has only one piece of storage that cannot be changed.
When using final with object rather than primitives the meaning gets a bit confusing.
With a primitive, final makes the value a constant, but with an object handle, final makes
the handle a constant. The handle must be initialized to an object at the point of
declaration and the handle can never be changed to point to another object.

Overloading methods:
Overloading is a powerful feature, but we should use it only when needed. To create
an overloaded method, different method definitions each with the same name but
different parameter lists are created. Java allows method overloading as long as the each
parameter list is unique for the same method name. Java differentiates overloaded
methods with the same name, based on the number and type of parameters to that method
and not on the return type. When a method is called, Java chooses the method definition
to execute, depending on the method name and number and type of arguments. If
methods are chosen to have the same names and parameter lists but different return types
then the compiler returns an error. The variable names in the parameter list do not matter.
Only the number and the type of the parameters matter.

class Load {
String fname;
String lname;
int age;
String prof;
Load fload( String fname, String lname, int age, String profession) {
this.fname = fname;
this.lname = lname;
this.age = age;
this.profession = profession;
return this;
}
Load fload ( String fn, String ln) {
fname = fn;
lname = ln;
return this;
}
Load fload (String fnme, String lnme, String pr) {
fname = fnme;
lname = lnme;
profession = pr;
return this;
}
Load fload (String fna, String lna, int ag) {
fname = fna;
lname = lna;
age = ag;
return this;
}
void print ( ) {
System.out.println( fname + “ “ + lname + “ “ + age + “ “ +
profession);
System.out.println ( “ “ );
}
public static void main(String args[]) {
Load loads = new Load ( );
System.out.println ( “ The values are : “);
System.out.println ( );
loads.fload (“Arun”,”Kumar”, 23, “Engineer”);
loads.print ( );
loads.fload (“Shankar”,”Narayanan”);
loads.print ( );
loads.fload (“Gautham”,”Bhaskaran”,”Doctor”);
loads.print ( );
loads.fload (“Nakul”,”Mahadevan”,26);
loads.print ( );
}
}
Save the file as Load.java
Compile the file using javac Load.java
Run the file using java Load

The output appears as


The values are:
Arun Kumar 23 Engineer
Shankar Narayanan 23 Engineer
Gautham Bhaskaran 23 Doctor
Nakul Mahadevan 26 Doctor

It has a print ( ) method that prints the values of the various arguments supplied to the
various methods.

More About Classes


Encapsulation links data with the code that manipulates it. However, encapsulation
provides another important attribute: access control. Through encapsulation, we can
control what parts of a program can access the members of a class. Java provides a rich
set of access specifiers. Some aspects of access control are related mostly to inheritance
or packages.
Access Specifiers:
Access control is the process of controlling visibility of a variable or method. When a
method or variable is visible to another class, its methods can reference the method or
variable. There are four levels of visibility that are used. Each level is more restrictive
than the other and provides more protection than the one preceding it.

Public
Any method or variable is visible to the class in which it is defined. If the method or
variable must be visible to all classes, then it must be declared as public. A variable or
method with public access has the widest possible visibility. Any class can use it.

Package
Package is indicated by the lack of any access modifier in a declaration. It has an
increased protection and narrowed visibility and is the default protection when none has
been specified.

Protected
This specifier is a relationship between a class and its present and future subclasses. The
subclasses are closer to the parent class than any other class. This level gives more
protection and narrows visibility.
The package and protected access specifiers have been dealt with while dealing
with packages.

Private
It is narrowly visible and the highest level of protection that can possibly be obtained.
Private methods and variables cannot be seen by any class other than the one in which
they are defined. They are extremely restrictive but are most commonly used. Any
representation unique to the implementation is declared private. An object’s primary job
is to encapsulate its data and limit manipulation. This is achieved by declaring data as
private.

class pri {
private int x = 10;
void var( ) {
System.out.println ( “The private value is “ + x);
}
public static void main( String args[]) {
pri p = new pri( );
p.var( );
}
}
Save the file as pri.java
Compile the file using javac pri.java
Execute the file as java pri

The output is:


The private value is 10

The class pri has a private instance variable x. This variable can be accessed only inside
the class. The method var displays this variable using println method. The main method
creates an instance of the class and invokes var method. It is important to note that the
instance variable x of the object cannot be accessed directly from the main since it is
declared private. The following code, when included in main, will result in a compilation
error.

System.out.println( “value = “ + p.x);

To determine the class of an object:


To find out the class to which the object belongs, the getclass( ) can be used. This method
is defined in the object class and is available to all objects. The object class has a method
getname( ), which returns a String representing the name of the class. The following code
retrieves the class name of the object.

String s = Obj.getclass( ).getName( );

Alternatively, the instanceof operator can be used. This operator has two operands
namely, the object on the left and the name of the class on the right. The expression
returns a boolean depending upon the object being an instance of the named class or
anyone of its subclasses. For example, if a variable s is declared to be an instance of the
string class, then it can be checked if s is an instance of the String class as follows:
String s = new String( );
if ( s instanceof String) {
<set of statements>
}

Object Reference
Each new class created adds another type that can be used just like simple types. When a
new variable is declared, classname can be used as a type. Such variables refer to
instances or objects of that class. These variables are known as object references. An
instance is an individual copy of the class template with its own set of data called
instance variables. When the type of a variable is declared as a class, it has a default
value of null – a reference of type Object and is thus type-compatible with all other
classes. The null object has no value.

An object reference is a memory pointer. These pointers cannot be manipulated. Object


references point at an intermediate data structure which stores the type information as
well as the current address of the actual instance data.

Java Class Library


The Java class library provides a set of classes guaranteed as available in any commercial
Java environment. These classes are in the Java package. The Java Developer’s Kit,
comes with documentation for the entire Java class library which has descriptions of each
class’s instance variables, methods, constructors, and interfaces. Exploring the Java class
library and its method is a good way to start learning Java.
A list of the class packages that are part of the Java class library are:
java.lang: Classes that apply to the language itself which includes the object class, the
String class and the system class. It also contains the special classes for the primitive
types (Integer, Character, Float).
java.util: Utility classes such as Date as well as simple collection classes such as
Vector and Hashtable.
java.io: Input and output classes for writing to, and reading from streams and for
handling files.
java.net: Classes for networking support, including Socket and URL.
java.awt: (Abstract Window Toolkit) : Classes to implement a graphical user
interface, including classes for Window, Menu, Button Font, Checkbox. This package
also includes classes for processing images.
java.applet: Classes to implement Java applets, including the Applet class itself as
well as the Audioclip interface.

The development environment may also include additional classes that provide other
utilities or functionality. Although these classes may be useful, they will not be available
to others, as they are not part of the standard Java library. This is particularly important
for applets, because applets are expected to run on any platform. The classes inside the
Java package are guaranteed to be available in all Java environments.
Importing Class:
Classes external to a program must be imported before they can be used. To import a
class, the import keyword should be used as:
Syntax:
import <classname>;
The classes in Java are arranged in hierarchial order. The Java library consists of a
number of packages. These packages contain a set of related classes. The whole path of
the class must be specified to import a class from the Java library, For instance, to import
the Date class from the util package use the code:

import java.util.Date;
It is also possible to import all classes that belong to a package using * symbol.

import java.awt.*;
All the classes in java.lang package are automatically imported when a program is
compiled.

Open a new file and enter the code:


import java.awt.Point;
class Lib {
public static void main(String args[]) {
point p = new point(2,2);
p.x = 12;
p.y = 12;
System.out.println (“The value of p.x is “+p.x);
System.out.println (“The value of p.y is “+p.y);
}
}

Save the file as Lib.java


Compile the file using javac Lib.java
Run the file using java Lib

The output appears as:


The value of p.x is 12
The value of p.y is 12

The point class is imported in the program. An instance of this class is created inside the
main method. The variables in the object are initialized and displayed using println
method.

Command Line Arguments:


A generic Java program can be enabled to operate on different kinds of input by passing
command line arguments. Arguments to Java programs can be passed by appending them
to the command line when the Java program is run. These arguments can be grouped by
using double quotes that are removed before the arguments are passed to the program.
The Java program stores the command line arguments in the array of strings which is
passed to the main ( ) method in the program. Inside the main ( ) method, the arguments
can be handled by iterating over the array of arguments. The arguments are passed to the
main ( ) method as an array of strings and to treat them as non-strings, they are to be
converted to the specific type.

Let us see an example passing of command line arguments to a program.

Open a file and type the following code.

class Argument {
public static void main(String args[]) {
System.out.println ( “The first argument value is: “ +args[0]);
}
}

Save the file as Argument.java


Compile the file using javac Argument.java
Run the file as java Argument
The output appears as
The first argument value is : This is my first argument.

In this example, the main method outputs the first command line argument. The example
assumes that at least one argument is passed to the program. If the program is executed
without an argument, an error occurs. If more than one argument is passed, it is ignored.

Constructor
Constructors are called whenever an instance of a given class is created. A constructor
method is a special kind of method that determines how an object is initialized when
created. They have the same name as the class and do not have any return type.
When the keyword new is used to create an instance of a class, Java allocates memory for
the object, initializes the instance variables and calls the constructor methods. Every class
has a default constructor that does not take any argument and the body of it does not have
any statements. Constructors can be overloaded.

Open a file and enter the following code:

class Con {
int i;
int j;
Con ( int a, int b) {
i = a;
j = b;
}
void print ( ) {
system.out.println ( “ The addition of “ + i + “ and “ + j +” gives “ + (i + j));
}
public static void main(String args[]) {
Con c;
c = new con(10,10);
c.print ( );
System.out.println (“ “);
c = new con(25,25);
c.print ( );
System.out.println (“ “);
}
}
Save the file as Con.java
Compile the file using javac Con.java
Run the file using java Con

The output appears as

The addition of 10 and 10 gives 20


The addition of 25 and 25 gives 50
The constructor passes arguments is declared in the code. It also indicates the print
method which is used to display the values of the constructor arguments.

Calling Another Constructor


A constructor can be called from another constructor. When a constructor is written, the
functionalities of another defined constructor can be used. A call to the constructor can be
made from the constructor currently being defined. To call a constructor defined in the
current class, use:
this (arg1, arg2, arg3……….)
The arguments to this are the arguments to the constructor.

Open a file and type the following code:


class point {
int x,y;
point ( int x, int y) {
this.x = x;
this.y = y;
}
point ( ) {
this (-1,-1);
}
public static void main(String args[]) {
point p = new point ( );
System.out.println (“x =” +p.x+”, y = “+p.y);
p = new point (10,10);
System.out.println (“x =” +p.x+”, y = “+p.y);
}
}

Save the file as point.java


Compile the file using javac point.java
Execute the file as java point
The output appears as:
x = -1, y = -1

In this example, the second constructor calls the first constructor and initializes the
instance variables.

Finalizer:
Finalizer method function in contradiction to the constructor method. Finalizers are called
by garbage collector on an object, when garbage collection determines that there are no
more references to the object and its memory is reclaimed. A subclass overrides the
finalize method to dispose of system resources or to perform other cleanup. The finalizer
method is represented by finalize( ).
The object class defines a default finalizer method, which does nothing. To create a
finalizer method for the classes, the finalize( ) method can be overridden as shown in the
following:

Syntax:
protected void finalize ( ) {
<set of statements>
}

Any cleaning required may be included inside the body of the finalize( ) method. This
method can be called at any point of time. Calling finalize( ) need not trigger an object to
be garbage collected. Removing references to an object will cause it to be marked for
deletion. Finalizer methods are best used for optimizing the removal of an object.
Some points on finalize( ) method.
 Every class inherits the finalize( ) method from java.lang.Object
 The method is called by the garbage collector when I determines no more
references to the object exist.
 The Object finalize method performs no actions but it may be overridden by
any class
 Normally it should be overridden to clean-up non-Java resources i.e. closing
a file.
 If overriding finalize( ) method, it is good programming practice to use a
try-catch-finally statement and to always call super.finalize ( ).
Overloading Constructors:
In addition to overloading normal methods, we can also overload constructor methods.
In fact, for most real-world classes that we create, overload constructors will be a normal
one, not the exception. Constructors can also take varying numbers and types of
parameters. This enables creation of objects with the properties required. The constructor
takes a different number of arguments each time and gives the same to the print method
for display.

Example:
Open a file and type the following
public class Box
{
String iname;
int iqty;
int price;
Box ( int itemqty, String itemname, int itemprice) {
iname = itemname;
iqty = itemqty;
price = itemprice;
}
Box ( int q, String i1name) {
iname = i1name;
price = q;
iqty = price/10;
}
Box (String iiname, int iprice) {
iname = iiname;
price = (int) (iprice – (0.1));
}
void print( ) {
System.out.println (“ item name : “ +iname);
System.out.println (“ Quantity : “ +iqty);
System.out.println (“ price : “ +price);
}
public stati void main (String args[]) {
Box item;
item = new Box(10, “ Pen” 10);
item.print ( );
item = new Box ( 10, “Bag”);
item.print ( );
item = new Box ( “Toys”, 25);
item.print ( );
}
}
Save the file as Box.java
Compile it as javac Box.java
Execute the file as java Box

The output of the program is


Item name : Pen
Quantity : 10
Price : 10
Item name : Bag
Quantity : 1
Price : 10
Item name : Toys
Quantity : 0
Price : 25

Introducing Nested and Inner Classes:


Nested class:
It is possible to define a class within another class; such classes are known as nested
classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus,
if class B is defined within class A, then B is known to A, but not outside of A. A nested
class can either be static or non-static. While static nested classes are called as static
nested classes, non-static nested classes are called as inner classes. 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.
There are two types of nested classes: static and non-static. A static nested class is one
which has the static modifier applied. Since it 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 and because of this restriction, static nested classes are used seldom.

Inner class:
The most important type of nested class is inner class. An inner class is a non-static
nested class. It has access to all of the variables and methods of its outer class. An inner
class is a nested class whose instance exists within an instance of its enclosing class and
has direct access to the instance members of its enclosing instance.

Syntax:
class <Enclosingclass> {
class <Innerclass> {
<set of statements>
}
}

The interesting feature about the relationship between these two classes is not that the
innerclass is inside the Enclosingclass. The instance of the innerclass can exist only
within an instance of the Enclosingclass and it has direct access to instance variables and
methods of its enclosing instance. Thus, an inner class is fully within the scope of its
enclosing class.

Example:
Open a file and write the following:
class Outer
{
int outer_x = 100;
void test( )
{
Inner inner = new Inner ( );
inner.display ( );
// this is an inner class
class Inner
{
void display ( )
{
System.out.println (“display : outer_x = “ +outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String arg[])
{
Outer outer = new Outer ( );
Outer.test ( );
}
}

Output:

Display: outer_x = 100

In the program, an inner class named Inner is defined within the scope of class Outer.
Therefore, any code in class Inner can directly access the variable outer_x. An instance
method named display( ) is defined inside Inner. This method displays outer_x on the
standard output stream. The main( ) method of the example creates an instance of class
Outer and invokes its test( ) method. That method creates an instance of class Inner and
the display( ) method is called.

Garbage Collection:
A key feature of Java is its garbage-collected heap, which takes care of freeing
dynamically allocated memory that is no longer referenced. Since the heap is garbage-
collected, Java programmers do not have to explicitly free allocated memoty.
Garbage collection is the process of automatically freeing objects that are no longer
referenced by the program. This frees the programmer from having to keep track of when
to free allocated memory, thereby preventing many potential bugs.
Java has no malloc or free functions. Since every complex data structure is an object,
they are all allocated via the new operator, which allocates space for an object on the
heap of memory.
The memory available for objects is called a heap because the user doesn’t have to
think about it. It is just a loosely collected heap of object instances. From new keyword,
the user actually gets a handle to an object and not the memory address.
The actual memory allocated for this object may move around, as the program runs,
but the user doesn’t have to worry about that because this memory will be available for as
long as the program cares for it. As soon, as the user no longer have any references of any
kind to the object, the memory it is occupying will become available for reuse by the rest
of the system. The user doesn’t have to call free or delete. This is known as garbage
collection.
Garbage Collection occurs during the execution of the program. It will not occur simply
because one or more objects exist that are no longer used.
Garbage Collection can also be known as litter recycling, because the user doesn’t even
have to drag the objects to the curb to have them collected. It’s just dropping and
forgetting them. The garbage collector runs wherever the system is idle, or when a
requested allocation fails to find enough memory.

Summary:
A class is a template for multiple objects with similar features. The requirements for
the creation of a class include a source file with the class keyword in it followed by a
legal identifier and a pair of curly braces for the body.
Attributes are individual things that differentiate an object from another and determine
the appearance, state or other qualities. Class variables are global to a class and to all the
instances of the class.
The new operator creates a single instance of a named class and returns a reference to
that object. Methods are functions that are defined inside classes operating on instances
of those classes. The four levels of access control are public, package, protected and
private. The Java class library provides the set of classes that are guaranteed to be
available in any commercial Java environment. A constructor method is a special kind of
method that determines how an object is initialized when created. Constructors have the
same name as the class and do not have any return type. The constructors are different
from methods in this context.
Finalizer methods function in contradiction to the constructor methods. Finalizers
are called just before the object is garbage collected and its memory is reclaimed. An
inner class is a nested class whose instance exists within an instance of its enclosing class
and has direct access to the instance members of its enclosing instance. In Java
deallocation happens automatically. The technique that accomplishes this is called
garbage collection. Garbage Collection occurs during the execution of the program. It
will not occur simply because one or more objects exist that are no longer used.
Arrays and Strings
An array is an object that stores a list of items. Each slot in an array holds individual
elements. An array should be of single type, comprising of integers, Strings and so on. To
create an array, a variable to hold the array is declared, and a new object is created and
assigned to it. An array is a data structure which defines an ordered collection of a fixed
number of homogeneous data elements. This means that all elements in the array have the
same data type. The size of an array is fixed and cannot increase to accommodate more
elements. Arrays can be primitive data types or reference types. Each array object has an
instance variable, length, which specifies the number of elements the array can
accommodate.
Simple arrays are one-dimensional arrays, i.e. a simple list of values. Since arrays can
store object references, the object referenced can also be array objects. This allows
implementation of array of arrays.

Declaring Array Variables:


An array variable declaration has the following:

Syntax:
<elementType>[] <arrayName>;
Or
<elementType> <arrayName>[];
Where <elementType> can be a primitive datatype or a reference type (i.e. a class name
or an interface name). Note that the array size is not specified.
Array declaration is akin to any other variable declaration. Array variable indicates the
type of object that the array holds. It also indicates the name of the array followed by
empty brackets. The brackets may be inserted after the specification of the type instead of
succeeding the variable.
Example:
int arr[];

Creating Array Objects:


An array can be constructed for a specific number of elements of the elements type, using
the new operator. The resulting array reference can be assigned to a variable of the
corresponding type:

Syntax:
<arrayName> = new <elementType>[<noofElements>];
Initializing an Array:
Java provides the means of declaring, constructing and explicitly initializing an array in
one language construct:

Syntax:
<elementType>[] <arrayName> = { <arrayInitializerCode> };
This form of initialization applies to member as well as local arrays.
The initialization code in the block results in the construction and initialization of array.
Syntax:
int[] anIntArray = {1,3,49,2,7,15};

After declaring an array, create and assign objects to it. Two methods can be used to
create the array – initialization of the array or usage of the new keyword. The new
keyword creates an instance of the array. The number of elements that the array will hold
must be specified. The two modes of creating an array are given:
int iarr[] = new int [10];
char carr[] = {‘a’, ‘b’, ‘c’, ‘d’};

Example:
Open a file and enter the following:

class Array {
int i;
int da[] = {1,2,3,4,5};
void disp( ) {
System.out.println(“Displaying Array Details”);
For ( i=0;i<5;i++) {
System.out.println (da[i]);
}
}
public static void main(String args[]) {
Array d = new Array( );
d.disp( );
}
}
Save the file as Array.java
Compile the file using javac Array.java
Run the file as java Array

The output appears as


Displaying Array Details:
1
2
3
4
5

The array is being initialized at the point of declaration and hence, it is not necessary to
specify the number of elements that the array would hold or their size. The method, disp,
prints the array elements. In the main method, an instance of the class is created and the
disp method is invoked.
Accessing Array Elements:
The array subscript expression must be used to change and test the values of the array.
To access an element in the array, subscript expression is employed. Array subscripts
start with zero. All array subscripts are checked to ensure that they are within the
boundaries of the array. If the array subscript is calculated at runtime as part of a looping
control and it ends outside the boundaries of the array, then the interpreter produces an
error. To avoid overrunning the end of an array, its length can be tested using the length
instance variable. This variable is available for all array objects irrespective of the type.
The usage is,
int len = arr.length

Changing Array Elements:


A value can be assigned to a slot in the array by inserting an assignment statement after
the array access expression. When a value is assigned to a slot, a reference to that object
is created. When values are reassigned, references are also reassigned. Arrays of
primitive types copy the values from one slot to another. Having references to array
objects means that multiple references to the same object is possible.

Open a new file and enter the code:


class Number1 {
int i;
int arr[] = new int[10];
void add( ) {
int j = 100;
for (i=0;i<arr.length;i++) {
arr[i] = j;
j++;
}
}
void show( ) {
for ( i=0;i<arr.length; i++) {
System.out.println ( “The “ + i + “array element is “ + arr[i]);
}
}
public static void main (String args[]) {
Number1 n = new number1( );
n.add( );
n.show( );
}
}

Save the file as Number1.java


Compile the file as javac Number1.java
Execute the file as java Number1

The output appears as:


The 0 array element is 100
The 1 array element is 101
The 2 array element is 102
The 3 array element is 103
The 4 array element is 104
The 5 array element is 105
The 6 array element is 106
The 7 array element is 107
The 8 array element is 108
The 9 array element is 109

The add method assigns values to the array. The show method displays element of the
array. In the main method, a new instance of the class is created. The add method is
invoked to assign values that are displayed by calling the show method.

Multidimensional Arrays:
Since array elements can be an object reference and arrays are objects, array elements can
themselves reference other arrays. In Java, an array of arrays can be defined as follows:

Syntax: <elementType>[] [] ….[] <arrayName>;


Or
Syntax: <elementType> <arrayName>[] [] ….[];

Arrays of arrays are also loosely called Multidimensional arrays.

Syntax: int[] []mXnArray; // 2-dimensional array

is equivalent to

Syntax: int[] [] mXnArray[]; // 2-dimensional array

Java does not support multidimensional arrays. However, an array can be created. The
following example shows the creation of an array of arrays.

Example:
Open a file and enter the code.
class Coord {
int i = 0;
int j = 0;
int coor[] [] = new int[3][3];
void set( ) {
coor[0][0] = 1;
coor[0][1] = 0;
coor[0][2] = 0;
coor[1][0] = 0;
coor[1][1] = 1;
coor[1][2] = 0;
coor[2][0] = 0;
coor[2][1] = 0;
coor[2][2] = 1;
}
void show( ) {
for (i=0;i<3;i++) {
for (j=0;j<3;j++) {
System.out.println (coor[i] [j] + “ “);
}
System.out.println (“ “);
}
}
public static void main (String args[]) {
Coord c = new Coord( );
c.set ( );
c.show( );
}
}

Save the file as Coord.java


Compile the file using javac Coord.java
Execute the file using java Coord

The output appears as:


100
010
001

Values are set into the array using the set( ) method. The array is displayed using the
show( ) method.

AN INTRODUCTION TO STRINGS

String is an array of characters. String defines an object and a full description


of it requires an understanding of several object-related features. The String type is used
to declare String Variables. Consider the following fragments:

String str = “this is a test for string declaration “;


System.out.println(str);

Here, str is an object of type string. It is assigned the string “this is a test”. This string is
displayed by the println( ) statement.
Strings are instances of the class string. They are real objects, and hence, enable
communication, testing and modification. When a string literal is used in the program,
Java automatically creates instances of the string class.

Example:
Open a file and enter the following:
class Strings {
String names[] = {“Aashish”,”Anand”,”Arun”,”Adithya”};
void show( ) {
System.out.println (“My Favourite Names Are “);
}
}
public static void main (String args[]) {
String s = new Strings( );
s.show ( );
}
}

Save the file as Strings.java


Compile the file as javac Strings.java
Execute the file using java Strings

The output appears as:


My Favourite Names Are:
Aashish
Anand
Arun
Adithya
The code declares a string array and initializes it. The array is displayed using the or loop.

String Constructors:
The String class supports several constructors. To create an empty String, we have to call
the default constructor. Calling the default constructor with no parameters as shown
below can create an empty string:

String s = new String ( )


The above example will create an instance of String with no characters in it. In order to
create a String initialized with characters, we need to pass in an array of char to the
constructor.
String(char chars[ ])
The following code fragment creates a String instance with the three characters from the
char array as the initial value of the string s. The code will print the string “abc”.

Char chars[ ] = {‘a’,’b’,’c’};


String s = new String (chars);
System.out.println(s);

There is another constructor that follows the specification of the starting index and
number of characters that have to be used. The following code fragment explains this
constructor,

String(char chars[ ], int startIndex, int numchars)

For example:
Char chars[ ] = {‘a’,’b’,’c’,’d’,’e’,’f’};
String s = new String(chars,2,3);
System.out.println(s);

This would print “cde” because ‘c’ was at the index 2 and we specified count of 3
characters to be used to construct the String.

String API:
There are methods for:
 Getting the character at a given position within the string – charAt( )
 Seeing if a character or string exists within a string – indexOf( )
 Getting the number of characters in a String – length( )
 Extracting a substring from a string – substring( )

String Length:
The length of a string is the number of characters that it contains. To obtain this value,
call the length( ) method, shown as:
int length( )
The following fragments prints “3”, since there are three characters in the string s:
Char chars[] = {‘a’,’b’,’c’};
String s = new String(chars);
System.out.println(s.length( ) );

String Literals:
We can also use a string literal to initialize a String object. For example, the following
code fragment creates two equivalent strings:
Char chars[ ] = {‘a’,’b’,’c’};
String s1 = new String(chars);
String s2 = “abc”; // use string literal

Since a String object is created for every string literal, we can use a string literal any
place we can use a String object. For example, we can call methods directly on a quoted
string as if it was an object reference, as the following shows. It calls the length( ) method
on the string “abc”. As expected, it prints “3”.
System.out.println(“abc”.length( ) );
String concatenation:
Java does not allow operators to be applied to String objects. The one exception to this
rule is the operator, which concatenates two strings, producing a String object as the
result. This allows to group together the series of + operation. The ‘+’ sign does not mean
“addition” when it is used with String objects. The ‘+’sign does not mean “addition”
when it is used with String objects. When used with strings and other objects, the +
operator creates a single string that contains the concatenation of all its operands.

For example:

String age = “9”;


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

This displays the string “He is 9 years old.”

String concatenation with other data types:


We can concatenate strings with other types of data.
For example
int age = “9”;
String s = “He is “+age+” years old.”;
System.out.println(s);

In this case, age is an int rather than another String, but the output produced is the same
as before. This is because the int value in age is automatically converted into its string
representation within a String object. This string then concatenated as before. The
compiler will convert an operand to its string equivalent whenever the other operand of
the + is an instance of String.
intern( ) produces one and only string handle for each unique character sequence.

String conversion and toString( ):

The toString( ) method has this general form:


String toString( )
To implement toString( ), simply return a String object that contains the human-readable
string that appropriately string that describes an object of your class. By overriding
toString( ) for classes that you create, you allow the resulting strings to be fully integrated
into Java’s programming environment.

String Methods:
The String class provides a number of methods to compare and search strings. Some
important methods in this class are listed.
Method Use
length( ) Number of characters in String.
charAt( ) The char at a location in the string.
getChars( ), getBytes( ) Copy chars or bytes into an external array.
toCharArray( ) Produces a char[] containing the characters
in the String.
equals( ), equalsIgnoreCase( ) An equality check on the contents of the
two Strings.
compareTo( ) Result is negative, zero or positive
depending on the lexicographical ordering
of the String and the argument. Uppercase
and lowercase are not equal.
regionMatches( ) Boolean result indicates whether the region
matches.
startsWith( ) Boolean result indicates if the String starts
with the argument.
endsWith( ) Boolean result indicates if the argument is a
suffix.
indexOf( ), lastIndexOf( ) Returns-1 if the argument is not found
within this String, otherwise returns the
index where the argument starts.
lastIndexOf( ) searches backwards from
end.
substring( ) Returns a new String object containing the
specified character set.
concat( ) Returns a new String object containing the
original String’s characters followed by the
characters in the argument.
replace( ) Returns a new String object with the
replacements made. Uses the old String if
no match is found.
toLowerCase( ), toUpperCase( ) Returns a new String object with the case
of all letters changed. Uses the old String if
no changes need to be made.
trim( ) Returns a new String object with the
whitespace removed from each end. Uses
the old String if no changes need to be
made.
valueOf( ) Returns a String containing a character
representation of the argument.
intern( ) Produces one and only one String handle
for each unique character sequence
It is seen that every String method returns a new String object when it is necessary to
change the contents. Also notice that if the contents do not require any change, the
method will just return a handle to the original String. This saves storage and overhead.

Example:
Open a file and enter the code:
class String {
public static void main(String args[]) {
String s = “Now is the time for all good men” + “ to come to the aid of their
country” +” and pay their taxes”;
String s1 =”Hello world”;
String s2 = “Hello”;
String s3 = “HELLO”;
System.out.println(“index of t = “ +s.indexOf(‘t’));
System.out.println(“last index of t = “ +s.lastIndexOf(‘t’));
System.out.println(“index of (t,10) =” +s.indexOf(‘t’,10));
System.out.println(“last index of (t,60) = “ +s.lastIndexOf(‘t’,60));
System.out.println(s1.substring(6));
System.out.println(s1.substring(3,8));
System.out.println(s2.concat(“World”));
System.out.println(s2.replace(‘l’,’w’));
System.out.println(s3.toLowerCase( ));
System.out.println(s1.trim( ));
}
}
Save the file as String.java
Compile the file as javac String.java
Execute the file as java String

The output appears as:


Now is the time for all good men of the country to come to the aid of their country and
pay their taxes
index of t = 7
last index of t = 83
index of (t,10) = 11
last index of(t,60) = 55
world
lo wo
HelloWorld
Hewwo
hello
Hello world

The String Class Vs The StringBuffer Class


Java has two classes with similar contents, but different functionality. These are the
String and StringBuffer classes. Having these two separate classes probably allows Java
to be much more efficient in its use of memory.
The two classes differ in that instances of the String class cannot be modified in place,
while instances of the StringBuffer class can be modified in place.
Since instance of the String class cannot be modified in place, calling a method such as
toUpper or toLower on a String typically causes another String to be returned. This can
force the use of lots of temporary variables. If you are building a string, the best way to
do it is with a StringBuffer and the StringBuffer.append( ) method. Adding to a string is
way slower.

StringBuffer:
StringBuffer is a peer class of String that provides much of the common use functionality
of strings. Strings represent fixed-length character sequences.StringBuffer represents
varied length character sequences. StringBuffer may have characters and substrings
inserted in the middle, or appended at the end. The compiler automatically creates a
StringBuffer to evaluate certain expressions, in particular when the overloaded operators
+ and += are used with String objects.

public class buf {


public static void main(String args [] ) {
String foo = “foo”;
String s = “abc” + foo + “def” + Integer.toString (47);
System.out.println(s);
// The “equivalent” using StringBuffer:
StringBuffer sb = new StringBuffer(“abc”); // Creates string!
sb.append (foo);
sb.append (“def”); // Creates String!
Sb.append (Integer.toString (47));
System.out.println (sb);
}
}

Save the file as buf.java


Compile the file using javac buf.java
Run the file using java buf

The output appears as:


abcfoodef47
abcfoodef47

In the creation of String s, the compiler is actually performing the rough equivalent of the
subsequent code that uses sb. A StringBuffer sb is created and append( ) is used to add
new characters directly into the StringBuffer object. While this is more efficient, it is
worth noting that each time we create a quoted character string like “abc” and “def”, the
compiler actually turns those into String objects. Thus, there may be more objects created
than we expect, despite the efficiency afforded through StringBuffer.

StringBuffer methods

Method Use
toString( ) Creates a String from this StringBuffer.
length( ) Returns the number of characters in the
StringBuffer.
capacity( ) Returns current number of spaces allocated.
ensureCapacity( ) Makes the StringBuffer hold atleastthe
desired nmber of spaces.
setLength( ) Truncates or expands the previous
character string. If expanding, pads with
nulls.
charAt( ) Returns the char at that location in the
buffer.
setCharAt( ) Modifies the value at that location.
getChars( ) Copy chars into an external array. There is
no getBytes( ) as in String.
Append( ) The argument is converted to a string and
appended to the end of the current buffer,
increasing the buffer if necessary.
insert( ) The second argument is converted to a
string and inserted into the current buffer
beginning at the offset. The size of the
buffer is increased, if necessary.
reverse( ) The order of the characters in the buffer is
reversed.

The most commonly-used method is append( ), which is used by the compiler when
evaluating String expressions containing the ‘+’ and ‘+=’ operators. The insert( ) method
has a similar form, and both methods perform significant manipulations to the buffer
rather than creating new objects.


Casting And Converting:
Casting is used to convert the value of one type to another. Casting is the mechanism of
converting the value of an object or primitive type into another type. The result of the
cast is a new reference or value. Casting does not affect the original object or value. The
concept that is involved in casting is simple enough but for the fact that Java has both
primitive types and object types. Casting is of three types namely, casting between
primitive types, casting between object types and converting primitive types to objects
and then extracting primitive values out of those objects.
TYPE CONVERSION AND CASTING
In any application, there may be many situations in which one data type may need to
be converted to another data type. Also, since java is an object oriented language, we
may have situations where we need to convert between parent and child classes. These
transformations are achieved by means of –what is called process-in java.

TYPES OF CASTING
There are basically 2 types of casting: Implicit casting and explicit casting.
Implicit casting means simply assigning one entity to another without any transformation
guidance to the compiler. If the two types are compatible, then java will perform the
conversion automatically.
Example:
int t = 100;
long h =t;// Implicit casting
CASTING INCOMPATIBLE TYPES

Although the automatic type conversions are helpful, they will not fulfill all needs.
For example, what if you want to assign a long value to a int variable? This conversion
will not be performed automatically, because a int is smaller than a long. This kind of
conversion is sometimes called a narrowing conversion or explicit casting. Explicit
casting means specifically informing the compiler about the transformation that is
expected.
long h = 100.00;
int t = (int) h; // Explicit casting
A different type of conversion will occur when a floating-point value is assigned to an
integer type: truncation. Integers do not have fractional components. Thus, when a
floating-point value is assigned to an integer type, the fractional component is lost. When
integer value is assigned to a floating-point value then a decimal point with two zeros
will be added.
For example:

Class Conversion
{
public static void main(Stringarg[])
{
byte b;
int i = 256;
double d = 323.142;
System.out.println(“\n conversion of int to byte”);
b = (byte) i;
System.out.println(“i and b” + i + “ “ + b);
System.out.println(“\n conversion of double to int”);
i = (int) d;
System.out.println(“d and i “+ d + “ “ +i);
System.out.println(“\nconversion of double to byte”);
b = (byte) d;
System.out.println(“d and b “+ d + “ “ +b);
}
}

Save the file as Conversion.java and compile it as javac Conversion.java


Execute the file as java Conversion.
The output of the program is
Conversion of int to byte
i and b 256 1
Conversion of doubt to int
d and i 323.142 323
Conversion of double to byte
d and b 323.142 67

Casting Objects:
Instances of class can be cast to instances of other classes. There is only one restriction,
the class of the object being cast and the class that it is being casted to must be related by
inheritance. Some objects may not explicitly cast. An instance of a subclass can be used
anywhere a superclass is expected because a subclass contains all the information that a
superclass contains. Casting an object to an instance of one of that object’s superclass
loses the information the original subclass provided and requires a specific cast. To cast
an object to another class,use:
(classname) object;
The classname is the name of the class we want to cast the object to. Object is a reference
to the object being cast. Casting creates a reference to the old object of the type
classname and the old object of the type classname and the old object continues to exist.

Converting primitive Types to Objects:


Converting primitive types to objects cannot be done explicitly. Primitive types and
objects are two distinct things. Java.lang package includes several special classes that
correspond to each primitive type. For example, Integer for int, Float for float, Boolean
for Boolean etc. These classes can be used to create objects that encapsulate the primitive
types. To convert the values back into primitive values, we have methods that can be
utilized.

Summary:
An array is a data structure which defines an ordered collection of a fixed number of
homogeneous data elements. Array declaration is similar to any other variable
declaration. To change and test the values of the array, use the array subscript expression.
To assign a value of slot, include an assignment statement after the array access
expression. Java does not multidimensional arrays. However, an array of arrays can be
created.
A combination of characters is known as String. Strings are instances of the class String.
Casting is a mechanism of converting the value of an object or primitive type into another
type. Casting between primitive types allows conversion of one primitive type to another.
This occurs most commonly between numeric types. Conversion of primitive types to
objects cannot be done explicitly.
INHERITANCE

Inheritance is one of the cornerstones of object-oriented


programming because it allows the creation of hierarchial classifications. Using
inheritance, we can create a general class that defines traits common to a set of related
items. This class can be then inherited by other, more specific classes, each adding those
things that are unique to it. In Object-oriented programming, inheritance refers to the
properties of a class being available to many other classes. A derived class / sub class is
one that has been created from an existing class. It inherits all of the instance variables
and methods defined by the superclass and add its own, unique elements. The original
class is called as base class / super class.
The main advantage of inheritance is reusability of code. Once a class is defined and
debugged, it can be used to create new subclasses. In addition to saving a lot of time and
effort, retyping the same code becomes unnecessary. Data and methods of a super class
are declared private, the derived class cannot access them. To deal with this situation,
protected is used.
Inheritance is the process of deriving a class from a super class or a base class. The
derived class has a larger set of properties than its base class. To inherit a class, we
simply incorporate the definition of one class into another by using the extends keyword.
When a subclass is derived from a single super class, the inheritance is called single
inheritance and when it is derived from more than one super class, it is called multiple
inheritance. Java supports single inheritance only.

For example:
Organism Class Hierarchy

Organism

Living Organism Non-Living Organism

A class called Living Organism is derived from the class called Organism. Every instance
of the Living Organism class, apart from Organism, has its own features. From the class
called car, different classes based on model, color, quality, etc. can be derived. Figure
shows some of the subclass of Organism super class.

A simple example:

// Create a super class


Class A {
int i, j;
void showij( )
{
System.out.println(“i and j:” + i + “” + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk( )
{
System.out.println(“k:” + k);
}
void sum( ) {
System.out.println(“i + j + k:” + (i + j + k));
}
}

class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A( );
B superOb = new B( );
// The superclass may be used by itself.

superOb.i = 10;
superOb.j = 20;
System.out.println(“Contents of superOb:”);
superOb.showij( );
System.out.println( );

/* The subclass has access to all public members of its superclass. */

subOb.i = 7;
subOb.j = 8;
subOb.k =9;
System.out.println(“Contents of subOb:”);
subOb.showij( );
subOb.showk( );
System.out.println(“Sum of i, j and k in subOb:”);
subOb.sum( );
}
}
The output of the program is:
Contents of superOb:
i and j: 10 20

Contents of subOb:
i and j: 7 8
k: 9

Sum of i, j and k in subOb:


i + j + k: 24

The subclass B includes all of the members of its superclass A. This is why subOb
can access i and j and call showij( ). Inside sum( ), i and j can be referred to directly, as if
they were part of B.
Even though A is a superclass for B, it is also a completely independent, stand-alone
class. Being a superclass for a subclass does not mean that the superclass cannot be used
by itself. Further, a subclass can be a superclass for another subclass.
The general form of a class declaration that inherits a superclass is shown:

class subclass-name extends superclass-name


{
// body of class
}

We can only specify one superclass for any subclass that we create. Java does not
support the inheritance of multiple superclasses into a single subclass.

Java Class Hierarchy:

The Java class hierarchy begins with the class object as its super class. This is the most
common class in the hierarchy. Each subclass of the hierarchy apart from inheriting the
features of the object class has distinct features. Each of the subclasses has been defined
for a specific purpose. Thus the object class definition is found to be abstract and further
down the hierarchy, there are clear specifications to define an object. If a class is defined
without any superclass, the object class acts as its super class.
Boolean

Character

Object
Compiler

String

Number

Class

Runtime

Thread

Java Class Hierarchy

Super classes must be defined in such a way that its information can be used
time and again by its derived classes. Changing a class or inserting a class in the
hierarchy reflects in all its derived classes. As a result, the need to recompile all these
classes is eliminated. When an object calls a method, Java compiler first checks for the
method definition in the same class in which the method is defined. If it is not found, it
checks its superclasses one by one. If it is unable to locate the method definition, then the
compiler issues an error message.

To run a file, these are the steps:


The base class and the derived class are created and stored in separate files.
The filename for any class is similar to the class name with .java extension.
The files containing base class and derived class are compiled separately and the
derived class alone is run, since it contains the main( ) method.
To run the base class separately, include the main( ) method and initialize an object
of the base class type.

Example:
Open a file and type the following:

class Wood {
String type = “teak”;
String finish = “coarse”;
void showDet ( ) {
System.out.println (“ instance of class” + this.getclass( ).getName( ));
System.out.println (“-----------------------------------“);
System.out.println (“type of wood –“ + type);
System.out.println (“finish is – “ +finish);
}
}

Save the file as Wood.java and compile


Do not run this file

Open a new file and enter the following code

class Woodtable extends Wood {


int legs=4;
void show( ) {
System.out.println (“Woodtype – “ + type);
System.out.println (“finish – “ + finish);
System.out.println (“legs – “ + legs);
}
public static void main (String args[ ]) {
Woodtable t = new Woodtable ( );
t.show( );
}
}

Save the file as Woodtable.java


Compile the file and run the class file using java

The output appears as:

Woodtype – teak
finish - coarse
legs – 4

The word extends indicates that Woodtable has been derived from the class Wood. An
attribute called legs and a method called show( ) are defined in the subclass. It not only
displays the details of its attribute, but also of the base class.

Creating a Multilevel Hierarchy and the use of super( ):


We have been using simple class hierarchies that consist of only a superclass and a
subclass. However, we can build hierarchies that contain as many layers of inheritance as
we wish. It is perfectly acceptable to use a subclass as a superclass of another. For
example, given three classes called A, B and C. C can be a subclass of B, which is a
subclass of A. when this type of situation occurs, each subclass inherits all of the traits
found in all of its superclasses. In this case, C inherits all aspects of B and A.

When Constructors are called:


Constructors are methods that have the same name as that of the class. It initializes
the values for all the class attributes. Constructors cannot be overridden. This is because
each class has its constructor with its own name.
When a class hierarchy is created, the constructors are called in order of derivation, from
superclass to subclass. Since super( ) must be the first statement executed in a subclass’
constructor, this order is the same whether or not super( ) is used. If super( ) is not used,
then the default or parameterless constructor of each superclass will be executed. The
following program explains when constructors are executed:

// Create a super class.


class A {
A( ) {
System.out.println(“Inside A’s constructor.”);
}
}
// Create a subclass by extending class A.
class B extends A {
B( ) {
System.out.println(“Inside B’s constructor.”);
}
}
// Create another subclass by extending B.
class C extends B {
C( ) {
System.out.println(“Inside C’s constructor.”);
}
}

class CallingCons {
public static void main(String args[]) {
C c = new C( );
}
}

The output appears as:

Inside A’s constructor


Inside B’s constructor
Inside C’s constructor

The constructors are called in order of derivation.

Constructor functions are executed in order of derivation, because a superclass has no


knowledge of any subclass. Any initialization it needs to perform is separate from and
possibly prerequisite to any initialization performed by the subclass. Therefore, it must be
executed first.

Method Overriding:
Methods in the derived class can have a similar name as the base class. This is to ensure
that a method, when called in the program, works the same for both the base and the
derived class.
In the class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to override
the method in the superclass. When an overridden method is called from within a
subclass, it will refer to the version of that method defined by the subclass. The version of
the method defined by the superclass will be hidden.
When a method is called on an object, the Java compiler first searches for the method in
the class of that object. If the method is not found there, then the compiler searches for
the method in the hierarchy until it is found.

// Method overriding.

class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show( ) {
System.out.println(“i and j: “ + i + “ “ + j);
}
}

class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}

// display k – this overridden show( ) in A


void show( ) {
System.out.println(“K:” + K);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show( ); // this calls show( ) in B
}
}
The output appears as:
K: 3

When show( ) is invoked on an object of type B, the version of show( ) defined within B
is used. That is, the version of show( ) inside B overrides the version declared in A. If we
wish to access the superclass version of an overridden function, we can do so by using
super.

Usage of the keyword super before the methods getDet( ) and showDet( ) in the derived
classes, enables accepting and displaying of details for all three classes. The method
getDet( ) will have an extra line before the try block in both the class and category class
as follows

super.getDet( );

The showDet( ) method also has an extra line before displayingthe details of its own
class, to display the details of its base classes as follows:

super.showDet( );

Why Overridden Methods:


Overridden methods allow Java to support run-time polymorphism. Polymorphism is
essential to object-oriented programming for one reason: it allows a general class to
specify methods that will be common to all its derivatives, while allowing subclasses to
define the specific implementation of some or all of those methods. Overridden methods
are another way that Java implements the “one interface, multiple methods” aspect of
polymorphism.

Using Abstract Classes:

Abstract class ensures in some way that a subclass does indeed, override all necessary
methods. Java’s solution to this problem is the abstract method. We require that certain
methods to be overridden by subclasses by specifying the abstract type modifier.
To declare an abstract method, use this general form:

abstract type name(parameter-list);


Here no method body is present. Any class that contains one or more abstract methods
must also be declared abstract. To declare a class abstract, we can simply use the abstract
keyword in front of the class keyword at the beginning of the class declaration. There can
be no objects of an abstract class. That is, an abstract class cannot be directly instantiated
with the new operator. Such objects would be useless, because an abstract class is not
fully defined. Also, we cannot declare abstract constructors, or abstract static methods.
Any subclass of an abstract class must either implement all of the abstract class must
either implement all of the abstract methods in the superclass, or be itself declared
abstract.

Using Final with Inheritance:


The keyword final has three uses. First, it can be used to create the equivalent of a named
constant. The other two uses of final apply to inheritance.

Using Final to prevent Overriding:


While method overriding is one of Java’s most powerful features, there will be times
when we will want to prevent it from occurring. To disallow a method from being
overridden, specify final as a modifier at the start of its declaration. Methods declared as
final cannot be overridden. The following fragment explains final:

class A
{
final void meth( )
{
System.out.println(“This is a final method.”);
}
}
class B extends A
{
void meth( ) { //ERROR! Can’t override.
System.out.println(“Illegal!”);
}
}

As meth( ) is declared as final, it cannot be overridden in B. If we attempt to do so, a


compile-time error will result.

Using Final to prevent Inheritance:

Sometimes we need to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final, declares all of its methods as final too. It
is illegal to declare a class as both abstract and final since an abstract is incomplete by
itself and relies upon its subclasses to provide complete implementations.
Here is an example of a final class:
final class A {
// ….
}
// The following class is illegal.
Class B extends A { // ERROR! Can’t subclass A
//……
}
As a common implication, it is illegal for B to inherit A since A is declared as final.

Summary:

Inheritance is one of the cornerstones of object-oriented


programming because it allows the creation of hierarchial classifications. Using
inheritance, we can create a general class that defines traits common to a set of related
items. In Object-oriented programming, inheritance refers to the properties of a class
being available to many other classes. The Java class hierarchy begins with the class
object as its super class. This is the most common class in the hierarchy. Abstract class
ensures in some way that a subclass does indeed, override all necessary methods.

PACKAGE & EXCEPTION HANDLING

Java allows to group classes in a collection called a package. Packages are convenient
for organizing the work and for separating the work from code libraries provided by
others. It is possible to run out of unique names for classes in a big programming
environment. There may be situations when two or more persons use the same name for
their classes. So, Java provides us with a feature called package to avoid this problem.

Packages contain a set of classes in order to ensure that class names are unique.
Packages are containers for classes that are used to compartmentalize the class name
space. Packages are stored in a hierarchial manner and are explicitly imported into new
class definitions.

CLASSPATH Variable:
Whenever a class is created without any package statement, it is implied that the class is
included in Java’s default package. In case of writing small programs it is not necessary
for the package name to be mentioned. The necessity for packages can be understood in
real time application environment.
The Java compiler and the interpreter search the .class files in the path specified in
CLASSPATH environment variable. The current working directory is, by default,
included in this variable. Hence, it is possible to compile and execute the programs from
the existing directory. In case of creating a package, ensure that the root directory of the
package is included in the CLASSPATH variable.
Creation of a Package:
The following steps are involved in the creation of a package.
 Create a directory, which has the same name as the package
 Include package command, along with the package name, as the first statement in
the program.
 Write class declarations
 Save the file in the directory as NameOfClass.java where NameOfClass is the
name of the class
 Compile this file using javac
 There are two ways of using this program – change to previous level directory
and use java packageName.className or set the CLASSPATH variable
accordingly.
It explains the creation of a sample package and subpackage and their usage of the same
in a program.

Example:
Open a file and enter the following code:
Create a directory called pack

package pack;
public class Class1 {
public static void main( ) {
System.out.println(“hello”);
}
}

Save the file as Class1.java inside the pack directory.

A package called pack has now been created which contains a class Class1.
 Create a subdirectory called subpack inside the pack directory\
 Open a new file and enter the following code:

package pack.subpack;
public class Class2 {
public static void farewell( ) {
System.out.println(“bye”);
}
}

Save the file as Class2.java inside the subpack directory


A subpackage called subpack has now been created with class Class1 in it.

Open a file and enter the following code:

import pack.*;
import pack.subpack.*;
Class Importer {
public static void main(String arg[]) {
Class1.greet( );
Class2.farewell( );
}
}

Save the file as Importer.java in the root directory of the package.


Compile the file using javac Importer.java
Run the file using java Importer

The output appears as:

hello
bye

Access Protection:
Java has different types of access specifiers namely private, public, protected, private
protected and package. By default, variables and methods declared within a class without
access specifiers are accessible to all classes within the same package.

Importing Packages:
To make use of classes within different packages, the import statement is used. Once
imported, the classes within the package can be used by the program. All standard
packages of Java are included within a package called java. By default, all programs
import the java.lang package. Specific classes belonging to one particular package can be
imported or all of them can be simultaneously imported using *.
java.awt.Graphics. imports the Graphics class of the awt package into the program and
java.awt.* imports all the classes of the awt package into the program. User-defined
packages can also be imported just like the standard packages.

Type the following command at the command prompt, to create the p1 directory.
mkdir p1
Open a new file and enter the following code:

// Note declarations of the class


package p1;
public class Lmn {
public void m3( ) {
System.out.println(“inside package p1 – class Lmn”);
}
}
Save the file as Lmn.java in the p1 directory
Change the current directory to p1
Compile the file using javac Lmn.java
In order to use the above created package p1 within a program, the methods and classes
within it should be declared as public. This is the reason for declaring the method m3( )
as a public method.

Open a file and enter the following code:

// Uses package p1
import p1.*;
class Testpack {
public static void main(String args[]) {
Lmn a = new Lmn( );
System.out.println(“Creating an object of p1 package Lmn class….”);
System.out.println(“Possible because of importing”);
System.out.println(“Calling method of Lmn class”);
System.out.println(“ ---------------------------“);
a.m3( );
System.out.println(“----------------------------“);
}
}

Save the file as Testpack.java in any directory other than p1


Change the directory to the directory in which Testpack.java resides
Compile the program using javac Testpack.java
Run the program using java Testpack

The output appears as:

Creating an object of p1 package Lmn class….


Possible because of importing
Calling method of Lmn class
-------------------------.
inside package p1 – class Lmn
-------------------------.

This program imports Lmn class from package p1. An object of this class is created and
the method m3( ) within it is called.

INTERFACES

An interface is Java’s way of dealing with the common situation of wanting a class to
reflect the behavior of two (or even more) parents. This is often called multiple
inheritance. Though Java possesses most of the features of c++, multiple inheritance is
not supported by Java. In order to balance this drawback, the originators of Java have
introduced the idea of interfaces. An interface consists of a set of method definitions. Any
class implementing it should provide code for all its methods.

An interface is a collection of abstract behavior that individual classes can


implement. It is defined like a class.
Syntax:
<access> <interfaceName> {
<returnType> <methodName1> (<parameter-list>);
<returnType> <methodName2> (<parameter-list>);
.
.
.
<type> <variableName1> = <value>;
<type> <variableName2> = <value>;
.
.
.
}

Here access is either public or without specification and its accessibility remains as
mentioned. The keyword interface implies that the following method definitions form an
interface rather than a class definition. The interface should not contain implementation
for its methods. Any method belonging to an interface, which is implemented within a
class, should be declared as public.
Variables can also be declared within an interface. When variables are included within an
interface, they become final and static i.e. the variables cannot be changed by the class
implementing them.

Properties of Interfaces:
Although interfaces are instantiated with new, they have certain properties similar to
ordinary classes. For example, once we set up an interface, we can declare that an object
variable will be of that interface type.

Comparable x = new Tile(….);


Tile y = new Tile(…);

if (x.compareTo(y) < 0)…


We can always assign an object variable of a type that implements an interface to an
object variable declared to be of that interface type. Next, we use instanceOf to check if a
object is of a specific class, we can use instanceOf to check if an object implements an
interface:

If (anObject instanceof Comparable) {…..}


Also, nothing prevents from extending one interface in order to create another. This
allows for multiple chains of interfaces that go from a greater degree of generality to a
greater degree of specialization. For example, suppose we had an interface called
Moveable.

public interface Moveable


{
public void move(double x, double y);
}
Then , we could have an interface called Powered that extends it:

public interface Powered extends Moveable


{
public String powerSource( );
}

Although we cannot put instance fields or static methods in an interface, we can supply
constants in them.
For example:
Public interface Powered extends Moveable
{
public String powerSource(PoweredVehicle);
public static final int SPEED_LIMIT=95;}
Classes can implement multiple interfaces. This gives the maximum amount of flexibility
in defining a class’ behavior. For example, Java has an important interface built into it,
called Cloneable. If class implements Cloneable, the clone method in the object class will
make a bitwise copy of the class’ objects.

Class Tile extends Rectangle implements Cloneable,Comparable


We need to use commas to separate the interfaces that describe the characteristics which,
is supplied.

The Cloneable Interface:


When we make a copy of a variable, the original and the copy are references to the
same object.
This means a change to either variable also affects the other.

Day bday = new Day(1953, 11, 5);


Day d = bday;
d.advance(100); // oops – also changed bday

The clone method is a protected method of object, which means that our code cannot
simply call it. Only the Day class can clone Day objects.

Implementation:
The methods belonging to an interface are looked up at runtime. Usually, when a method
of a class is called from another method, Java compiler ensures that its definition exists
and is compatible. This leads to static and nonextensible class environment. Thus when a
method has to be used by many classes, it is pushed higher up in the hierarchy, to ensure
that it is available to all of them. Interfaces provide a different approach. They collect
such methods and disconnect them from their hierarchy. Thus classes are able to access
methods of an interface or a series of interfaces.

Interface References:
It is possible to declare variables, which have reference to an interface rather than a
class. An object thus created can access only the implemented method and cannot access
methods of its own class.

Variables in Interfaces:
Variables can be declared within an interface. The advantage of declaring variables
within an interface is that they become globally available to all classes and need not be
declared explicitly in classes implementing them.

Exception Handling:
The Java programming language provides a mechanism known as exception to help
programs report and handle errors. When an error occurs, the program throws an
exception. It means that the normal flow of the program is interrupted and that the
runtime environment attempts to find an exception handler—a block of code that can
handle a particular type of error.

There are five keywords for handling the exceptions. They are as follows- try, catch,
finally, throws and throw.
The try statement identifies a block of statements within which an exception might be
thrown.
The catch statement must be associated with a try statement and identifies a block of
statements that can handle a particular type of exception. The statements are executed if
an exception of a particular type occurs within the try block.
The finally statement must be associated with a try statement and identifies block of
statements that are executed regardless of whether or not an error occurs within the try
block.
The throws statement is used when a method is capable of causing an exception that it
does not handle, it must specify this behavior so that callers of the method can guard
themselves against that exception.
The throw statement enables a program to throw an exception explicitly.

Exception Types:
Unchecked exceptions
Checked exceptions

All exception types are subclass of the built-in class Throwable. It helps to handle
exceptions and errors. The Throwable class has two subclasses – Exception and Error.
Thus, Throwable is at the top of the exception class hierarchy. Error conditions are
normally not trapped by Java programs. Error conditions normally occur in case of
failures, which cannot be handled by programs. Exception of type Error are used by the
Java run-time system to indicate errors having to do with run-time environment. Stack
overflow is an example of error condition.
Exceptions can be caught or re-thrown to a calling method.

The RuntimeException Class:


The main subclass of Exception class is the RuntimeException class. This class has about
30 subclass, many of them are further subclassed. This class generates error that occurs
during the execution of a program.
Unchecked Exceptions:
The RuntimeException class and its subclasses are not so important for what they do,
but for what they do not do. Exceptions instantiated from RuntimeException and its
subclasses are referred as unchecked exceptions.
Basically, an unchecked exception is a type of exception that we can optimally handle, or
ignore. If we elect to ignore the possibility of an unchecked exception and one occurs,
our program will terminate. If we elect to handle an unchecked exception and one occurs,
the result will depend on the code that we have written to handle the exception.
Checked Exceptions:
All exceptions instantiated from the Exception class or from subclasses of Exception
other than RuntimeException and its subclasses must either be:
 Handled with a try block followed by a catch block (or)
 Declared in a throws clause of any method that can throw them
In other words, checked exceptions cannot be ignored when we write the code in our
methods. The Exception classes in this category represent routine abnormal conditions
that should be anticipated and caught to prevent program termination.
Checked by the Compiler:
Our code must anticipate and either handle or declare checked exceptions. Otherwise, our
program would not compile. (These are exception types that are checked by the
compiler.)

Default Exception Handling:


When a program throws an exception, it comes to a stop. This exception should be
caught by an exception handler and dealt with immediately. In case of provision of an
exception handler, the handling is done by handler. Suppose there are no handlers, the
Java runtime system provides default handlers. This displays a string, which describes the
exception and the point at which the exception occurred, after which the program
terminates.

Object

Throwable

Error Exception

IOException RuntimeException
Using try and catch:
If there is a possibility of an exception being generated in a program, it is better to handle
it explicitly. This can be handled by using try and catch keywords. Doing so, it provides
two benefits. First, it fixes the error. Second, it prevents the program from terminating
automatically.
To guard against and handle a run-time error, simple enclose the code inside the try
block. Immediately following the try block include the catch clause. The catch clause can
have statements explaining the cause of the exception generated. The scope of each
clause is restricted to a try block. It is possible to have multiple catch statements for one
try block. The exception of a program can continue once the exception has been handled.

General form:

try {
statements(s)
} catch (exceptiontype name) {
statements(s)
} finally {
statements(s)
}

Example:

Open the file and type the following code:

public class Exc


{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 56 / d;
System.out.println (“this will not be printed”);
}
catch(Exception e)
{
System.out.println(“Division by zero”);
}
System.out.println(“After catch statement”);
}
}

Save the file as Exc.java


Compile the file using javac Exc.java
Run the file as java Exc
The output is:

Division by zero
After catch statement.

Multiple catch Statement:


In some cases, more than one exception could be raised by a single piece of code. To
handle this type of situation, two or more catch clauses are used, each catching a different
type of exception. These catch statements are searched by the exception thrown in order.
When an exception is thrown the first one type matches the exception continues after the
try/catch block.

Example:

Open a file and enter the following code:

class multicatch
{
try
{
int c[] = {1};
// array of one element is declared.
c[5] = 99;
// here value is assigned to fifth element in array.
System.out.println(“c =” +c[5]);
}
catch(ArithmeticException e )
{
System.out.println(“ divide by 0: “+e);
}
catch(ArrayIndexOutOf BoundsException e)
{
System.out.println(“array index oob: “ +e);
}
System.out.println(“after try/catchblocks:”);
}
}

Save the file as muticatch.java


Compile the file as javac multicatch.java
Run the file as java multicatch

Finally statement:
When an exception is generated in a program, sometimes it may be necessary to perform
certain activities before termination. The activities may be closing of a file, deleting a
graphics object created, etc. In such cases, the try block, apart from the catch clause, also
has finally block within which activities mentioned above can be performed. This block
is executed after the execution of statements within the try/catch block. In case an
exception is thrown, the finally block will be executed even if no catch matches it. The
finally block can be used to handle any exception generated within a try block. It may be
added immediately after the try block or after the last catch block.
Example:
Open a file and enter the following:

import java.io.*;
class FinallyException {
public static void main(String args[]) {
try {
InputStream f1 = null;
int size = f1.available( );
for (int i = 0;i<size; i++) {
System.out.println((char)f1.read( ));
}
} catch (IOException e) { }
catch (NullPointerException n) {
System.out.println(“exception generated : “ +n);
}
finally {
System.out.println(“---------------------------.”);
System.out.println(“inside finally “);
System.out.println(“Welcome to DMISS”);
System.out.println(“-------------------------.”);
}
}
}

Save the file as FinallyException.java


Compile the file using javac FinallyException.java
Run the file as java FinallyException

The output of the program is:

Exception generated : java.lang.NullPointerException


-------------------------------.
inside finally
Welcome to DMISS
----------------------.

The above program creates an InputStream object and initializes it to null. Utilizing this
object, it checks for the size of the file and tries to read the contents within the for loop.
Since the InputStream object is initialized to null, a NullPointerException is generated
while trying to read it. This is caught by the catch clause. After the execution of the
statements inside the catch clause, finally clause is reached. Once the statement inside,
this block are executed, the program terminates.

The throws Statement:


Whenever a program does not want to handle exceptions using the try block, it can use
throws clause. The throws clause is responsible to handle the different types of
exceptions generated by the program. This clause usually contains a list of the various
types of exceptions that are likely to occur in the program.
Open a file and enter the following code:

// to describe usage of throws clause


class Throws {
public static void main( String args[]) throws ArithmeticException {
System.out.println(“inside main”);
int i = 0;
int j = 40 / i;
System.out.println(“ this statement is not printed”);
}
}

Save the file as Throws.java


Compile the file as javac Throws.java
Run the file as java Throws

The output appears:

inside main
Exception in thread “main” java.lang.ArithmeticException: / by zero
At ThrowsException.main (ThrowsException.java:5)
The main( ) method of this program expects the generation of ArithmeticException but
does not want to handle it using the try/catch block. Note that, after the display of the
description of the exception, the program terminated automatically. The last print
statement in the program is never executed.

The throw Statement:


Any Java code can throw an exception: code, code from the package written by someone
else or the Java runtime system. The throw statement is used explicitly throw an
exception. First, a handle on an instance of Throwable must be got into a catch clause or
by creating one using the new operator. The general form of throw statement:

throw <Throwableinstance>
where <Throwableinstance> is the instance when the throw has to be executed. The flow
of execution stops immediately after the throw statement and the next statement is not
reached. The closest enclosing try block is inspected to see if it has a catch clause which
matches the type of the Throwable instance. If it finds a match, then control is transferred
to that statement. If no match is found, the next enclosing try statement is inspected and
the cycle continues till the outermost exception handler stops the program.

throw new Throwable_subclass;

Open the file and enter the following code:

class throwme
{
public static void main(String args[])
{
try
{
float z (float)x / (float)y;
if (z < 0.01)
{
throw new IOException(“io”);
}
} catch(IOException e)
{
System.out.println(“Input output error” + e); }
}
}

Save the file as throwme.java


Compile the file using javac throwme.java
Execute the file using java throwme

Creating User-defined Exceptions:


Although Java’s built-in exception handles most common errors, which will probably
want to create the user-defined Exception types to handle situation specific to the
applications. Customized exceptions are necessary to handle abnormal conditions of
applications created by the user. The advantage of creating such an exception class is
that, according to situations defined by the user an exception can be thrown. It is also
possible to set any condition or value to a variable and generate user-defined exception.

Example:
class MyException extends Exception
{
private int detail;

MyException(int a)
{
detail = a;
}

public String toString( )


{
return “MyException [“+detail+”] “;
}
}

class ExceptionDemo
{
static void compute(int a) throws MyException
{
System.out.println(“ called compute (“ + a+ “)”);
If(a > 10)
throw new MyException(a);
System.out.println(“normal exit”);
}

public static void main(String args[])


try
{
compute(1);
compute(20);
}
catch(MyException e)
{
System.out.println(“caught “+e);
}
}
}
The user-defined exception class contains the constructor inside which the private
variable is initialized. The toString( ) method returns a string that denotes the point at
which the exception has occurred. The UserdefException class contains getInt( ) which
accepts numbers as input from the user. If characters are entered as input,
NumberFormatException is generated and the program terminates.

List of system Exceptions:

Exception Description
ArrayIndexOutOfBoundsException When array index is invalid
CharConversionException For character conversion problems during
ObjectStreamWriter operations
EOFException For signaling the reading of end-of-file
FileNotFoundException For signaling when requested file is not
found
IOException For general problems during I/O operations
InterruptedIOException For signaling that an I/O operation was
interrupted
InvalidClassException When unable to re-create a class during
deserialization
NegativeArraySizeException When array size is negative
NumberFormatException When the string passed is not a number
SQLException When error occurs during a database access
UnknownHostException When the host cannot be located

Summary:

Packages contain a set of classes in order to ensure that its class names are unique.
Packages are containers for classes that are used to compartmentalize the class name
space. An interface is a collection of abstract behavior that individual classes can
implement.
An exception is an abnormal condition, which arises during the execution of a program.
Java handles exceptions using five keywords – try, catch, finally, throws and throw. The
code sequence that is to be guarded should be placed inside the try block. The catch
clause should immediately follow the try block. Whenever a program does not want to
handle exceptions using the try block, it can use the throws clause. Customized
exceptions are necessary to handle abnormal conditions of applications created by the
user.
I/O Packages
The java.io package provides an extensive library of classes for dealing with
input and output. Java provides streams as a general mechanism for dealing with data I/O.
Streams implement sequential access of data. A stream in Java is a path along which data
flows. It has a source and a destination. Both the source and the destination may be
physical devices or programs or other streams in the same program. The concept of
sending data from one stream to another has made streams in Java a powerful tool for file
processing.
There are two kinds of streams: byte streams and character streams. An input stream is
an object that an application can use to read a sequence of data and an output stream is an
object that an application can use to write a sequence of data. An input stream acts as a
source of data and an output stream acts as a destination of data.
The following are the entities that can act as both input and output streams:
 An array of bytes or characters
 A file
 A pipe
 A network connection

Again, Java streams are classified into basic types, namely, input stream and output
stream. An input stream extracts (i.e. reads) data from the source (file) and sends it to the
program. Similarly, an output stream takes data from the program and sends (i.e. writes)
it to destination (file).
Streams can be chained with filters to provide new functionality. In addition to dealing
with bytes and characters, streams are provided for input and output of Java primitive
values and objects.

The file class:


Files are the primary source and destination for data within most programs. File I/O
operation is common in any language. Java devotes a whole range of methods found in a
class called File in the java.io package to perform these operations. A file is the only
object in the I/O (Input/Output) package that references an actual disk file. The file name
should follow the conventions of the platform on which it is loaded. The File class only
describes the properties of a File object. It does not specify how it retrives data from
stored files.
Java treats files and directories as objects of the File class. A directory is also treated
as a File object with an additional property – a list of file names that can be displayed
using list ( ) method.
A file is a collection of related records placed in a particular area on the disk. A
record is composed of several fields and a field is a group of characters. Characters in
Java are Unicode characters composed of two bytes, each byte containing eight binary
digits 1 or 0.
Storing and managing data using files is known as file processing which includes
tasks such as creating files, updating files and manipulation of data. Java supports many
powerful features for managing input and output of data using files. Reading and Writing
of data in a file can be done at the level of bytes or characters or fields depending on the
requirements of a particular application. Java also provides capabilities to read and write
class objects directly. Note that a record may be represented as a class object in Java. The
process of reading and writing objects is called object serialization. A Directory is also a
file in java with additional properties.
Constructors:
Objects of the File class can be created using three types of File constructors. The first
type accepts the name of the file as a string as:

File f1 = new File( “c: /java/temp”);


In the above type of constructor, it is assumed that a Windows based platform is being
used, the file name is temp and that it is under c:\java directory.

The next type of initializing a file as:


File f2 = new File(“c:/java”,”temp”);
In the above type, the first parameter specifies the directory path and the second denotes
the name of the file to be located under that directory.
The last type of constructor also takes two string parameters are:
File f3 = new File(“java”,”temp”);
In the above type, the first parameter is a directory name under which the file name
contained in the second parameter is to be created.

File or Directory Existence:


exists( ) Method:
A file object is created using a path name. Whether the pathname denotes an entry that
actually exists in the file system can be checked using the exists( ) method:
Boolean exists( )
Since a File object can represent a file or directory, the following methods can be used to
distinguish whether a given File object represents a file or a directory respectively:
isFile( )/ isDirectory( ) Method:

boolean isFile( );
boolean isDirectory( );

Read and Write Access:


To check whether the specified file has write and read access, the following methods can
be used. They throw a SecurityException if general access is not allowed, i.e. the
application is not even allowed to check whether it can read or write a file.

boolean canWrite( );
boolean canRead( );

getName( ) Method:
This method is used to obtain the name of the file specified.
getPath( ) / getAbsolutePath( ) Method:
These method facilitate us to obtain the path of the file specified and the absolute path of
the file specified.

getParent( ) Method:
This method returns a String object that contains the Parent directory.

lastModified( ) Method:
This method returns the last modification time of the file.

length( ) Method:
This method is used to know the file size in bytes.

delete( ) Method:
This is used to delete the specified file. In case of directory, it must be empty before it
can be deleted.
The flush( ) method helps in clearing the buffer.

Renaming Files and Diectories:


A file or a directory can be renamed, using the following method which takes the new
pathname from its argument:
renameTo( ) Method
It takes a file object that becomes the destination or the renamed file, as its parameter.
Listing Directory Entries:
A directory is a file that contains a list of other files and directories. To create a File
object and it is directory, that isDirectory( ) method will return true.
call list( ) : it is on that object to extract the list of other files and directories inside.
The list( ) method is used o list the contents of the specified directory. The
list(FilenameFilter) method by accepting the extension of the files as command line
parameters and displaying those files.

String[] list( )
The list of files is returned in an array of String objects.
e.g.,
File f1 = new File(“/java”);
String s[] = f1.list( );

Filename Filter:
It defines only a single method, accept( ), which is called once for each file in a list. Its
general form is
boolean accept(File directory, String filename);
The accept( ) method returns true for files in the directory specified by directory that
should be included in the list and returns false for those files that should be excluded.
Creating a new Files and Directories:
The file class can be used to create files and directories. A file can be created whose
pathname is specified in a File object using the following method:

Boolean create NewFile( ) throws IOException


It creates a new, empty file named by the abstract pathname if and only if, a file with this
name does not already exist. The returned value is true if the file was successfully
created, false if the file already exists. Any I/O error results in an IOException.

mkdir( ) Method:
This method is used to create a directory and returns a Boolean indicating the success of
the creation.

Example:

Open a file and enter the following:

import java.io.*;
class File{
public static void main(String args[]) throws IOException {
File f = new File(“c:/java/temp”);
if(f.mkdir ( ))
System.out.println(“created a directory”);
else
System.out.println(“unable to create a directory”);
}
}

It creates a directory called temp under c:\java directory. On successful creation the first
message is displayed, if not the second message is displayed.

Methods in Streams:
A stream is a path of communication between the source of information and the
destination.

File Streams:
File stream comprises of the FileInputStream and FileOutputStream.

The classes FileInputStream and FileOutputStream define byte input and output streams
that are connected to files. Data can only be read and written as a sequence of bytes.
File InputStream:
The FileInputStream class helps in reading data from the actual disk files. Any object of
this class can be created using the keyword new.
An input stream for reading bytes can be created using the following constructors.
FileInputStream(String name) throws FileNotFoundException
FileInputStream(File file) throws FileNotFoundException
FileInputStream(FileDescriptor fdobj)
Syntax:
InputStream f = new FileInputStream(“c:/java/temp”);
File f = new File(“c:/java/temp”);
InputStream f1 = new FileInputStream(f);

The file can be specified by its name, through a File or a FileDescriptor object. If the file
does not exist, a FileNotFoundException is thrown. If it exits, it is set to be read from the
beginning.
FileOutputStream:
The FileOutputStream class helps to create a file and write data into it. An Output Stream
for writing bytes can be created using the constructors:
FileOutputStream(String name) throws FileNotFoundException
FileOutputStream(String name, Boolean append) throws FileNotFoundException
FileOutputStream(File file) throws IOException
FileOutputStream(FileDescriptor fdobj)
The System.err method is used to print error messages.

The file can be specified by its name, through a File object or using a File Descriptor
object. If the file does not exist, it is created. If it exists, its contents are reset, unless the
appropriate constructor is used to indicate that output should be appended to the file.
The FileInputStream class provides an implementation for the read( ) methods in its
superclass InputStream. Similarly, the FileOutputStream class provides an
implementation for the write( ) methods in its superclass OutputStream.
The FileInputStream class is used to create objects that can read data files stored on disk.
The class FileOutputStream does not allow appending data to an existing file.

Filter Streams:
A filter is a high-level stream that provides additional functionality to an underlying
stream to which it is chained. The data from the underlying stream is manipulated in
some way by the filter. The FilterInputStream and FilterOutputStream classes, together
with their subclasses, define input and output filter streams. Sub classes
BufferedInputStream and BufferedOutputStream implement filters that respectively
buffer input from, and output to, the underlying stream.

Stream Classes:
The java.io package contains a large number of stream classes that provide capabilities
for processing all types of data. These classes may be categorized into two groups based
on the data type on which they operate.

Byte stream classes – that provide support handling I/O operations on bytes.
Character stream classes – that provide support for managing I/O operations on
characters.
These two groups may further be classified based on their purpose. Byte stream and
character stream classes contain specialized classes to deal with input and output
operations independently on various types of devices.

Java Stream Classes

Byte Stream Classes Character Stream Classes

Input Stream Classes OutputStreamClasses Reader Classes Writer Classes

Byte Stream Classes:

Byte Stream Classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes. Since the streams are
unidirectional, they can transmit bytes in only one direction and therefore java provides
two kinds of byte stream classes: input stream classes and output stream classes.

Byte Input Stream Classes:


Input stream classes that are used to read 8-bit bytes include a superclass known as
Input Stream and a number of subclasses for supporting various input-related functions.

byteArrayInputStream b = new ByteArrayInputStream(buf []);

It takes a byte array as its parameter. The next constructor helps to create a
ByteArrayInputStream from the specified array of bytes.

byteArrayInputStream b = new ByteArrayInputStream(b[], int n, int m);

InputStream Classes Hierarchy


Object

Input Stream

FileInputStream SequenceInputStream

PipeInputStream ObjectInputStream

ByteArrayInputStream StringBufferInputStream

FilterInputStream

BufferedInputStream PushbackInputStream

DataInputStream

DataInput

The super class InputStream is an abstract class and therefore it cannot create instances of
the class. It uses the subclasses that inherit from the class.

OutputStreamClass:
This class implements a buffer, which can be used as an Output Stream.
The size of the buffer increases as data is written into the stream. The data is retrieved
using the methods toByteArray( ) and toString( ).
There are two types of constructors. They are:

OutputStream o = new ByteArrayOutputStream( );

This creates a buffer of 32 bytes to store the data.


OutputStream o1 = new ByteArrayOutputStream(int);
The above constructor creates a buffer of size int. These methods return void and throw
an IOException on error conditions.

Output class Hierarchy:

Object

Output Stream

FileOutputStream ObjectInputStream

PipeOutputStream ByteArrayObjectStream

FilterOutputStream

BufferedOutputStream PushbackOutputStream

DataOutputStream

DataOutput

The InputStream class defines methods for performing input functions such as

Reading bytes
Closing streams
Marking positions in streams
Skipping ahead in a stream
Finding the number of bytes in a stream

Methods of InputStream/Reader:

The read( ) Method:


It reads a byte from the input stream. This method without any parameters returns an
integer representation of the next available byte of input.

The read(byte b[]) Method:


It reads an array of bytes into b. It returns the actual number of bytes successfully read.

The read(byte b[], int n, int m) Method:


It reads m bytes into b starting from the nth byte, returning the number of bytes
successfully read.

The read(char buf[],int n, int m) Method:


It reads m bytes into buf array of characters starting from the nth byte.

The available( ) Method:


This method gives number of bytes available in the input.

The skip(n) Method:


This method skips over n bytes from the input stream.

The mark( ) Method:


This method places a mark at the current point in the input stream that remains until a
certain number of bytes are read.

The reset( ) Method:


This method goes back to the beginning of the stream.

The close( ) Method:


This method closes input stream. Further attempts to read will result in IOException.

BufferedInputStream:
This class accepts input by using a buffered array of bytes that acts as a cache and it
utilizes the mark( ) and reset( ) method.

InputStream s = new BufferedInputStream(new FileInputStream(“temp”));


This code creates BufferedInputStream for the file temp.

PushbackInputStream:
This class is used to read a character from the InputStream and return the same.
PrintStream:
This method is widely used in Java applications. The two methods that are very familiar
to us are System.out.println( ) and System.out.print( ). System.in is an InputStream.

Output Stream Classes:


OutputStream classes are derived from the base class OutputStream. Like InputStream,
the OutputStream is an abstract class and therefore it cannot instantiate it. The several
subclasses of the OutputStream can be used for performing the output operations.
The OutputStream includes methods that are designed to perform the following tasks:

Writing bytes
Closing streams
Flushing streams

Methods:

The write( ) Method:


This method writes a byte to the output stream.

The write(byte[] b) Method:


This method writes all bytes in the array b to the output stream.

The write(byte b[], int n, int m) Method:


This method writes m bytes from array b starting from nth byte.

The flush( ) Method:


This method finalizes the output state to clear any buffers.

The close( ) Mehod:


This method closes the output stream. Further attempts to write will generate an
IOException.

BufferedOutputStream:
The output is stored in a buffered array of bytes, which acts as a cache for writing. A
specific number of bytes can be buffered using the nesting facility offered by the
FilterStream.

OutputStream s = new BufferedOutputStream(new FileOutputStream(“temp”));


This class uses the flush( ) method, which pushes the written bytes through the buffer.

Character Stream Class:


Character streams can be used to read and write 16-bit Unicode characters. Like byte
streams, there are two kinds of character stream classes, namely, reader stream classes
and writer stream classes.
ReaderStreamClasses:
Reader stream classes are designed to read character from the files. Reader class is the
base class for all other classes in the group. These classes are functionally very similar to
the input stream classes, except input streams use bytes as their fundamental unit of
information, while reader streams use characters.
Writer Classes:
The functionality of the writers is similar to the output streams and it is possible to write
one block of bytes or characters.

FileReader:
The FileReader class enables reading character files. It uses default character encoding.
FileReader class is similar to FileInputStream class and its constructors are identical to
those of FileInputStream class. The constructor shown here, can throw a FileNotFound
Exception:

public FileReader(File f)

CharArrayReader:
The CharArrayReader allows the usage of a character array as an InputStream. The usage
of CharArrayReader class is similar to ByteArrayInputStream. The constructor is:

public CharArrayReader(char ch[]);

StringReader:
The StringReader class reads characters from a string. The constructor is:

public StringReader(String s);

InputStreamReader:
The InputStreamReader class reads bytes from an input stream and converts them to
characters according to a mapping algorithm. The default mapping identifies bytes as
common ASCII characters and converts them to Java’s Unicode characters. The
constructor is:
public InputStreamReader(InputStream istream)

FilterReader:
The FilterReader class allows the reading of filtered character streams. There is one
instance variable in, which is protected reference to the Reader that is being filtered.

protected FilterReader(Reader r)

BufferedReader:
This class accepts a Reader object as its parameter and adds a buffer of characters to it.
This class is mainly useful because of its readLine( ) method.
public BufferedReader(Readetr r)

Writer class:
There are various methods of writer class. They are:

FileWriter:
The FileWriter allows writing character files. It uses the default character encoding and
buffer size. The usage of FileWriter class is similar to that of FileOutputStream class. The
constructor is given and it can throw an IOException.
public FileWriter(File f)

CharArrayWriter:
It uses a character buffer as an output stream. It is used in situations where
ByteArrayOutputStream is used. The constructor is:
public CharArrayWriter( )

PrintWriter:
The PrintWriter class contains methods that makes the generation of formatted output
simple. It can be used instead of PrintStream. The constructor is:
public PrintWriter(OutputStream ostream)

The stream is not flushed each time the println( ) method is called.

FilterWriter:
The FilterWriter class is used to write filtered character streams. It has one instance
variable out, which is a protected reference to the Writer that is being filtered.
protected FilterWriter(Writer w)

BufferedWriter:
The bufferedWriter class buffers data to the character output stream. BufferedWriter
class functionality is the same as BufferedOutputStream class. The constructor is:
public BufferedWriter(writer w)

Other Useful I/O Classes:


The java.io package supports many other classes for performing certain specialized
functions. They include among others:
 RandomAccessFile
 StreamTokenizer

Random Access Files:


It enables us to read and write bytes, text and Java data types to any location in a file.
Although it is not a stream class, it provides the same platform-independent formatting
methods as the DataStream classes. The constructor to create a RandomAccessFile object
takes two arguments. The first argument specifies the file either as a string containing the
file name or as a file object. The second argument is a string that takes the value “r” if the
file is to be read but not written, or he value “rw” if the file is to be both read and written.
If the specified file does not exist, it is automatically created.

RandomAccessFile thefile = new RandomAccessFile(“Sample.txt”,”rw”);

The seek( ) method specifies the byte-offset from the beginning of the file, at which input
and output is to commence.

StreamTokenizer:
The class StreamTokenizer, a subclass of Object can be used for breaking up a stream of
text from an input text file into meaningful pieces called tokens. The behaviour of the
StreamTokenizer class is similar to that of the StringTokenizer class that breaks a string
into its component tokens. A stream is tokenized by creating a Stream Tokenizer with a
Reader object as its source and then setting parameters for the screen. A scanner loop
invokes nextToken, which returns the token type of the next token in the screen.

When nextToken recognizes a token, it returns the token type as its value and also sets
the type field to the same value. There are four token types:

TT_WORD: A word is scanned. The String field sval conatins the word that is scanned.

TT_NUMBER: A number is scanned. The double field nval contains the value of the
number. Only decimal floating numbers are recognized.

TT_EOL: An end-of-line is found.

TT-EOF: The end-of-file is reached.

Summary:

There are different subclasses of the InputStream and the OutputStream. The
FileInputStream and FileOutputStream help in reading/ writing data from actual disk
files. ByteArrayInputStream and ByteArrayOutputStream make use of byte array as the
source and perform the reading and writing operations on that array.
StringBufferInputStream is similar to ByteArrayInputStream. It is used as a stored string
as the source.
PushbackInputStream takes input from the input stream and places it back without
disturbing it. The PrintStream has two methods System.out.print( ) and
System.out.println( ) which are widely used. The StreamTokenizer helps to break the
InputStream into tokens.
Events and User Interface Components
EVENTS:

Events are signals which are fired when the state of a component is changed
(e.g., when a button is pressed, when a menu is pressed etc.). In the event of a signal
firing it is necessary to handle the event based on the requirement. For example, a new
window opens when a button is pressed. If any interactive environment, the program
should be able to respond to actions performed by the user. These actions can be, mouse
click, key press or selection of a menu item. The basis of event-driven programming is
typing events to code that responds to those events.
Java’s Abstract Windowing Toolkit (AWT) communicates these actions to the program
using events. When the user initiates an action, the AWT generates an event and
communicates it to event handlers. These event handlers can respond to the events
appropriately.
Often it may be required to perform some task based on the action performed by the user.
For example, if a user clicks on a button, a text message stating the action performed by
the user may be made to get displayed on the status bar. All these process comprise of
what is called as Event Handling.
When a component is activated, that is, when the internal state of the component is
modified a source is generated. This is nothing but a source to the event.
A single component can take events from different sources. For example, an applet
should be made ready to receive the events from the different sources. This is done by the
Listeners which are nothing but interfaces with abstract methods which could be
implemented on generation of the corresponding event.
Event Listeners are not used whenever a component handles its own events.
The actions that have to be performed on the components listening to the event like a
mouse click on an applet are called Event Handling.
The whole of event handling in Java 1.0 AWT is done using two methods action( )
and handleEvent( ) method. The action( ) method has three parameters namely – the
event that has occurred, the x and y co-ordinates at which this event occurred. The
handleEvent( ) method is called automatically for an object and an Event object is created
and passed on to it.
Event Delegation Model:
In the new event model, an event is propagated from a “source” object to a “Listener”
object by invoking a method on the listener and passing in the instance of the event
subclass which defines the event type generated. When an event is fired, it is received by
one or more listeners that act on that event. Each event listener is an object of a class that
implements a particular type of listener interface. Event types are encapsulated in a class
hierarchy rooted at java.util.EventObject and one level below this is java.awt.AWTEvent
package.
A Listener is an object that implements a specific EventListener interface extended from
the generic java.util.EventListener.
An EventListener interface defines one or more methods that are to be invoked by the
event source in response to each specific event type handled by the interface.
An Event Source is an object that originates events. The source defines the set of events it
emits by providing a set of set<EventType> Listener(for single-cast) and/or
add<EventType>Listener(for multi-cast) methods which are used to register specific
listeners for those events.
An adapter class includes all methods specified by the corresponding interface but not
providing any functionality.

The primary design goals of the model in the AWT are:


 To make it simple and easy to learn
 To support a clean separation between application and GUI code
 To facilitate the creation of robust event handling code which is less error-prone
 To make it flexible enough to enable varied application models for event fl9ow
and propagation
 To support backward binary compatibility with the old model

Whenever an AWT component wants to handle its own events, the component’s subclass
created has to do two things:
Enable receipt of events by calling enableEvents( )
Provide a processActionEvent ( ) method which is called whenever the component is
activated.
The delegation method is the best-suited method to handle events. It is not possible for a
component to handle its events at all times. Hence this should be assigned to a different
object called listeners. This process is called delegation. Each component class in AWT
has one addxxxListener( ) method for each event type that the component generates.

Methods in Listener Interface:

Listener Interface Window Adapter Methods in Interface


ActionListener actionPerformed(ActionEvent)
AdjustmentListener AdjusmentValueChanged
(AdjustmentEvent)
ComponentListener componentHidden(ComponentEvent)
ComponentAdapter componentShown(ComponentEvent)
componentMoved(ComponentEvent)
componentResized(ComponentEvent)
ContainerListener componentAdded(ContainerEvent)
ContainerAdapter componentRemoved(ContainerEvent)
FocusListener focusGained(FocusEvent)
FocusAdapter focusLost(FocusEvent)
KeyListener keyPressed(KeyEvent)
KeyAdapter keyReleased(KeyEvent)
keyTyped(KeyEvent)
MouseListener mouseClicked(MouseEvent)
MouseAdapter mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
MouseMotionListener mouseDragged(MouseEvent)
MouseMotionAdapter mouseMoved(MouseEvent)
WindowsListener windowOpened(WindowEvent)
WindowsAdapter windowClosing(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
ItemListener itemStateChanged(ItemEvent)
TextListener textValueChanged(TextEvent)

Event Handling Types:


There are two types of events which are provided by AWT: low-level and semantic.
An EventListener interface typically has a separate method for each distinct event type
the event class represents.
Low-level event classes are defined by the AWT are as:

 ComponentEvent
 FocusEvent
 InputEvent
 KeyEvent
 MouseEvent
 ContainerEvent
 WindowEvent

They represent a low-level input or window-system occurrence on a visual component on


the screen.
Low-level event listeners are as:
 ComponentListener
 ContainerListener
 FocusListener
 KeyListener
 MouseListener
 MouseMotionListener
 WindowListener

Semantic Events:
Semantic events are defined at a higher-level to encapsulate the semantics of a user
interface component’s model.
AWT defines semantic class as:
 ActionEvent
 AdjustmentEvent
 ItemEvent
 TextEvent
Listener interfaces are

 ActionListener
 AdjustmentListener
 ItemListener
 TextListener

Using Adapters for simplicity:


Some listener interfaces have only one method, which can be implemented easily.
However, certain listener interfaces have multiple methods and the program may require
just one of the methods defined in the program. But, all the methods of the interface has
to be implemented in the class as otherwise the class cannot be instantiated. For example,
if a class requires handling the window closing event it needs to use only one method of
the WindowListener interface. But WindowListener interface has many other methods
which also have to be specified in the program.
To solve the problem, each of the listener interfaces that have more than one method, is
provided with adapters, the names of which are specified in the second table. Each
adapter provides default methods for each of the interface methods so that the method
required by the program alone need to be overridden. The following code extends
WindowAdapter and overrides only the windowClosing( ) method of the
WindowAdapter interface.

class MyWindowListener extends WindowAdapter


{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

The whole point of the adapters is to make the creation of listener classes easy. There is a
downside to adapters, however, in the form of a pitfall. Suppose a code using
WindowAdapter is written like the one below:

class MyWindowListener extends WindowAdapter


{
public void WindowClosing(WindowEvent e)
{
System.exit(0);
}
}
The coding will compile and the program will run perfectly except that closing the
window will not exit the program. Note that the name of the method has got changed.
The code has a method of the name – WindowClosing( ) instead of windowClosing( ). A
simple slip in capitalization results in the addition of a completely new method.
Ultimately, the method WindowClosing( ) is not called when the window is closing and
the desired result is not got.

Mouse Events:
These are generated whenever a mouse is moved, clicked, pressed, released, etc. The
MouseEvent class represents these events as six constant values. There are two types of
mouse event listeners – MouseListener and MouseMotionListener.

The MouseListener interface has the following definition:

public interace MouseListener {


public void mouseClicked (MouseEvent e);
public void mousePressed (MouseEvent e);
public void mouseEntered (MouseEvent e);
public void mouseExited (MouseEvent e);

public void mouseReleased (MouseEvent e);


}

The MouseMotionListener interface has the following definition:

public interface MouseMotionListener {


public void mouseDragged (MouseEvent e);
public void mouseMoved (MouseEvent e);
}

An alternate way of handling mouse events is by letting components process their own
ordinary mouse events using enableEvents(AWTEvent . MOUSE-EVENT_MASK) and
processMouseEvent( ) methods.

Keyboard Events:
These are generated on pressing or releasing a key. The KeyEvent class contains
constants to represent the keys pressed or typed. The event listener corresponding to these
types of events is the KeyListener. The interface has the following definition:

public interface KeyListener {


public void keyPressed (KeyEvent e);
public void keyReleased (KeyEvent e);
public void keyTyped (KeyEvent e);
}
Components can process their own key events using
enableEvents(AWTEvent .KEY_EVENT_MASK) and processKeyEvent( ) methods.

USER INTERFACE COMPONENTS:


The Component class is the abstract superclass of the nonmenu-related Abstract
WindowToolkit components. All the user interface components and container classes are
derived from the class. The Component class is the superclass of the AWT classes which
implements graphical user interface controls. These components include windows, dialog
boxes, buttons, labels, textfields and other common GUI components.
There are two major sets of classes derived from the component class:
Container classes – They are generic AWT components that can contain other
components.
User Interface component classes – These include components like Button, Label etc.

Containers:
The Container class is a subclass of Component. It has additional methods that allow
other Component objects to be nested within it. A Container can store other Container
objects. It is responsible for laying out any components which it contains. User interface
components added to a container are tracked in a list. The order of the list will define the
components front-to-back stacking order within the container. If no index is specified
when adding a component to a container, it will be added to the end of the list.
Components have to be necessarily added to a container if they have to be displayed on
the screen.
The basic functionalities of containers are encapsulated in an abstract class, Container.
This class has methods that allow other components to be nested within it. The Panel is a
simple non-abstract container that can contain other components. The add( ) method of
the Container class can be used to add components to a Panel. The Applet class is derived
from the Panel class and hence, can act as a container. This property of the applet shall be
exploited by adding user interface components and other containers directly to the applet.
The Applet class, though derived from the Panel does not belong to the AWT package.
The AWT package contains a number of component classes that are typical elements of
any interactive user interface. These classes are called as User Interface component
classes, are derived from the abstract Component class. The Component class defines a
number of methods that can be used on any of the classes that are derived from it.

Panel:
The Panel class is a concrete subclass of Container. It does not add any new methods but
uses the methods of Container class. A Panel may be thought of as a recursively nestable,
concrete screen component. Panel is the superclass for Applet. When screen output is
directed to an applet, it is drawn on the surface of a Panel object. In essence, a Panel is a
window that does not contain a title bar, menu bar, or border.
Other Components can be added to Panel object by its add( ) method. Once these
components have been added, they can be positioned and resized manually using the
setLocation( ), setSize( ), or setBounds( ) methods defined by Component.

Window:
The window class creates a top-level window. A top-level window is not contained
within any other project; it is placed directly on the desktop.

Frame:
Frame encapsulates a “window”. It is a subclass of window and has a title bar, menu bar,
borders and resizing corners. When a Frame window is created by a program, rather than
an applet, a normal window is created.

Methods Used in Components as well as Containers:

setSize (Dimension d): It resizes the corresponding component.


setSize(int width, int height) : It resizes the corresponding component so that it has
width and height.
setFont(font f): It sets the font of the component.
setEnabled(Boolean b): It enables or disables the corresponding component, depending
on the value of the parameter b.
setVisible(Boolean b): It shows or hides the corresponding component depending on
the value of parameter b.
setForeground(Color c): It sets the foreground color of the corresponding component.
setBounds(int x, int y, int width, int height): It moves and resizes the component.
setBounds(Rectangle r): It moves and resizes the corresponding component to conform
to the new bounding rectangle r.
setBackground(Color c): It sets the background color of the component.
getBackground( ): It gets the background color of the component.
getBounds( ): It gets the bounds of the corresponding component in the form of a
Rectangle object.
getFont( ): It gets the font of the corresponding component.
getForeground( ): It gets the foreground color of the corresponding component.
getSize( ): It returns the size of the component in the form of a dimension object.

Button:
Buttons are components that can contain a label. The button is similar to a push button in
any other GUI. Pushing a button causes the run time system to generate an event. This
event is sent to the program. The program in turn can detect the event and respond to the
event. Clicking a button generates an ActionEvent. It can be created using the new
keyword in association with the constructors that are defined it. Buttons must be added to
the containers before they can be used. Once the buttons have been created and added the
can be used. When a button is clicked the AWT sends an instance of the ActionEvent to
the button, by calling the processEvent on the button. The processEvent method of the
button receives all the events of the button. This then passes an action event along by
calling its processActionEvent. The processActionEvent then passes the action event to
any action listeners that have registered an interest in action events generated by the
button. Any application that has to perform an action based on the button has to
implement the ActionListener and register the listener to receive the events from the
button, by calling its addActionListener method.

Button Component:
Constructor that can be used with the Button component
Button( ) : It constructs a button with no label.
Button(String label) : It constructs a button with the label specified.

Some of the methods that can be used in relation to a Button Component

addActionListener(ActionListener 1): It adds the specified action listener to receive


action events from the corresponding button.
getActionCommand( ): It returns the command name of the action event fired by the
corresponding button.
getLabel( ): It returns the label of the corresponding button.
paramString( ): It returns the parameter string representing the state of the corresponding
button.
setLabel(String label): It sets the label of the button to the value specified.

CheckBox:
Checkboxes are user interface components that have dual state: checked and unchecked.
Clicking on it can change the state of the checkbox. The checkbox class is used to
implement labeled checkbox and radio button GUI controls. If a checkbox object is not
associated with a checkboxGroup object, it is implemented as traditional checkbox. If a
checkbox object is associated with a checkboxGroup object, it is implemented as a radio
button. The Checkbox class provides five constructors that allow the checkbox label,
initial state and checkboxGroup object to be specified. The checkbox class provides
methods for getting and setting the label and state of the checkbox and its
checkboxGroup object. The state of the checkbox is Boolean. The checkbox class also
provides methods for identifying event-handling code.
The checkboxGroup class is used with the checkbox class to implement radio buttons.
All checkbox objects that are associated with a checkboxGroup object.
Java supports two types of checkboxes: exclusive and non-exclusive.

Exclusive Checkboxes: Only one among a group of items can be selected at a time. If an
item from the group is selected, the checkbox currently checked is deselected and the
new selection is highlighted. The exclusive checkboxes are also called radio buttons.
Non-Exclusive Checkboxes:
It is not grouped together and each checkbox can be selected independent of the other.

The various constructors of checkboxes are:


Checkbox( ): It creates a checkbox with no label.
Checkbox(String label): It creates a checkbox with the specified label.
Checkbox(String label, Boolean state): It creates a checkbox with the specified label and
sets the specified state.
Checkbox(String label, Boolean state, CheckboxGroup group): It creates a checkbox with
the specified label and sets the specified state and places it in the specified group. The
position of the checkbox group and state can be interchanged.

Methods that are supported by checkboxes:


getCheckboxGroup( ): It determines the group of the checkbox.
getLabel( ): It gets the name of the corresponding checkbox.
getSelectedObjects( ): It returns an array (length 1) containing the checkbox label or null
if the checkbox is not selected.
getState( ): It determines if the checkbox is in the ‘on’ or ‘off’ state.
setCheckboxGroup(CheckboxGroup g): It sets the corresponding checkbox’s group to the
specified one.
setLabel(String label): It sets the label of the corresponding checkbox to the value
specified.
setState(boolean state): It sets the state of the corresponding checkbox to the value
specified.

Frame Window:
After the applet, the type of window which user will most often create is derived from
Frame. It creates a standard-style window.
Types of Frame’s constructors:

Frame( )
Frame(String title)
The first form creates a standard window that does not contain a title. The second form
creates a window with the title specified by the string title.

Setting the window’s Dimension:


The setSize( ) method is used to set the dimensions of the window.
void setSize(int newWidth, int newHeight)
void setSize(Dimension newSize)
The new size of the window is specified by newWidth and newHeight, or by the width
and height fields of the Dimension object passed in newSize. The dimensions are
specified in terms of pixels.
The getSize( ) method is used to obtain the current size of a window. Its signature is
shown:
Dimension getSize( )
The method returns the current size of the window contained within the width and height
fields of a Dimension object.
Hiding and Showing a Window:
After a frame window has been created, it will not be visible, until user calls method
setVisible( ). Its signature is shown:
void setVisible(boolean visibleFlag)
The component is visible if the argument to this method is true.
Setting a Window’s Title:
The user can change the title in a frame window using setTitle( ), which has
void setTilte(String newTitle)
here, new title is the new title for the window.

Closing a frame window:


To intercept a window-close event, the user must implement the windowClosing( )
method of the WindowListener interface.

Choice:
The choice class is used to implement pull-down lists that can be placed in the main area
of a window. These lists are known as option menus or a pop-up menu of choices and
allow the user to select a single menu value. The UI component displays the currently
selected item with an arrow to its right. On clicking the arrow, the menu opens and
displays options for a user to select. The Choice class provides a single, parameterless
constructor. It also provides access methods that are used to add items to the list, count
the number of items contained in the list, select a list item, handle events and determine
which list item is selected. To create a choice menu, a choice object is instantiated. Then,
various items are added to the choice by using the addItem( ) method.

Example:
Open a new file and enter the following code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code = “choice” height = 300 width =300> </applet>*/
public class choice extends Applet
{
Choice colors;
public void init( )
{
colors = new Choice( );
colors.addItem(“red”);
colors.addItem(“blue”);
colors.addItem(“green”);
add(colors);
}
}

Save the file as Choice.java.

The various constructors that ca be used to create a choice object are:

Choice( ): It creates a new choice menu.


Methods are:
add(String item): It adds an item to the corresponding choice menu.
addItem(String item): It adds an item to the corresponding choice.
getItem(int index): It gets the string at the specified index of the corresponding choice
menu.
getItemCount( ): It returns the number of items in the corresponding choice menu.
getSelectedIndex( ): It returns the index of the currently selected item.
getSelectedObjects( ): It returns an array (length 1) containing the currently selected
item.
getSelectedItem( ): It gets a representation of the current choice as a string.
insert(String item, int index): It inserts the item into the corresponding choice at the
specified position.
remove(int position): It removes an item from the corresponding choice menu at the
specified position.
remove(String item): It removes the first occurrence of item from the corresponding
Choice menu.
removeAll( ): It removes all items from the corresponding choice menu.
select(int pos): It sets the selected item in the corresponding Choice menu to be item
at the specified position.
select(String str): It sets the selected item in the corresponding Choice menu to be
item whose name is equal to the specified string.

Canvas:
A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the user.
An application must subclass the Canvas class in order to get useful functionality such as
creating a custom component. The paint method must be overridden in order to perform
custom graphics on the canvas. The canvas does not have a size that is useful to the end
user and hence the setsize method has to be used to render a meaningful canvas on the
screen.
The constructor is:
Canvas( ): It constructs a new canvas.
Methods:
addNotify( ): It creates a peer o the canvas.
paint(Graphis g): this method is called to repaint the corresponding canvas.

FileDialog:
The FileDialog class displays a dialog window from which the user can select a file.
Being a modal dialog, it blocks the rest of the application until the user has chosen a file.

The constructors used here are:


FileDialog(Frame parent) : It creates a file dialog for loading a file.
FileDialog(Frame parent, string title): It creates a file dialog window with the specified
title for loading a file.
FileDialog(Frame parent, String title, int mode) : It creates a file dialog window with the
specified title for loading or saving a file.
Methods are:
getDirectory( ): It gets the directory of the corresponding file dialog.
getFile( ): It gets the file of the corresponding file dialog.
GetFilenameFilter( ): It determines the file dialog’s filename filter.
getMode( ): It indicates whether the file dialog is in the save mode or open mode.
setDirectory(String str): It sets the directory of the file dialog window to the one
specified.
setFile(String file): It sets the selected file for the corresponding file dialog window to the
one specified.
setFilenameFilter(filenamefilter filter): It sets the filename filter for the specified file
dialog window to the specified value.
setMode(int mode): It sets the mode of the file dialog.

Label:
The most basic GUI component is the label, which is simply a text that is displayed at a
particular location of a GUI container. The label class of the java.awt package provides
the capability to work with labels. The class ‘label’ provides three label constructors:
 A default parameterless constructor for creating blank label objects.
 A constructor that takes a String object that specifies the label’s text.
 A constructor that takes a String object and an alignment constant.
The Label class provides six methods for working with the label’s text and alignment and
also for performing other operations. The setText( ) and getText( ) methods are used to
access the label’s text. It would display a single line of text in a container. The text can be
changed by an application but the user cannot edit the text. Labels do not generate any
events. A label is similar to a button can be created using its constructor in combination
with a keyword new.
The constructors used are:
Label( ): It constructs an empty label.
Label(String text): It constructs a string with the corresponding text.
Label(String text, int alignment): It constructs a string with the text, with the specified
alignment. The alignment could be CENTER, LEFT, RIGHT.

The various methods are:


getText( ): It gets the text of the corresponding label.
paramString( ): It returns the parameter string representing the state of the corresponding
level.
setText(String text): It sets the text for the corresponding label to the specified text.

List:
The List class implements single- and multiple-selection list GUI controls. The lists
provided by the list class are more sophisticated than those provided by the choice class.
The list class lets specifying the size of the scrollable window in which the list items are
displayed and select multiple items from the list. The difference between a list and a
choice menu are:
 Unlike Choice, which displays only the single-selected item, the list can be made
to show any number of choices in the visible window.
 The list can be constructed to allow multiple selections.

The various constructors are:


List( ): It creates a new scrolling list of items.
List( int rows) : It creates a new scrolling list of items with the specified number of
visible lines.
List( int rows, boolean multiplemode) : It creates a new scrolling list of items to display
the specified number of rows.

Methods:
add(string item): It adds the specified item at the end of the scrolling list.
add(string item, int index): It adds the specified item at the position specified.
deselect(int index): It deselects the item at the specified index.
getItem(int index): It gets the item at the specified index.
getItemCount( ): It gets the number of items in the list.
getItems( ): It gets the items in the list.
getMinimumSize( ): It determines the minimum size of the scrolling list.
getMinimumSize(int rows): It gets the minimum dimensions for a list with the specified
number of rows.
getPreferredSize( ): It gets the preferred size of the corresponding scrolling list.
getPreferredSize(int rows): It gets the minimum dimension for a list with the specified
number of rows.
getRows( ): It gets the number of visible lines in the corresponding list.
getSelectedIndex( ): It gets the index of the selected item in the list.
getSelectedItem( ): It gets the selected item in the corresponding list.
select(int index): It selects the item at the specified index in the corresponding list.
setMultipleMode(boolean b): It sets the flag that allows multiple selection in the
corresponding list.

ScrollPane:
ScrollPane is a container class which implements automatic horizontal and/or vertical
scrolling for a single child component. The display policy for the scrollbars can be set to
as needed, always and never. The constructors of scrollPane are:
ScrollPane( ): It creates a new scroll pane container with the scroll bar policy of “as
needed”.
ScrollPane(int Scrollbardisplaypolicy): It creates a new scrollpane container.

Methods:
getScrollbarDisplayPolicy( ): It returns the display policy for the corresponding scroll
bars.
setScrollPosition(int x, int y): It scrolls to the specified position within the child
component.

Scrollbar:
Scrollbars are used to select a value between a specified minimum and maximum. It has
the following components:
 The arrows at either end allow incrementing or decrementing the value
represented by the scrollbar.
 The thumb’s (or handle’s) position represents the value of the scrollbar.
The constructors of scrollbar are:
Scrollbar( ): It constructs a vertical scroll bar.
Scrollbar(int orientation): It constructs a new scroll bar with the specified orientation.
Scrollbar(int orientation, int maxvalue, int visible, int minimum, int maximum): It
constructs a new scroll bar with the specified orientation, initial value, page size,
minimum and maximum values.

Methods:
getBlockIncrement( ): It gets the block increment of the corresponding scroll bar.
getMaximun( ): It gets the maximum value of the corresponding scroll bar.
getMinimum( ): It gets the minimum value of the corresponding scroll bar.
getOrientation( ): It determines the orientation of the corresponding scroll bar.
getValue( ): It gets the current value of the corresponding scroll bar.
setBlockIncrement(int v): It sets the block increment for the corresponding scroll bar.
setMaximum(int newMaximum): It sets the maximum value for the corresponding scroll
bar.
setMinimum(int newminimum): It sets the minimum value for the corresponding scroll
bar.
setValue(int newvalue): It sets the value of the corresponding scroll bar to the specified
value.

Textfield:
Textfields are GUI components that accept text input from the user. They are often
accompanied by a Label control. The Textfield class implements a one-line text entry
field. It provides four constructors that are used to specify the width of the text field in
character columns and the default text to be displayed within the field. It provides several
methods for accessing the field’s size and for specifying whether the characters typed by
the user should be displayed.
The constructors are:
TextField( ): It constructs a new text field.
TextField(int columns): It creates a new text field with the specified number of columns.
TextField(String text): It constructs a new text field initialized with the specified text.
TextField(String text, int columns): It constructs a new text field initialized with the
specified text with the specified number of columns.

Methods are:
getColumns( ): It gets the number of columns in the corresponding text field.
getEchoChar( ): It gets the character that is to be used for echoing.
setColumns(int columns): It sets the number of columns in the text field.
setEchoChar(char c): It sets the echo character for the text field.
setText(String t): It sets the text that is presented by the corresponding text component to
be specified text.

TextArea:
Sometimes, a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multi-line editor called TextArea. TextArea is a
subclass of TextComponent. It behaves like TextFields except that they have more
functionality to handle large amounts of text. The functionalities include:
Text areas can contain multiple rows of text. Text areas have scrollbars that permit
handling of large amounts of data.
The constructors are:
TextArea( ): It constructs a new text area.
TextArea(int rows, int columns): It constructs a text area with the specified number of
rows and columns.
TextArea(String text): It constructs a new text area with the specified text.
TextArea(String text, int rows, int columns): It constructs a new text area with the
specified text, and specified number of rows and columns.
TextArea(String text, int rows, int columns, int scrollbar): It constructs a new text area
with the specified text, and specified number of rows and columns and visibility of the
scrollbar.

The various methods are:


append(String str): It appends the given text to the text area’s content.
getColumns( ): It gets the number of columns of the text area.
getMinimumSize( ): It determines the minimum area of the text area.
getRows( ): It gets the number of rows in the text area.
Insert(String str, int pos): It inserts the specified string at the specified position.
setColumns(int columns): It sets the number of columns for the text area.
SetRows(int rows): It sets the number of rows for the text area.

Summary:
Java’s AWT generates events when user performs actions like mouse click, key press,
etc. When an event is fired, it is received by one or more listeners that act on that event.
A Listener is an object that implements a specific EventListener interface extended from
the generic java.util.EventListener. An EventListener interface defines one or more
methods that are to be invoked by the event source in response to each specific event type
handled by the interface. The Component class is the abstract superclass of the non
menu-related Abstract Window Toolkit components. All the user interface components
and container classes are derived from the class. The Panel class is a concrete subclass of
Container. Buttons are components that can contain a label. The button is similar to a
push button in any other GUI. The choice class is used to implement pull-down lists that
can be placed in the main area of a window. A Canvas component represents a blank
rectangular area of the screen onto which the application can draw or from which the
application can trap input events from the user. ScrollPane is a container class which
implements automatic horizontal and/or vertical scrolling for a single child component.
Textfields are GUI components that accept text input from the user. They are often
accompanied by a Label control. Text areas can contain multiple rows of text. Text areas
have scrollbars that permit handling of large amounts of data.

Thread and Multithreading


A thread executes a series of instructions. Every line of code that is executed
is done so by a thread. Some threads can run for the entire life of the applet, while others
are alive for only a few milliseconds. A thread also creates a new thread or kills an
existing one. Threads run in methods or constructors. Thread is a line of execution. In a
single-threaded system there is only one execution line. That is, only one part of the
program is in the process of execution at any one time. Java provides a class Thread,
which permits creation of a new execution line. In order to create an applet that uses
threads, an instance of class Thread needs to be created and conveyed to the part of the
applet that it will be associated with. It is the smallest unit of code that is dispatched by
the scheduler.

Fundamentals of Threads:

Java provides built-in support for multithreaded programming. A multithreaded


program contains two or more parts that can run concurrently. Thus, multithreading is a
specialized form of multitasking. There are two different types of multitasking: process-
based and thread-based. A process is a program that is executing. Thus, process-based
multitasking is the feature that allows the computer to run two or more programs
concurrently. In a thread based multitasking environment, the thread is the smallest unit
of dispatchable code. This means that a single program can perform two or more tasks
simultaneously.
Thus, a process can contain multiple threads to execute its different sections. This is
called multithreading.
The class java.lang.Thread is used to create and control threads. To create a thread, a
new instance of the class must be created. Thread.start( ) must be called to actually make
the thread run. When Thread.start( ) is called, the thread begins executing in the run( )
method of the target class. A new Thread class always starts running the public void
run() method of a class.
When a program requires user input, multithreading enables creation of a separate thread
for the task alone. The main thread can continue with the execution of the rest of the
program. Programs not using multithreading will have to wait until the user has input a
value for the continuation of the execution of the program. The merits of using threads
are: It can be created faster and requires less overheads. Interprocess communication and
context switching is faster. It uses maximum CPU time.
There are four states associated with a thread. They are:
New: When a thread is created, it is in the new state. New implies that the thread object
has been created but it has not started running. It requires the start( ) method to start it.
Runnable: A thread is said to be in runnable state, when it is executing a set of
instructions. The run( ) method contains the set of instructions. This method is called
automatically after start( ) method.
Dead: The normal way for a thread to die is by returning from it’s run( ) method. We can
also call stop( ), but this throws an exception that’s a subclass of Error. Throwing an
exception should be a special event and not part of normal program execution, thus the
use of stop( ) is discouraged. There is also a destroy( ) method that should be called if we
can avoid it, since it is drastic and does not release object locks.
Blocked: The thread could be run but there is something that prevents it. While a thread
is in the blocked state the scheduler will simply skip over it and not give it any CPU time.
Until a thread re-enters the runnable state it will not perform any operations.

Common Thread Methods:


Some of the thread methods are:
start( ): The start method starts execution of the invoking object. It starts executing in the
run( ) method of its Runnable target that was set when the constructor was called. This
method can be called only once. It can throw an IllegalThreadStateException if the thread
was already started.
stop( ): This method terminates the invoking object. Currently, the thread does not stop
unless it is running. If it is suspended, it does not die until it starts running again.
suspend( ): This method suspends the invoking object. The thread will become runnable
again if it gets the resume ( ) method.
sleep( ): This method suspends execution of the executing thread for the specified
number of milliseconds. It can throw an InterruptedException.
resume( ): The resume( ) method restarts the suspended thread at the point at which it was
halted. The resume( ) method is called by some thread outside the suspended one, there is
a separate class called Resumer which does just that. Each of the classes demonstrating
suspend/resume has an associated resumer.
There are two ways to create a thread:
1. Extend the Thread class: With this technique the new class inherits from the class
Thread. The Thread can start running in the class’s run method.
2. Implement the Runnable interface: This technique is probably more common that
extending the Thread class. It is not necessary to define a new class to run the
thread. If a thread is to start running in the applet, it must use the Runnable
interface. The applet cannot inherit from both the Thread and Applet classes. An
applet with the Runnable interface must have a run ( ) method for the thread to
start.
There is not much difference between the two approaches. Both extending the Thread
class and implementing the Runnable interface have the same functionality. But if it
extend the thread class from the class it would not be able to extend any other class,
since Java does not support multiple inheritance. The interface approach must be used
if the thread is to actually start in the applet class. But if the thread is going to be
running in its own class, it may be more convenient to extend the Thread class.
Thread has various constructors. All of them create a new thread. The thread does not
start running until Thread.start( ) is called. When Thread.start( ) is called, the new
thread starts running in the run( ) method of an object. The constructors are:
Thread( )
Thread(Runnable)
Thread(ThreadGroup)
Thread(String)
Thread(ThreadGroup,String)
Thread(Runnable,String)
Thread(ThreadGroup,Runnable,String)

The constructors can use three possible parameters:


String: The name of the new thread is the parameter String. A thread can gets its
name by calling Thread.getName( ).
ThreadGroup: The new thread will belong to the group specified by the parameter
ThreadGroup. A ThreadGroup can be used to organize a thread.
Runnable: The Runnable parameter is an object that has implemented the Runnable
interface. The thread will start executing in the run( ) method of the Runnable
parameter when Thread.start( ) has been called.

Implementing Runnable
The easiest way to create a thread is to create a class that implements the Runnable
interface. Runnable abstracts a unit of executable code. Creation of a thread object
using Runnable interface can be constructed. To implement Runnable, a class needs
to implement a single method called run( ), which is declared as:
Public void run( )
Inside run( ), it will define the code that constitutes the new thread. The run( ) can call
other methods, use other classes and declare variables, just like the main thread can.

Example:
Open a new file and enter the following code:

class NewThread implements Runnable


{
Thread t;
NewThread( )
{
super(“demo thread”);
System.out.println(“child thread: ”+this);
start( );
}
}
public void run( )
{
try
{
for(int i=5; i>0; i--)
{
System.out.println(“Child Thread: “+i);
Thread.sleep(500);
}
}
catch(Interrupted Exception e)
{
System.out.println(“Child interrupted.”);
}
System.out.println(“Child thread gets finished.”);
}
}
class runthread
{
public static void main(String args[])
{
try
{
System.out.println(“Main Thread: “+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(“Main thread interrupted.”);
}
System.out.println( );
System.out.println(“Main thread gets finished.”);
System.out.println( );
}
}

Save the file as NewThread.java


Compile the file using javac NewThread.java
Execute the file using java NewThread.

Passing this as the first argument indicates that a new thread is calling the run( )
method on this object. A new object of NewThread class is created as the first step,
which calls its constructor. Inside the constructor, a new thread is created using one of
Thread class constructor, which takes as parameters- the object itself and a string.
This helps in creating new child threads apart from the main method. The start( )
method starts each of the newly created threads. Automatically, control passes to the
run( ) method. Within it, the sleep( ) method of the Thread class suspends the thread
for 500 milliseconds. Since this method generates an exception, it is enclosed within
try block. Simultaneously, the main thread continues with the execution of the main
program. The main thread enters the try block inside main( ) method and exits at the
end of the for loop. It is ensured that the child thread created is destroyed before main
thread terminates.

The output is
child thread Thread[Dem
calling run method
after calling run method
main thread: L 5
child thread: 5
child thread: 4
main thread: L 4
child thread: 3
child thread: 2
main thread: L 3
child thread: 1
main thread: L 2
child thread: L 1
main thread interrupted.

ThreadGroup is a data structure that controls the state of a collection of threads as a


whole.

Extending Thread:
The second way to create a thread is to create a new class that extends Thread and
then to create an instance of that class. The extending class must override the run( )
method, which is the entry point for the new thread. It must also call start( ) to begin
execution of the new thread.
The first constructor of Thread class can be given as
Thread(Runnable, String)
A new thread is created with the specified name. It applies the run( ) method on the
specified target. The next constructor creates a new thread in the specified
ThreadGroup with the specified name and it applies the run( ) method on the
specified target.
Thread(ThreadGroup, Runnable, String)

Example:
class NewThread extends Thread
{
NewThread( )
{
super(“demo thread”);
System.out.println(“child thread: “+this);
start( );
}
public void run( )
{
try
{
for(int i=5; i>0;i--)
{
System.out.println(“child thread: “+i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(“child interrupted”);
}
System.out.println(“Existing child thread”);
}
}
class extendthread
{
public static void main(String args[])
{
new NewThread( );
try
{
for(int i=5;i>0;i--)
{
System.out.println(“main thread: “+i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(“main thread interrupted”);
}
System.out.println(“main threa exiting”);
}
}

This program generates the same output. The child thread is created by instantiating an
object of NewThread, which is derived from thread. The call to super( ) inside
NewThread, invokes the Thread Constructor:
public Thread(String threadName)
here, threadName is the name of the thread.
The run( ) method executes using the newly created thread while the rest of the program
uses the main thread.

Methods of Thread Class:


The methods available in thread class are:
activeCount( ): It returns the current number of active Threads in this ThreadGroup.
currentThread( ): It returns a reference to the currently executing Thread object & it is
a static method.
isAlive( ): It is used to check whether given thread is alive.
getName( ): It gets and returns this Thread’s name.
getPriority( ): It gets and returns the Thread’s priority.
setName(String): It sets the Thread’s name.
setPriority(int): It sets the Thread’s priority.
join( ): It waits forever for this Thread to die.
toString( ): It returns a String representation of the Thread, including the thread’s
name, priority and thread group.

More on Threads:
It intends to introduce concepts like synchronization of threads to enable data
integrity, inter thread communication using wait( ), notify( ) and thread priorities.

Synchronization:
Two or more threads accessing the same data simultaneously may lead to loss of data
integrity. A way to prevent data from being corrupted by multiple threads is to prevent
the interruption of critical regions. Critical regions are placed where only one thread
should be running at once. Java uses the concept of monitor or a semaphore to enable the
loss of data integrity. A monitor is an object, used as a mutually exclusive lock. At a
time, only a thread can access the monitor. A second thread cannot enter the monitor until
the first comes out. Till such time, the other thread is said to be waiting. The keyword
synchronized is used in the code to enable synchronization. The word synchronized can
be used along with a method or within a block.

public void run( )


{
int i = 0;
int tmp;
for(; ;)
{
for(i=0;i<1000;i++)
{
synchronized(this)
{
num=num+10;
num=num-10;
}
}
try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
}
synchronized(this)
{
tmp=num;
}
System.out.println(Thread.currentThread( ).getName( )+ “sees the
number:”+tmp);
}
}

The following lines make up a protected critical region:

synchronized (this)
{
num =num+10;
num =num_10;
}
synchronized (this) ensures that only one thread can be in the following code bloc. The
argument this tells the thread to use the lock for this object.
The variable num is also referenced when the string is printed. The new code is as
follows:

synchronized (this)
{
tmp=num;
}
System.out.println(currentThread( ).getName( )+ “sees the number:” +tmp);
A critical region is used to copy num to temporary storage. The string is then printed
using the temporary storage. It would have been possible to synchronize the print line
directly, but it would cut performance because the print line does many other things hat
have nothing to do with referencing num. All the threads waiting to enter the critcal
region will needlessly wait longer while the print line is executed. Generally, the
synchronized blocks should be as small as possible while still protecting the critical
region. Both i and tmp are method variables so each running thread has its own private
copy. So it is not necessary that they have to be synchronized.

Deadlocks:
Deadlock is a special error that needs to be avoided that relates specifically to
multitasking, which occurs when two threads have a circular dependency on a pair of
synchronized objects. Deadlocks are always a danger in multithreaded environments.
Deadlock is a difficult bug to debug for two reasons:
 It occurs only rarely, when the two threads time-slice in ju8st the right way.
 It may involve more that two threads and two synchronized objects.
A common problem in concurrent programming is coordinating access to a shared
resource by enforcing a synchronization condition between multiple concurrent
processes. There are several algorithms available for preventing deadlocks.

Interthread Communication:
Java has three wait( ) and two notify( ) methods that aid in synchronizing threads. The
wait( ) methods cause the thread to pause in the critical region. While paused, the thread
releases its lock. It must get the lock again before it starts executing again. The notify( )
methods wake up threads that have called wait( ). Calling notify( ) when no wait( ) has
been called has no effect. The methods shown below are in object class and can only be
called in a synchronized block or method.

 public final void wait( ): This method causes the thread to wait forever until
a notify( ) or notifyAll( ) is called. The thread releases its lock on the critical
regions so that other threads may enter.
 public final void wait(long m): This method causes the thread to wait m
milliseconds for a notify( ) or notifyAll( ) to be called. After the time is
expired, the thread tries to resume execution. However, it must first re-obtain
the lock for the critical region. Another thread may have entered the critical
section while the thread was waiting.
 public final void wait(long m, int n): This method is similar to the previous
one except that it waits for m milliseconds plus n nanoseconds.
 public final void notify(): This method wakes up a thread that has previously
called wait( ). The thread that was waiting has to get the lock before it can
resume execution. It has to wait until the current thread leaves the critical
region. Only one thread that has called wait( ) is woken up. It is not
guaranteed that the first thread that called wait( ) is the first one woken up.
 public final void notifyAll( ): This method wakes up all the threads that have
called wait( ). Each waiting thread has to get the lock for the critical region
before it resumes. There can still be only one thread running in the critical
section at once.

Thread Priorities:
Java assigns to each thread a priority that determines how that thread should be treated
with respect to others. Thread priorities are integers that specify the relative priority of
one thread to another. As an absolute value, a priority is meaningless; a higher-priority
thread does not run any faster than a lower-priority thread it is the only thread running.
Instead, a thread’s priority is used to decide when to switch from one running thread to
the next. This is called a context switch. Each thread created has a priority attached to it.
The scheduler allocates time in accordance to these priorities. A thread with higher
priority can preempt the lower priority thread, thus taking CPU’s time. The yield( )
method enables provision of CPU’s time to threads with equal priority and prevents
monopolization of a single thread.The rules that determine when a context switch takes
place are simple:
 A thread can voluntarily relinquish control: This is done by explicitly yielding,
sleeping, or blocking on pending I/O.
 A thread can be preempted by a higher-priority thread. In this case, a lower-
priority thread that does not yield the processor is simply preempted- no matter
what it is doing—by a higher-priority thread. Basically, as soon as a higher-
priority thread wants to run, it does. This is called preemptive multitasking.
To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.

The general form is:


final void setPriority(int level)

here, level specifies the new priority setting for the calling thread. The value of level
must be within the range MIN_PRIORITY and MAX_PRIORITY. Currently, these
values are 1 and 10, respectively. To return a thread to default priority, specify,
NORM_PRIORITY, which is currently 5. These priorities are defined as final variables
within Thread.

Summary:
A thread is a line of execution and is the smallest unit of code that is dispatched by the
scheduler. A process containing multiple threads to execute its different section is called
multithreading. There are four states associated with a thread namely- new, runnable,
blocked and dead. Creation of new threads is done by creating objects of class Thread
and using Runnable interface. The keyword synchronized is used in the code to enable
synchronization. Java offers interprocess communication through the use of wait( ),
notify( ), notifyAll( ) methods of object class and all are synchronized methods. The
thread class has final variables declared like-NORM_PRIORITY,
MINIMUM_PRIORITY and MAXIMUM_PRIORITY to set default priorities.

Java Lang Package


The java.lang package is the package that is by default imported into any Java
program. This package includes several classes and interfaces. It provides classes that are
fundamental to the Java programming language. It is Java’s most widely used package.
Object class:
The object class is the base class of every class in Java. It defines the methods that every
class in Java supports. The methods defined in the object class are:
 public Boolean equals(Object ob)
 public string toSring( )
 protected Object clone( )
 protected void finalize( )
 public int hashCode( )
 public final void wait( )
 public final void notify( )
public Boolean equals(Object ob):
This method help in defining whether two objects contain the same members. It returns
either a true or false value.

public string toSring( ):


This method helps in printing the object to the outputStream. The default implementation
of toString prints the object’s class name and its hash code. The function can be
overridden to include additional information.

protected Object clone( ):


The clone( ) method creates a duplicate copy of an object. The class has to implement the
Cloneable interface when the object is used in this function.

protected void finalize( ):


When the object is removed from the memory by the garbage collector finalize( )
method is called. Overriding is not necessary for the function finalize( ).

public final void wait( ):


The wait( ) method is for making the thread in which the object is running to wait for
some time.

public final void notify( ):


The notify( ) method is for signaling the thread which is waiting to resume its operation.
If notify( ) is called before the object starts waiting, then notify( ) is ignored.

System class:
System class consists of a number of useful methods that deal with runtime environment.
It contains three public data streams. They are as follows:

public static InputStream in


public static PrintStream out
public static PrintStream err
These streams help in reading from or writing to the console.
Package: This class encapsulates version data associated with a package. This object
contain information about the implementation and the specification of a java package. It
is available in the classloader that loaded the class.

Interfaces of java.lang:
It contains three interfaces namely Cloneable, Comparable and Runnable.
Cloneable:
A class implements the cloneable interface to indicate to the Object.clone( ) method. The
exception CloneNotSupportedException will be thrown if the user clones instances,
which do not implement the Cloneable interface. This interface declares no methods.
Comparable:
Classes that implement Comparable interface contain objects that can be compared with
each other. It declares only one method. The syntax is:
int compareTo (Object obj)
This method compares the invoking object with obj. It returns 0 if the values are equal. A
negative value is returned if the invoking object has a lower value. Otherwise, a positive
value is returned. compareTo( ) method is defined by Byte, Character, Float, Long, Short,
String and Integer classes.
Runnable:
Any class that initiates a separate thread of execution must implement the Runnable
interface. It defines only one abstract method, called run( ). It is the method which is the
entry point to the thread. Threads that are created by the user must implement abstract
void run( ) method.

Wrapper class:
The java.lang package includes a number of classes that “wrap” a primitive data type in a
reference object. These classes constitute the wrapper classes. The wrapper classes
provide object versions of primitive data types. These classes include methods for
converting the value from one data type to another.
Number:
The Number class is the super class for the wrapper class like int, long, float and double
types. Any class that expects an instance of a Number may be passed an Integer, Long,
Float or Double class.
Integer:
The Integer class provides a wrapper for the int data type. It contains methods for
converting integers to Strings and vice versa.
The constructor use these form:
public Integer(int val)
public Integer(String s) throws NumberFormatException
Long:
The Long class provides a wrapper for the long data type. It contains methods for
converting long to strings and vice versa. The constructor takes the following form:
public Long(long val)
public Long(String s) throws NumberFormatException
Byte:
The Byte class provides a wrapper for the byte data type. It contains methods for
converting byte to strings and vice versa. The constructor takes the following form:
public Byte(byte val)
public Byte(String s) throws NumberFormatException

Short:
The Short class provides a wrapper for the Short data type. It contains methods for
converting Short to strings and vice versa. The constructor takes the following form:
public Short(Short val)
public Short(String s) throws NumberFormatException

Float:
The Float provides a wrapper for the float data type. In addition to string conversion, it
provides a way to directly manipulate the bits in a float. The following constructors are
supported by the Float class.
public Float(float value)
public Float(double value)
public Float(String s) throws NumberFormatException

Double:
The Double class provides a wrapper for the double data type. This class supports the
following constructors:
public Double(double value)
public Double(String s) throws NumberFormatException

Character:
The Character class provides a wrapper for the char data type. It contains methods for
converting characters to numeric digits and vice versa, to check whether a given character
is an alphabet, number and so on. This class has single constructor.

Boolean:
The Boolean class provides a wrapper for the Boolean data type. It has two types of
constructors.
public Boolean(boolean Value)
public Boolean(String str)
The class has a method called valueOf( ) that accepts a string as its argument. This
method can be used as an alternate way of creating a Boolean object from a String.

Void:
The wrapper class Void is used for rounding out the set of wrappers for primitive types.
This wrapper class has no constructor or method and contains only the TYPE attribute
that is common to all the wrapper classes.

Process:
The abstract Process encapsulates a process-that is an executing program. It is used
primarily as a super class for the type of objects created by exec( ) in the Runtime class.
Process contains the abstract methods.
Void destroy( ): It terminates the process.
int exit Value( ): It returns an exit code obtained from a subprocess.
InputStream getErrorStream( ): It returns an input stream that reads input from the
process’ err output stream.
InputStream getInputStream( ): It returns an input stream that reads input from the
process’ out output stream.
OutputStream getOutputStream( ): It returns an output stream that write output from the
process’ in input stream.
Int waitFor( ) throws: It returns the exit code returned by the interruptedException.

Runtime:
The Runtime class encapsulates the run – time environment. Runtime object can get a
reference by calling the static method Runtime.getRuntime( ).Once the reference to the
current Runtime object is obtained, it calls several methods that control the state and
behaviour of the Java Virtual Machine.
Method:
Process exec(String progName) throws IOException: It executes the program specified
by progName as a separate process. An object of type Process is returned that describes
the new process.
Process exec(String progName, String environment[]) throws IOException) throws
IOException: It executes the program specified by progName as a separate process with
the environment specified by the environment. An object of type process is returned that
describes the new process.
Runtime Permission:
This class is for runtime permission. A runtime Permission contains a target name and
they do not have any specific actions list. The target name is the name of the runtime
permission.
CreateClassLoader: It is the creation of a class loader. Using this permission application
this can instantiate their own class loaders could load their own rogue classes into the
system.
CreateSecurityManager: It is the creation of a new security manager. It is the sensitive
methods, which have information about other classes or the execution stack, can be
disclosed with this permission.
setIO: It is used for setting of System.out, System.in, and System.err. This allows
changing the value of the standard systems streams. A hacker may change System.in to
monitor the user input, or may set System.err to a “null” OutputStream, which would
hide any error messages sent to System.err.
modifyThread: It is used for the modification of threads. This allows a hacker to start or
suspend any thread in the system.
getProtectionDomain: It is used for the retrieval of the ProtectionDomain for a class. This
allows code to obtain policy information for a particular code source.
readFileDescriptor: It is used for reading of file descriptors. This would allow code to
read the particular file associated with the file descriptor read. This is dangerous if the file
contains confidential data.

Class Loader:
The class ClassLoader is an abstract class. It is responsible for loading classes. Array
classes are created automatically by the Java runtime. Class loaders do not create objects
for array classes. Security managers use class loaders to indicate security domains. The
class Loader class uses a delegation model to search for classes and resources. Each
instance of Class Loader has an associated parent class loader.
The ClassLoader searches for the class in its parent class loader before attempting to find
the class itself, whenever called for searching a class.
The virtual machine has a built-in class loader called the bootstrap class loader.
Bootstarp class loader acts as a parent class loader. All the methods and constructors
created by a class loader may reference other classes also.
Security Manager:
The security manager class allows applications to apply a security policy. It can decide an
application whether to allow a sensitive operation to be performed or not. The security
manager is set by the setSecurityManager method in class System and it is obtained by
the getSecurityManager method. checkPermission method has only one argument, which
performs security checks within the current executing thread. To overcome this the
getSecurityContext method includes a context argument.

About java.math class:


The java.math class contains methods that are used for geometric and trigonometric
solutions.
Methods in Math class:
sin:
The syntax is:
public static double sin(double a)
The sin method has only one double value a as the parameter. It returns the trigonometric
sine of an angle.

cos:
The syntax is:
public static double cos(double a)
The cos method has only one double value a as the parameter. It returns the trigonometric
cosine of an angle.

tan:
The syntax is:
public static double tan(double a)
The tan method has only one double value a as the parameter. It returns the trigonometric
tangent of an angle.

asin:
The syntax is:
public static double asin(double a)
The asin method has only one double value a (whose arc sine is to be returned) as the
parameter. It returns the arc sine of an angle, in the range of –pi/2 through pi/2.

acos:
The syntax is:
public static double acos(double a)
The acos method has only one double value as a parameter. It returns the arc cosine of an
angle, in the range of 0.0 through pi.

atan:
The syntax is:
public static double atan(double a)
The atan method has only one double value a (whose arc tangent is to be returned) as the
parameter. It returns arc tangent of an angle, in the range of –pi/2 through pi/2.

toRadians:
The syntax is:
public static double toRadians(double angdeg)
The toRadians method has only one double value angdeg as the parameter. It converts an
angle measured in degrees to the equivalent angle measured in radians.

toDegrees:
The syntax is:
public static double toDegrees(double angrad)
The toDegrees method has only one double value angrad as the parameter. It returns the
measurement of the angle angrad in degrees.

exp:
The syntax is:
public static double exp(double a)
The exp method has only one double value a as the parameter. It returns the exponential
number exponential number e raised to the power of a double value.

log:
The syntax is:
public static double log(double a)
The log method has only one double value a as the parameter. It returns the natural
logarithm (base e) of a double value.

sqrt:
The syntax is:
public static double sqrt(double a)
The sqrt method has only one double value a as the parameter. It returns the square root
of a, if the argument is NaN or less than zero, the result is NaN.

IEEEremainder:
The syntax is:
public static double IEEEremainder(double f1, double f2)
It calculates the remainder operation on two arguments. It has two parameters f1(the
dividend) and f2(the divisor) and is returns the remainder when f1 is divided by f2.

ceil:
The syntax is:
public static double ceil(double a)
The ceil method has only one double value a as the parameter. It returns the smallest
double value that is not less than the argument and is equal to a mathematical integer.

floor:
The syntax is:
public static double floor(double a)
The floor method has only one double value a as the parameter. It returns the largest
double value that is not greater than the argument and is equal to a mathematical integer.

rint:
The syntax is:
public static double rint(double a)
The rint method has only one double value a as the parameter. It returns the closest
double value to a that is equal to a mathematical integer. If two double values that are
equally close to the value of the argument, it returns the integer value that is event.

atan2:
The syntax is:
public static double atan2(double a, double b)
Two double values a and b are the parameters for the method. It converts rectangular
coordinates (b, a) to polar (r, theta). This method computes the phase theta by computing
an arc tangent of a/b in the range of –pi to pi.

pow:
The syntax is:
public static double pow(double a, double b)
Two double values a and b are the parameters for the method. It returns the value of the
first argument raised to the power of the second argument. If (a==0.0) then b must be
greater than 0.0. Otherwise an exception is thrown. An exception will also occur
if(a<=0.0) and b is not equal to a whole number.

round:
The syntax are:
public static int round(float a)
public static long round(double a)

The first syntax has only one float value a as the parameter. It returns the closest integer
to a. If the argument is negative infinity, the result is equal to the value of
Integer.MIN_VALUE. If it is a positive infinity, the result is equal to the value of
Integer.MAX_VALUE.
The second syntax has only one double value a as the parameter. It returns the closest
long to the argument. If the argument is negative infinity, the result is equal to the value
of Long.MIN_VALUE. If it is a positive infinity, the result is equal to the value of
Long.MAX_VALUE.

random:
The syntax is:
public static double random( )
It gives a random number greater than or equal to 0.0 and less than 1.0. The values that
are returned are chosen pseudorandomly.
abs:
The syntax are:
public static int abs(int a)
public static long abs(long a)
public static float abs(float a)
public static double abs(double a)
The first syntax has only one int value a as the parameter. It returns the absolute value of
int value. If the argument is positive, the same argument is returned. If the argument is
negative, the negation of the argument is returned.
The second syntax has only one long value a as the parameter. It returns the absolute
value of long value. If the argument is positive, the same argument is returned. If the
argument is negative, the negation of the argument is returned.
The third syntax has only one float value a as the parameter. It returns the absolute value
of float value. If the argument is positive, the same argument is returned. If the argument
is negative, the negation of the argument is returned.
The fourth syntax has only one double value a as the parameter. It returns the absolute
value of argument. If the argument is positive, the same argument is returned. If the
argument is negative, the negation of the argument is returned.

max:
The syntax are:
public static int max (int a, int b)
public static long max (long a, long b)
public static float max (float a, float b)
public static double max (double a, double b)
The first syntax has two int values a and b. These are the two parameters which returns
the larger of two int values a and b.
The second syntax has two long values a and b. These are the two parameters which
returns the larger of two long values a and b.
The third syntax has two float values a and b. These are the two parameters which returns
the larger of two float values a and b. If either value is NaN, then the result is NaN.
Unlike the numerical operators, this method considers negative zero to be strictly smaller
than positive zero.
The fourth syntax has two double values a and b. These are the two parameters which
returns the larger of two long values a and b. If either value is NaN, then the result is
NaN. Unlike the numerical operators, this method considers negative zero to be strictly
smaller than positive zero.

min:
The syntax are:
public static int min (int a, int b)
public static long min (long a, long b)
public static float min (float a, float b)
public static double min (double a, double b)
The first syntax has two int values a and b. These are the two parameters which returns
the smaller of two int values a and b.
The second syntax has two long values a and b. These are the two parameters which
returns the smaller of two long values a and b.
The third syntax has two float values a and b. These are the two parameters which returns
the smaller of two float values a and b. If either value is NaN, then the result is NaN.
Unlike the numerical operators, this method considers negative zero to be strictly smaller
than positive zero.
The fourth syntax has two double values a and b. These are the two parameters which
returns the smaller of two long values a and b. If either value is NaN, then the result is
NaN. Unlike the numerical operators, this method considers negative zero to be strictly
smaller than positive zero.

Summary:

The object class is the base class of every class in Java. It defines the methods that every
class in Java supports. The Runnable interface identifies a class as being Runnable as a
separate thread. The abstract Process class encapsulates a process –that is, an executing
program. Package class is one that encapsulates version data associated with a package.
Package objects contain version information about the implementation and specification
of a Java package. A RuntimePermission contains a target name and they don’t have any
specific actions list. A class loader is an object that is responsible for loading classes. The
Security Manager class allows applications to apply a security policy.

Util Package
Util package is the Java’s most prominent package and it contains Java’s most
powerful subsystems: Collections. A collection, sometimes called as a container, is
simply an object that groups multiple elements into a single unit. Collections are used to
store, retrieve and manipulate data and to transmit data from one method to another.
Collections represent data items that form a natural group. Java contained collection
implementations like array, Vector, Hashtable and dictionary, they did not contain a
collections framework.
Collection Framework:
A collections framework is a unified architecture for representing and manipulating
collections. All collections frameworks contain three things:

 Interfaces: It is the abstract data types representing collections. It allow


collections to be manipulated independently of the details of their representation.
In object-oriented languages like Java, these interfaces generally form a hierarchy.
 Implementations: It concrete implementations of the collection interfaces. In
essence, these are reusable data structures.
 Algorithms: It is the methods that perform useful computations, like searching
and sorting, on objects that implement collection interfaces. These algorithms are
said to be polymorphic because the same method can be used on many different
implementations of the appropriate collections interface. In essence, algorithms
are reusable functionality.
The merits of the Collections framework:
It reduces programming effort by providing useful data structures and algorithms.
Increases program speed and quality, since the implementation of each interface are
interchangeable.
It allows interoperability among unrelated APIs.
Extending or adapting a collection is easy.
It reduces the effort in designing new APIs.
It encourages the reuse of the software since the interfaces and algorithms are
reusable.

Interfaces:
The core collection interfaces are the interfaces used to manipulate collections and to
pass them from one method to another. The basic purpose of these interfaces is to allow
collections to be manipulated independently of the details of their representation. The
core collection interfaces are the heart and soul of the collections framework. The core
collection interfaces form a hierarchy: a Set is a special kind of Collection and a
SortedSet is a special kind of Set and so forth.

Core of collection Interfaces

Collection

Set List

SortedSet

Map

SortedMap
Note that the hierarchy consists of two distinct tress: a Map is not a true Collection.
Collection interfaces is at the top of the hierarchy. It enables us to work with group of
objects. The List interface extends the Collection interface and handles sequences. The
Set interface also extends the Collection interface and handles sets. The collection
interfaces allow some methods to be optional. These optional methods enable us to
modify the contents of a collection. Collections that support these methods are called
modifiable and those that do not support are called unmodifiable. If an attempt is made to
invoke an unsupported operation, the UnsupportedOperationException is thrown.
Implementations are responsible for documenting which of the optional operations they
support. All of the JDK’s general purpose implementations all of the optional operations.

Collection Interface:
The collection interface is the root of the collection hierarchy. A Collection represents a
group of objects, known as its elements. Some Collection implementations allow
duplicate elements and others do not. Some are ordered and others unordered. The Java
Development Kit does not provide any direct implementations of this interface: It
provides implementations of more specific sub interfaces like Set and List. This interface
is the least common denominator that all collections implement. Collection is used to
pass collections around and manipulate them when maximum generality is desired.

Methods of the Collection interface:

 boolean add(Object a): It adds the given object to the current collection. It returns true
if the object was added.

 boolean addAll(Collection c): It adds all the elements of the Collection c to the
current collection. It returns true when the element is added.

 void clear( ): It removes all the elements from the current collection.

 boolean contains(Object a): It checks whether the object a is an element of the current
collection.

 boolean containsAll(Collection c): It checks whether the current collection contains


all the elements of the collection c.
 boolean equals(Object a): It checks whether the object a and the current collection are
equal.

 int hashCode( ): It returns the hash code of the current collection.

 boolean isEmpty( ): It checks whether the current collection is empty.

 Iterator iterator( ): It returns an iterator for the current collection.

 boolean remove(Object a): It removes an instance of the object a from the current
collection.

 boolean removeAll(Collection c): It removes all the elements of the Collection c


from the current collection.

 boolean retainAll(Collection c): It retains only the elements of the Collection c in the
current Collection and removes all the other elements from it.

 int size( ): It returns the number of elements of the current collection.

 Object[ ] toArray( ): It returns a copy of all the elements of the current collection to
an Object array.

 Object[ ] toArray(Object a[]): It returns a copy of only those elements of the current
collection whose type matches that of the object array a, to an object array.
Set:
A Set is a Collection that cannot duplicate elements. Set abstraction is used to represent
sets like the cards comprising a poker hand, the courses making up a process running on a
machine.
Set Interface:
The Set interface extends Collection and contains no methods other than those inherited
from Collection. It adds restriction that duplicate elements are prohibited. Set also adds a
stronger contract on the behaviour of the equals and HashCode operations, allowing Set
objects with different implementation types to be compared meaningfully. Two Set
objects are equal if they contain the same elements. It also adds restriction on the equals()
and hashCode( )mehods. There are two Set implementations. They are HashSet and
TreeSet. HashSet stores its elements in a hash table, is the best-performing
implementations. TreeSet stores its elements in a red-black tree, guarantees the order of
iteration.

Collection noDups = new HashSet(c);


It works by creating a Set initially containing all the elements in c. It uses the “standard
Collection constructor”.

SortedSet Interface:
The SortedSet interface extends the Set interface. The elements of this interface are
sorted in ascending order. If the current set does not contain any element, then many of
the methods listed in the table throw the NoSuchElementException. When an object is
incompatible with the elements in a set then the ClassCastException is thrown. A
NullPointerException is thrown if we attempt to use a null object and null is not allowed
in the set.
Methods:
 Comparator comparator( ): It returns the comparartor of the current sorted set. It
returns null if the natural ordering is used for the set.

 Object first( ): It returns the first element of the current sorted set.

 SortedSet headSet(Object a):It returns a SortedSet that contains elements less than the
object a from the current sorted set.

 Object last( ): It returns the last element of the current sorted set.

 SortedSet subSet(Object a, Object b): It returns a SortedSet containing elements


between the object a and object b-1.

 SortedSet tailSet(Object a): It returns a SortedSet containing elements greater than or


equal to a from the current sorted set.

The methods of the SortedSet interface can be divided into three categories. They are:

 Range-view operations
 Endpoint operations
 Comparator Accessor

Range-view operations:
It performs arbitrary range operations over the sorted set. The range-view of a sorted set
remains valid even if the original sorted set is modified directly. This is because the
range-view of a sorted set is a window of a portion of the set that lies in the designated
part of the element-space. Any change to the range-view is written back to the original
sorted set and vice versa. The methods subSet, headSet and tailSet are the Range-view
operations of the sorted set. The subSet method is used for a sorted set of strings called
stringSet.
int count = stringSet.subset (“a”,”z”).size( )
The search includes a but excludes b while searching. If we want to exclude both the
letters while searching, then the code statement will be as:
int count = stringSet.subset (“a\0”,”z”).size( )
On the other hand, in order to include both the letters in the search, we give the code
statement as:
int count = stringSet.subset (“a”,”z\0”).size( )
The headset method is used to view the sorted set from the beginning upto the specified
object. To view all the letters upto z from the sorted set named stringSet, the code is:
SortedSet s1= stringSet.headSet (“z”);
The tailSet method is used to view the sorted set starting from the specified object upto
the end of the sorted set.
SortedSet s1 = stringSet.tailSet(“z”);

Endpoint Operations:
The Endpoint operations, namely, the first and last methods are used to return the first
and the last elements of the sorted set. These methods can be used in combination with
the range-view operations to get desired result.
String s = stringSet.headSet(“z”).last( )

Comparator Accessor:
The comparator method is the comparator accessor that returns the comparator used to
sort the set. If the set is sorted according to the natural order of its elements, then the
method returns a null.

Iterator Interface:
Iterator allows the user to remove elements from the current collection during the
iteration with well-defined semantics, whereas Enumeration does not allow such removal.
Method names have been improved in Iterators as compared to Enumeration.
There was no safe way to remove elements from a collection while traversing it with an
Enumeration. The semantics of the operation were ill-defined and differed from
implementation to implementation.
The Iterator interface is:
public interface Iterator
{
boolean hasNext( );
Object next( );
void remove( );
}

Methods used are:


 boolean hasNext( ): If the iteration has more elements then it returns true, else, it
returns false.

 Object next( ): It returns the next element in the iteration. If the iteration has no more
elements, then it throws the NoSuchElementException.

 void remove( ): It removes the last element returned by the iterator, from the current
collection. It can be called only once per call to the next method.

Operations:
It is used in Sets to perform standard set-algebraic operations.
 containsAll: It returns true if the target Collection contains all of the elements in
the specified Collection ( c).
 addAll: It adds all of the elements in the specified Collection to the target
Collection.
 retainAll: It removes from the target Collection all of its elements that are not
also contained in the specified Collection. It retains only those elements in the
target Collection that are also contained in the specified Collection.
 removeAll: It removes from the target Collection all of its elements that are
contained in the specified Collection.
 clear: It removes all elements from the Collection.

List:
A List is an ordered collection. Lists can duplicate elements. The user of a List generally
has precise control over where in the List each element is inserted. The operations of the
List interface are:
 Positional Access: It manipulates element based on their numerical position in the
list.
 Search: It searches for a specified object in the list and return its numerical
position.
 List Iteration: It extends Iterator semantics to take advantage of the list’s
sequential nature.
 Range-view: It performs arbitrary range operations on the list.

Methods:
 void add(int index, Object a): It inserts the object a into the current list at the position
specified by index. The preceding elements are shifted up in the list.
 boolean addAll(int index, Collection c): It inserts the element of the Collection c into
the current list at the position specified by the index. The preceding elements are
shifted up in the list.

 Object get(int index): It returns the object stored at the position specified by index,
within the current collection.

 int indexOf(Object a): It searches for the object a in the current list and returns the
index of its first instance.

 int lastIndexOf(Object a): It searches for the object a in the current list and returns the
index of the last instance.

 ListIterator listiterator( ): It returns an iterator to the start of the current list.

 ListIterator listiterator(int index): It returns an iterator to the current list that begins at
the position specified by the index.
 Object remove(int index): It removes the element at the position specified by index
from the current list.
 Object set(int index, Object a): It assigns a to the position specified by index in the
current list.

 List subList(int starting, int ending): It returns a list that includes elements from the
position specified by starting to the position specified by ending –I in the current list.

The methods of the interface can be categorized into methods used for Positional Access,
Search, List Iteration and Range-view. The get, set, add, remove and addAll methods are
the methods used for Positional access. The indexOf and lastIndexOf methods are used
for search. The two listIterator methods are used for Iteration. The subList method is the
Range-view method.

Map Interface:
Map is an object that maps keys to values and cannot contain duplicate values. Each key
can map to at most one value only. The interface consists of methods for Basic
operations, Bulk operations, and Collection Views. The basic operations are the put, get,
remove, containsKey, containsValue, size and isEmpty methods. The bulk operations are
putAll and clear methods. The Collection Views are keySet, values and entrySet
methods.
public interface Map
{
//Basic Operations
Object put(Object key, Object value);
Object get(Object key);
Object remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size( );
boolean isEmpty( );

//Operations:
void putAll(Map t);
void clear( );

//Collection Views
public Set keySet( );
public Collection values( );
public Set entrySet( );

//Interface
public interface Entry {
Object getKey( );
Object getValue( );
Object setValue(object val);
}
Method:
 Void clear( ): It removes all the mappings from the current map.
 boolean containsKey(Object key): It checks whether the current map contains a
mapping for the key key.
 boolean containsValue(Object val): It checks whether the current map maps one or
more keys to the value val.
 Set entrySet( ): It returns a set view of the mappings in the current map.
 boolean equals(Object a): It checks whether the object a is equal to the current map.
 Object get(Object key): It returns the value to which the current map maps the key
key.
 int hashCode( ): It returns the hash code value of the map.
 Boolean IsEmpty( ): It checks whether the current map contains any key value
mappings.
 Set keySet( ): It returns a set of view of the keys in the current map.
 Object put(Object key, Object val): It associates the val with the key in the current
map.
 void putall(Map m): It copies all the mappings from the map m to the current map.
 Object remove(Object key): It removes the mapping is present for the key in the
current map.
 int size( ): It returns the number of key-value mapping in the current map.
 Collection values( ): It returns a collection view of the values contained in the current
map.

SortedSet:
A SortedSet is a set that maintains its elements in ascending order. Several additional
operations are provided to take advantage of the ordering. The SortedSet interface is used
for things like word lists and membership rolls.

SortedMap:
A SortedMap is a Map that maintains its mapping in ascending key order. It is the Map
analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and
telephone directories.

SortedMap Interface:
The SortedMap interface extends the Map interface. The SortedMap interface maintains
its entries in the ascending order, sorted either according to the natural order of the key or
according to a comparator provided while creating the SortedMap.

public interface SortedMap extends Map {


Comparator comparator( );
SortedMap subMap(Object fromKey, Object toKey);
SortedMap headMap(Object toKey);
SortedMap tailMap(Object fromKey);

Object firstKey( );
Object lastKey( );
}
Methods:
 Comparator comparator( ): It returns the comparator associated with the current
sorted map.

 Object firstKey( ): It returns the currently lowest key in the sorted map.

 SortedMap headMap(Object key):It returns a view of that portion of the current


sorted map whose keys are less than key.

 Object lastKey( ): It returns the currently highest key in the sorted map.

 SortedMap subMap(Object from, Object to): It returns a view of that portion of


the sorted map whose keys range from the key specified by from, to the key
specifie by to. The range includes from and excludes to.

 SortedMap tailMap(Object from): It returns a view of that portion of the sorted


map whose keys are greater than or equal to the key specified by from.

Implementations:
Implementations are the actual data objects used to store the collections. Some of the
classes provide the full implementation and can be used. The others are abstract and are
used as starting points for creating concrete collections. The standard collection classes
are:
 AbstractCollection: The AbstractCollection class provides a skeleton
implementation of the Collection interface. To implement an unmodifiable
collection, it is sufficient to extend the class and provide implementations for the
iterator and size methods. We have to additionally override the add method of the
class and the iterator returned by the iterator method must implement its remove
method in order to implement a modifiable collection.
 AbstractList: The AbstractList class extends the AbstractCollection class and
provides a skeletal implementation of the List interface. To implement a
modifiable list, it has to additionally override the set and remove methods. To
implement an unmodifiable list, it would extend the class and provide
implementations for the get and size methods.
 AbstractSequentialList: This class extends the AbstractList class and it is the
implementation of the List interface. It is used by a collection that uses sequential
access rather than random access to access its elements. To implement a list, it has
to extend the class and provide implementations for the listIterator and size
methods.
 LinkedList: It extends the AbstractSequentialList class and implements the List
interface. It implements all the optional list operations.
 ArrayList: It extends the AbstractList class and is a resizable-array
implementation of the List interface. It provides methods to manipulate the size of
the array that is used to store the list internally.
 AbstractSet: It extends the AbstractCollection class and provides the skeletal
implementation of the Set interface. It doe not override any of the
implementations from the AbstractCollection class. It adds implementations for
equals and hashCode.
 HashSet: It extends the AbstractSet class and implements the Set interface. It is
backed by a hash table. It offers constant time performance for the basic
operations.
 TreeSet: It extends the Abstractset interface and implements the Set interface. It is
backed by the TreeMap instance. It assures that the sorted set will be in ascending
order, sorted according to the bnatural order.

ArrayList class:
It provides methods to manipulate the size of the array used to store the list internally.
The size of the array is greater than or equal to the size of the list and it can grow or
shrink dynamically as we add or remove elements to or from the list.
The constructors used are:
1. ArrayList( ): It creates an empty array list.

2. ArrayList(Collection c): It creates an array list whose elements are taken from the
Collecton c, in the order returned by c’s iterator.

3. ArrayList(int cap): It creates an empty array list whose initial capacity is specified
by cap.

The methods are:


 Object clone( ): It returns a duplicate of the current instance of the ArrayList.
 void ensureCapacity(int min): It increases the capacity of the ArrayList instance
to ensure that it can hold a minimum of min number of elements.
 Object[ ] toArray( ): It returns an array containing the elements of the current list
in the correct order.
 Object[ ] toArray(Object[ ] a): It returns an array containing the elements of the
list a in the correct order.
 void trim ToSize( ): It trims the capacity of the current ArrayList instance to the
current size of the list.

LinkedList Class:
It provides a linked-list data structure. The constructors are:
 LinkedList( ): It creates an empty linked list.

 LinkedList(Collection c): It creates a linked list using the elements of the collection c.

The methods are:


 void addFirst(Object a): It inserts the object a at the beginning of the current list.

 void addLast(Object a): It inserts the object a at the end of the current list.
 Object getFirst( ): It returns the first element in the current list.

 Object getLast( ): It returns the last element in the current list.

 Object removeFirst( ): It removes the first element from the current list.

 Object removeLast( ): It removes the last element from the current list.

HashSet Class:
It creates a collection that uses a hash table for storage. It offers constant time
performance for basic operations. The constructors are:
 HashSet( ): It creates an empty hash set.

 HashSet(Collection c): It creates a hash set whose elements are taken from the
collection c.

 HashSet(int cap): It creates a hash set with the initial capacity specified by cap.

 HashSet(int cap, float load): It creates a hash set with the initial capacity specified by
cap and the load factor specified by load.

TreeSet Class:
It is used for storing large amounts of sorted information that must be retrieved quickly.
The constructors are:
 TreeSet( ): It creates an empty trees set. Its element will be sorted in the ascending
order according to the natural order of the elements.
 TreeSet(Collection c): It creates a tree set whose elements are taken from the
collection c.
 TreeSet(Comparator com): It creates a tree set whose elements are sorted according to
the comparator com.
 TreeSet(SortedSet s): It creates a tree set whose elements are taken from the sorted set
s.

HashMap Class:
It provides all of the optional map operations. It also allows null values and null key.
Initial capacity and the load factor are the two parameters that affect the instance of the
HashMap. The initial capacity determines the capacity of the hash table when it is
created. The load factor determines how full the hash table can become before its
capacity is automatically increased. It implements the method of its predecessors. It does
not contain any method of its own.
The constructors are:
 HashMap( ): It creates an empty map with the default capacity and load factor.
 HashMap(int cap): It creates an empty map with the capacity specified by cap and
default load factor.

 HashMap(int cap, float load): It creates an empty map with the capacity specified by
cap and the load factor specified by load.

 HashMap(Map m): It creates a map with the mappings specified by the map m.

TreeMap Class:
It maps in the ascending key order. The constructors are:
 TreeMap( ): It creates an empty tree map. The elements of the tree map will be sorted
according to the natural order of its keys.

 TreeMap(Comparator com): It creates an empty tree based map. The elements of the
tree map will be sorted based on the comparator com.

 TreeMap(Map m): It creates a tree map whose elements are taken from the Map m
and sorted based on the natural order of its keys.

 TreeMap(SortedMap s): It creates a tree map whose elements are taken from the
sorted map s and sorted in the same order as that of s. This class implements the
methods of its predecessor and does not define any additional methods of its own.

Algorithms:
It is static method within the Collection class. These methods include methods for
sorting, searching, shuffling, data manipulation, etc. The first argument of this method is
the collection on which the operation is performed. Many of this method operate on the
List interface and a couple of them operate on arbitrary objects of the Collection
interface. When it is comparing incompatible types, this method throw
ClassCastException. To modify an unmodifiable collection, this method throws
UnsupportedOperationException.
The methods are:
 int binarySearch(List l,Object a): It searches for the object a in the list l using binary
search algorithm and returns the position of a in the list. If the object is not found, it
returns -1. The collection has to be sorted before this method is executed.

 int binarySearch(List l, Object a, Comparator com): It searches for the object a in the
list l according to the comparator c and returns the portion of a in the list. If the object
is not found, it returns -1.

 void copy(List l1, List l2): It copies the elements of the list l2 to list l1.

 Enumeration enumeration(Collection c): It returns an enumeration over the collection


c.
 void full(List l, Object a): It assigns the object a to each element of the list l.

 Object max(Collection c): It returns the maximum element of the collection c


according to the natural ordering of its elements. The collection need not be sorted.

 Object max(Collection c, Comparator com): It returns the maximum element of the


collection c according to order specified by the comparator c. The collection need not
to be sorted.

 Object min(Collection c): It returns the minimum element of the collection


caccording to the natural ordering of its elements.

 Object min(Collection c, Comparator com): It returns the minimum element of the


collection c according to order specified by the comparator c.

 List nCopies(int n, Object a): It returns n copies of the object a in an immutable list.

 void reverse(List l): It reverses the sequence of the elements in the list l.

 Comparator reverseOrder( ): It returns a reverse comparator.

 void shuffle(List l, Random rand): It shuffles the list l according to a default source of
randomness.

 Set singleton(Object a): It returns the object a as an immutable set.

 void sort(List l): It sorts the elements of the list l in the ascending order according to
the natural order according to the natural order of its elements.

 void sort(List l, Comparator com): It sorts the elements of the list l according to the
order specified by the comparator com.

 Collection synchronizedCollection(Collection c): It returns a synchronized, a thread-


safe collection based on the collection c.

 List synchronizedList(List l): It returns a synchronized, a thread-safe list based on the


list l.

 Map synchronizedMap(Map m): It returns a synchronized, a thread-safe map based


on the map m.

 Set synchronizedSet(Set s): It returns a synchronized, a thread-safe set based on the


set s.
 SortedMap synchronizedSortedMap(SortedMap s): It returns a synchronized, a
thread-safe sorted map based on the sorted map s.

 SortedMap synchronizedSortedSet(SortedSet s): It returns a synchronized, a thread-


safe sorted set based on the sorted set s.

 Collection unmodifiableCollection(Collecton c): It returns an unmodifiable collection


based on the collection c.

 List unmodifiableList(List l): It returns an unmodifiable list based on the list l.

 Map unmodifiableMap(Map m): It returns an unmodifiable map based on the map m.

 Set unmodifiableSet(Set s): It returns an unmodifiable set based on the set s.

 SortedMap unmodifiableMap(SortedMap s): It returns an unmodifiable sorted map


based on the sorted map s.

 SortedSet unmodifiableSortedSet(SortedSet s): It returns a unmodifiable sorted set


based on the sorted set s.

These are the collection of the synchronization method list.

Unmodifiable Methods: It returns the views of their corresponding collections. The return
values of the unmodifiable methods cannot be modified. These views are helpful when a
process that uses the collection should not be allowed to modify it.
The Collection class defines two immutable fields. One of them is empty list named
EMPTY_LIST and the other one is an empty set named EMPTY_SET.

Legacy Classes and Legacy Interfaces:


Legacy Classes and Legacy Interfaces contained some classes and an interface, which
were used to store objects. The Legacy Classes are synchronized as opposed to the
classes in the collections framework. The Legacy classes are Dictionary, Hashtable,
Properties, Stack and Vector. The Legacy Interface is the Enumeration interface.

Vector:
The Vector container was the only self-expanding sequence in Java. It implements a
growable array of objects. Its component can be accessed using an integer index. Each
Vector maintains a capacity and capacityIncrement. The capacity is always greater than
or equal to the vector size. Vector defines its own methods for adding and retrieving
objects from the container. The difference between a Vector and an ArrayList is that the
methods of the Vector class are synchronized, that is, they can be accessed from multiple
threads.
The constructors are:
 Vector( ): It creates an empty vector. Its size is 10 and capacity increment is 0.

 Vector(Collection c): It creates a vector containing the elements of the Collection c.


The elements are accessed in the order returned by the collection’s iterator.

 Vector(int cap): It creates an empty vector with initial capacity specified by cap and
capacity increment 0.

 Vector(int cap, int inc): It creates an empty vector with initial capacity specified by
cap and capacity increment increment specified by inc.

The Methods are:


 void add(int ind, Object a): It adds the object a at the portion specified by ind in the
current Vector.
 boolean addAll(int ind, Collection c): It adds the elements of the collection c into the
current Vector, at the position ind.
 int capacity( ): It returns the capacity of the vector.
 void clear( ): It removes all the elements from the vector.
 boolean contains(Object a): It checks whether the object a is an element of the
Vector.
 void copyInto(Object[ ] a): It copies the elements of the Vector into the array a.
 Object elementAt(int ind): It returns the element of the Vector at the position ind.
 boolean equals(Object a): It checks whether the object a is equal to the current vector.
 Object firstElement( ): It returns the first element of the current vector.
 int indexOf(Object a, int ind): It searches for the first occurrence of the object a in the
current Vector, starting the search at the index ind.
 void insertElementAt(Object a, int ind): It inserts the object a at the position specified
by ind, in the current vector.
 boolean isEmpty( ): It checks whether the current vector is empty or has any
elements.
 Object lastElement( ): It returns last element of the vector.
 Object remove(int ind): It removes the element at the position ind in the current
vector.
 boolean remove(Object a): It removes the first occurrence of the object a in the
current vector.
 void removeRange(int from, int to): It removes those elements from the current
vector whose index is between from and to.
 int size( ): It returns the number of elements in the current vector.
 Object[ ] toArray(Object[ ] a): It returns an array containing the elements of the
current Vector in the correct order.

Dictionary:
It is an abstract class which maps keys to values and operates similar to Map. Every key
and value is an object in the class. Each key is mapped to at most one value. It contains
only one constructor, that is: Dictionary( ).
Methods are:
 Enumeration elements( ): It returns an enumeration containing the elements in the
current dictionary.
 Object get(Object a): It returns the value to which the object a is mapped. If the object
a is not present in the dictionary, then a null object is returned.
 boolean isEmpty( ): It checks whether the current dictionary contains any key.
 Enumeration keys( ): It returns an enumeration containing the keys in the current
dictionary.
 Object put(Object key, Object val): It maps the object key to the object val in the
current directory.
 Object remove(Object a): It removes the key specified by the object a and its value
from the current dictionary and returns the value associated with a.
 int size( ): It returns the number of entries in the current dictionary.

Hashtable:
It stores key-value pairs in a hash table. It must specify the key and the value to be
mapped to that key. The key is hashed and the hash code is used as the index of the
position at which the value is stored. The object of the Hashtable class must override the
hashcode( ) and equals( ) methods of the Object class. The hashCode( ) method is used to
convert the key to its equivalent hash code, and equals( ) method is used to compare two
objects.
The constructors are:
 Hashtable( ): It creates an empty hash table with default capacity and load factor.
 Hashtable(int cap): It creates an empty hash table with the initial capacity specified
by cap and default load factor.
 Hashtable(int cap, float load): It creates an empty hash table with the initial capacity
specified by cap and the load factor specified by load.
 Hashtable(Map m): It creates a hash table whose mappings are those of the map m.

The methods are:


 void clear( ): It removes all the keys from the hash table.
 Object clone( ): It creates a duplicate of the current hash table.
 boolean contains(Object a): It checks whether the hash table contains any key mapped
to the value specified by a.
 boolean containsKey(Object a): It checks whether the hash table contains a key
specified by a.
 boolean containsValue(Object a): It checks whether the hash table contains one or
more keys mapped to value specified by a.
 Enumeration elements( ): It returns an enumeration containing the values of the
current hash table.
 Object get(Object a): It returns the value associated with the key specified by a.
 boolean isEmpty( ): It checks whether the hash table is empty.
 Enumeration keys( ): It returns an enumeration containing the keys of the current
hash table.
 Object put(Object a, Object b): If the key specified by a is already present in the hash
table then it is mapped to the value specified by b.
 void rehash( ): It increases the size of the hash table and rehashes its key.
 Object remove(Object a): It removes the key specified by a and its associated value
from the hash table and returns the value.
 int size( ): It returns the number of keys in the current hash table.
 String toString( ): It returns a string representation of the hash table.

Enumeration:
It is the only one legacy interface. It defines methods, which help us to enumerate the
elements in a collection of objects. It has been superceded by Iterator.
The methods are:
 boolean hasMoreElements( ): It checks whether the enumeration contains more
elements.
 Object nextElement( ): It returns the next element of the enumeration. If there are no
more elements to retrieve then it throws NoSuchElementException.

Properties:
It is a subclass of Hashtable. It is used to maintain lists of values in which the key is a
String and the value is also a String. The Properties class is used by many other Java
classes. It represents a persistent set of properties. Each key and its value in the property
list is a string. It can also contain another property list as its “defaults”. The default
property list will be searched if the key is not present in the current property list. This
class is used by many other Java classes.
The constructors are:
 Properties( ): It creates an empty property list with no default values.
 Properties(Properties def): It creates an empty property list with the default
values specified by def.
The Methods are:
 String getProperty(String key): It returns the value associated with the key in the
current property list.
 String getProperty(String key, String prop): It returns the value associated with
the key in the current property list.
 void list(PrintStream out): It sends the property list to the output stream specified
by out.
 void list(PrintWriter str): It sends the property list to the output stream specified
by str.
 void load(InputStream in): It inputs a property list from the input stream specified
by in.
 Enumeration propertyNames( ): It returns an enumeration of the keys in the
current property list.
 Object setProperty(String key, String val): It calls the hashtable method put to
associate the value specified by val with the key specified by val.
 void store(OutputStream out, Sring desc): It writes the property list in the
Properties table to the output stream specified by out.
Other Classes of the Util Package:

The util package is fundamental to any platform. It provides classes and interfaces. These
classes and interfaces help the programmers to fulfil the wide range of their programming
needs. It also contains collection framework, legacy collection classes, event model, date
and time facilities, internationalization, and utility classes like BitSet, Calendar, String
tokenizer, Date, Locale and Random.

Classes of java.util package:


String tokenizer:
The processing of text often consists of parsing a formatted input string. Parsing is the
division of text into a set of discrete parts, or tokens, which in a certain sequence can
convey a semantic meaning. The StringTokenizer class provides the first step in the
parsing process, called the lexer or scanner. It implements the Enumeration interface.
Therefore, using StringTokenizer, we can enumerate the individual tokens contained in
the given input string. To use string tokenizer, the input string should contain delimiters.
Delimiters are characters that separate tokens. Each character in the delimiter’s string is
considered a valid delimiter. The default set of delimiters consists of the white space
characters like space, tab, new line and carriage return.

The constructors are:

public StringTokenizer(String str):


It constructs a String tokenizer for the specified string. The tokenizer uses the default
delimiter set, which is “\t\n\r\f”: the space character, the tab character, the newline
character, the carriage-return character and the form-feed character. Parameters:
str - a string to be parsed.

public StringTokenizer(String str, String delim):


It constructs a string tokenizer for the specified string. The characters in the delim
argument are the delimiters for separating tokens. Parameters: str- a string to be parsed.
delim – the delimiters.

public StringTokenizer(String str, String delim, boolean returndelims):


It constructs a string tokenizer for the specified string. All the characters in the delim
argument are the delimiters for separating tokens. If the returnDelims flag is true, then the
delimiter characters are also returned as tokens. Each delimiter is returned as a string of
length one. If the flag is false, the delimiter characters are skipped and only serve as
separators between tokens. Parameters: str- a string to be parsed.
delim- the delimiters, returnDelims- flag indicating whether to return the delimiters as
tokens.

The methods are:


 boolean hasMoreTokens( ): It checks whether there are more tokens available
from the tokenizer’s string. It returns true if one or more tokens remain in the
string and returns false if there are none.

 String nextToken( ): It returns the next token from the string tokenizer.
String nextToken(String delim): It returns the next token as a String and sets the
delimiters string.

 boolean hasMoreElements( ): It returns the same value as the hasMoreTokens


method. It exists so that this class can implement the Enumeration interface.

 Object nextElement( ): It returns the same value as the nextToken method, except
that its declared return value is Object rather than String. It exists so that this class
can implement the Enumeration interface.

 int countTokens( ): It determines the number of tokens left to be parsed and


returns the result.

BitSet:
This class creates a special type of array that holds bit values. It can increase the size as
needed. It makes is similar to a vector of bits. Usually it is use to efficiently store many
“on/off” information. Its efficiency was only seen in size not for speed. The BitSet
container is slightly slower than using an array of some native type. The minimum size of
the BitSet is 64 bits long. The constructors are:
 BitSet( ): It creates a default object.
 BitSet(int size): It allows the user to specify its initial size.
The methods are:
 void and (BitSet bitSet): It adds the contents of the invoking BitSet object with
those specified by bitSet. The result is placed into invoking object.

 void andNot (BitSet bitSet): For each 1 bit in bitSet , the corresponding bit in the
invoking BitSet is cleared.

 boolean get (int bitIndex): It returns the current state of the bit at the specified
index.
 int hashCode( ): It returns the hash code for the invoking object.

 String toString( ): It returns the string equivalent of the invoking BitSet object.

 Void xor (BitSet bitSet): XORs the contents of the invoking BitSet object with
that specified by BitSet. The result is placed into invoking object.

Date:
The Date class encapsulates the current date and time. It represents a specific instant of
time, with millisecond precision. The Date class has two additional functions. It allows
the interpretation of dates as year, month, day, hour, minute and second values. It also
allowed the formatting and parsing of date strings. The constructors are:
 Date( ): It allocates a Date object and initializes the object with current date and
time, so that it represents the time at which it was allocated, measured to the
nearest millisecond.
 Date(long millisec): It accepts only one argument that equals the number of
milliseconds that have elapsed.

The methods are:


 boolean after(Date date): It checks whether this date is after the specified date.
 boolean equals(Object date): It checks whether the invoking Date object contains
the same time and date as the on specified by date.
 Object clone( ): It duplicates the invoking Date object.
 Int compareTo(Date datei): It compares the value of the invoking object with that
of date and returns 0 if the values are equal.
 Int compareTo (Object obj): It operates identically to compareTo(Date) if obj is of
class Date.
 void setTime(long time): It sets the time and date as specified by time, which
represents as elapsed time in milli-seconds.
 String toString( ): It converts the date object to a String.

1. public Date( ): It allocates a Date object and initializes it so that it represent


the time at which it was allocated, measured to the nearest millisecond.
2. public Date(long date): It allocates a Date object and initializes it to represent
the specified number of milliseconds.
3. public Date(int year, int month, int date): It allocates a Date object and
initializes the year, month and date.
4. public Date(int year, int month, int date, int hrs, int min): It allocates a Date
object and initializes it so that it represents the instant at the start of the minute
specified by the year, month, date, hrs and min arguments.
5. public Date(int year, int month, int date, int hrs, int min, int sec): It allocates a
Date object and initializes it so that it represents the instant at the start of the
second specified by the year, month, date, hrs, min and sec arguments.
6. public Date(String s): It allocates a Date object and initializes it so that it
represents the date and time indicated by the string s, which is interpreted as if
by the parse method.

Date Comparison:
There are three ways to compare any two Date objects. First way is by using getTime( )
to obtain the number of milliseconds that have elapsed. The second way is by using
before( ), after( ) and equals( ). The third way is by using compareTo( ) method, which is
defined by the Comparable interface and implemented by Date.
Calendar:
The Calendar class provides a set of methods that allows the user to convert a time in
milliseconds to a number of useful components. This method provides no public
constructors. It is an abstract base class for converting between a Date object and a set of
integer fields such as year, month, day, hour and so on. A Date object represents a
specific instant in time with millisecond precision. It defines several protected instance
variables. The method areFieldSet is a boolean that indicates if the time components have
been set. The fields is an array of integers that holds the components. The isSet is a
Boolean array that indicates if a specific time component has been set.
The methods are:
 Abstract void add (int which, int val): It adds val to the time or date component
Specified by which. To substract, add a negative value, which must be one of the
fields defined by calendar, such as calendar.HOUR.
 final void clear ( int which): Zeros the time component specified in the invoking
object.
 final int get( int calendarField): It returns the value of one component of the
invoking object. The component is indicated by calendarField.
 static locale[ ]getAvailableLocales( ): It returns an array of Locale objects that
contains the locales for which calendars are available.
 static Calendar getInstance (TimeZone tz): It returns a Calendar object for the
TimeZone specified by tz. The default locale is used.
 static Calendar getInstance (TimeZone tz, Locale locale): It returns a Calendar
object for the TimeZone specified by locale. The default timezone is used.
 final void set(int year, int month, int dayOfmonth, int hours, int minutes, int
seconds): It sets various date and time components of the invoking object.

Subclasses of calendar interpret a Date according to the rules of a specific calendar


system. The platform provides one concrete subclass of calendar: GregorianCalendar.
Gregorian calendar:
This class implements the normal Gregorian calendar. The get Instance( ) method of
Calendar returns a GregorianCalendar initialized with the current date and time in the
default locale and TimeZone. A Calendar object can produce all the time field values
needed to implement the date-time formatting for a particular language and calendar
style. When the calendar is lenient, it accepts a wider range of field values than it
produces. A non-lenient GregorianCalendar throws an exception when given out-of-range
field settings. There are also several constructors for the GregorianCalendar objects. The
default, GregorianCalendar( ), initializes the object with the current date and time in the
default locale and TimeZone.

The constructors are:


 GregorianCalendar (int year, int month, int dayOfMonth): It sets the time to
midnight.
 GregorianCalendar (int year, int month, int dayOfMonth, int hours, int minutes):
It sets the time with hours and minutes.
 GregorianCalendar (int year, int month, int dayOfMonth, int hours, int minutes,
int seconds): It also adds seconds.
 GregorianCalendar(Locale locale): It creates objects initialized with the current
date and time using the specified locale.
 GregorianCalendar(TimeZone timezone): It creates objects initialized with the
current date and time using the specified TimeZone.
 GregorianCalendar(TimeZone timezone, Locale locale): It creates objects
initialized with the current date and time using the specified TimeZone and
Locale.
It provides an implementation of all the abstract methods in calendar. It also provides
some additional methods.

TimeZone:
It is another time-related object. The TimeZone allows the user to work with TimeZone
offsets from Greenwich Mean Time(GMT). TimeZone also computes daylight saving
time. It supplies only the default constructor.
The methods are:
 Object clone( ): It returns a TimeZone-specific version of clone( ).
 Static String [ ] getAvailableIDs (int timeDelta): It returns a TimeZone object
that represents the names of all TimeZones that are timedelta offset from GMT.
 Static TimeZone getDefault( ): It returns a TimeZone object that represents the
default timezone used on the host computer.
 abstract int getOffset (int era, int year, int month, int day of month, int day of
week, int millisec): It returns the offset that should be added to GMT to compute
local time.
 Abstract int getRawOffset( ): It returns the raw offset that should be added to
GMT to compute local time.
 void set Time(long time): It sets the time and date as specified by time.
 static void setDefault(TimeZone tz): It sets the default TimeZone to be used on
this host.tz is a reference to the TimeZone object to be used.
 abstract void setRawOffset(int millis): It sets the offset in milliseconds from
GMT.
 abstract boolean useDaylightTime( ): It returns true if the invoking object uses
daylight saving time.

Simple TimeZone:
It is a subclass of the TimeZone class. It implements TimeZone’s abstract methods an
allows us to work with TimeZones for a Gregorian calendar. The constructors are:
 SimpleTimeZone (int timeDelta, String tzName)
 SimpleTimeZone (int timeDelta, String tzId, int dstMonth0, int datDayInMonth0,
int dstDay0, int time0, int dstMonth1, int dstDayInMonth1, int dstDay1, int
time1)
 SimpleTimeZone(int timeDelta, String tzld, int dstMonth0, int dstDayInMonth0,
int dstDay0, int time0, int dstMonth1, int dstDayInMonth1, int dstDay1, int time1,
int dstDelta)

Locale:
The Locale class is used to produce objects that describe a geographical or cultural
region. The format used to display dates, times and numbers are different in various
regions. The Locale class defines the following constants that are useful for setting the
current locales. The constructor is:
Locale( ): It would represent a specific places.

Random:
The Random class is a generator of pseudorandom numbers. These are called
pseudorandom numbers because they are simply uniformly distributed sequences. The
constructors are:
Random( ): It creates a number generator that uses the current time as the starting value.
Random(long seed): It allows the user to specify a seed value manually. If the user
initializes a Random object with a seed, then it would define the starting point for random
sequence. If the user uses the same seed to initialize another Random object, the user has
to extract the same random sequence. To generate different sequences, different seed
values have to be specified. The easiest way to do is to use the current time to seed a
Random object, thus reducing the possibility of getting repeated sequences.
The Methods are:
 Boolean nextBoolean( ): It returns the next boolean random number.
 void nextBytes(byte vals[ ]): It fills vals with randomly generated values.
 Int nextInt(int n): It returns the next int random number within the range zero to n.
 long nextLong( ): It returns the next long random number.
 void setTime(long time): It sets the time and date as specified by time, which
represents the time elapsed in milli-seconds from midnight.
 void setSeed (long newSeed): This method sets the seed value.

Observable:
The observable class is used to create subclasses that other parts of the program can
observe. When an object of such a sub class undergoes a change, observing classes are
notified. This class would implement the Observer interface, which defines update( )
method. The update( ) method is called when an observer is notified of a change in an
observed object. An object that is being observed must follow the rules. First, if is has
changed, it must call setChanged( ). Second, when it is ready to notify observers of the
change, it must call notifyObservers( ). This causes the update( ) method in the observing
object(s) to be called.
 notifyObserver( ) has two forms: One that takes an argument and one that does
not take an argument. If the user calls notifyObservers( ) with an argument, this
object is passed to the observer’s update( ) method as its second parameter.
Otherwise, null is passed to update( ). The user can use the second parameter for
passing any type of object that is appropriate for the application.
The methods are:
 void addObserver (Observer obj): It adds to the list of objects observing the
invoking object.
 Protected void clearChanged ( ): It returns the status of the invoking object to
“unchanged”.
 int countObservers( ): It returns the number of objects observing the invoking
object.
 void deleteObserver (Observer obj): It removes obj from the list of objects
observing the invoking object.
 void notifyObservers (Object obj): It notifies all the observers that it has changed
by calling update( ).obj is passed as an argument to update( ).

Observer Interface:
The user must implement an observable interface to observe an observable object. It
defines only one method:
void update(Observable observob, Object arg)

observOb is the object being observed, and arg is the value passed by notifyObservers( ).
The update( ) method is called when a change in the observed object takes place.

Summary:
A collection is an object that groups multiple elements into a single unit. A collections
framework is a unified architecture for representing and manipulating collections.
Collection frameworks are composed of three things. They are interfaces,
Implementations and Algorithms. The collection interface is at the top of the hierarchy. It
enables us to work with groups of objects. The List interface extends the Collection
interface and handles sequences. The Set interface also extends the Collection interface
and handles sets. The extension of the Set interface is the SortedSet interface.
Implementations are the actual data objects used to store the collections. Algorithms are
static methods within the Collections class.

These methods include methods for sorting, searching, shuffling, data manipulation, etc.
The legacy classes are Dictionary, HashTable, Properties, Stack and Vector. The legacy
interface is the Enumeration interface. StringTokenizer implements the Enumeration
interface. A BitSet class creates a special type of array that holds bit values. This array
can increase in size as needed. This makes it similar to a vector of bits. The Date class
encapsulates the current date and time. The abstract Calendar class provides a set of
methods that allows the user to convert a time in milliseconds to a number of useful
components. GregorianCalendar is a concrete implementation of a Calendar that
implements the normal Gregorian calendar. The Observable class is used to create
subclasses that other parts of the program can observe.

Abstract Window Toolkit


The Abstract Window Toolkit (AWT) is for Basic GUI (Graphical User Interface)
programming. The way the basic AWT library deals with the user interface elements is to
delegate their creation and behaviour to the native GUI toolkit on each target platforms.
AWT can also be used to create stand-alone windows that run in a GUI environment,
such as Windows. The AWT classes are contained in the java.awt package. It is one of
the Java’s largest packages. It includes a rich set of user interface components, a powerful
event handling model, graphics and image tools, layout managers and support for data
transfer. It also supports JavaBeans architecture. Every AWT component is a simple
bean. It has several subsystems that support the development of Graphical User Interface
programs. The subsystems include Graphics, Components, Containers, Layout managers
and Event system.

Windows in AWT:
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 are used by applets and those derived from Frame, which creates a Standard
window.
The component class is the superclass, of AWT classes which implements graphical user
interface controls. These components include windows, dialog boxes, buttons, labels, text
fields and other common GUI components. The Component class provides a common set
of methods that are used by all these subclasses, including methods for working with
event handlers, images, fonts, and colors.
Component contains many GUI-related subclasses, its container subclass is used to define
components that can contain other components. It provides methods for adding,
retrieving, displaying, counting and removing the components that it contains. The
container class also provides methods for working with layouts. The layout classes
control the layout of components within a container. The container class has three major
subclasses: Window, panel and scrollpane. Window provides a common superclass for
application mein windows (Frame objects) and Dialog windows.

Java programs are classified into two groups namely applications and applets. Java
applications do not require a browser to run whereas applet requires a browser to run.
They can be created like any normal programming language programs.

Applet:
An applet is a Java class that can be downloaded and executed by the web browser. It is a
specific type of Java technology. An applet runs in the environment of the web browser.
An applet is a dynamic and interactive program that can run inside a web page displayed
by a Java-capable browser such as HotJava or Netscape. HotJava Browser is a World
Wide Web Browser used to view Web pages, follow links and submit forms. It can be
downloaded and play applets on our system.

Running an Applet:
Example:
http://somelocation(new.html)
Here the browser loads the URL.
Then browser loads HTML document(HTML file)
<HTML>
<APPLET CODE….>
</APPLET>

Then browser runs the applet.


Location
http://somefile/local/newHTML

Applets and Applications:


Java applications are simple stand-alone programs that can run using the Java Interpreter
from the command line. Java applets are run from inside a World Wide Web browser that
supports Java applets. A reference to an applet is embedded in a Web page using a
special HTML tag. An applet is also executed using appletviewer application, which is a
part of Java Development Kit. Applets have an added advantage as they are run inside
Java browser that provides frame, event-handling facility, graphics context and
surrounding user interface.

Applets are executed either by a Web browser or by an Applet viewer. Execution of an


applet does not begin at main( ). Instead, execution of an applet is started and controlled
with an entirely different mechanism. Output to an applet’s window is not performed by
System.out.println( ), it is handled with various AWT methods, such as drawstring( ),
which outputs a string to a specified location. Input is also handled differently when
compared to an application.

Creation of an Applet:
Open a new file and type the following code:

import java.awt.*;
public class MyApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
g.drawString(“My applet”, 100, 40);
}
}

Save the file as MyApplet and compile it using javac. This will result in the creation of
a .class file for the same.
Now create an HTML file
<html>
<head>
<body>
<APPLET CODE = “MyApplet.class” WIDTH = 400 HEIGHT = 400>
</APPLET>
</body>
</head>
</html>

Save this file as MyApplet.html in the same directory as that of the .java file.
Run the file.

Applet Tag:
The Applet tag is used to start an applet from both an HTML document and from an
applet viewer. The syntax for the standard Applet tag is:
<APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
[WIDTH = pixels HEIGHT = pixels]
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[<PARAM NAME = AttributeName VALUE = AttributeValue>]
[<PARAM NAME = AttributeName 2 VALUE = AttributeValue>]
….
</APPLET>

The <applet> tag is used to start the applet from inside the HTML document as well as
from the appletviewer. Each <applet> tag is executed in separate windows by the
appletviewer while the Java capable browser is capable of executing numerous applets
inside a single web page. This code instructs the browser or the applet viewer to load the
compiled Java applet, namely the .class file. The size of display of the applet is initialized
using the WIDTH and HEIGHT tags. To indicate the end of the applet, </applet> tag is
used. It is essential to end the applet using the tag, otherwise it will not be executed.
CODEBASE:
CODEBASE is an optional attribute that specifies the base URL of the applet code,
which is the directory that will be searched for the applet’s executable class file.
CODE:
It is a required attribute that gives the name of the file containing user applet’s
complied .class file. This file is relative to the code base URL of the applet, which is the
directory that the HTML file was in.
ALT:
The ALT tag is an optional attribute used to specify a short text message that should be
displayed. This attribute is utilized if the browser understands the <Applet> tag but is
unable to display the applet.
NAME:
NAME is an optional attribute used to specify a name for the applet instance. To obtain
an applet by name, use getApplet( ), which is defined by the AppletContext interface.
WIDTH AND HEIGHT:
WIDTH AND HEIGHT are required attributes that give the size (in pixels) of the applet
display area.
ALIGN:
ALIGN is an optional attribute that specifies the alignment of the applet with these
possible values: left, right, top, bottom, middle, baseline, texttop, absmiddle and
absbottom.
VSPACE AND HSPACE:
These attributes are optional. VSPACE specifies the space, in pixels, above and below
the applet. HSPACE specifies the space, in pixels, on each side of the applet.
PARAM NAME AND VALUE:
The PARAM tag allows the user to specify applet specific arguments in an HTML page.
Applets access their attributes with the getParameter( ) method.
USING APPLETVIEWER:
The applet code can be run using an appletviewer. In this case, the appletviewer is typed
at the command prompt followed by the name of the Java file. The general format is:
C> appletviewer filename.java
The applet tag has to be included in the Java file itself and has to be commented.
APPLET HIERARCHY:
All applets are the subclasses of the class Applet. Applet class belongs to the package
java.applet. Therefore, all user-defined applet must import java.applet package. Applet
extends from a class called Panel present in the package java.awt. This class provides
support for Java’s windows-based graphical user interface. Thus, Applet provides all of
the necessary support for window-based activities. The class Component in the java.awt
package has various visual component attributes. The subclass of Component class
namely the Container class contains methods for including various other container
objects. The immediate super class of the Applet class namely Panel class is basically a
window title bar and menu bar.
Passing Parameters to an Applet:
To pass parameters to an applet, two things are required- a special parameter tag in the
HTML file and the code in the applet to parse those parameters. The special parameter
tag in the HTML file is <PARAM>. This has two attributes namely NAME and VALUE.
The init( ) method of the applet, contains a method called getParameter ( ). This method
takes one argument – the string representing the name of the parameter being looked for
and returns a string containing the corresponding value of that parameter. If this method
is required to return types other than strings, it has to be converted explicitly.

The Applet Class:


The class java.applet.Applet is a subclass of java.awt.panel. An applet is a window-based
program. Applets are event driven. Event driven means for every interaction from the
user, a particular action takes place in the applet. An applet resembles a set of interrupt
service routines. An applet will wait until an event occurs. The AWT notifies the applet
about an event by calling an event handler that has been provided by the applet. The
applet must take appropriate action and then quickly return control to the AWT. The
Applet provides methods that load and display images and methods that load and play
audio clips.
The Methods are:
void destroy( ): It is called by the browser just before an applet is terminated.
AccessibleContext getAccessibleContext( ): It returns the accessibility context for the
invoking object.
AppletContext getAppletContext( ): It returns the context associated with the applet.
String getAppletInfo( ): It returns a string that describes the applet.
AudioClip getAudioClip(URL,url): It returns an AudioClip object that encapsulates the
audio clip found at the location specified by the URL and having the name specified by
the clipName.
URL getCodeBase( ): It returns the URL associated with the invoking applet.
URL getDocumentBase( ): It returns the URL of the HTML documents that invokes the
applet.
Locale getLocale( ): It returns a Locale object that is used by the various locale-sensitive
classes and methods.
String getParameter(String paramName): It returns the parameter associated with
paramName. Null is returned if the specified parameter is not found.
void init( ): It is called when an applet begins execution. It is the first method called for
any applet.
boolean isActive( ): It returns true if the applet has been started. It returns false if the
applet has been stopped.
void play(URL url): If an audio clip is found at the location specified by URL, the clip is
played.
void resize(Dimension dim): It resizes the applet according to the dimensions specified
by dim. Dimension is a class stored inside java.awt. It contains two integer fields: width
and height.
void resize(int width, int height): It resizes the applet according to the dimensions
specified by width and height.
Final void setStub(AppletStub stubObj): It makes stubObj the stub for the applet. A stub
is a small piece of code that provides the linkage between the applet and the browser.
void showStatus (String str): It displays string given in ‘str’ in the status window of the
browser or applet viewer.
void start( ): It called by the browser when an applet starts execution. It is automatically
called after init( ) when an applet first begins.
void stop( ): It is called by the browser to suspend execution of the applet. Once stopped,
an applet is restarted when the browser calls start( ).

Life Cycle of an Applet:


An applet has well-defined life cycle. Applets do not need to be explicitly constructed.
The runtime environment associated with their applet context – the Web browser or
applet viewer, automatically constructs them.
 The init( ) method: It is called as soon an applet is started. It provides the
capability to load applet parameters and perform any necessary initialization
processing.

 The start( ) method: It is executed after the init( ) method. It serves as the
execution entry point for an applet, when it is initially executed and restarts the
applet.

 The stop( ) method: It is used to halt the running of an applet. It provides the
capability to stoop( ) an applet’s execution when the Web page containing the
applet is no longer active.

 The destroy( ) method: It is used to free the memory occupied by the variables
and objects initialized in the applet. Any clean up activity that needs to be
performed can be done in this method. The destroy( ) method applies only to
applets whereas the finalize( ) method is generally used to clean up a single
object. It is used at the end of an applet’s life cycle to perform any termination
processing. The stop( ) method is always called before destroy( ).

 The paint( ) method: It helps in drawing, writing, and creating a colored


background or an image onto the applet. It takes an argument to import the
Graphics class as import java.awt.Graphics.

 The repaint( ) method: It is used in case an applet is to be repainted. The repaint( )


calls the update( ) method, to clear the screen of any existing content. The update(
) method in turn calls the paint( ) method that then draws the contents of the
current frame. Repaint( ) method can be done mentioning time in milliseconds to
be performed in future. If the time expires before update( ) can be called, update
is not summoned. It takes four arguments to update only a part of the screen. The
first two arguments are the x and y coordinates, the next two arguments are the
width and the height of the image. This helps in faster updation of the screen.

Life cycle of an Applet


Init

Start Reload or resize the browser or return to web page

Leave Web page Stop

Exit Browser Destroy

Applet Display Method:


Applets are displayed in a window and they use the AWT to perform input and output.
To output a string to an applet, use drawstring( ) which is a member of the Graphics
class. An object of Graphics class provides the surface for painting.
void drawString(string message, int x, int y)
here, message is the string to be output beginning at the coordinate (x, y). In a Java
window, the upper-left corner is location (0, 0). To set the background color of an
applet’s window, use setBackground( ). To set foreground color, use setForground( ).
void setBackground(Color newColor)
void setForeground(Color newColor)
User can set the foreground and background colors in the init( ) method. Current settings
for the background and foreground colors can be obtained by calling getBackground( )
and getForeground( ). They are defined by the Component.
Color getBackground( )
Color getForeground( )
It is a very simple applet that sets the background color and the foreground color and
displays a message in which the init( ), start( ) and paint( ) methods are called when an
applet starts up.

Graphics and Images: In Java, all graphics operations can be performed using the
java.awt package. This package contains various classes and methods for painting
graphics and images.
The Graphics Class:
This method is used for drawing strings, lines, rectangles and other shapes defined in the
Graphics class, which is a part of the java.awt package. To draw figures in Java, one
should understand java’s coordinate system which is a scheme for identifying every
possible point on the screen. Any shape or diagram can be displayed on the screen by
specifying the coordinates.

Graphics Contexts and Graphics Objects:


To draw any picture on the screen, first it must obtain a graphics context. A graphics
context is the one which enables drawing on the screen in Java. A graphics context alone
is not sufficient to draw strings or images on the screen. Graphics object must be used to
draw graphics on the screen. Actually a Graphics object manages the graphics context by
controlling how information is drawn on the screen. This object contains various methods
for drawing strings, lines, rectangles and other shapes. Graphics operations are performed
differently on different platforms. Drawing operations performed in Windows will not be
the same as performed in a Unix based system. This is because when java is implemented
on each platform, a subclass of Graphics is created that actually implements all the
drawing capabilities. Component class is the superclass for most of the classes in the awt.
This class has one method called paint takes a Graphics object as an argument. This
object will be passed to the paint method by the system whenever a paint operation
occurs for a component.
public void paint (Graphics g)
The Graphics object g receives a reference to an object of the system’s derived Graphics
class in order to draw graphics on the screen. By default, the paint method, which is
defined in the component class, does nothing. This method is called automatically when
an applet is initially executed. Component class has two methods, they are: repaint and
update. These two methods are useful when the screen needs to be repainted. To call this
paint method, a call is made to the component’s repaint method. This will call update
method to clear the component’s of any previous drawing. Finally update calls paint
directly. Repaint method should not be overridden since it performs some system
dependent tasks. Update method is used to reduce the flickering in an animation and it
can be overridden.

Methods:
 void drawBytes (byte[] data, int offset, int length, int x, int y): It draws the text
given by the specified byte array, using the graphics graphics context’s current
font and color, data- the data to be drawn, offset- the start offset in the data,
length- the number of bytes that can be drawn, x- the x coordinates of the baseline
of the text, y- the y coordinates of the baseline of the text.
 void drawChars (char[] data, int offset, int length, int x, int y): It draws the text
given by the specified character array, using this graphics context’s current font
and color.
 abstract void drawstring (String str, int x, int y): It draws the text given by the
specified string, using this graphics context’s current font and color.

Drawing Lines, Rectangles, Ovals:


In Java, the Graphics class of java.awt package has several methods to draw lines,
rectangles, ovals, arc and other geometrical shape.
The Methods are:
drawLine( int x1, int y1, int x2, int y2): It draws a line with x1, y1 which is the starting
point coordinates and x2, y2 denotes the ending point coordinates.
drawRect( int x1, int y1, int width, int height): It draws a rectangle with x1, y1 as the top
left corner coordinates of the rectangle.
fillRect( int x1, int y1, int width, int height): It fills a rectangle with x1, y1 as the top left
corner coordinates of the rectangle.
drawRoundRect( int x1, int y1, int width, int height, int width1, int height1): It draws a
rectangle with the width and height of angle corners.
fillRoundRect( int x1, int y1, int width, int height, int width1, int height1): It fills a
rectangle with the width and height of angle corners.
draw3DRect (int x1, int y1, int width, int height, true/false): It is same as drawRect( )
except for the last parameter which takes true value to give raised rectangle and false
value to give lowered rectangle.
drawPolygon ( int xs, int ys, pts): It draws a polygon with xs which is an array of integers
representing x coordinates, ys which is an array of integers representing y coordinates
and pts which is an integer containing the total number of points.
fillPolygon (int xs, int ys, pts): It fills a polygon with xs which is an array of integers
representing x coordinates, ys which is an array of integers representing y coordinates
and pts which is an integer containing the total number of points.
drawOval (int x1, int y1, int width, int height): It draws a oval with x1, y1 which is the
coordinates of top corner, width of oval and height of oval.
fillOval (int x1, int y1, int width, int height): It fills a oval with x1, y1 which is the
coordinates of top corner, width of oval and height of oval.
drawArc ( int x1, int y1, int width, int height, angle1, angle2): It draws an arc in which
the degrees value at which the arc starts in angle1 and the degree value at which the arc
ends.
fillArc ( int x1, int y1, int width, int height, angle1, angle2): It fills an arc in which the
degrees value at which the arc starts in angle1 and the degree value at which the arc ends.

While drawing a polygon, the number of x coordinates and y coordinates must be equal.
It may be difficult to find the 3D effect of the 3D rectangles due to very small line width.

The Font Class:


It represents the fonts. Text can be written inside an applet using different fonts. The font
class of Java offers a wide variety of fonts like TimesRoman, Courier, Helvetica, Futura,
etc. Font names are strings representing the family of the font. An object of the Font class
is created using new. Some of the Font styles available are BOLD, PLAIN, ITALIC.
These are integer constants and they can be added.
Though Java offers a wide variety of fonts, it must be available within the working
environment. The default font substituted by the system, in case the font specified is not
available, is Courier.

Some of the constants are:


static int BOLD: A constant representing a bold font style.
static int PLAIN: A constant representing a plain font style.
static int ITALIC: A constant representing a italic font style.
protected String name: The logical name of this Font, as passed to the constructor.
protected int size: The point size of this Font, rounded to integer.
protected int style: The style of this Font, as passed to the constructor.

The Constructors are:


Font (String name, int style, int size): It creates a new Font from the specified name, style
and point size.
The methods are:
abstract void setFont(Font f): It sets this graphics context’s font to the specified font.
int getStyle( ): It returns an integer value that indicating the current font style.
int getSize( ): It returns an integer value that indicating the current font size.
String getFamily( ): It returns the font’s family name as a string.
boolean isPlain( ): It returns true if the font is plain.
boolean isBold( ): It returns true if the font is bold.
boolean isItalic( ): It returns true if the font is italic.

The FontMetrics Class:


It defines a font metrics object, which encapsulates information about the rendering of a
particular font on a particular screen. The FontMetrics class is used to obtain precise
information on a specific font such as height, descent, ascent leading between lines.

The Methods are:


abstract Font getFont( ): This will return a Font object representing the current font.
public int getAscent( ): It returns a value representing the ascent of a font in points.
public int getDescent( ): It returns a value representing the descent of a font in points.
public getLeading( ): It returns a value representing the leading of a font in points.
public FontMetrics getFontMetrics( ): It returns a current font metrics.
stringWidth( string): It returns a width of the string passed as a parameter.
charWidth(char): It is same as stringWidth( ), except that parameter passed is a character.

The Color Class:


Java provides different methods and behaviors for dealing with color through the Color
class found in the java.awt package. The foreground and background colors can also be
set for an applet.
Colors are represented as a combination of red, blue and green. Each component
can have a number between 0 and 255. 0,0,0 is black and 255,255,255 is white. A range
of colors can be obtained using these values. The color specified should be available
within the current java working environment. Colors not available in the standard color
objects can be created using new.

The Methods are:


setColor( ) Method: It can be used to set the color by the Graphics class objects.
setBackground( ) Method: It sets the background color of the applet and it takes the color
object as its parameter.
setForeground( ) Method: It is used to change the color of the whole applet after it has
been drawn. It also takes a color object as its parameter.
getBackground( ) Method: It gets the background color of the applet.
getForeground( ) Method: It gets the foreground color of the applet.
getColor( ) Method: It helps to know the present color of an applet belonging to the
Graphics/Color class.
Images and Animation: Images are objects of the Image class, which is part of the
java.awt package. Images are manipulated using the classes found in the java.awt.image
package. There are three common operations that occur when working with images:
creating an image, loading an image and displaying an image. In Java, the image class is
used to refer the images in memory and to images that must be loaded from external
sources. Complex pictures are drawn using professional drawing tools like Corel Draw
etc., and are stored as picture files (gif, jpeg, bmp etc.). These image files are then loaded
into the program and displayed. High quality images are drawn using drawing tools or
scanned from photographs can be displayed with relative ease and image files can be
edited or modified independent of the program file without affecting the program.

Methods are:
• getImage ( URL, String) : It loads an image from an URL. URL specifies the
location from which the image is to be loaded. String is usually the name of the
image file.
• drawImage (Image, x, y, imageObserver): It draws an image at the given
coordinates. Image object refers to the picture to be drawn x, y are the coordinates
where the image is to be drawn. ImageObserver is usually the applet itself.
The parameter URL (Uniform Resource Locator) in the getImage( ) method refers to
location where the image is stored. The Applet class provides a helper function
getCodeBase( ) which returns the path (URL) of the .class file. So the method calls the
gif from the directory where the file is stored.
The getImage( ) function loads an image from file and stores it in the instance variable
image. The paint( ) method of the applet, displays the image at coordinates using the
drawImage( ) method. The parameter this passed in the drawImage( ) function call acts as
the ImageObserver which monitors the drawing of the image. For most methods related
toimage, an image observer needs to be passed. The Image class provides two methods
getWidth( ) and getHeight( ) to find the width and height of an image. The showStatus
method is used to display the width and height of the image.

Creating Images:
Java allows the creation of off screen images. The createImage( ) method of the Applet
class creates a blank image of the specified dimensions. To draw on the image surface,
the graphics object of the image is specified.
The getGraphics( ) method of the Image class returns the graphics context of the image.
This Graphics object can be used for drawing on the image surface. Drawings made using
the Graphics object are rendered on the image surface and not on the screen. When the
drawing is complete, the image can be flipped on the screen using the drawImage( )
method.
The Methods are:
• create Image(width, height): It creates a new image of specified width and height.
• get Graphics( ): It gets the graphics context of the image. The graphics object can
be obtained can be used for drawing on the image surface.
Loading an Image:
The getImage( ) method defined by the applet class has the following forms to load an
image:
• image getImage (URL url): It returns an Image object that encapsulates the image
at the location specified by url.
• image getImage (URL url, String imageName): It returns an Image object that
encapsulates the image found at the location specified by url and having the name
specified by imageName.
Displaying an Image:
Image can be displayed by using drawImage( ), which is a member of the Graphics class.
Boolean drawImage(Image imgObj, int left, int top, ImageObserver imgOb).
ImageObserver:
ImageObserver is an interface used to receive notification as an image is being generated.
ImageObserver defines only one method: ImageUpdate( ).
Double Buffering:
Images are useful for storing pictures and for offscreen drawing surfaces. This allows
rendering any image. Drawing a complicated image could take several milliseconds seen
by the user as flashing or flickering. Use of an offscreen image to reduce flicker is called
double buffering, because the screen is considered a buffer for pixels and the offscreen
image is the second buffer, where pixels can be prepared for display.
Media Tracker:
A Media Tracker is an object that will check the status of an arbitrary number of images
in parallel. To use Media Tracker, a new instance is created and addImage( ) method is
used to track the loading status of an image.
Media Tracker is used when loading a group of images. If all of the images are not
downloaded, something else can be displayed to entertain the user until the images get
downloaded.
Clipping:
It is a technique by which drawing area can be restricted to a small portion of the screen.
A clipping region is an area where drawing is allowed. Any drawing outside the clipping
region is clipped off and not displayed. The graphics class method clipRect( ) creates
rectangular clipping regions. Once the clipping rectangle is set, any drawing done outside
the rectangular region is clipped off. If a call to a graphics method results in a drawing
that extends outside the clipping rectangle, only that part of the drawing that lies inside
the clipping region is displayed.

Animation:
Animation is a technique by which an object is moved on the screen. The object to be
moved can be simple drawing or a complex image loaded from an image file. This object,
in animation jargon, is called a frame of animation.
Animation involves the following steps:
• The object is drawn at a location on the screen.
• The object’s location is changed – the object at the old location is erased.
• The object is repainted at the new location.
Animation, involves a loop in which the object gets painted, erased and again repainted.
The loop starts when the animation begins and lasts till the object reaches the destination.

Summary:
An applet is a dynamic and interactive program that runs inside a Web page displayed by
a Java capable browser. This can also be executed using the appletviewer application.
Parameters can be passed to an applet by using the param tag, which has two attributes
NAME and VALUE. The major activities involved in an applet are the initialization and
creation of objects and variables, starting, painting, stopping and destroying the created
objects and variables. There are methods available to do all these activities. The
Graphics, Color and Font classes help in drawing figures, setting colors and fonts. The
getImage( ) method of the Applet class is used to load an image from an image file. The
drawImage( ) method is used to display images either at normal size or scaled to different
sizes. The createImage( ) method of the Applet class creates a blank images of specified
dimension. Clipping is a technique by which drawing area is restricted to a small region.
Animation is a technique by which an illusion of an object moving on the screen is
created.

JFC
The Java Foundation Class was developed to address the AWT. Its visual
components extend the AWT container class. The methods contained in the Component
and Container classes that AWT are valid for JFC visual classes. The AWT user interface
classes are now superseded by classes provided by the JFC. The support classes play an
important part in JFC applications. AWT support classes, those that do not create a native
window are not replaced by JFC classes. JFC includes user interface called the Swing
components.

Swing:
Swing component is a graphical user interface (GUI) development. These components
are a collection of lightweight visual components. Swing components contain a
replacement for the heavy weight AWT components as well as complex user-interface
components. It contain pluggable look and feel (PL&F). This allows all applications to
run with the native look and feel on different platforms. PL&F allows applications to
have the same behavior on various platforms. JFC contains operating system neutral look
and feel. Swing components do not contain peers. Swing components allow mixing AWT
heavyweight and Swing lightweight components in an application.
Lightweight components can have transparent pixels whereas heavyweight components
are always opaque. Lightweight components can be non-rectangular while heavyweight
components are always rectangular.
It is a JavaBean Compliant. This allows components to be used easily in a Bean aware
application building program. The root of the majority of the Swing hierarchy is the
JComponent class. This class is an extension of the AWT container class.
Swing components comprise of a large percentage of the JFC release. The Swing
component toolkit consists of over 250 pure Java classes and 75 interfaces contained in
about 10 packages. They are used to build lightweight user interfaces. Swing consists of
user interface (UI) classes and non-user interface classes. The non-UI classes provide
services and other operations for the UI classes.

Packages are:
javax.swing.plaf.basic: It contains classes that define the default look and feel of swing
components.
javax.swing.border: It contains the border interface and their related interfaces.
javax.swing.plaf.multi: It consists of multiplexing UI classes.
javax.swing.plaf: It consists of classes that provide swing components with pluggable
look and feel capabilities.
javax.swing.table: It contains classes and interfaces specific to the swing table
component.
javax.swing.text: It contains classes and interfaces for text manipulation components
contained in the swing toolkit.
javax.swing.tree: It contains classes that are used with the swing tree component.
javax.swing.undo: It contains interfaces and classes required to implement the undo
functionality.

Wide Variety of Components: Class names that start with ‘J’ are the components that are
added to an application. The remaining files in the swing package contain the utility
classes and interfaces that the components use to function.
Pluggable Look and Feel:
The user can select a look and feel and this can be plugged in. An interface made of
Swing components can look like a Win32 app, a Motif app or a Mac app. It can use the
new look and feel. Any user can select the pluggable look and feel already present or
develop their own pluggable look and feel. The plaf package includes the standard
‘Pluggable Look And Feel’ classes.

MVC Architecture:
It is used throughout the Swing component set. The View and Controller parts of the
architecture are combined in the component. Each component has an associated Model
class and an interface it uses. The user can provide their own data-model for a component
by subclassing the Model class or by implementing the appropriate interface.

Action Objects:
Action-interface objects provide a single point of control for program actions. When the
Action object is disabled, the GUI items that reference it are automatically disabled. The
Action interface extends ActionListener, specifying an enabled property as well as
properties for text-descriptions and graphic icons.

Keystroke Handling:
The JComponent architecture makes it easy to handle keyboard events in nested
components. A user can register interest in a particular combination of keystrokes by
creating a KeyStroke object and registering it with the component. When the keystroke
combination is registered along with its associated action, certain conditions have to be
specified.
The conditions include are
• The component has the focus.
• A child or grandchild of the component has the focus.
• The window in which the component is present has the focus.

Nested Containers:
Swing was designed to manage nested containers gracefully. The main ‘heavyweight’
containers as well as the major ‘lightweight’ containers all delegate their operations to a
JRootPane. This commonality produces a high degree of regularity in container nesting.
The JRootPane class uses a JLayeredPane to manage a content pane and an optional
menu bar in a way that is virtually transparent to the user. It also provides for a glass pane
—a single pane that can overlap multiple containers and can be used for drawing or to
intercept mouse actions.

Virtual Desktops:
The JDesktopPane and JInternalFrame classes can be used to create a virtual desktop, or
‘multiple document interface’. A JInternalFrame can be specified as iconizable,
expandable, or closable, while the JDesktopPane provides real estate for them to operate
in.

Compound Borders:
Insets can be specified with a blank border. Here, many border styles are available, which
can be combined to create compound borders.

Customized Dialogs:
The JOptionPane class provides a variety of static methods that the user can invoke to
create and display both message dialogs and user-choice dialogs in a variety of formats.
The message displayed in the dialog can be a string, a string-generating object, or an
arbitrary component. Choice buttons can be replaced with components that are specified
for user selections.

Standard Dialog Classes:


The standard dialogs that are currently available include:
• JFileChooser
• JColorChooser
Structured Table and Tree Components:
The JTable class provides a data-aware matrix. JTree provides hierarchical-structuring of
data elements.

Powerful Text Manipulations:


In addition to single-font text fields and text areas, Swing provides a JPassword field for
hidden input and a JTextPane class for displaying multi-font text. In addition, the
JEditorPane class provides editing capabilities for multi-font text, while the text.html
packages handle text encoded in HyperText Markup Language(HTML) or
RichTextFormat(RTF).

Generic Undo Capabilities:


The undo package provides generic undo capabilities that can be used in a variety of
situations.
Accessibility Support:
Swing has built-in support for developers to make products that are compatible with
Assistive Technologies. All the Swing components implement interface Accessible.
Drag and Drop:
The JFC drag and drop capabilities allow the transfer of data between Java applications,
as well as to native applications. A component may be a drag source, a drop target, or
both. Interfaces define methods required to be a drag source or drop target. Implementing
these interfaces allows the component to participate in a drag operation. An aspect of
drag and drop is flavour maps. A flavour map is a mapping between the device dependent
data type and the Java device independent data type. This allows a Java application to
transfer data with a native application without requiring the Java application to know the
specifics about the native data types. Drag and drop between a Java application and a
native application requires support from the native operating system.
The java.awt.dnd package offers support for drag and drop. This package consists of four
interfaces and fourteen classes that define the drag and drop operations. There is an
interface that a drag source and a drop target must implement, as well as an interface for
the data flavours that can be transferred.

Java2D:
A set of tools has been introduced for dealing with two dimensional drawings and
images. These extensions include provision for colorspaces, text, line art and printing.

JComponent:
The JComponent class is the root of the visual component class hierarchy in the JFC. The
visual components are known as the “J” classes. The functionality contained in the JFC.
The JComponent class is a repository of functionality for all visual components. The
JComponent class is at the top of the hierarchy of all contained in the JFC.
Client Properties:
A piece of information that can be attached to any JFC component is known as the client
property. The property basically consists of a name – value pair. The name is a key that
uniquely identifies the value for a particular instance. These properties are used internally
by the JFC in many situations. Components that extend JFC visual components can store
data in client properties as well as arbitrary code that create and use instances of JFC
visual components. An arbitrary object can be associated with a JFC visual component
instance by using the putClientProperty method that is present in the JComponent class.
When the property is placed on the component, a key is associated with the object. The
client property can be obtained later using the getClientProperty method and the key used
when adding the property. Any number of client properties can be added to a component.
Each property has a unique key.
When a client property is set, the PropertyChange event is fired by the component that
contains the property. The name of the property change event is the value returned from
the toString method key used to store the client property. This provides a versatile
mechanism for attaching the data to a visual component and allowing other objects to
look for changes in the property.
ToolTip Support:
ToolTips are the pop up windows common in user interfaces that present the user with
short informative messages. These are also known as flyover help. The JComponent class
contains a client property for ToolTips. The ToolTips is stored as a client property rather
than a member variable to save space. All JComponent instances do not contain
ToolTips.
Border Property:
The JComponent class contains a Border property. This refers to a class that implements
the Border interface. Painting of the border is handled by the component when a border is
specified for the component. When a border has been set for a JComponent instance, the
size of the border is used as the insets property for that component.
Size Preferences:
AWT components contain the methods getPreferredSize, getMinimumSize and
getMaximumSize to aid layout managers arrange containers. JComponent adds the
setPreferredSize, setMinimumSize and setMaximumSize methods for setting the sizes. If
one of the sizes has been set via one of these methods, the associated get method returns
the size rather than computing the size based on state. This adds flexibility.

Keystroke Handling:
The JComponent class provides keystroke-handling functionality. These methods provide
much higher level interface than processing individual keystroke events in a subclass of
JComponent. The registerKeyboardAction method is used to bind a keystroke to an
ActionListener. Registering enables the keyboard action. Internally,the JComponent class
stores a Hashable of registered keyboard actions, as a client property. There are three
situations i.e., WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW,
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, in which the keystroke event
could occur.
The KeyStroke instance contains its key character, key code, modifiers and a flag for key
pressed or released state. The key character is the character representation of the
KeyStroke instance. The key code is the integer code defined in the keyEvent class. The
modifier field represents any modifier for the KeyStroke. The final field represents the
KeyStroke instance as a key pressed or key released keystroke. KeyStroke instances are
immutable. This allows the instances to be cached and shared.

Scrolling Support:
JFC provides traditional scrolling of any component by using the JscrollPane and
Jviewport classes. Once the component is placed in a viewport contained in a scroll pane,
scrollbards can be used to translate the view of the component. The JComponent class
also supports autoscrolling. When the JComponent instance has autoscrolling enabled,
the component will scroll when the mouse is dragged in the component.

Focus Transversal Support:


JFC contains a default focus manager that determines the component that has to obtain
the focus when the focus transversal request is made. The default focus manager
determines the next component that will receive the input focus and then transfers focus
to that component. The default search algorithm is a top to bottom, left to right search.
Altering the focus manager can modify the search algorithm or have the components in
the view contain hints for the focus manager.

Property Listener Support:


JFC visual components are compliant with the JavaBeans specification. The JComponent
class contains the methods for manipulating property change listeners and convenience
methods for sending notifications to the listeners. The two types of property change
listeners are: PropertyChangeListener and VetoableChangeListener. A
PropertyChangeListener simply receives notification when properties change in the
object that the listener is registered with. A VetoableChangeListener can take a more
active role in the changing of the property.

Pluggable Look and Feel Support:


The JComponent class is the place where the support for pluggable look and feel support
is located. This class defines methods that other classes must override if they have to
support the pluggable look and feel architecture. The UIManager uses these methods to
determine the user interface class for instances. They are typically used when an instance
is created to initialize the user interface and when the look and feel changes for the
application.

Double Buffering:
All JFC components are lightweight components and hence display flashing is a major
concern, making double buffering a necessity. JComponent class does it in a memory
efficient way.
JComponent provides the ability to specify transparency of components, paint parts of
components, and with a pluggable look and feel.

Containers:
JFC has components called containers. Container is used to hold other
components. Some of the containers are general and some are used for specific purposes.
The advantage of containers is that other containers can be added to them. JPanel is the
simplest of JFC containers. It extends JComponent. The Box class is a container
component that contains a BoxLayout. The box class extends Container class.
JLayeredPane is used for controlling components that overlap. It is the parent class for
JDesktopPane. JToolBar is another container that can be dragged around inside its
parent container.

JPanel
JPanel class is provided to give a concrete container class. JPanel inherits the
features contained in the JComponent class.
The various constructors that can be used to create a Jpanel are given below:

• Jpanel()
• Jpanel(boolean isDoubleBuffered)
• Jpanel(LayoutManager layout)
• Jpanel(LayoutManager layout, boolean isDoubleBuffered)

Methods supported by this class are:

• getAccessibleContext()
• getUIClassID()
• paramString()
• updateUI()

Example:

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
class panel extends JFrame {
public panel() {
setTitle("Box 1");
JPanel contentpane = (JPanel)getContentPane();
contentpane.setLayout(new GridLayout());
JButton ok = new JButton("OK");
contentpane.add(ok);
JButton cancel = new JButton("CANCEL");
contentpane.add(cancel);
}

public static void main(String[] args) {


Panel b = new Panel();
b.setSize(400,400);
b.setVisible(true);
}
}
Save the file as panel.java
Compile the file using javac panel.java
Run the file using java panel

Output:

Box Class

This is a light weight container that uses a BoxLayout object as its Layout
manager. The Box class can create several kinds of invisible components that affect
layout: glue, struts, and rigid areas. The component positions could be controlled by the
glue components. If a fixed amount of space is required between components, then the
strut could be used.
When it is configured to align components along the y-axis adding components to
the Box is like stacking objects in a box. The Box class also contains several static
methods that create invisible components to help control the layout of the container. It
does not extend the JComponent and hence the properties of this class are not inherited.

Box Layout Class


BoxLayout class is a layout manager that allows multiple components to be laid
out either vertically or horizontally. It is similar to FlowLayout manager. It allows
components to be stacked vertically as well as placed horizontally. The layout manager
also does not wrap components. The constants X_AXIS and Y_AXIS are defined in the
BoxLayout class to specify a left to right or top to bottom component arrangement.
The BoxLayout class respects a component’s minimum and maximum size
properties. When components stacked along the Y-Axis, the BoxLayout class tries to
size each component to its preferred height. Each component is of the same width. The
BoxLayout class adheres to the minimum and maximum sizes of components while
laying out a container.

Invisible and rigid Components

Since the components are placed next to each other, the container appears
cramped. This could be avoided by adding invisible components to the container. The
Box class contains static methods that return invisible components, which could be used
to arrange components on the container.
There are three types of invisible components. They are:
• Rigid
• Glue
• Struts
Example:
The following examples illustrates the usage of the BoxLayout layout manager:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

class Box0 extends JFrame {


public Box0() {

try{
setTitle("Box 1");
JPanel contentpane = (JPanel)getContentPane();
contentpane.setLayout(new BorderLayout());
Box mainbox = new Box(BoxLayout.Y_AXIS);
JButton ok = new JButton("OK");
contentpane.add("North",ok);
JButton cancel = new JButton("CANCEL");
contentpane.add("South",cancel);
myadapter myapp = new myadapter();
addWindowListener(myapp);
}
catch(Exception e)
{
System.out.println(e);
}
}

private class myadapter extends WindowAdapter {


public void windowClosing(WindowEvent e) {
try{
System.exit(0);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

private static void main(String args[]) {


Box0 b = new Box0();
b.setSize(400,400);
b.setVisible(true);
}
}

Save the file as Box0.java


Compile the file using javac Box0.java
Run the file using java Box0
Output:

JRootPane:
The fundamental component in the container hierarchy is the JRootPane. In the
same way, JComponent is fundamental to the JFC/Swing components. JRootPane is
fundamental to the JFC/Swing window, frame and pane containers. However while other
classes use inheritance to take advantage of JComponent’s capabilities, the container
classes delegate operations to a JRootPane instance.
This is a unique component with a well-defined role. It acts as only a child for
JWindows. Jdialogs, JFrames and JInternalFrames and controls access to the parent’s
display area. Components are added only through the root pane.
The JRootPane has four parts:
• The Menu Bar
• The Content Pane
• The Layered Pane
• The Glass Pane

i) Menu Bar
The menu bar represents the window, dialog, frame, or the internal
frame’s main menu bar which appears below the title bar. The root pane
does not have a default menu bar and hence the user has to explicitly
assign a menu bar to the root pane. This is done by creating a JMenuBar
and passing this to the root pane with the corresponding method.
ii) Content Pane
The Content pane represents the main display area of the window, dialog,
frame or internal frame. The default content pane, which is an instance of
the Jpanel could be used.
iii) Layered Pane
The layered Panel is an instance of the JLayeredPane and acts as a parent
to the Menu Bar. Content Pane and the Glass Pane. It places the Menu Bar
and Content Pane in the same layer.
iv) Glass Pane
The Glass Pane is transparent and can be completely overlay the window,
dialog, frame or internal frame main area. When set to visible, it is still
invisible but can be used to intercept any input to the components in the
root pane’s Content Pane or Layered Pane.

The Glass Pane is transparent and can completely overlay the window. , dialog,
frame or internal frame main area. When set to visible, it is still invisible but can be used
to intercept any input to the components in the root pane’s Content Pane or Layered Pane.
The constructors that can be used to create a root pane are discussed below:

JRootPane() – Creates a JRootPane, setting up its glassPane, LayeredPane,


and contentPane.

The various methods that can be used in conjunction with the class are as follows:
• createContentPane()
• createGLassPane()
• createLayeredPane()
• createRootLayout()
• getContentPane()
• getDefaultButton()
• getGlassPane()
• getJMenuBar()
• getLayeredPane()
• setDefaultButton(JButton defaultButton)
• setContentPane(Component glass)
• setGlassPane(Component glass)
• setMenuBar(JMenuBar menu)
• setLayeredPane(JLayeredPane layered)

JToolBar

JToolBar provides a component, which is useful for displaying used Actions or


controls. The user can drag it out into a separate window. JToolBar’s parent container
should use the BorderLayout to support the behaviour mentioned above.
By default, the JToolBar uses the BoxLayout. JToolBars generally contain only
the icons JButton or JToggleButtons. The components in a JToolBar can also be space
with a separator or one of the Box component’s padding components.
The constructors that can be used to create instances of this class are:
• JToolBar()
• JToolBar(int orientation)

The various methods that can be used in conjunction with this class are:
• add(Action a)
• addSeparator()
• addSeparator(Dimension size)
• getComponentAtIndes(int i)
• getComponentIndex(Component c)
• getMargin()
• getOrientation()

JTabbedPane
Tabs components are added to a TabbedPane object by using the addTab and
insert Tab methods. A tab is represented by an index corresponding to the position it was
added in, where the first tab has an index equal to 0 and the last tab has an index equal to
the tab count minus 1.
The TabbedPane uses a SingleSelectionModel to represent the set of tab indices
and the currently selected index. If the tab count is greater than 0, then there will always
be a selected index, which by default will be initialized to the first tab. If the tab count is
0, then the selected index will be -1.
This class i.e., JTabbedPane allows multiple components to be added but displays
only a single component at a time. Tabs are located on one of the sides of the displayed
component that allow the user to choose which component is currently visible in the
centre of the tabbed pane. The various constructors that can be used to create a
JTabbedPane are listed below:
• JTabbedPane()
• JTabbedPane(int tabPlacement)

Tab placement is a bound property that can be changed after creation. Changes to the
properties of the class can be done using methods, some of which are listed below:
• add(Component component)
• add(Component component, int index)
• add(Component component, object constraints, int index)
• addTab(String title, Component component)
• getBackgroundAt(int index)
• getBoundsAt(int index)
• getComponentAt(int index)
• getForegroundAt(int index)
• getSelectedComponent()
• getSelectedIndex()
• getTabCount()
• setForegroundAt(int index, color foreground)

Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tab extends JFrame {
JTabbedPane fpane = new JTabbedPane();
JPanel First = new JPanel();
JPanel Second = new JPanel();
JPanel Third = new JPanel();
JPanel contentpane = (JPanel)getContentPane();

public tab()
{
getContentPane().setLayout(new BorderLayout());
fpane.addTab("First",First);
fpane.addTab("Second", Second);
fpane.addTab("Third",Third);
fpane.setSelectedIndex(0);
contentpane.add(fpane);
getContentPane().add(fpane,BorderLayout.CENTER);
}

public static void main(String args[]) {


tab newtab = new tab();
newtab.setVisible(true);
newtab.setSize(400,400);
}

Save the file as tab.java


Compile the file using javac tab.java
Run the file using java tab
Output:

Scrolling Components

JFC provides the JScrollPane class, which allows any component to be easily
scrolled. The JScrollPane class manages horizontal and vertical scrollbars, column and
row header components, corner components, and a viewport. All components need to be
visible in every scroll pane. The view port in the scroll pane manages the actual
component that is to be scrolled. The horizontal header scrolls right and left as the
contents scrolls, but not vertically.
JViewport:

JViewport is the “viewport” or “porthole” through which the underlying


information is seen. While scrolling, what moves is the viewport. JViewport class is
used by JScrollPane class to manage the view of the underlying components being
displayed in the scroll pane. The JVeiwport class extends the JComponent class. When
a scrollbar contained in the scroll pane is scrolled, the viewport is the one that moves.
The constructors for the class are listed below:

• JViewport() – Creates a JViewport

A viewport can be configured to create an off-screen image the buffers the visual
representation of the visual port of the child component. This allows the viewport to
scroll faster. If the viewport has not been scrolled, when the viewport’s paint method is
called, the component is drawn to the image that is then copied to the display. If the
viewport has been scrolled, the image is moved the appropriate amount and then the
exposed portion of the child component is drawn to the image. The complete image is
then copied to the display. Scrolling is thereby performed faster, because repainting need
not be done for the entire component when only a small scroll is performed. The off-
screen image is known as a backing store.
The JViewport class has methods that can be used for a variety of purposes.
Some of these are listed below:

• getViewPosition()
• getViewSize()
• remove(Component child)
• SetBackingStoreEnabled(boolean x)
• setBorder(Border border)
• setView(Component view)

When a component is first added to a viewport, its upper left corner is aligned with the
upper left corner of the viewport. This is not true when the component is scrolled.

ViewportLayout Layout Manager:

ViewportLayout is the default layout manager for JViewport. JViewportLayout


defines a policy for layout that should be useful fro most applications. The viewport
makes its view the same size as the viewport, however it will not make the view smaller
than its minimum size. As the viewport grows the view is kept bottom justified until the
entire view is visible. Subsequently the view is kept top justified.
The default behaviour of the JViewport class is to create an instance of the
Viewport Layout class to manage its child component. The layout manager positions
components that are smaller than the viewport in the upper left corner, leaving extra
space below or to the right of the component. If however, the origin of the component is
displayed and the component is smaller that the viewport, the component is then resized
to the size of the viewport. If the component implements the Scrollable interface and is
set to track the viewport’s size, the component is sized to the viewport’s size.

JScrollPane:

JScrollPane is a specialized container that manages a viewport, optional vertical


and horizontal scrollbars and optional row and column heading view ports. The
JViewPort provides a window or viewport onto a data source – for example a text file.
That data source is the ‘Scrollable client’ displayed by the JViewPort view. A
JScrollPane basically consists of JScrollBars, a JViewPort and the writin between
them. In addition to the scrollbars and viewport, a JScrollPane can have a column header
and a row header. The column header viewport automatically scrolls left and right,
tracking the left-right scrolling of the main viewport. The row header acts in a similar
fasion. By default, the corners are empty. A component can be placed into a corner. The
size of corner components is entirely determined by the size of the headers and scroll bars
that surround them.
JScrollPane class is typically used for scrolling purposes. It is an extension of
JComponent. The JViewport class manages components that have to be scrolled. The
JScrollPane class manages a single viewport in the centre of its area. The various
methods that can be used to control the JScrollPane class are listed below:
• createHorizontalScrollBar()
• createVerticalScrollBar()
• createViewport()
• getColumnHeader()
• getCorner(String key)
• getHorizontalScrollBar()
• getRowHeader()
• getVerticalScrollBar()
• getViewport()
• setColumnHeader(JViewport columnHeader)
• setHorizontalScrollBar(JScrollBar horizontalScrollBar)
• setLayout(LayoutManager layout)
• setVerticalScrollBar(JScrollBar verticalScrollBar)

The constructors that can be used to create the JViewport are:

• JScrollPane()
• JScrollPane(Component view)
• JScrollPane(Component view, int vsbPolicy, int hsbPolicy)
• JScrollPane(int vsbPolicy, int hsbPolicy)
ScrollPanelLayout Layout Manager:

JScrollPane uses the ScrollPaneLayout manager layout manager.


JScrollPanelLayout is responsible for nine components:
• a viewport
• two scrollbars
• a row header
• a column header
• four corner components

The ScrollPaneLayout class sizes the horizontal scrollbar and the column header to
their preferred heights and to the width of the scroll pane, less the width of the row
header and vertical scrollbar, if either of them are visible. Similarly, the vertical scrollbar
and the row header are sized to their preferred widths and to the height of the scroll pane,
less the height of the column header and horizontal scrollbar, if either of them is visible.
The viewport is given the remainder of the scroll pane’s size. The corner components are
sized to the height and width of their adjacent components.
Scrollbar display can be controlled by using the corresponding fields and
methods. Similarly, row and column headings can also be controlled. Corner components
can also be controlled.

Split Pane

Many user interfaces allow multiple views to appear in the same frame. The user
can drag the divider between the views to allocate the space given to each view. JFC
provides JSplitPane class to manage two components that can be interactively resized by
the user. Split panes can be nested.

JSplitPane

JSplitPane is used to divide two components. The two components are


graphically divided based on the look and feel implementation, and the user can then
interactively resize the two components. The two components can be aligned left to right
or top to bottom.

When the user is resizing the components, the minimum size of the components is
used to determine the max/min position the components can be set to. If the minimum
size of the two components is greater than the size of the split pane, the divider will not
allow resizing.

The constructors that can be used to create split panes are listed below:
• JSplitPane()
• JSplitPane(int newOrientation)
• JSplitPane(int newOrientation, Component newLeftComponent,
Component newRightComponent)
• JSplitPane(int newOrientation, boolean newContinuousLayout,
Component newLeftComponent, Component
newRightComponent)
• JSplitPae(int newOrientation, Boolean newContinuousLayout)

The various methods that can be used to manipulate split panes are listed below:
• getBottomComponent()
• getDividerLocation()
• getDividerSize()
• getLastDividerLocation()
• getLeftComponent()
• getMaximumDividerLocation()
• isContinuousLayout()
• remove(Component component)
• setOrientation(int orientation)

Internal Frames

Multiple document interface(MDI) has become very popular. This type of


interface contains many frame window contained in a single top-level frame. The internal
frames can be sized, dragged and iconified independently of the other frames. The top-
level frame groups the internal frames. If the top-level frame is iconified then all internal
frames are also iconified. MDI allows all the views in an application to be contained in a
single frame.
The JFC contains all the JInternalFrame and JDesktopPanes classes that
provide a frame and a frame management pane that can be added to other frames. Internal
frames are added to the desktop pane, which interfaces with the desktop manager. A
complete MDI interface is not provided in the JFC.

JInternalFrame

JInternalFrame is a lightweight object that provides many of the features of a


native frame including dragging, closing, becoming an icon, resizing, title display and
support for a menu bar. Generally, an instance is created and added to a
DestktopManager object maintained by the JDesktopPane. The JInternalFrame
contentPane is where the child components are added.

The various constructors that can be used to create an instance of this class are:
• JInternalFrame()
• JInternalFrame(String title, boolean resizable, boolean closable,
Boolean maximizable, Boolean iconifiable)
• JInternalFrame(String title, boolean resizable, boolean closable,
Boolean maximizable)
• JInternalFrame(String title, boolean resizable, boolean closable)
• JInternalFrame(String title, boolean resizable)
• JInternalFrame(String title)

Some of the methods that may be used in conjunction with internal frames are
listed below:
• dispose()
• createRootPane()
• getBackground()
• GetDefaultCloseOperation()
• getDesktopPane()
• getForeground()
• getLayeredPane()
• setBackground(Color c)
• setClosable(boolean b)
• setClosed(boolean b)
• setContentPane(Container c)

JDesktopPane

JDesktopPane is a container used to create a multiple-document interface or a


virtual desktop. JInternalFrame objects can be created and added to the JDesktopPane.
JDesktopPane extends JLayeredPane to manage the potentially overlapping internal
frames. It also maintains a reference to an instance of DesktopManager that is set by the
UI class for the current Look and Feel (L&F).
This class is normally used as the parent of JInternalFrames to provide a
pluggable DesktopManager object to the JInternalframes. The installUI of the L&F
specific implementation is responsible for setting the desktopManager variable
appropriately. When the parent of a JInternalFrame is a JDesktopPane, it should
delegate most of its behaviour to the desktopManager(closing, resizing, etc).

The constructor that is used to create a desktop pane is:

• JDesktopPane()
Some of the methods that may be used in conjunction with the desktop pane are
listed below:

• getAllFrames()
• getAllFramesInLayer(int layer)
• getDesktopManager()
• setDesktopManager()
• setDesktopManager(DesktopManager d)

DesktopManager Interface

A JDesktopPane object owns DesktopManger objects. They are responsible for


implementation L&F specific behaviours for the JDesktopPane. JInternalFrame
implementations should delegate specific behaviours to the DesktopManager.
There are various methods that are associated with the desktop manager interface
and these are listed below:

• maximizeFrame(JInternalFrame f)
• MinimizeFrame(JInternalFrame f)
• ActivateFrame(JInternalFrame f)
• endResizingFrame(JComponent f)
• endDraggingFrame(JComponent f)
• dragFrame(JComponent f, int newX, int newY)
• deiconify((JInternalFrame f)
• deactivateFrame(JInternalFrame f)
• beginDraggingFrame(JComponent f)
• closeFrame(JInternalFrame f)
• beginResizingFrame(JComponent f, int direction)

JLayeredPane

This is a general container for controlling components that overlap. Its main role
is to act as the parent class of the JDesktopPane. When components are added to a
JLayeredPane, the setBounds() method should be used to place it because
JLayeredPane uses a null layout manager. Components that are added to a
JLayeredPane can be given relative layer values which determine which components are
on top of other components.
An Integer object specifies each component’s depth in the container, where
higher-numbered components sit “on top” of other components. JLayeredPane divides
the depth-range into several different layers. Putting a component into one of those layers
makes it easy to ensure that components overlap properly, without having to worry about
specifying numbers for specific depths. JLayeredPane manages its list of children like
Container, but allows for the definition of several layers within itself. Children in the
same layer are managed exactly like the normal Container object, with the added feature
that when children components overlap, children in higher layers are displayed above the
children in lower layers. Each layer is a distinct integer number. The layer attribute can
be set on a Component by passing an Integer object during the add call.

The constructor that can be used to create a layered pane is:


• JLayeredPane()

The various methods that can be used in conjunction with the layered pane are
listed below:
• getComponentCountInLayer(int layer)
• getComponentsInLayer(int layer)
• getComponentsToLayer()
• getIndexOf(Component c)
• getLayer(Component c)
• highestLayer()
• lowestLayer()
• moveToBack(Component c)
• remove(int index)
• setLayer(Component c, int layer)
• setPosition(Component c, int position)

OVERVIEW :

Evolution of Java GUI programming :

• The AWT (Abstract Window Toolkit) has been present in all versions of Java
• The AWT objects are built above native code objects, giving a native look-and-
feel
• The AWT objects are a least common denominator of all platforms
• The Swing objects are a separate library for JDK 1.1
• The Swing objects are in pure Java, and have the same look-and-feel on all
platforms
• The L&F of Swing objects can be customised to particular styles
• In JDK 1.2, the Swing objects are part of the Java Foundation Classes
• The JFC objects will provide a superset of each platform's objects
• The AWT objects will decrease in importance over time

Greater set of objects


The Swing set includes

• JButton
• JCheckbox
• JCheckboxMenuItem
• JColorChooser
• JComboBox
• JDesktopIcon
• JDesktopPane
• JDialog
• JDirectoryPane
• JEditorPane
• JFileChooser
• JFrame
• JInternalFrame
• JLabel
• JLayeredPane
• JList
• JMenu
• JMenuBar
• JMenuItem
• JOptionPane
• JPanel
• JPasswordField
• JPopupMenu
• JProgressBar
• JRadioButton
• JRadioButtonMenuItem
• JRootPane
• JScrollBar
• JScrollPane
• JSeparator
• JSlider
• JSplitPane
• JTabbedPane
• JTable
• JTextArea
• JTextField
• JTextPane
• JToggleButton
• JToolBar
• JToolTip
• JTree
• JViewport
• JWindow

Capability

• Each object has greater capabilities than its corresponding AWT object
• Some capabilities are object-specific
• Some are available across all objects
o internationalisation
o customisable UI

JFrame

• JFrame is the Swing equivalent of Frame


• It adds double buffering to avoid flickering during drawing
• It has a slightly different interface to geometry management - things are added to
a contentPane
• It can hold a JMenuBar

Hello World using Swing


import javax.swing.*;

public class JHello extends JFrame {

public static void main(String argv[])


{
new JHello();
}

JHello() {
JLabel hello = new JLabel("Hello World");
getContentPane().add(hello, "Center");
setSize(200, 200);
setVisible(true);
}
}

JButton

• JButton's can have an image and/or text label with controllable placement
• Similarly for JLabel, JCheckBox, JRadioButton
• These extend appearance of corresponding AWT objects

JButton with Image


A button may be made with an icon image

import javax.swing.*;
import java.awt.*;

public class JButtonImage extends JFrame {

public static void main(String argv[]) {


new JButtonImage().setVisible(true);
}
public JButtonImage() {
ImageIcon image1 =
new ImageIcon("bart.gif");
ImageIcon image2 =
new ImageIcon("swing.small.gif");
JButton btn1 = new JButton(image1);
JButton btn2 = new JButton(image2);

Container pane = getContentPane();


pane.setLayout(new GridLayout(1, 2));
pane.add(btn1);
pane.add(btn2);
pack();
}
}
If the image has a transparent background (the second one), it looks better on pressing the
button

JButton with more icons and text


Pressed, rollover and disabled icons can also be set

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

public class TestRollover extends JFrame {

static public void main(String argv[]) {


new TestRollover().setVisible(true);
}
public TestRollover() {
ImageIcon left =
new ImageIcon("left.gif");
ImageIcon leftRollover =
new ImageIcon("leftRollover.gif");
ImageIcon leftDown =
new ImageIcon("leftDown.gif");

JButton button = new JButton("Left",


left);
button.setPressedIcon(leftDown);
button.setRolloverIcon(leftRollover);
button.setRolloverEnabled(true);
button.setToolTipText(
"This is a Button with a RolloverIcon");

getContentPane().add(button, "Center");
pack();
}
}

JButton with animated icon:

• The image can be animated by using a multipart gif file


• No other changes are needed
• See Checkbox in SwingSet

Property change listeners

• Most components have state that can change


• Some of this is Bean's information, and generates ChangeEvents
• For example, JButton fires an event on change of text, any icon, alignment or text
position, or change in the model (button pressed, released, etc)

EVENTS:

AWT events:

• Event model in Java 1.0 is poor s/w engineering, based on class Event
• In Java 1.1 it changes to a new model called AWTEvent
• This event handling model is unchanged for Java 1.2
• Event handling is the same for Swing and AWT components
• Events are handled by listeners, not by subclasses of GUI objects
AWT Event classes:

The class AWTEvent has subclasses:

• ComponentEvent
• FocusEvent
• KeyEvent
• MouseEvent
• WindowEvent
• ActionEvent
• AdjustmentEvent
• ItemEvent

AWT Event ids:


Some of these classes have an id value to distinguish between them

• KeyEvent: KEY_PRESSED, KEY_RELEASED, KEY_TYPED


• ComponentEvent: COMPONENT_MOVED, COMPONENT_RESIZED,
COMPONENT_SHOWN, COMPONENT_HIDDEN
• MouseEvent: MOUSE_CLICKED, MOUSE_DRAGGED, MOUSE_PRESSED,
etc

Triggering event:
Events are posted by user actions (or may be done programmatically)

• ActionEvent
o click on JButton
o click on JMenuItem
o press <enter> key in JTextField

Listeners
Listeners are objects that handle events

• ActionEvent handled by ActionListener


• KeyEvent handled by KeyListener
• Mouse motion events handled by MouseMotionListener (optimisation)
• Other Mouse events handled by MouseListener

Listeners as interfaces
Listeners are defined as interfaces and must be implemented by the application

public interface ActionListener


extends EventListener {
public void actionPerformed(ActionEvent e);
}
public interface MouseListener
extends EventListener {
public void mouseClicked(MouseEvent e);
public void mousePressed(MouseEvent e);
public void mouseReleased(MouseEvent e);
public void mouseEntered(MouseEvent e);
public void mouseExited(MouseEvent e);
}

Registering listeners

• Each GUI object generates certain events


• For each class of AWTEvent there is an add<Event>Listener
• e.g. For Button, MenuItem and TextField there is a method
addActionListener()
• e.g. For all Component and JComponent addMouseListener()

Simple Delegation program (1)

import javax.swing.*;
import java.awt.event.ActionListener;

public class JDelegateDemo


extends JFrame {
public static void main(String argv[]) {
new JDelegateDemo().setVisible(true);
}

public JDelegateDemo() {
// create the GUI objects
JButton left = new JButton("Left");
JButton right = new JButton("Right");
JLabel label = new JLabel(" ",
SwingConstants.CENTER);

// set their geometry


Container pane = getContentPane();
pane.add(left, "West");
pane.add(right, "East");
pane.add(label, "Center");
pack();

// continue constructor
// create a listener and add it to each Button
SimpleListener simple =
new SimpleListener(label);
left.addActionListener(simple);
right.addActionListener(simple);
}
}

/**
* A listener object that is invoked
* when a Button is activated it finds
* the Button's label and sets it in a Label
*/
class SimpleListener implements ActionListener {

private JLabel label;

public SimpleListener(JLabel l) {
// the listener needs to know the Label
// it will act on
label = l;
}

public void actionPerformed(ActionEvent e) {


// get the label showing in whichever
// Button was pressed
String name = e.getActionCommand();

// set this in the Label object


label.setText(name);
}
}

Event Delivery Model

• The path taken by events is different for AWT components and Swing components
• Native events are generated by user actions, such as mouse clicks.
• Native events are translated into Java events, and sent to a Java object which has
a native window
• The difference is that all AWT objects have a native window, but only some Swing
objects such as JFrame have one
• For the AWT, events have to be finally delivered to native objects to have visual
effect
• For Swing, a container has to pass events to its Swing components to have visual
as well as semantic effect
Event Model (2)
For a mouse press and mouse release on a Button inside a Frame, the following
sequences for Java using X Windows occur

The Motif Pushbutton recognises that it has been clicked and sends an ActionEvent
Event Model (3)
For a mouse press and mouse release on a JButton inside a JFrame, the following
sequences for Java using X Windows occur

The JButton now recognises it has been clicked

Changing key values (1)


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

public class MapKey extends Frame {


public static void main(String argv[]) {
new MapKey().setVisible(true);
}
public MapKey() {
TextField text = new TextField(20);
add(text);
pack();
text.addKeyListener(new ToUpper());
}
}

Changing key values (2)

class ToUpper implements KeyListener {

public void keyTyped(KeyEvent e) {


// empty
}

public void keyPressed(KeyEvent e) {


e.setModifiers(Event.SHIFT_MASK);
}

public void keyReleased(KeyEvent e) {


// empty
}
}

Consuming events

• Events may need to be ``blocked'' from reaching objects sometimes


o In password entry, keystrokes need to be caught by the application but not
reach the Text object for display
o A GUI builder might use mouse clicks to select objects such as Button, but
not activate the Button
• The delegation model allows this for key and mouse events
• Events are discarded by calling the method AWTEvent.consume()

Consuming events
This key listener discards non-alphabetic events:
public class Alpha implements KeyListener {
public void keyPressed(KeyEvent e) {
if (! Character.isLetter(e.getKeyChar())) {
Toolkit.getDefaultToolkit().beep();
e.consume();
}
}
public void keyReleased(KeyEvent e) {
// empty
}
public void keyTyped(KeyEvent e) {
// empty
}
}

Generating Events

• Events may be created and placed on the event queue for applications
• The event queue is found from
Toolkit.getDefaultToolkit().getSystemEventQueue()
• The event queue is not accessible yet from applets (need applet queue)
• Posting events works for Swing objects, but not for AWT objects

GEOMETRY:

Insets

• An inset gives a top, bottom, left and right border within which a Container lays
out its contents.
• Insets should probably be treated as readonly

Borders

• Borders of various kinds can be created, using the insets


• Types include: bevelled, etched, empty, lined
• Borders can be chained to e.g. add a title to a bevel border

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class TestBorder extends JFrame {

static public void main(String argv[]) {


new TestBorder().setVisible(true);
}

public TestBorder() {
Border border = BorderFactory.
createBevelBorder(
BevelBorder.RAISED);
JLabel label = new JLabel("Hello");
label.setBorder(border);
getContentPane().add(label, "Center");
pack();
}
}

Layout Objects

• Geometry layout is done by an associated Layout object


• Layout objects include
o BorderLayout - NSEW layout
o FlowLayout - left-to-right with overflow
o GridLayout - regular rectangular grid
o GridBagLayout - general gridded layout
• CardLayout allows ``flipping'' through a set of ``cards''

BorderLayout

• Objects are added to the "North", "South", "West", "East" or "Center"


• Safer programs may use BorderLayout.NORTH, etc (compiler catches errors)
• This is the default layout for JFrame
• An example program is

BorderLayout (2)

import java.awt.*;

class TestBorderLayout extends JFrame {


public TestBorderLayout() {
Container pane = getContentPane();
pane.add(new JButton("Push Me W"), "West");
pane.add(new JButton("Push Me E"), "East");
pane.add(new JButton("Push Me S"), "South");
pane.add(new JButton("Push Me N"), "North");
setSize(400, 200);
setVisible(true);
}
}

Building your own manager

• LayoutManager is declared as an interface



• public interface LayoutManager {
• void addLayoutComponent(String name, Component comp);
• void removeLayoutComponent(Component comp);
• Dimension preferredLayoutSize(Container parent);
• Dimension minimumLayoutSize(Container parent);
• void layoutContainer(Container parent);
• }

Building your own manager


The following manager sets the size of its (single) child (ignoring insets):

class SizeLayout implements LayoutManager {


Dimension size;

public SizeLayout() {
size = new Dimension(0, 0);
}

public SizeLayout(Dimension s) {
size = new Dimension(s);
}

public void setSize(Dimension s) {


size = new Dimension(s);
}

public Dimension getSize() {


return new Dimension(size);
}

public void
addLayoutComponent(String n, Component c) {
}

public void
removeLayoutComponent(Component c) {
}

public Dimension
preferredLayoutSize(Container parent) {
if (parent.countComponents() == 0)
return new Dimension(width, height);

// use the first component added


Component c = parent.getComponent(0);
return c.preferredSize();
}

public Dimension
minimumLayoutSize(Container parent) {
if (parent.countComponents() == 0)
return new Dimension(width, height);

// use the first component added


Component c = parent.getComponent(0);
return c.minimumSize();
}

public void
layoutContainer(Container parent) {
if (parent.countComponents() == 0)
return;

// use the first component added


Component c = parent.getComponent(0);
c.setBounds(0, 0, size.width, size.height);
c.validate();
}
}

Building constraint managers

• LayoutManager2 contains extra methods for building constraint managers


Reusing GridBagLayout
Layout managers can also be built by restricting the use of a complex manager such as
GridBagLayout. This manager gives a ``box of buttons'' layout

public class ButtonBoxLayout


implements LayoutManager {

GridBagLayout gridbag = new GridBagLayout();


GridBagConstraints constraints =
new GridBagConstraints();

public void
addLayoutComponent(String name, Component comp) {
// empty -this should never be called
}

public void
removeLayoutComponent(Component comp) {
// empty - no state maintained here
}

// the next three methods restore state


// if the parent has had changes done to
// its children, before calling gridbag
public Dimension
preferredLayoutSize(Container parent) {
if ( ! parent.isValid()) {
layoutButtons(parent);
}
return gridbag.preferredLayoutSize(parent);
}

public Dimension
minimumLayoutSize(Container parent) {
if ( ! parent.isValid()) {
layoutButtons(parent);
}
return gridbag.minimumLayoutSize(parent);
}

public void
layoutContainer(Container parent) {
if ( ! parent.isValid()) {
layoutButtons(parent);
}
gridbag.layoutContainer(parent);
}

/**
* Find the height of the first component,
* and add half of it
* above and below using ipady.
* Find the largest width, and set ipadx
* for all components to give it that width
*/
protected void layoutButtons(Container parent) {

int width = parent.getSize().width;


int nbuttons = parent.getComponentCount();

if (nbuttons == 0)
return;

constraints.weightx = 1.0;
// stretch each component vertically
constraints.ipady =
parent.getComponent(0).
getPreferredSize().height/2;

// find the largest width


Dimension compSize;
int maxWidth = 0;
for (int n = 0; n < nbuttons; n++) {
compSize = parent.getComponent(n).
getPreferredSize();
maxWidth = Math.max(compSize.width, maxWidth);
}

// use the largest width or increase


// using available space
maxWidth = Math.max(width/(nbuttons*2), maxWidth);

// set the ipadx to make each button the same size


for (int n = 0; n < nbuttons; n++) {
Component component = parent.getComponent(n);

compSize = component.getPreferredSize();
constraints.ipadx = maxWidth - compSize.width;
gridbag.setConstraints(component, constraints);
}
}
}

Composite Objects
Rather than doing geometry afresh each time, one can create new composite objects
which are just reused in toto

public class LabelledTextField extends JPanel {


protected JLabel label;
protected JTextField text;

public LabelledTextField(String lab, int cols) {


setLayout(new BorderLayout());
label = new JLabel(lab);
text = new JTextField(cols);
add(label, BorderLayout.WEST);
add(text, BorderLayout.CENTER);
}

public String getText() {


return text.getText();
}

public void addActionListener(ActionListener al) {


text.addActionListener(al);
}
}

Swing component architecture

• Swing uses a simplified version of Model-View-Controller


• Each component has a view (UI) and a model
• The model and the view (UI) can be independently changed
JButton structure

• A JButton is a subclass of AbstractButton


• An AbstractButton has a ButtonModel which can be manipulated by

• public ButtonModel getModel();
• public void setButtonModel(ButtonModel);

• An AbstractButton has a ButtonUI which can be manipulated by



• public ButtonUI getUI();
• public void setUI(ButtonUI ui);

ButtonModel

• ButtonModel contains many state features of a button, such as isArmed,


isSelected, isEnabled, isPressed, isRollover, keyAccelerator, actionCommand.
• It also maintains lists of listeners: actionListener, changeListener
• These are usually accessed by methods in JButton

• public boolean isSelected() {
• return model.isSelected():
• }
ButtonUI

• The UI elements do not maintain component state.


• They implement methods

• paint()
• getPreferredSize()
• getMinimumSize()

• A ButtonUI asks JButton and its model for any state


Button UI elements

• An AbstractButton holds many UI elements that are independent of presentation:


defaultIcon, PressedIcon, etc, and image/text alignment such as
verticalAlignment, verticalTextPosition
Button listeners
There is a set of listeners to decouple model and view from state change listeners

• A BasicButtonListener responds to events (such as mousePressed()) by calling


methods in DefaultButtonModel (such as setArmed(true))
• A ButtonChangeListener responds to change events posted by the model and fires
a state change notification in the Button
• A state change notification in the Button is noticed by the BasicButtonListener
which calls repaint() in the Button
• repaint() in the Button calls paint() in the BasicButtonUI

Button instance

Changing the model

• Problem: create a button that counts how often it has been pressed
• A state count of the number of times needs to be kept
• Define a new model CountButtonModel to extend DefaultButtonModel by this
count
• Define a new class CountButton to install this model
• Hide the model by access method getCount() on CountButton

CountButtonModel

public class CountButtonModel


extends DefaultButtonModel {

protected int count = 0;


public int getCount() {
return count;
}

public void setPressed(boolean b) {


// b is true if pressed,
// false if released
super.setPressed(b);
if (b) {
count++;
}
}
}

CountButton

public class CountButton extends JButton {

public CountButton() {
this(null, null);
}

public CountButton(Icon icon) {


this(null, icon);
}

public CountButton(String text) {


this(text, null);
}

public CountButton(String text, Icon icon) {


super(text, icon);
// Create the model
setModel(new CountButtonModel());
}

public int getCount() {


return ((CountButtonModel) model).getCount();
}
}

Using the CountButton is done by e.g.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import CountButton;

public class TestCountButton extends JFrame


implements ActionListener{

static public void main(String argv[]) {


new TestCountButton().setVisible(true);
}

public TestCountButton() {
CountButton btn = new CountButton("Press me");
getContentPane().add(btn, BorderLayout.CENTER);
pack();
btn.addActionListener(this);
}

public void actionPerformed(ActionEvent evt) {


CountButton btn = (CountButton) evt.getSource();
System.out.println("Count: " + btn.getCount());
}
}

Changing the UI

• The supplied UI's are standard(Windows), motif, jlf (Java Look and Feel)
• Microsoft have not yet granted permission for the standard L&F to be available
on non-Windows platforms
• Changing the UI involves two calls

• UIManager.setLookAndFeel(String)
• SwingUtilities.updateComponentTreeUI(Component)

where the String is eg "javax.swing.motif.MotifLookAndFeel" and the Component


is the toplevel Frame or Applet

• Building your own L&F means writing a UI for every component.

JList

• JList extends functionality of List, and requires programmatic changes


• JList has a list of Object, not just String
• The list can be set by a constructor
• The contents of a JList are stored in the ListModel model, and you change the list
by methods of the model
• The UI uses a CellRenderer to paint each element of a list, and this can be set by
an application
• The listeners are ListSelectionListeners rather than ItemListeners

JList with Strings

• A JList with a set of String is best made using a constructor



• String [] elmts = {"one", "two", "three"};
• Jlist list = new JList(elmts);

Simple JList example


This uses a list of Strings, like List

import javax.swing.event.*;
import javax.swing.*;

public class TestList extends JFrame


implements ListSelectionListener {

static public void main(String argv[]) {


new TestList().setVisible(true);
}

public TestList() {
String [] elmts = {"one", "two", "three"};
JList list = new JList(elmts);
getContentPane().add(list, "Center");
pack();
list.addListSelectionListener(this);
}

public void valueChanged(ListSelectionEvent evt) {


JList list = (JList)
evt.getSource();
String value = (String)
list.getSelectedValue();
if (value != null &&
! evt.getValueIsAdjusting()) {
System.out.println("Selected: " +
value);
}
}
}

JList using Icons


This shows a list of icons

import javax.swing.event.*;
import javax.swing.*;

public class TestIconList extends JFrame


implements ListSelectionListener {
static public void main(String argv[]) {
new TestIconList().setVisible(true);
}

public TestIconList() {
ImageIcon images[] = new ImageIcon[2];
images[0] = new ImageIcon("bart.gif");
images[1] = new ImageIcon("swing.small.gif");

JList list = new JList(images);


getContentPane().add(list, "Center");
pack();
list.addListSelectionListener(this);
}

public void valueChanged(ListSelectionEvent evt) {


JList list = (JList) evt.getSource();
int value = list.getSelectedIndex();
if (value != -1 && ! evt.getValueIsAdjusting()) {
System.out.println("Selected: " + value);
}
}
}

Rendering JList with a Component


This shows a list of image+text, where rendering is done by calling paint() on a JLabel:

import java.awt.*;
import javax.swing.event.*;
import javax.swing.*;
public class TestLabelList extends JFrame {

static public void main(String argv[]) {


new TestLabelList().setVisible(true);
}

public TestLabelList() {

JList list = new JList(new String [] {"Bart", "Swing"});


getContentPane().add(list, "Center");
list.setCellRenderer(new LabelCellRenderer());
pack();
}
}

class LabelCellRenderer extends JLabel


implements ListCellRenderer {

static protected ImageIcon images[] = {


new ImageIcon("bart.gif"),
new ImageIcon("swing.small.gif")
};

public LabelCellRenderer() {
setOpaque(true);
}

public Component
getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
setText(value.toString());
setIcon(images[index]);
setBackground(isSelected ?
Color.red : Color.white);
setForeground(isSelected ?
Color.white : Color.black);
return this;
}
}
Rendering JList
Draw your own shapes in a JList

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

public class TestDrawList extends JFrame


implements ListSelectionListener {
static public void main(String argv[]) {
new TestDrawList().setVisible(true);
}

public TestDrawList() {

JList list = new JList(new String []


{"Circle", "Square"});
getContentPane().add(list, "Center");
list.setCellRenderer(new DrawCellRenderer());

// fix cell sizes since list doesn't know them


list.setFixedCellWidth(30);
list.setFixedCellHeight(30);
pack();
}
}

class DrawCellRenderer extends JComponent


implements ListCellRenderer {

protected int index;


boolean selected;

public boolean isOpaque() {


return true;
}

public Component
getListCellRendererComponent(
JList list,
Object value,
int index,
boolean selected,
boolean cellHasFocus) {
this.index = index;
this.selected = selected;
return this;
}

public void paint(Graphics g) {


Color fg, bg;

if (selected) {
fg = Color.green;
bg = Color.black;
} else {
fg = Color.red;
bg = Color.white;
}

// fill background
g.setColor(bg);
g.fillRect(0, 0, getWidth(), getHeight());

// draw shape
g.setColor(fg);
if (index == 0) {
g.fillOval(5, 5, 25, 25);
} else {
g.fillRect(5, 5, 25, 25);
}
}
}

Scrolling list

• Scrolling is not a part of JList


• Use a ScrollPane

• JScrollPane scrollPane = new JScrollPane();
• scrollPane.getViewport().setView(list);

Text replacements

• JTextArea acts as a drop in replacement for TextArea


• JTextField acts as a drop in replacement for TextField
• JPasswordField is a safer replacement for JTextField used with setEchoChar()
• JTextPane can display multiple fonts, colours, etc.

Model

The model is known as a Document, and can be shared between Text objects.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;

public class Text2 extends JFrame {

public static void main(String argv[]) {


new Text2().setVisible(true);
}

public Text2() {
JTextArea text1 = new JTextArea("starting text", 5, 30);
JTextArea text2 = new JTextArea(5, 30);
text2.setDocument(text1.getDocument());

Border border = BorderFactory.


createLineBorder(Color.black);
text1.setBorder(border);
text2.setBorder(border);

Container pane = getContentPane();


pane.setLayout(new GridLayout(2, 1));
pane.add(text1);
pane.add(text2);
pack();
}

Styles

• A style is a set of text display characteristics such as FontSize, ForegroundColor,


isItalic, etc
• A style is manipulated by e.g.

• StyleConstants.setForeground(style, Color.red)

• A StyleContext can hold many styles


• A JTextPane can have a DefaultStyledDocument as a model
• A DefaultStyledDocument has a StyleContext
• Styles can be applied to portions or all of a Document by e.g.

• JTextPane.setCharacterAttributes(Style, Boolean)
• DefaultStyledDocument.setLogicalStyle(int, Style)

Changing document colours


This program allows you to select a colour from a menu. Any text entered after that will
be in that colour

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;

public class TestStyle extends JFrame


implements ActionListener {

private Style redStyle, blueStyle, greenStyle;


private JTextPane text;

public static void main(String argv[]) {


new TestStyle().setVisible(true);
}

public TestStyle() {
JTextPane text = createEditor();
getContentPane().add(text, "Center");
setJMenuBar(createMenu());
setSize(200, 200);
}

private JMenuBar createMenu() {


JMenuBar mbar = new JMenuBar();
JMenu color = new JMenu("Color");
mbar.add(color);

JMenuItem mi = new JMenuItem("Red");


color.add(mi);
mi.addActionListener(this);
mi = new JMenuItem("Blue");
color.add(mi);
mi.addActionListener(this);

mi = new JMenuItem("Green");
color.add(mi);
mi.addActionListener(this);

return mbar;
}

public void actionPerformed(ActionEvent evt) {


Style style = null;
String color = (String) evt.getActionCommand();
if (color.equals("Red")) {
style = redStyle;
} else if (color.equals("Blue")) {
style = blueStyle;
} else if (color.equals("Green")) {
style = greenStyle;
}
text.setCharacterAttributes(style, false);
}

private JTextPane createEditor() {


StyleContext sc = createStyles();
DefaultStyledDocument doc = new DefaultStyledDocument(sc);

return (text = new JTextPane(doc));


}

private StyleContext createStyles() {


StyleContext sc = new StyleContext();

redStyle = sc.addStyle(null, null);


StyleConstants.setForeground(redStyle,
Color.red);

blueStyle = sc.addStyle(null, null);


StyleConstants.setForeground(blueStyle,
Color.blue);

greenStyle = sc.addStyle(null, null);


StyleConstants.setForeground(greenStyle,
Color.green);
StyleConstants.setFontSize(greenStyle, 24);

return sc;
}
}

Convenience Action Listeners

• StyledEditorKit has a set of ActionListener's that do the actionPerformed() for


you
• These can be added to e.g. MenuItem

• ActionListener a =
• new StyledEditorKit.ForegroundAction(
• "set-foreground-red",
• Color.red);
• mi.addActionListener(a);

• See Sun example StylePad for more examples

FileChooser

• Some widgets can be used standalone, or can be embedded in dialogs


• JFileChooser and JColorChooser have a convenience method to post a dialog
• Standalone mode for JFileChooser doesn't work properly in Swing 1.0, but does
in JDK 1.2 beta 4

// using an embedded JFileChooser

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

public class BasicChooser extends JFrame


implements ActionListener {
JFileChooser chooser;

static public void main(String argv[]) {


new BasicChooser().setVisible(true);
}
public BasicChooser() {
getContentPane().add(chooser = new JFileChooser(),
BorderLayout.CENTER);
chooser.addActionListener(this);
pack();
}

public void actionPerformed(ActionEvent e) {


System.out.println(chooser.getSelectedFile().
getName());
}
}

// using a JFileChooser in a dialog

import java.awt.*;
import javax.swing.*;

public class BasicChooser extends JFrame {


JFileChooser chooser;

static public void main(String argv[]) {


BasicChoser bc = new BasicChooser();
bc.setVisible(true);
chooser.showOpenDialog(bc);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You selected file: " +
chooser.getSelectedFile().getName());
}
}

public BasicChooser() {
setSize(100, 100);
}
}

Menus

• All menu components are subclassed from JMenuComponent (JMenuBar, JMenu,


JMenuItem, JCheckboxMenuItem).
• Menus are pulldown or popup
• Menus can be changed by the setJMenu() of JFrame. This unmaps the old menu
and maps the new one
• Menus can be set on any element, not just JFrames

JMenuBar

• JMenuBar provides a horizontal bar containing menu selections


• Pulldown menus hang from there
• It is added to Frame by Frame's method setJMenu(JMenuBar)

JMenu

• The default constructor



• JMenu(String label)

creates a non-tearable menu.

• The constructor

• JMenu(String label, boolean tearOff)

allows control of this

JMenuItem and JCheckboxMenuItem

• JMenuItem is an ordinary selection element


• A JMenuItem with name ``-'' is a separator
• A constructor allows a ``hot-key'' to be associated with a JMenuItem
• JCheckboxMenuItem can be set to on or off

Menus, toolbars and abstract actionsMenus can be created as above

• Toolbars can be created using JToolBar


• Often they duplicate behaviour, i.e. have the same listeners
• Often they must be manipulated together e.g. disabled
• AbstractAction looks after this
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class TestAction extends JFrame {


OpenAction openAction = new OpenAction();
SaveAction saveAction = new SaveAction();

public static void main(String argv[]) {


new TestAction().show();
}

TestAction()
{
createMenu();
createToolBar();
setSize(300, 300);
}

private void createMenu()


{
JMenuBar mb = new JMenuBar();
JMenu fileB = new JMenu("File");
mb.add(fileB);

fileB.add(openAction);
fileB.add(saveAction);

setJMenuBar(mb);
}

private void createToolBar() {


JToolBar bar = new JToolBar();
bar.add(openAction);
bar.add(saveAction);
getContentPane().add(bar, BorderLayout.NORTH);
}
}

class OpenAction extends AbstractAction {

public OpenAction() {
super("Open", new ImageIcon("open.gif"));
}

public void actionPerformed(ActionEvent e) {


System.out.println("Open action");
}
}

class SaveAction extends AbstractAction {

public SaveAction() {
super("Save", new ImageIcon("save.gif"));
}

public void actionPerformed(ActionEvent e) {


System.out.println("Save action");
}
}

Dialogs

• JOptionPane allows simple dialogs to be built


• The dialogs are modal
• The simplest use is just a oneline inline call

Dialog types
The dialog types can be

• ERROR_MESSAGE
• INFORMATION_MESSAGE
• WARNING_MESSAGE
• QUESTION_MESSAGE
• PLAIN_MESSAGE

This controls the default icon used

Dialog buttons
The dialog buttons can be

• DEFAULT_OPTION
• YES_NO_OPTION
• YES_NO_CANCEL
• OK_CANCEL

You can choose your own buttons (labels or images)


Default warning dialog

Use JOptionPane.showMessageDialog():

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

public class TestWarning extends JFrame


implements ActionListener {

public static void main(String argv[]) {


new TestWarning().setVisible(true);
}

public TestWarning() {
JButton btn = new JButton("Show dialog");
getContentPane().add(btn, "Center");
pack();
btn.addActionListener(this);
}

public void actionPerformed(ActionEvent evt) {


JOptionPane.showMessageDialog(this,
"Warning",
"Warning Dialog",
JOptionPane.WARNING_MESSAGE);
}
}

Confirmation dialog

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

public class TestConfirmation extends JFrame


implements ActionListener {

public static void main(String argv[]) {


new TestConfirmation().setVisible(true);
}
public TestConfirmation() {
JButton btn = new JButton("Show dialog");
getContentPane().add(btn, "Center");
pack();
btn.addActionListener(this);
}

public void actionPerformed(ActionEvent evt) {


int response = JOptionPane.showConfirmDialog(this,
"Answer Yes or No",
"Confirmation Dialog",
JOptionPane.YES_NO_OPTION);
String responseStr = null;
if (response == JOptionPane.YES_OPTION) {
responseStr = "Yes";
} else {
responseStr = "No";
}
System.out.println("Response: " + responseStr);
}
}
Input dialog

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

public class TestInput extends JFrame


implements ActionListener {

public static void main(String argv[]) {


new TestInput().setVisible(true);
}

public TestInput() {
JButton btn = new JButton("Show dialog");
getContentPane().add(btn, "Center");
pack();
btn.addActionListener(this);
}

public void actionPerformed(ActionEvent evt) {


String response = JOptionPane.showInputDialog(this,
"Enter name",
"Input Dialog",
JOptionPane.DEFAULT_OPTION);
System.out.println("Response: " + response);
}
}

Other dialogs

• You can also present a list of options and choose one


• More general dialogs have to be custom built - including you doing the placement
of buttons (a special layout manager, SyncingLayoutManager, is not public)

Keyboard traversal

• There is a default keyboard traversal mechanism, such as TAB moving focus to


the right in GridLayout
• Additional control may be obtained using the registerKeyboardAction(),
which adds an ActionListener to specified keys

The following program moves an X around a 3x3 set of buttons by use of the arrow keys

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class TestKeyboardAction extends JFrame


implements ActionListener {

protected JButton [] buttons = new JButton[9];

static public void main(String argv[]) {


new TestKeyboardAction().show();
}

public TestKeyboardAction() {
Container pane = getContentPane();
pane.setLayout(new GridLayout(3, 3));

Border border = BorderFactory.


createLineBorder(
Color.black);
KeyStroke up = KeyStroke.getKeyStroke(
KeyEvent.VK_UP, 0);
KeyStroke down = KeyStroke.getKeyStroke(
KeyEvent.VK_DOWN, 0);
KeyStroke left = KeyStroke.getKeyStroke(
KeyEvent.VK_LEFT, 0);
KeyStroke right = KeyStroke.getKeyStroke(
KeyEvent.VK_RIGHT, 0);

JRootPane rootPane = getRootPane();


rootPane.registerKeyboardAction(this,
"up", up,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
rootPane.registerKeyboardAction(this,
"down", down,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
rootPane.registerKeyboardAction(this,
"right", right,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
rootPane.registerKeyboardAction(this,
"left", left,
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

for (int n = 0; n < 9; n++) {


JButton button = new JButton();
button.setBorder(border);
button.setName(new Integer(n).toString());
pane.add(button);

buttons[n] = button;
}
setSize(200, 200);
}

public void actionPerformed(ActionEvent e) {

Component focusOwner = getFocusOwner(); // Window method


String name = focusOwner.getName(); // get btn's name
int index = Integer.parseInt(name); // as an int
buttons[index].setText(""); // clear text
String action = e.getActionCommand();

// find next index for this action


if (action.equals("up")) {
index = (index < 3) ? index + 6 : index - 3;
} else if (action.equals("down")) {
index = (index > 5) ? index - 6 : index + 3;
} else if (action.equals("left")) {
index = (index == 0) ? index = 8 : index - 1;
} else { // assume right
index = (index == 8) ? index = 0 : index + 1;
}

buttons[index].setText("X"); // set text in next btn


buttons[index].requestFocus(); // and focus to it
}
}

Summary:
Java Foundation Class was developed to address the AWT. Its visual components
extend the AWT container class. The methods contained in the Component and Container
classes that AWT are valid for JFC visual classes. Swing offers a number of advantages
such as pluggable look and feel, MVC architecture, keystroke handling, action objects,
needed containers, virtual desktops, compound borders etc. Application services covers a
wide range of service, which includes keyboard navigation, multithreaded event queue,
undo, bounded range model etc.

You might also like