java notes

advertisement
JAVA
1
Introduction to Java
2
History
Developed by James Gosling at Sun
Microsystems.
Introduced in 1995.
Is one the fastest growing programming
technologies of all time.
3
Features
• Simple
• Object Oriented
• Architecture neutral
• High performance
• Multithreaded
• Robust
• Distributed
• Portable
• Dynamic
• Secure
4
The Byte Codes
In the Java programming language, all source code is
first written in plain text files ending with the .java
extension.
Those source files are then compiled into .class files
by the Java compiler (javac).
A .class file does not contain code that is native to
your processor; it instead contains bytecodes-- the
machine language of the Java Virtual Machine.
The Java launcher tool (java) then runs your
application with an instance of the Java Virtual
Machine.
5
Bytecode
It is a highly optimized set of
instructions designed to be executed by
the Java run-time system,known as
JVM.
6
7
Platform Independence
8
9
Creating Your First Application
Create a source file. A source file
contains text, written in the Java
programming languageYou can use any
text editor to create and edit source
files.
10
Compile the source file into a .class
file. The Java compiler, javac, takes
your source file and translates its text
into instructions that the Java Virtual
Machine can understand. The
instructions contained within this file
are known as bytecodes.
11
Run the program. The Java launcher
(java) uses the Java Virtual Machine to
run your application.
12
Create a Source File
/** * The HelloWorldApp class implements an
application that * simply displays "Hello World!" to
the standard output. */
class HelloWorldApp
{
public static void main(String[] args)
{
//Display "Hello World!"
System.out.println("Hello World!");
}
}
13
Compile the Source File
C:\java\javac HelloWorldApp.java
Run the Program
In the same directory, enter at the prompt:
C:\java\java HelloWorldApp
14
Example Explained…
class HelloWorldApp { …}
About the class
It is the basic building block of an objectoriented language such as Java
It is a template that describes the data and
behavior associated with instances of that
class
15
When you instantiate a class you create an
object that looks and feels like other
instances of the same class.
The data associated with a class or object is
stored in variables;
the behavior associated with a class or
object is implemented with methods.
Methods are similar to the functions or
procedures in procedural languages such as
C.
16
The main Method
In the Java programming language, every
application must contain a main method
whose signature looks like this:
public static void main(String[] args) {..}
17
The method signature for the main method
contains three modifiers:
 public indicates that the main method can
be invoked by any object.
 static indicates that the main method is a
class method (as opposed to an instance
method).
void indicates that the main method doesn't
return any value.
18
2. Data
Types,Variables and
Arrays
19
Data type
A data type is a scheme for representing
values. An example is int which is the
integer, a data type.
Values are not just numbers, but any kind of
data that a computer can process.
The data type defines the kind of data that is
represented by a variable.
As with the keyword class, Java data types
are case sensitive.
20
Primitive Java Data Types
21
Objects
All data in Java falls into one of two
categories: primitive data and objects.
There are only eight primitive datatypes.
Any data type you create will be an object.
An object is a structured block of data. An
object may use many bytes of memory.
The data type of an object is its class.
Many classes are already defined in the Java
Development Kit.
A programmer can create new classes to
meet the particular needs of a program.
22
Integers:byte,short,int and long
Floating point numbers:float,double
Characters:char
Boolean:boolean
23
Data Type
Size
(bytes)
(byte)
byte
1
128 to 127
boolean
1
true or false
char
2(unicode)
A-Z, a-z, 0-9, etc
short
2
-32768 to 32767
int
4
(about )–2 million to 2 million
long
8
(about)-10E18 to 10E18
float
4
-3.4E38 to 3.4E18
double
8
-1.7E308 to 1.7E308
Range
24
Integers
All of these are signed,positive and negative
values.
byte.The smallest integer type is byte.
It is signed 8 bit type
Useful when working with a stream of data
from a network or file.
Declared using byte keyword. Eg: byte b,c;
25
short
short is a signed 16 bit
Least used Java type.
short s;
short t;
26
int
Commonly used integer type is int
Signed 32 bit
Eg: int rollnum;
27
long
Signed 64 bit type.
Useful in situations where an int type is
not large enough to hold the desired
value.
The range of a long is quite large.
Eg:long days,seconds,distance
28
Floating-point Types
Also known as real numbers
Used when evaluating expressions that
require fractional precision.
29
float
The type float specifies a singleprecision value that uses 32 bits of
storage
Declaration Eg:
Float hightemp,lowtemp;
30
double
Denoted by doublekeyword
Uses 32 bits of storage
Specifies double precision .
Eg: double pi,r,a;
31
Characters
In Java the data type used to store
characters is char.
Java uses unicode to represent
characters.(Unicode defines fully
international character set that can
represent all of the characters found in
all human languages.)
It requires 16 bits
32
Booleans
Java has a primitive type called
boolean, for logical values
It can have only one of two possible
values,true or false.
33
Literals
Integer literals
Floating-point literals
Boolean literals
Character literals
String literals
34
Variables
Basic unit of storage in a Java program
It is defined by a combination of an
identifier,type and an optional initializer.
All variables have a scope,which defines
their visible
35
Declaring a variable
All variables must be before they can
be used.
Synatx:
type identifier [=value1][,identifier];
Identifier is the name of the variable
36
Names of Variables
Use only the characters 'a' through 'z', 'A'
through 'Z', '0'through '9', character '_', and
character '$'.
A name cannot contain the space character.
Do not start with a digit.
A name can be of any reasonable length.
Upper and lower case count as different
characters. i.e.,Java is case sensitive. So SUM
and Sum are different names.
A name cannot be a reserved word keyword).
A name must not already be in use in this
block of the program.
37
Assignment Statements
variables are expected to vary by
having new values placed into them as
the program runs.
An assignment statement is one way
to change the value of a variable.
38
Assignment Statements
public class example
{
public static void main ( String[] args )
{
int states;
// a declaration of a
variable
states = 50;
// an assignment statement
System.out.println(“The variable states
contains: ” + states);
}
}
39
Assignment Statement Syntax
Assignment statements look like this:
variableName = expression;
The equal sign "=" means "assignment."
variableName is the name of a variable that
has been
declared somewhere in the program.
expression is an expression that has a value.
An assignment statement asks for the
computer to performtwo steps, in order:
1. Evaluate the expression (that is: calculate a
value.)
2. Store the value in the variable.
40
Expressions
An expression is a combination of literals,
operators, variables, and parentheses used to
calculate a value.
E.g. 49-x/y
literal: characters that denote a value, like:
3.456
operator: a symbol like plus ("+") or times
("*").
variable: a section of memory containing a
value.
parentheses: "(" and ")".
41
Scope and life a variable
A block defines a scope.
A scope determines what objects are
visible to other parts of the program.
It also determines the lifetime of those
objects.
42
Type conversion and Casting
Java’s Automatic Conversions
When one type of data is assigned to
another type of variable ,an automatic
type conversion will take place if:


The two types are compatible
The destination type is larger than the
source type ( This type of conversion is
known as widening conversion ) .
43
Casting Incompatible Types
When the destination type is larger than
the source type automatic conversion
fails.
So it should be cast.
A cast is simply an explicit type
conversion
44
The general form :
(target-type)value;
Eg:
int a;
byte b;
b=(byte) a;
45
Arrays
An array is a group of like-typed
variables that are referred to by a
common name
Arrays of any type can be created and
may have one or more dimension.
A specific element in an array is
accessed by its index.
46
One Dimensional Arrays
It is a list of like-typed variables.
To create an array ,an array variable of
desired type should be created.
General Form:
Type var-name[];
Eg:int month_days[];
47
All though month_day is an array
variable, no array actually exists.
Its value will be set to null,which
represents an array with no value.
It should be linked to actual physical
array of integers using new
new is a special operator that allocates
memory.
48
So it should be
array–var=new type[size];
i.e.., obtaining array is a two step process.
First: a variable of the desired array type must
be declared.
Second: The memory that will hold the array
should be allocated using new and assign it
to the variable.
49
Multidimensional Arrays
Eg:
int twoD [][] =new int [4][5]
50
Operators
1. Arithmetic Operators
2. Increment Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operators
6.Conditional Operators
51
Comments
A comment is a note written to a human
reader of a program.
The program compiles and runs exactly the
same with or without comments.
Comments start with the two characters "//"
(slash slash).
Those characters and everything that
follows them on the same line are ignored by
the java compiler.
52
Comments
Another style: /*..*/ or /**….*/
With this style of comment, everything
between the two characters "/*" and
the two characters "*/" are ignored by
the compiler.
There can be many lines of comments
between the "/*" and the "*/".
53
Command Line Arguments
A command-line argument is the
information that directly follows the
program’s name on the commandline
when it is executed.
To access the command-line arguments
inside a Java program
is quite easy—they are stored as strings
in the String array passed to main( ).
54
Command Line Arguments
A Java application can accept any
number of arguments from the
command line.
The user enters command-line
arguments when invoking the
application and specifies them after the
name of the class to be run
55
Program1
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +
args[i]);} }
56
Output
java CommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1
57
Parsing Numeric
Command-Line Arguments
If an application needs to support a numeric
command-line argument, it must convert a
String argument that represents a number,
such as "34", to a numeric value.
int firstArg;
if (args.length > 0) {
firstArg = Integer.parseInt(args[0]);
}
58
Program 2
public class arg {
public static void main (String[] args) {
int num = args.length;
System.out.println(num);
}
}
59
Program 3
class args
{
public static void main(String [] arg)
{
int a =Integer.parseInt(arg[0]);
System.out.println("The limit u entered is "+a);
int i,f=1;
for(i=1;i<=a;i++)
{f=f*i;}
System.out.println("The factorial is : "+f);
}
}
60
3.Control Statements
61
Selection Statements
Supports two selection statements:
if and switch
These allow us to control the flow of
the program’s execution based upon
conditions known only at run time.
62
if
Conditional branch statement.
General Form
If (condition)
statement1;
else
statement2;
63
Nested ifs
If (i==0)
{
if (j<20) a=b;
if(k>100) c=d;
else a=c;
}
else a=d;
64
The if-else-if ladder
if (condition1)
statement1;
else if(condition2)
statement2;
else if(condition3)
statement3;
.....
else statement;
eg:IfElse.java
65
switch
Java’s multiway branch statement.
Better than large series of if-else-if
statements.
66
switch :
General form
switch(expression){
case value1:
//statement sequence
break;
Case value2:
//statement sequence
break;
…
Case valueN:
//statement sequence
break;
default:
//statement sequence
67
switch
Expression must be of type
byte,short,int,char;
Each of the value specified in the case
statements must be of a type
compatible with the expression.
Duplicate case values are not allowed.
Eg:SampleSwitch.java
68
switch
The value of the expression is compared with
each of the literal values in the case
statements.
If a match is found the code sequence
following that case statement is executed.
If none of the constants matches the value of
the expression,then the default statement is
executed.
69
switch
Default statement is optional.
The break statement is used inside the
switch to terminate a statement
sequence.
If no break statement is given execution
will continue on into the case.
70
Nested switch statements
switch may be used as a part of the
statement sequence of an outer switch.
71
More on switch….
switch can only test for equality
While if can evaluate any type of Boolean
expression.
No two case constants in the same
switch can have identical values.
A switch statement is usually more
efficient than a set of nested ifs.
72
Iteration Statements:
Meant for executing selected
instructions repeatedly until a
terminating condition is met.
while ,do-while ,for
73
while
Most fundamental loop statement
The body of the loop will be executed
as long as the conditional expression is
true.
When the condition becomes false
control passes to the next line of code
immediately following the loop.
74
while
true
Continue
condition ?
false
true
Statement(s)
Next
statement
75
while :
While (condition)
{
// body of the loop
}
76
While : Order of Execution
(1)
while
(<
Cond. Expr.
(2) True
(4)
< Statement
>)
(3)
>
False
77
Three things
There are three things to consider when your
program has a loop:
1.The initial values must be set up correctly.
2.The condition in the while statement must
be correct.
3.The change in variable(s) must be done
correctly.
78
While :
program1
class while1
{
public static void main(String args[]) {
int i=0;
int a =Integer.parseInt(args[0]);
while(i<a) {
System.out.println("hi");
i++; }
}
}
79
while:
while loop evaluates its conditional
expression at the top of the loop,so the
body of the loop will not execute even
once if the condition is false .
Hence it is an entry-controlled loop.
80
do-while
Conditional expression is evaluated at
the bottom of the loop.
Always executes its body at least once.
Hence an exit controlled loop
81
do-while
Statement(s)
true
Continue
condition ?
false
Next
statement
82
do-while :General Form
do
{
//body of the loop
}while(condition);
Condition must be a boolean expression.
83
do-while:
program1
class dowhile
{
public static void main(String args[]) {
int i=5;
int a =Integer.parseInt(args[0]);
do {
System.out.println("hi");
i++; }
while(i<a);
}
}
84
for
for(initialization;condition;iteration)
{
//loop body
}
85
for
1
for
2
( < expr 1> ;< expr 2 > ; < expr 3 ) >
3
6
True
4
< Statement
>
False
86
for
Evaluate
Control-variable Expression
expression
Adjustment
expression
Continue
condition?
false
true
Statement(s)
(loop-body)
Next
Statement
87
for
i = 0;
i=++
i < 100 ?
System.out.println
(“Welcome to
Java!”);
Next
statement
88
for:
program 1
class for1
{
public static void main(String args[])
int a =Integer.parseInt(args[0]);
for(int i=0;i<5;i++)
{
System.out.println("hi");
}
}
}
{
89
Declaring Variables in a for Statement
You can declare one or more variables within
the initialization portion of a for statement
A variable so declared will be local to the for
loop, and cannot be used outside of the loop
If you need to use such a variable outside of
a loop, then declare it outside the loop
90
for loop:
variations
Infinite Loop using for statement
for ( ; ; )
<statement>
Nested for statement

Multi dimensional array
for (i=0; i<N; ++i)
for (j=0; j<M; ++j)
matrix[i][j] = 0;
91
Jump Statements
The Java programming language
supports the following jumping
statements:
The break statement
The continue statement
The return statement
92
The break Statement
Continue
condition?
false
true
Statement(s)
break
Statement(s)
Next
Statement
93
Branch Statement - break Statement
Label break statement


Can be used instead of goto statement
Form
of usage
labelName :
Rep. St. 1 {
Rep. St. 2 {
// . . .
break;
// . . .
break labelName;
}
// . . .
}
94
Branch Statement - break Statement
To move control to the out of the block
From of break statement
break
int i = 1;[label] ;
while (true) {
if (i == 3)
break;
System.out.println("This is a " + i + " iteration");
++i;
}
95
The continue Statement
Continue
condition?
false
true
Statement(s)
continue
Statement(s)
Next
Statement
96
Branch Statement – continue Statement
To move control to the start of next repetition
Form of continue statement:
continue [Label] ;
When used in for statement
for (i=0; i<=5; ++i) {
if (i % 2 == 0)
continue;
System.out.println("This is a " + i + " iteration");
}
97
Branch Statement – continue Statement
When used in while statement
i = 0;
while (i <= 5) {
++i;
if (i % 2) == 0)
continue;
System.out.println("This is a odd iteration - " + i);
}
98
Branch Statement – continue Statement
Label continue statement
labelName:
Rep. St. 1 {
Rep. St. 2 {
// ...
continue;
// ...
continue labelName;
}
}
99
4. Introducing Classes
100
The General Form of a Class
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) { // body of
method }
type methodname2(parameter-list) {// body of method
}
// ...
type methodnameN(parameter-list) {// body of method
}
}
101
A Class Is a Type
A class is a special kind of programmerdefined type, and variables can be declared
of a class type
A value of a class type is called an object or
an instance of the class
A class determines the types of data that an
object can contain, as well as the actions it
can perform
102
Primitive Type Values vs. Class Type Values
A primitive type value is a single piece
of data
A class type value or object can have
multiple pieces of data, as well as
actions called methods
103
The Contents of a Class Definition
A class definition specifies the data items and
methods that all of its objects will have
These data items and methods are
sometimes called members of the object
Data items are called fields or instance
variables
Instance variable declarations and method
definitions can be placed in any order within
the class definition
104
The new Operator
An object of a class is named or declared by a
variable of the class type:
ClassName classVar;
The new operator must then be used to create
the object and associate it with its variable
name:
classVar = new ClassName();
These can be combined as follows:
ClassName classVar = new ClassName();
105
Declaring Objects
Obtaining objects of a class is a two-step
process.
First, you must declare a variable of the class
type. This variable does not define an object.
Instead, it is simply a variable that can refer
to an object.
Second,you must acquire an actual, physical
copy of the object and assign it to that
variable.
106
Declaring Objects
It is done using the new operator. The new
operator dynamically allocates (that is,
allocates at run time) memory for an object
and returns a reference to it.
This reference is, more or less, the address in
memory of the object allocated by new.
This reference is then stored in the variable.
107
Declaring Objects
Box mybox = new Box();
This statement combines the two steps just
described.
It can be rewritten as:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
108
Assigning Object Reference
Variables
Box b1 = new Box();
Box b2 = b1;
109
Introducing Methods
This is the general form of a method:
type name(parameter-list)
{
// body of method
}
110
Instance Variables and Methods
Instance variables can be defined as in the
following two examples
 Note the public modifier:
public String instanceVar1;
public int instanceVar2;
In order to refer to a particular instance
variable, preface it with its object name as
follows:
objectName.instanceVar1
objectName.instanceVar2
111
Instance Variables and Methods
Method definitions are divided into two parts: a heading
and a method body:
public void myMethod()
Heading
{
code to perform some action
Body
and/or compute a value
}
Methods are invoked using the name of the calling
object and the method name as follows:
classVar.myMethod();
Invoking a method is equivalent to executing the
method body
112
File Names and Locations
Reminder: a Java file must be given
the same name as the class it contains
with an added .java at the end

For example, a class named MyClass
must be in a file named MyClass.java
113
Returning a Value
The type of data returned by a method must
be compatible with the return type specified
by the method.
For example, if the return type of some
method is boolean, you could not return an
integer.
The variable receiving the value returned by a
method must also be compatible with the
return type specified for the method.
114
Adding a Method That Takes Parameters
Parameters allow a method to be
generalized.
That is, a parameterized method can
operate on a variety of data.
115
Methods That Return a Boolean Value
An invocation of a method that returns
a value of type boolean returns either
true or false
Therefore, it is common practice to use
an invocation of such a method to
control statements and loops where a
Boolean expression is expected

if-else statements, while loops, etc.
116
Methods with parameters
An empty set of parentheses in the
method heading indicates that methods
have no parameters.
Some methods need to receive
additional data via a list of parameters
in order to perform their work

These parameters are also called formal
parameters
117
Parameters of a Primitive Type
When a method is invoked, the appropriate
values must be passed to the method in the
form of arguments
 Arguments are also called actual parameters
The number and order of the arguments must
exactly match that of the parameter list
The type of each argument must be compatible
with the type of the corresponding parameter
int a=1,b=2,c=3;
double result = myMethod(a,b,c);
118
Parameters of a Primitive Type
In the preceding example, the value of each
argument (not the variable name) is plugged
into the corresponding method parameter
 This method of plugging in arguments for
formal parameters is known as the call-by-
value mechanism
119
Parameters of a Primitive Type
If argument and parameter types do not
match exactly, Java will attempt to make an
automatic type conversion
A primitive argument can be automatically
type cast from any of the following types,
to any of the types that appear to its right:
byteshortintlongfloatdouble
char
120
Parameters of a Primitive Type
A parameters is often thought of as a
blank or placeholder that is filled in by
the value of its corresponding argument
However, a parameter is more than
that: it is actually a local variable when
a method is invoked, the value of its
argument is computed, and the
corresponding parameter (i.e., local
variable) is initialized to this value
Even if the value of a formal parameter
is changed within a method (i.e., it is
used as a local variable) the value of the
argument cannot be changed
121
Pitfall: Use of the Terms
"Parameter" and "Argument"
Do not be surprised to find that people
often use the terms parameter and
argument interchangeably
When you see these terms, you may
have to determine their exact meaning
from context
122
main is a void Method
A program in Java is just a class that
has a main method
When you give a command to run a
Java program, the run-time system
invokes the method main
Note that main is a void method, as
indicated by its heading:
public static void main(String[] args)
123
Local Variables
A variable declared within a method definition
is called a local variable
 All variables declared in the main
method are local variables
 All method parameters are local
variables
If two methods each have a local variable of
the same name, they are still two entirely
different variables
124
Global Variables
Some programming languages include
another kind of variable called a global
variable
The Java language does not have
global variables
125
Final Variables
Declaring a variable with the final
keyword makes it impossible to
reinitialize that variable once it has
been initialized with an explicit value
126
Blocks
A block is another name for a compound
statement, that is, a set of Java statements
enclosed in braces,{}
A variable declared within a block is local to
that block, and cannot be used outside the
block
Once a variable has been declared within a
block, its name cannot be used for anything
else within the same method definition
127
The this Parameter
All instance variables are understood to
have <the calling object>. in
front of them
If an explicit name for the calling object
is needed, the keyword this can be
used

myInstanceVariable always means
and is always interchangeable with
this.myInstanceVariable
128
The this Parameter
this must be used if a parameter or other
local variable with the same name is used in
the method

Otherwise, all instances of the variable name will
be interpreted as local
int someVariable = this.someVariable
local
instance
129
The this Parameter
The this parameter is a kind of hidden
parameter
Even though it does not appear on the
parameter list of a method, it is still a
parameter
When a method is invoked, the calling
object is automatically plugged in for
this
130
Information Hiding and Encapsulation
Information hiding is the practice of
separating how to use a class from the details
of its implementation
 Abstraction is another term used to
express the concept of discarding details in
order to avoid information overload
131
Information Hiding and Encapsulation
Encapsulation means that the data and
methods of a class are combined into a
single unit (i.e., a class object), which
hides the implementation details
In Java, hiding details is done by
marking them private
132
Access Modifiers
Whereas a class can use just two of the
four access control levels (default or
public), members can use all four:
public
protected
default
private
133
Public Members
When a method or variable member is
declared public, it means all other
classes,regardless of the package they belong
to, can access the member (assuming the
class itself is visible).
134
Private Members
Members marked private can't be accessed
by code in any class other than the class in
which the private member was declared.
A private member is invisible to any code
outside the member's own class.
135
Protected and Default Members
The protected and default access control
levels are almost identical, but with onecritical
difference.
A default member may be accessed only if
the class accessing the member belongs to
the same package, whereas a protected
member can be accessed (through
inheritance) by a subclass even if the
subclass is in a different package.
136
public and private Modifiers
It is considered good programming
practice to make all instance variables
private
Most methods are public, and thus
provide controlled access to the object
137
Final Methods
The final keyword prevents a method
from being overridden in a subclass.
138
Final Arguments
Method arguments are the variable
declarations that appear in between the
parentheses in a method declaration.
A final argument must keep the same value
that the parameter had when it was passed
into the method.
139
Abstract Methods
An abstract method is a method that's been
declared (as abstract) but not implemented.
An abstract method declaration doesn't even
have curly braces for where the
implementation code goes, but instead
closes with a semicolon. In other words, it
has no method body.
140
Abstract Methods
It is illegal to have even a single
abstract method in a class that is not
explicitly declared abstract!
141
Ordinary methods vs abstract
methods
The method is not marked abstract.
The method declaration includes curly
braces, as opposed to ending in a
semicolon. In other words, the method
has a method body.
The method provides actual
implementation code.
142
More on abstract methods
The first concrete subclass of an abstract
class must implement all abstract methods of
the superclass.
A method can never, ever, ever be marked as
both abstract and final, or both abstract and
private.
The abstract modifier can never be combined
with the static modifier.
143
Methods with Variable Argument
Lists (var-args)
Java allows you to create methods that
can take a variable number of
arguments.
144
The declaration rules for var-args:
1. Var-arg type: When you declare a vararg parameter, you must specify the
type of the argument(s) this
parameter of your method can
receive.
145
The declaration rules for var-args:
2. Basic syntax :To declare a method using a
var-arg parameter, you follow the
type with an ellipsis (...), a space, and then
the name of the array that will hold the
parameters received.
146
The declaration rules for var-args:
3. Other parameters :It's legal to have
other parameters in a method that
uses a var-arg.
4. Var-args limits :The var-arg must be
the last parameter in the method's
signature, and you can have only one
var-arg in a method.
147
var-args: Examples
Legal:
void doStuff(int... x) { }
// expects from 0 to many ints //
as parameters
void doStuff2(char c, int... x) {
} // expects first a char,// then
0 to many ints
void doStuff3(Animal... animal) { }
// 0 to many Animals
148
var-args: Examples
Illegal:
void doStuff4(int x...) { }
// bad syntax
void doStuff5(int... x,
char... y) { } // too many
var-args
void doStuff6(String... s,
byte b) { } // var-arg must
be last
149
Overloading
Overloading is when two or more methods in
the same class have the same method name
To be valid, any two definitions of the method
name must have different signatures
150
Overloading
A signature consists of the name of a method
together with its parameter list
Differing signatures must have different
numbers and/or types of parameters
151
Overloading and Automatic Type
Conversion
If Java cannot find a method signature that
exactly matches a method invocation, it will
try to use automatic type conversion
The interaction of overloading and automatic
type conversion can have unintended results
152
Overloading and Automatic Type
Conversion
In some cases of overloading, because of
automatic type conversion, a single method
invocation can be resolved in multiple ways
 Ambiguous method invocations will
produce an error in Java
153
Pitfall: You Can Not Overload Based
on the Type Returned
The signature of a method only includes the
method name and its parameter types
 The signature does not include the type
returned
Java does not permit methods with the same
name and different return types in the same
class
154
You Can Not Overload Operators in
Java
Although many programming languages, such
as C++, allow you to overload operators (+, , etc.), Java does not permit this
 You may only use a method name and
ordinary method syntax to carry out the
operations you desire
155
Constructors
Java allows objects to initialize themselves
when they are created. This automatic
initialization is performed through the use of
a constructor, Because the requirement for
initialization is so common.
156
Constructors
constructor initializes an object immediately
upon creation.
It has the same name as the class in which it
resides and is syntactically similar to a
method.
Once defined,the constructor is automatically
called immediately after the object is created,
before the new operator completes.
157
You Can Invoke Another Method in a
Constructor
The first action taken by a constructor
is to create an object with instance
variables
Therefore, it is legal to invoke another
method within the definition of a
constructor, since it has the newly
created object as its calling object
It is even possible for one constructor to
invoke another
158
A Constructor Has a this Parameter
Like any ordinary method, every constructor
has a this parameter
The this parameter can be used explicitly, but
is more often understood to be there than
written down
The first action taken by a constructor is to
automatically create an object with instance
variables
Then within the definition of a constructor, the
this parameter refers to the object created by
the constructor
159
Constructors
They have no return type, not even void.
This is because the implicit return type of a
class’ constructor is the class type itself.
It is the constructor’s job to initialize the
internal state of an object so that the code
creating an instance will have a fully
initialized, usable object immediately
160
Include a No-Argument Constructor
If you do not include any constructors in
your class, Java will automatically
create a default or no-argument
constructor that takes no arguments,
performs no initializations, but allows
the object to be created.
161
Include a No-Argument Constructor
If you include even one constructor in
your class, Java will not provide this
default constructor
If you include any constructors in your
class, be sure to provide your own noargument constructor as well
162
Overloading Constructors
Constructors can also be overloaded
just like methods
163
Garbage Collection
To handle deallocation automatically.
When no references to to an object
exist,that object is assumed to be no
longer needed and the memory
occupied by the object can be claimed.
164
The finalize() Method
Sometimes an object will need to perform
some action when it is destroyed.
The mechanism used o handle such situation is
called finalization.
To include a finalizer to a class ,we have to
define finalize() method.
The Java run time system calls that method
whenever it is about to recycle an object of
that class.
165
finalize()
protected void finalize()
{
//finalization code here
}
Protected:it is a specifier that prevents access
to finalize() by code defined outside its class.
166
Using Objects as Parameters
One of the most common uses of object
parameters involves constructors.
167
Call-by-value
In general, there are two ways that a
computer language can pass an argument to
a subroutine.
The first way is call-by-value.
This method copies the value of an argument
into the formal parameter of the subroutine.
Therefore, changes made to the parameter
of the subroutine have no effect on the
argument.
168
call-by-reference
The second way :An argument can be
passed is call-by-reference.
In this method, a reference to an argument
(not the value of the argument) is passed to
the parameter.
Inside the subroutine, this reference is used
to access the actual argument specified in the
call. This means that changes made to the
parameter will affect the argument used to call
the subroutine.
169
Remember...
When a simple type is passed to a
method, it is done by use of call-byvalue.
Objects are passed by use of call-byreference.
170
Returning Objects
A method can return any type of data,
including class types that you create.
171
Recursion
Java supports recursion.
Recursion is the process of defining
something in terms of itself.
As it relates to Java programming,
recursion is the attribute that allows a
method to call itself.
A method that calls itself is said to be
recursive.
172
Default Variable Initializations
Instance variables are automatically initialized
in Java
 boolean types are initialized to false
 Other primitives are initialized to the zero
of their type
 Class types are initialized to null
However, it is a better practice to explicitly
initialize instance variables in a constructor
Note: Local variables are not automatically
initialized
173
Understanding static
It is possible to create a member that can be
used by itself, without reference to a specific
instance.
To create such a member, precede its
declaration with the keyword static.
When a member is declared static, it can be
accessed before any objects of its class are
created, and without reference to any object.
174
static ....
main( ) is declared as static
because it must be called before any
objects exist.
Instance variables declared as static
are, essentially, global variables.
175
static ....
Methods declared as static have
several restrictions.
They can only call other static
methods.
They must only access static data.
They cannot refer to this or super in
any way.
176
static ....
It is illegal to refer to any instance variables
inside of a static method.
Outside of the class in which they are
defined, static methods and variables can be
used independently of any object.
To do so, you need only specify the name of
their class followed by the dot operator.
177
Introducing final
A variable can be declared as final.
Doing so prevents its contents from
being modified.
This means that you must initialize a
final variable when it is declared.
Eg:final int FILE_NEW = 1;
178
Introducing Nested and Inner
Classes
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 has access to the
members, including private members, of
the class in which it is nested.
179
4. Inheritance
180
Inheritance
Using inheritance, you can create a
general class that defines traits
common to a set of related items.
This class can then be inherited by
other, more specific classes, each
adding those things that are unique to
it.
181
Inheritance
In the terminology of Java, a class that is
inherited is called a superclass. The class that
does the inheriting is called a subclass.
Therefore, a subclass is a specialized version
of a superclass.
It inherits all of the instance variables and
methods defined by the superclass and adds
its own, unique elements.
182
Inheritance Basics
To inherit a class, you simply incorporate the
definition of one class into another by using the
extends keyword.
The general form of a class declaration that
inherits a superclass is shown here:
class subclass-name extends superclass-name
{
// body of class
}
183
Member Access and Inheritance
Although a subclass includes all of the
members of its superclass, it cannot
access those members of the
superclass that have been declared as
private.
184
A Superclass Variable Can Reference
a Subclass Object
A reference variable of a superclass can
be assigned a reference to any subclass
derived from that superclass.
185
It is important to understand that it is the
type of the reference variable—not the
type of the object that it refers to—that
determines what members can be accessed.
That is, when a reference to a subclass
object is assigned to a superclass reference
variable, you will have access only to those
parts of the object defined by the superclass.
186
Using super
Whenever a subclass needs to refer to
its immediate superclass, it can do so
by use of the keyword super.
super has two general forms. The first
calls the superclass’ constructor.
The second is used to access a member
of the superclass that has been hidden
by a member of a subclass.
187
Using super to Call Superclass
Constructors
A subclass can call a constructor method
defined by its superclass by use of the
following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters
needed by the constructor in the superclass.
super( ) must always be the first statement
executed inside a subclass’ constructor.
188
Super()
// BoxWeight now uses super to initialize its Box
attributes.
class BoxWeight extends Box {
double weight;
// weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d,double m)
{
super(w, h, d); //
call superclass constructor
weight = m;
}
}
189
So....
When a subclass calls super( ), it is calling
the constructor of its immediate superclass.
Thus, super( ) always refers to the superclass
immediately above the calling class. This is
true even in a multileveled hierarchy.
Also, super( ) must always be the first
statement executed inside a subclass
constructor.
190
A Second Use for super
The second form of super acts somewhat like
this, except that it always refers to the
superclass of the subclass in which it is used.
This usage has the following
general form:
super.member
Here, member can be either a method or an
instance variable.
191
Super
...
This second form of super is most
applicable to situations in which
member names of a subclass hide
members by the same name in the
superclass.
super can also be used to call methods
that
are hidden by a subclass.
192
Creating a Multilevel Hierarchy
In a class hierarchy, if a superclass
constructor requires parameters, then
all subclasses must pass those
parameters “up the line.” This is true
whether or not a subclass needs
parameters of its own.
193
When Constructors Are Called
In a class hierarchy, constructors are called in
order of derivation, from superclass to
subclass.
Further, 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
parameter less constructor of each superclass
will be executed.
194
Method Overriding
In a 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.
195
Method Overriding
When an overridden method is called
from within a subclass, it will always
refer to the version of that method
defined by the subclass.
The version of the method defined by
the superclass will be hidden.
196
Method Overriding
Method overriding occurs only when the
names and the type signatures of the
two methods are identical. If they are
not, then the two methods are simply
overloaded.
The superclass version of an overridden
function can be accessed using super.
197
Dynamic method dispatch
Method overriding forms the basis for one of
Java’s most powerful concepts: dynamic
method dispatch.
Dynamic method dispatch is the mechanism
by which a call to an overridden method is
resolved at run time, rather than compile
time.
Dynamic method dispatch is important
because this is how Java implements run-time
polymorphism.
198
Dynamic method dispatch
When an overridden method is called
through a superclass reference, Java
determines which version of that
method to execute based upon the type
of the object being referred to at the
time the call occurs.
Thus, this determination is made at run
time.
199
Dynamic method dispatch
When different types of objects are
referred to, different versions of an
overridden method will be called.
In other words, it is the type of the
object being referred to (not the type of
the reference variable) that determines
which version of an overridden method
will be executed.
200
Dynamic method dispatch
Therefore, if a superclass contains a
method that is overridden by a
subclass, then when different types of
objects are referred to through
a superclass reference variable,
different versions of the method are
executed.
201
Now....
Why Overridden Methods ?
202
Using Abstract Classes
Any class that contains one or more
abstract methods must also be declared
abstract. To declare a class abstract,
you simply use the abstract keyword
in front of the class keyword at the
beginning of the class declaration.
203
Using Abstract Classes
There can be no objects of an abstract class.
That is, an abstract class cannot be directly
instantiated with the new operator.
We cannot declare abstract constructors, or
abstract static methods.
Any subclass of an abstract class must either
implement all of the abstract methods in the
superclass or be itself declared abstract.
204
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.
205
Using final to Prevent Overriding
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.
206
Using final to Prevent Inheritance
To prevent a class from being inherited
precede the class declaration with final.
Declaring a class as final implicitly
declares all of its methods as final, too.
207
5.Packages and Interfaces
208
Packages
Packages are containers for classes that are
used to keep the class namespace
compartmentalized.
Packages are stored in a hierarchical manner
and are explicitly imported into new class
definitions.
209
In general, a Java source file can contain any
(or all) of the following four internal parts:
A single package statement (optional)
Any number of import statements (optional)
A single public class declaration (required)
Any number of classes private to the package
(optional)
210
Defining a Package
To create a package is quite easy: simply
include a package command as the first
statement in a Java source file.
Any classes declared within that file will
belong to the specified package.
The package statement defines a name space
in which classes are stored. If you omit the
package statement, the class names are put
into the default package, which has no name.
211
Package …
This is the general form of the package
statement:
package pkg;
Here, pkg is the name of the package. For
example, the following statement creates a
package called MyPackage.
package MyPackage;
212
Package …
You can create a hierarchy of packages.
The general form of a multileveled
package statement is shown here:
package pkg1[.pkg2[.pkg3]];
213
Steps …
Save the file ,say AccountBalance.java, and
put it in a directory called ,say MyPack.
Next, compile the file. Make sure that the
resulting .class file is also in the MyPack
directory.
Then try executing the AccountBalance class,
using the following command line:
java MyPack.AccountBalance
214
Steps …
Remember, you will need to be in the
directory above MyPack when you execute
this command, or to have your CLASSPATH
environmental variable set appropriately.
As explained, AccountBalance is now part of
the package MyPack.
This means that it cannot be executed by
itself. That is, you cannot use this command
line:java AccountBalance
AccountBalance must be qualified with its
package name.
215
Access Protection
Classes and packages are both means of
encapsulating and containing the namespace
and scope of variables and methods.
Packages act as containers for classes and
other subordinate packages. Classes act as
containers for data and code.
The class is Java’s smallest unit of
abstraction.
216
Access Protection
Java addresses four categories of visibility for
class members:
Subclasses in the same package
Non-subclasses in the same package
Subclasses in different packages
Classes that are neither in the same package
nor subclasses
217
Access Protection
Anything declared public can be accessed from
anywhere.
Anything declared private cannot be seen outside
of its class.
When a member does not have an explicit access
specification, it is visible to subclasses as well as to
other classes in the same package. This is the
default access.
If you want to allow an element to be seen outside
your current package, but only to classes that
subclass your class directly, then declare that
element protected.
218
Importing Packages
In a Java source file, import statements
occur immediately following the package
statement (if it exists) and before any class
definitions.
This is the general form of the import
statement:
import pkg1[.pkg2].(classname|*);
219
All of the standard Java classes included with
Java are stored in a package called java.
The basic language functions are stored in a
package inside of the java package called
java.lang.
220
Interface
An defines a protocol of behavior that can be
implemented by any class anywhere in the
class hierarchy; it also defines a set of
methods but does not implement them.
A class that implements the interface agrees
to implement all the methods defined in the
interface, thereby agreeing to certain
behavior.
221
Definition:
An interface is a named collection of
method definitions, without
implementations.
222
Interface vs Abstract Class
An interface cannot implement any methods,
whereas an abstract class can.
A class can implement many interfaces but
can have only one superclass.
An interface is not part of the class hierarchy.
Unrelated classes can implement the same
interface.
223
Defining an Interface
An Interface has two components: The
interface declaration and the interface body.
The interface declaration defines various
attributes of the interface, such as its name
and whether it extends other interfaces.
The interface body contains the constant and
the method declarations for that interface.
224
The Interface Declaration
225
The Interface Declaration …
Two elements are required in an
interface declaration — the interface
keyword and the name of the
interface.
The public access specifier indicates
that the interface can be used by any
class in any package.
226
The Interface Declaration …
An interface declaration can have one other
component: a list of superinterfaces.
An interface can extend other interfaces, just
as a class can extend or subclass another
class.
But a class can extend only one other class,
an interface can extend any number of
interfaces. The list of superinterfaces is a
comma-separated list of all the interfaces
extended by the new interface.
227
The Interface Body
The interface body contains method
declarations for all the methods included in
the interface.
A method declaration within an interface is
followed by a semicolon (;) because an
interface does not provide implementations
for the methods declared within it.
All methods declared in an interface are
implicitly public and abstract.
228
The Interface Body
An interface can contain constant
declarations in addition to method
declarations.
All constant values defined in an
interface are implicitly public, static, and
final.
229
The Interface Body
Member declarations in an interface prohibit
the use of some declaration .
You cannot use transient, volatile, or
synchronized in a member declaration in an
interface.
Also, you cannot use the private and
protected specifiers when declaring members
of an interface.
230
Declaring Volatile Variables
If your class contains a member variable that
is modified asynchronously by concurrently
running threads, you can use Java's volatile
keyword to notify the Java runtime system of
this.
class VolatileExample {
volatile int counter;
...
}
231
Declaring Transient Variables
By default, member variables are part of the
persistent state of the object.
Member variables that are part of the
persistent state of an object must be saved
when the object is archived.
You use the transient keyword to indicate to
the Java virtual machine that the indicated
variable is not part of the persistent state of
the object.
232
Declaring Transient Variables
Like other variable modifiers in the Java
system, you use transient in a class or
instance variable declaration like this:
class TransientExample{
transient int hobo;
...
}
233
Implementing an Interface
To declare a class that implements an
interface, include an implements clause in
the class declaration.
Your class can implement more than one
interface (the Java platform supports multiple
inheritance for interfaces), so the implements
keyword is followed by a comma-separated
list of the interfaces implemented by the
class.
234
Implementing an Interface
By Convention: The implements clause
follows the extends clause, if it exists.
When a class implements an interface,
it is essentially signing a contract.
235
Implementing an Interface
Either the class must implement all the
methods declared in the interface and
its superinterfaces, or the class must be
declared abstract.
The method signature — the name and
the number and type of arguments — in
the class must match the method
signature as it appears in the interface.
236
Interfaces
Once it is defined, any number of
classes can implement an interface.
Also, one class can implement any
number of interfaces.
To implement an interface, a class must
create the complete set of methods
defined by the interface.
237
Using an Interface as a Type
When you define a new interface, you
are defining a new reference data type.
You can use interface names anywhere
you can use any other data type name.
238
Interfaces
...
When you implement an interface method, it
must be declared as public.
239
Interfaces Can Be Extended
One interface can inherit another by use of
the keyword extends. The syntax is the
same as for inheriting classes.
When a class implements an interface that
inherits another interface, it must provide
implementations for all methods defined
within the interface inheritance chain.
240
6. Exception-Handling
241
Exception-Handling
An exception is an abnormal condition
that arises in a code sequence at run
time. In other words,an exception is a
run-time error.
242
Exception-Handling Fundamentals
A Java exception is an object that describes
an exceptional (that is, error) condition that
has occurred in a piece of code.
When an exceptional condition arises, an
object representing that exception is created
and thrown in the method that caused the
error.
That method may choose to handle the
exception itself, or pass it on.
243
Exception-Handling Fundamentals
Either way, at some point, the exception
is caught and processed. Exceptions
can be generated by the Java run-time
system, or they can be manually
generated by your code.
244
Exception-Handling Fundamentals
Manually generated exceptions are
typically used to report some error
condition to the caller of a method.
245
Exception Handling
Java exception handling is managed via
five keywords: try, catch, throw,
throws, and finally.
246
Exception Handling
Briefly, here is how they work….
Program statements that you want to
monitor for exceptions are contained within a
try block.
If an exception occurs within the try block, it
is thrown.
Your code can catch this exception (using
catch) and handle it in some rational manner.
247
Exception Handling
System-generated exceptions are
automatically thrown by the Java runtime system.
248
To manually throw an exception, use the
keyword throw.
Any exception that is thrown out of a method
must be specified as such by a throws
clause.
Any code that absolutely must be executed
before a method returns is put in a finally
block.
249
general form of an exceptionhandling block:
try { // block of code to monitor for errors }
catch (ExceptionType1 exOb)
{ // exception handler for ExceptionType1 }
catch (ExceptionType2 exOb)
{ // exception handler for ExceptionType2 }
// ...
finally {// block of code to be executed
before try block ends }
250
Exception Types
There are two kinds of exceptions: runtime
and non runtime.
Runtime exceptions occur within the Java
runtime system:
Arithmetic exceptions, such as dividing by
zero; pointer exceptions, such as trying to
access an object’s members through a null
reference; and indexing exceptions, such as
trying to access an array element with an
index that is too large or too small.
251
Exception Types
…
A method does not have to catch or
specify runtime exceptions, although it
may.
252
Exception Types
…
Nonruntime exceptions are exceptions that
occur in code outside of the Java runtime
system. For example, exceptions that occur
during I/O are nonruntime exceptions.
The compiler ensures that nonruntime
exceptions are caught or specified; thus, they
are also called checked exceptions.
253
Uncaught Exceptions:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
254
Uncaught Exceptions:
When we don’t supply any exception
handlers of our own, the exception is
caught by the default handler provided
by the Java run-time system.
Any exception that is not caught by the
program will ultimately be processed by
the default handler.
255
Uncaught Exceptions:
The default handler displays a string
describing the exception, prints a stack trace
from the point at which the exception
occurred, and terminates the program.
Here is the output generated when this
example is executed.
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
256
Using try and catch
Although the default exception handler
provided by the Java run-time system is
useful for debugging, you will usually want to
handle an exception yourself.
Doing so provides two benefits. First, it
allows you to fix the error. Second, it prevents
the program from automatically terminating.
257
Using try and catch
To guard against and handle a run-time error,
simply enclose the code that you
want to monitor inside a try block.
Immediately following the try block, include a
catch clause that specifies the exception type
that you wish to catch.
258
try catch
...
The goal of most well-constructed
catch clauses should be to resolve the
exceptional condition and then
continue on as if the error had never
happened.
259
Multiple catch Clauses
In some cases, more than one
exception could be raised by a single
piece of code. To handle this type of
situation, you can specify two or more
catch clauses, each catching a different
type of exception.
260
Multiple catch Clauses
When an exception is thrown, each
catch statement is inspected in order,
and the first one whose type matches
that of the exception is executed.
After one catch statement executes,
the others are bypassed, and execution
continues after the try/catch block.
261
Multiple catch
...
When you use multiple catch statements, it is
important to remember that exception
subclasses must come before any of their
superclasses. This is because a catch
statement that uses a superclass will catch
exceptions of that type plus any of its
subclasses.
Thus, a subclass would never be reached if it
came after its superclass.Further, in Java,
unreachable code is an error.
262
Multiple catch
...
ArithmeticException is a subclass of
Exception, the first catch statement will
handle all Exception-based errors,
including ArithmeticException.
This means that the second catch
statement will never execute.
To fix the problem, reverse the order of
the catch statements.
263
Nested try Statements
The try statement can be nested. That
is, a try statement can be inside the
block of another try.
264
throw
It is possible for your program to throw an
exception explicitly, using the throw
statement.
The general form of throw is shown here:
throw ThrowableInstance;
Here, ThrowableInstance must be an object
of type Throwable or a subclass of
Throwable.
265
throw
...
Simple types, such as int or char, as well as
non-Throwable classes, such
as String and Object, cannot be used as
exceptions.
There are two ways you can obtain
a Throwable object: using a parameter into a
catch clause, or creating one with the new
operator.
266
throw
...
The flow of execution stops immediately after
the throw statement; any subsequent
statements are not executed.
The nearest enclosing try block is inspected
to see if it has a catch statement that
matches the type of the exception.
If it does find a match, control is transferred
to that statement.
267
throw
...
If not, then the next enclosing try
statement is inspected, and so on. If
no matching catch is found, then the
default exception handler halts the
program and prints the stack trace.
268
throws
If 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.
You do this by including a throws clause in
the method’s declaration.
A throws clause lists the types of
exceptions that a method might throw.
269
throws
This is necessary for all exceptions, except
those of type Error or RuntimeException, or
any of their subclasses.
All other exceptions that a method can throw
must be declared in the throws clause. If
they are not, a compile-time error
will result.
270
throws
General form
type method-name(parameter-list)
throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated
list of the exceptions that a method
can throw.
271
Exception Hierarchy
272
Exception Hierarchy
Exceptions1.doc
273
7. Multithreading
274
Multithreading Introduction
A multithreaded program contains two
or more parts that can run concurrently.
Each part of such a program is called a
thread,and each thread defines a
separate path of execution.
Thus, multithreading is a specialized
form of multitasking.
275
Thread
Introduction:
Every program you execute has a
beginning, an execution sequence, and
an end. At any given time during the
runtime of the program, there is a
single point of execution.
However, a thread itself is not a
program; it cannot run on its own.
Rather a thread runs within a program.
276
Thread
…
277
Definition:
A thread is a single sequential flow of
control within a program.
278
Thread States
A thread can be only in one of five states
New: This is the state the thread is in after
the Thread instance has been created, but
the start() method has not been invoked on
the thread.
It is a live Thread object, but not yet a thread
of execution.
At this point, the thread is considered not
alive.
279
Thread States
Runnable :This is the state a thread is in
when it's eligible to run, but the scheduler
has not selected it to be the running thread.
A thread first enters the runnable state when
the start() method is invoked, but a thread
can also return to the runnable state after
either running or coming back from a
blocked, waiting, or sleeping state.
When the thread is in the runnable state,it is
considered alive.
280
Thread States
Running: Where the action is. This is the
state a thread is in when the thread
scheduler selects it (from the runnable pool)
to be the currently executing process.
A thread can transition out of a running state
for several reasons, including because "the
thread scheduler felt like it."
There are several ways to get to the runnable
state, but only one way to get to the running
state: the scheduler chooses a thread from
the runnable pool.
281
Thread States
Waiting/blocked/sleeping This is the
state a thread is in when it's eligible to run.
The thread is still alive, but is currently not
eligible to run. In other words, it is not
runnable, but it might return to a runnable
state later if a particular event occurs.
Note also that a thread in a blocked state is
still considered to be alive.
282
Thread States
Dead: A thread is considered dead when its
run() method completes. It may still be a
viable Thread object, but it is no longer a
separate thread of execution.
Once a thread is dead, it can never be
brought back to life!
If you invoke start() on a dead Thread
instance, you'll get a runtime (not compiler)
exception...
283
Thread States
284
The Thread Class and the Runnable
Interface.
Java’s multithreading system is built upon the
Thread class, its methods, and its companion
interface, Runnable.
Thread encapsulates a thread of execution.
Since you can’t directly refer to the ethereal
state of a running thread, you will deal with it
through its proxy, the Thread instance that
spawned it.
To create a new thread, your program will
either extend Thread or implement the
Runnable interface.
285
The Main Thread
When a Java program starts up, one thread
begins running immediately.
This is usually called the main thread of your
program, because it is the one that is
executed when your program begins. The
main thread is important for two reasons:


It is the thread from which other “child” threads
will be spawned.
Often it must be the last thread to finish execution
because it performs various shutdown actions.
286
Creating a Thread
In the most general sense, you create a
thread by instantiating an object of type
Thread.
Java defines two ways in which this can be
accomplished:


You can implement the Runnable interface.
You can extend the Thread class, itself.
287
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.
You can construct a thread on any object that
implements Runnable.
To implement Runnable, a class need only
implement a single method called run( ),
which is declared as : public void run( )
288
Implementing Runnable
Inside run( ), you will define the code that
constitutes the new thread.
It is important to understand that run( ) can
call other methods, use other classes, and
declare variables, just like the main thread
can.
The only difference is that run( ) establishes
the entry point for another, concurrent thread
of execution within your program.
This thread will end when run( ) returns.
289
Implementing Runnable
After you create a class that implements
Runnable, you will instantiate an object of
type Thread from within that class. Thread
defines several constructors.
290
Thread Constructors
Thread():
Thread(Runnable target):
Thread(Runnable target, String name)
Thread(String name):
Thread(ThreadGroup group, Runnable target)
Thread(ThreadGroup group, Runnable target,
String name)
Thread(ThreadGroup group, String name)
291
After the new thread is created, it will not
start running until you call its start( )
method, which is declared within Thread.
In essence, start( ) executes a call to run( ).
The start( ) method is shown here:
void start( )
292
Inside NewThread’s constructor, a new
Thread object is created by the
following statement:
t = new Thread(this, "Demo Thread");
293
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.
294
Extending Thread …
The call to super( ) inside NewThread,
invokes the following form of
the Thread constructor:
public Thread(String threadName);
295
Choosing an Approach
Which one to create a new thread and
why ……….?
296
Creating Multiple Threads
Your program can spawn as many
threads as it needs other than the two
threads: the main thread and one child
thread.
297
Using isAlive( ) and join( )
Two ways exist to determine whether a
thread has finished. First, you can call
isAlive( ) on the thread. This method is
defined by Thread,.
general form is: final boolean isAlive( )
The isAlive( ) method returns true if the
thread upon which it is called is still running.
It returns false otherwise.
298
join( )
Second , you can call join( ) on the thread,
final void join( ) throws InterruptedException
This method waits until the thread on which it
is called terminates.
Its name comes from the concept of the
calling thread waiting until the specified
thread joins it.
299
join( )
Additional forms of join( ) allow you to
specify a maximum amount of time that
you want to wait for the specified
thread to terminate.
300
Thread Priorities
Currently, these Thread priorities are used by
the thread scheduler to decide when each
thread should be allowed to run.
In theory, higher-priority threads get more
CPU time than lower-priority threads.
In practice, the amount of CPU time that a
thread gets often depends on several factors
besides its priority.
A higher-priority thread can also preempt a
lower-priority one.
301
Thread Priorities
To set a thread’s priority, use the
setPriority( ) method, which is a member of
Thread. This is its general form:
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.
302
Thread Priorities
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.
You can obtain the current priority setting by
calling the getPriority( ) method of Thread,
syntax is :
final int getPriority( )
303
Moving out of Running state
A call to sleep(): Guaranteed to cause
the current thread to stop executing for
at least the specified sleep duration (it
might be interrupted before its specified
time).
304
Moving out of Running state
A call to yield() :Not guaranteed to do
much of anything, although typically it
will cause the currently running thread
to move back to runnable so that a
thread of the same priority can have a
chance.
305
Moving out of Running state
A call to join() :Guaranteed to cause
the current thread to stop executing
until the thread it joins with
completes, or if the thread it's trying to
join with is not alive, however, the
current thread won't need to back out.
306
Other Situations
The thread's run() method completes.
A call to wait() on an object
A thread can't acquire the lock on the object
whose method code it's attempting to run.
The thread scheduler can decide to move the
current thread from running to runnable in
order to give another thread a chance to run.
No reason is needed—the thread scheduler
can trade threads in and out whenever it
likes.
307
Synchronization
How does synchronization work?
With locks. Every object in Java has a built-in
lock that only comes into play when the
object has synchronized method code.
When we enter a synchronized non-static
method, we automatically acquire the lock
associated with the current instance of the
class whose code we're executing.
308
Synchronization
Only methods (or blocks) can be
synchronized, not variables or classes.
Each object has just one lock.
Not all methods in a class need to be
synchronized.
A class can have both synchronized and nonsynchronized methods.
309
Synchronization
When two or more threads need access to a
shared resource, they need some way to
ensure that the resource will be used by only
one thread at a time.
The process by which this is achieved is
called synchronization.
You can synchronize your code in either of
two ways. Both involve the use of the
synchronized keyword.
310
The synchronized Statement
- General formsynchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being
synchronized.
A synchronized block ensures that a call to a
method that is a member of object occurs
only after the current thread has successfully
entered object’s monitor.
311
Using Synchronized Methods
Eg:Synch .java
312
Thread Deadlock
Perhaps the scariest thing that can
happen to a Java program is deadlock.
Deadlock occurs when two threads are
blocked, with each waiting for the
other's lock.
Neither can run until the other gives up
its lock, so they'll sit there forever.
313
Interthread Communication
Multithreading replaces event loop
programming by dividing your tasks into
discrete and logical units. Threads also
provide a secondary benefit:
They do away with polling.
Polling is usually implemented by a loop that
is used to check some condition repeatedly.
Once the condition is true, appropriate action
is taken. This wastes CPU time
314
Interthread Communication
To avoid polling, Java includes an elegant
interprocess communication mechanism
via the wait( ), notify( ), and notifyAll( )
methods.
These methods are implemented as final
methods in Object, so all classes have them.
All three methods can be called only from
within a synchronized context..
315
Interthread Communication
wait( ):Tells the calling thread to give up the
monitor and go to sleep until some other
thread enters the same monitor and calls
notify( ).
notify( ) wakes up the first thread that called
wait( ) on the same object.
notifyAll( ) wakes up all the threads that
called wait( ) on the same object.
The highest priority thread will run first.
316
Interthread Communication
These methods are declared within
Object, as shown here:
final void wait( ) throws
InterruptedException
final void notify( )
final void notifyAll( )
317
wait() vs notify()
When the wait() method is invoked on an
object, the thread executing that code gives
up its lock on the object immediately.
However, when notify() is called, that doesn’t
mean the thread gives up its lock at that
moment.
If the thread is still completing synchronized
code, the lock is not released until the thread
moves out of synchronized code. So just
because notify() is called doesn’t mean the
lock becomes available at that moment.
318
8. java.lang
319
java.lang
introduction
It is Java’s most widely used package.
java.lang is automatically imported into all
programs. It contains classes and interfaces
that are fundamental to virtually all of Java
programming.
320
java.lang includes the following classes:
Boolean
Long
StackTraceElement
Byte
Math
StrictMath
Character
Number
String
Class
Object
StringBuffer
ClassLoader
Package
System
Compiler
Process
Thread
Double
Runtime
ThreadGroup
Float
RuntimePermission ThreadLocal
InheritableThreadLocal SecurityManager Throwable
Integer
Short
Void
321
interfaces:
java.lang also defines the following
interfaces:
Cloneable
Comparable
Runnable
CharSequence
322
Simple Type Wrappers
These classes encapsulate, or wrap, the
simple types within a class. Thus, they
are commonly referred to as type
wrappers.
323
Number
The abstract class Number defines a
superclass that is implemented by the classes
that wrap the numeric types byte, short, int,
long, float, and double.
Number has abstract methods that return the
value of the object in each of the different
number formats.
That is, doubleValue( ) returns the value as a
double, floatValue( ) returns the value
as a float, and so on.
324
byte byteValue( )
double doubleValue( )
float floatValue( )
int intValue( )
long longValue( )
short shortValue( )
325
The values returned by these methods
can be rounded.
Number has six concrete subclasses
that hold explicit values of each numeric
type:Double, Float, Byte, Short, Integer,
and Long.
326
Double and Float
Double and Float are wrappers for floating-point
values of type double and float,
respectively.
The constructors for Float are :
Float(double num)
Float(float num)
Float(String str) throws NumberFormatException
327
isInfinite( ) and isNaN( )
Float and Double provide the methods
isInfinite( ) and isNaN( ), which help when
manipulating two special double and float
values.
isInfinite( ) returns true if the value being
tested is infinitely large or small in
magnitude.
isNaN( ) returns true if the value being tested
is not a number
328
Converting Numbers to and from Strings
Java provides an easy way to convert the
string representation of a number into its
internal, binary format.
The Byte, Short, Integer, and Long classes
provide the parseByte( ), parseShort( ),
parseInt( ), and parseLong( ) methods,
respectively.
These methods return the byte, short, int, or
long equivalent of the numeric string with
which they are .called
329
Now …
WAP which sums a list of integers
entered by the user.(use readLine( ) to
read integers and parseInt( ) to convert
the strings to their int equivalents.)
Soln: ParseDemo.java
330
To convert a whole number into a decimal
string, use the versions of toString( )
defined in the Byte, Short, Integer, or Long
classes.
The Integer and Long classes also provide
the methods toBinaryString( ),
toHexString( ), and toOctalString( ),
which convert a value into a binary,
hexadecimal, or octal string, respectively.
331
Character
Character is a simple wrapper around a char.
The constructor for Character is
Character(char ch)
Here, ch specifies the character that will be
wrapped by the Character object being
created.
To obtain the char value contained in a
Character object, call charValue( ),as shown:
char charValue( ) : It returns the character.
332
Character includes several static
methods that categorize characters and
alter their case.
Eg: IsDemo.java
333
Boolean
Boolean is a very thin wrapper around
boolean values, which is useful mostly when
you want to pass a boolean variable by
reference.
It contains the constants TRUE and FALSE,
which define true and false Boolean objects.
334
Boolean
Boolean defines these constructors:
Boolean(boolean boolValue)
Boolean(String boolString)
In the first version, boolValue must be either
true or false. In the second version, if
boolString contains the string “true” (in
uppercase or lowercase), then the new
Boolean object will be true. Otherwise, it will
be false.
335
Void
The Void class has one field, TYPE,
which holds a reference to the Class
object for type void.
You do not create instances of this
class.
336
Process
The abstract Process class encapsulates a
process—that is, an executing program.
It is used primarily as a superclass for the
type of objects created by exec( ) in the
Runtime class.
337
Runtime
The Runtime class encapsulates the run-time
environment.
You cannot instantiate a Runtime object.
However, you can get a reference to the
current Runtime object by calling the static
method Runtime.getRuntime( ).
Once you obtain a reference to the
current Runtime object, you can call several
methods that control the state and behavior
of the Java Virtual Machine.
338
Runtime
Applets and other untrusted code typically
cannot call any of the Runtime methods
without raising a SecurityException.
Two of the most common uses of the
Runtime class: memory management and
executing additional processes.
339
Memory Management
Using freeMemory(),totalMemory() and
gc().
Eg: MemoryDemo.java
340
Executing Other Programs
In safe environments, you can use Java to
execute other heavyweight processes (that is,
programs) on your multitasking operating
system.
Several forms of the exec( ) method allow
you to name the program you want to run as
well as its input parameters.
341
Executing Other Programs
The exec( ) method returns a Process
object, which can then be used to
control how your Java program interacts
with this new running process.
For example use exec( ) to launch
notepad, Windows’ simple text
editor.
ExecDemo.java
342
System
The System class holds a collection of
static methods and variables.
The standard input, output, and error
output of the Java run time are stored
in the in, out, and err variables.
343
Using currentTimeMillis( ) to Time
Program Execution
Use the currentTimeMillis( ) method to
time how long various parts of your
program take to execute.
The currentTimeMillis( ) method returns
the current time in terms of
milliseconds since midnight, January 1,
1970.
Eg: Elapsed.java
344
Using arraycopy( )
The arraycopy( ) method can be used
to copy quickly an array of any type
from one place to another. This is much
faster than the equivalent loop written
out longhand in Java.
Eg:ACDemo.java
345
Method Description
static void arraycopy(Object source, int
sourceStart,Object target,int targetStart, int
size):
Copies an array. The array to be copied is
passed in source,and the index at which point
the copy will begin within source is passed in
sourceStart. The array that will receive the
copy is passed in target, and the index at
which point the copy will begin within target
is passed in targetStart. size is the number of
elements that are copied.
346
Object
Object is a superclass of all other
classes
347
Using clone( ) and the Cloneable
Interface
The clone( ) method generates a
duplicate copy of the object on which it
is called. Only classes that implement
the Cloneable interface can be cloned.
The Cloneable interface defines no
members. It is used to indicate that a
class allows a bitwise copy of an object
(that is, a clone) to be made.
348
Using clone( ) and the Cloneable
Interface
If you try to call clone( ) on a class that
does not implement Cloneable, a
CloneNotSupportedException is thrown.
When a clone is made, the constructor
for the object being cloned is not called.
A clone is simply an exact copy of the
original.
349
Cloning is a potentially dangerous action,
because it can cause unintended side effects.
If an object opens an I/O stream and is then
cloned, two objects will be capable of
operating on the same stream.
Further, if one of these objects closes the
stream, the other object might still attempt to
write to it, causing an error.
.
350
Because cloning can cause problems, clone( )
is declared as protected inside Object .
This means that it must either be called from
within a method defined by the class that
implements Cloneable, or it must be explicitly
overridden by that class so that it is public.
351
Class
Class encapsulates the run-time state of an
object or interface.
Objects of type Class are created
automatically, when classes are loaded.
You cannot explicitly declare a Class object.
Generally, you obtain a Class object by
calling the getClass( ) method defined by
Object.
352
ClassLoader
The abstract class ClassLoader defines how
classes are loaded.
Your application can create subclasses that
extend ClassLoader, implementing its
methods.
Doing so allows you to load classes in some
way other than the way they are normally
loaded by the Java run-time system
353
Math
The Math class contains all the floatingpoint functions that are used for
geometry and trigonometry, as well as
several general-purpose methods.
Math defines two double constants:


E (approximately 2.72)
PI (approximately 3.14).
354
Rounding Functions
The Math class defines several methods that
provide various types of rounding operations
static int abs(int arg) Returns the absolute
value of arg.
static int max(int x, int y) Returns the
maximum of x and y.
static double rint(double arg) Returns the
integer nearest in value to arg.
355
Compiler
The Compiler class supports the
creation of Java environments in which
Java bytecode is compiled into
executable code rather than
interpreted.
It is not for normal programming use.
356
Thread, ThreadGroup, and Runnable
The Runnable interface and the Thread
and ThreadGroup classes support
multithreaded programming.
357
The Runnable Interface
The Runnable interface must be implemented
by any class that will initiate a separate
thread of execution.
Runnable only defines one abstract method,
called run( ), which is the entry point to the
thread. It is defined like this:
abstract void run( )
Threads that you create must implement this
method.
358
ThreadGroup
ThreadGroup creates a group of threads. It
defines these two constructors:
ThreadGroup(String groupName)
ThreadGroup(ThreadGroup parentOb, String
groupName)
For both forms, groupName specifies the
name of the thread group. The first version
creates a new group that has the current
thread as its parent. In the second form, the
parent is specified by parentOb.
359
ThreadLocal and InheritableThreadLocal
ThreadLocal: Used to create thread
local variables.
Each thread will have its own copy of a
thread local variable.
InheritableThreadLocal: Creates thread
local variables that may be inherited.
360
Package
Java 2 added a class called Package that
encapsulates version data associated with a
package.
Package version information is becoming
more important because of the proliferation
of packages and because a Java program
may need to know what version of a package
is available.
361
RuntimePermission
RuntimePermission was added to
java.lang by Java 2. It relates to Java’s
security mechanism
362
Throwable
The Throwable class supports Java’s
exception-handling system, and is the
class from which all exception classes
are derived.
363
SecurityManager
SecurityManager is an abstract class that your
subclasses can implement to create a
security manager.
Generally, you don’t need to implement your
own security manager.
If you do, you need to consult the
documentation that comes with your Java
development system.
364
StackTraceElement
Java 2, version 1.4 adds the
StackTraceElement class. This class describes
a single stack frame, which is an individual
element of a stack trace when an exception
occurs.
Each stack frame represents an execution
point, which includes such things as the
name of the method, the name of the file,
and the source-code line number.
365
StackTraceElement
An array of StackTraceElements is
returned by the getStackTrace( )
method of the Throwable class.
366
The CharSequence Interface
CharSequence defines methods that
grant read-only access to a sequence of
characters.
This interface is implemented by String
and StringBuffer.
367
The Comparable Interface
Objects of classes that implement
Comparable can be ordered.
In other words, classes that implement
Comparable contain objects that can be
compared in some meaningful manner.
368
The Comparable Interface
The signature of the method is shown here:
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.
369
9. java.util
370
java.util package
The java.util package contains one of
Java’s most powerful subsystems:
collections.
371
The collections framework
Designed to meet several goals. First, the
framework had to be high-performance.
The implementations for the fundamental
collections (dynamic arrays, linked lists, trees,
and hash tables) are highly efficient.
You seldom, if ever, need to code one of
these “data engines” manually.
372
The collections framework
Second, the framework had to allow
different types of collections to work in
a similar manner and with a high
degree of interoperability.
373
The collections framework
Third, extending and/or adapting a collection
had to be easy. Toward this end, the entire
collections framework is designed around a
set of standard interfaces.
Several standard implementations (such as
LinkedList, HashSet, and TreeSet) of these
interfaces are provided that you may use asis.
374
The collections framework
Finally, mechanisms were added that
allow the integration of standard arrays
into the collections framework.
375
The collections framework
Another item created by the collections
framework is the Iterator interface.
An iterator gives you a general-purpose,
standardized way of accessing the elements
within a collection, one at a time..
Because each collection implements Iterator,
the elements of any collection class can be
accessed through the methods defined by
Iterator.
376
The Collection Interfaces
Interface
Collection
List
Set
SortedSet
Description
Enables you to work with
groups of objects; it is at the
top of the collections hierarchy
Extends Collection to handle
sequences (lists of objects)
Extends Collection to handle
sets, which must contain
unique elements
Extends Set to handle sorted
sets
377
All the core collection interfaces are
generic. For example, this is the
declaration of the Collection interface.
public interface Collection<E>...
The <E> syntax tells you that the
interface is generic.
378
When you declare a Collection instance
you can and should specify the type of
object contained in the collection.
Specifying the type allows the compiler
to verify (at compile-time) that the type
of object you put into the collection is
correct, thus reducing errors at runtime.
379
The Collection Interface
The Collection interface is the
foundation upon which the collections
framework is built.
It declares the core methods that all
collections will have.
380
The Collection Interface
Several of these methods can throw an
UnsupportedOperationException. This occurs
if a collection cannot be modified.
A ClassCastException is generated when one
object is incompatible with another, such as
when an attempt is made to add an
incompatible object to a collection.
381
The Collection Interface
Objects are added to a collection by calling
add( ).
You can add the entire contents of one
collection to another by calling addAll( ).
You can remove an object using remove( ).
To remove a group of objects, call
removeAll( ).
You can remove all elements except those of
a specified group by calling retainAll( ).
To empty a collection, call clear( ).
382
The Collection Interface
You can determine whether a collection
contains a specific object by calling
contains( ).
To determine whether one collection contains
all the members of another, call
containsAll( ).
You can determine when a collection is
empty by calling isEmpty( ).
383
The Collection Interface
The number of elements currently held
in a collection can be determined by
calling size( ).
Two collections can be compared for
equality by calling equals( ).
384
The List Interface
The List interface extends Collection
and declares the behavior of a
collection that stores a sequence of
elements.
Elements can be inserted or accessed
by their position in the list, using a
zero-based index. A list may contain
duplicate elements.
385
The List Interface
To the versions of add( ) and addAll( )
defined by Collection, List adds the methods
add(int, Object) and addAll(int, Collection).
These methods insert elements at the
specified index.
Also, the semantics of add(Object) and
addAll(Collection) defined by Collection are
changed by List so that they add elements to
the end of the list.
386
The List Interface
To obtain the object stored at a specific
location, call get( ) with the index of the
object.
To assign a value to an element in the
list, call set( ), specifying the index of
the object to be changed.
To find the index of an object, use
indexOf( ) or lastIndexOf( ).
387
The List Interface
In addition to the operations inherited from
Collection, the List interface includes
operations for the following:
Positional access — manipulates elements
based on their numerical position in the list
Search — searches for a specified object in
the list and returns its numerical position
Iteration — extends Iterator semantics to
take advantage of the list's sequential nature
388
The Set Interface
The Set interface defines a set.
It extends Collection and declares the
behavior of a collection that does not allow
duplicate elements.
Therefore, the add( ) method returns
false if an attempt is made to add duplicate
elements to a set.
It does not define any additional methods of
its own.
389
The SortedSet Interface
The SortedSet interface extends Set and declares
the behavior of a set sorted in ascending order.
Several methods throw a NoSuchElementException
when no items are contained in the invoking set.
A ClassCastException is thrown when an object is
incompatible with the elements in a set.
A NullPointerException is thrown if an attempt is
made to use a null object and null is not allowed in
the set.
390
The SortedSet Interface
SortedSet defines several methods that make set
processing more convenient.
To obtain the first object in the set, call first( ).
To get the last element, use last( ).
You can obtain a subset of a sorted set by calling
subSet( ), specifying the first and last object in the
set.
If you need the subset that starts with the first
element in the set, use headSet( ).
If you want the subset that ends the set, use
tailSet( ).
391
Summary of Interfaces
The core collection interfaces are the
foundation of the Java Collections
Framework.
The tree starts with the Collection interface,
which provides for the basic functionality
used by all collections, such as add and
remove methods. Its subinterfaces — Set,
List, and Queue — provide for more
specialized collections.
392
Summary of Interfaces
The Set interface does not allow
duplicate elements. This can be useful
for storing collections such as a deck of
cards or student records.
The Set interface has a subinterface,
SortedSet, that provides for ordering of
elements in the set.
393
Summary of Interfaces
The List interface provides for an
ordered collection, for situations in
which you need precise control over
where each element is inserted. You
can retrieve elements from a List by
their exact position.
394
Summary of Interfaces
The Queue interface enables additional
insertion, extraction, and inspection
operations.
Elements in a Queue are typically
ordered in on a FIFO basis.
395
The Collection Classes
AbstractCollection
Implements most of the
Collection interface.
AbstractList
Extends AbstractCollection
and implements most of
the List interface.
AbstractSequentialList Extends AbstractList for
use by a collection that
uses sequential rather
than random access of its
elements.
396
The Collection Classes
LinkedList
ArrayList
Implements a linked list by
extending
AbstractSequentialList.
Implements a dynamic array
by extending AbstractList.
397
The ArrayList Class
The ArrayList class extends AbstractList
and implements the List interface.
ArrayList supports dynamic arrays that
can grow as needed.
In Java, standard arrays are of a fixed
length. After arrays are created, they
cannot grow or shrink.
Eg: ArrayListDemo .java
398
ArrayList :constructors
1. ArrayList( ):Builds an empty array list.
2. ArrayList(Collection c):Builds an array
list that is initialized with the elements of the
collection c.
3. ArrayList(int capacity):Builds an array list
that has the specified initial capacity.
The capacity is the size of the underlying
array that is used to store the elements. The
capacity grows automatically as elements
are added to an array list.
399
Obtaining an Array from an ArrayList
Done by calling toArray( ).
Several reasons exist why you might want to
convert a collection into an array such as:
To obtain faster processing times for certain
operations. To pass an array to a method that
is not overloaded to accept a collection.
To integrate your newer, collection-based
code with legacy code that does not
understand collections.
[Eg: Next]
400
ArrayListToArray.java
401
The LinkedList Class
The LinkedList class extends
AbstractSequentialList and implements
the List interface.
It provides a linked-list data structure.
It has the two constructors, shown
here:
LinkedList( )
LinkedList(Collection c)
402
The LinkedList Class
The first constructor builds an empty
linked list.
The second constructor builds a linked
list that is initialized with the elements
of the collection c.
403
The LinkedList Class
In addition to the methods that it inherits, the
LinkedList class defines some methods of its
own for manipulating and accessing lists.
To add elements to the start of the list,use
addFirst( );
to add elements to the end, addLast( ).
Their signatures are shown here:
void addFirst(Object obj)
void addLast(Object obj) Here, obj is the item
being added.
404
The LinkedList Class
To obtain the first element, call getFirst( ).
To retrieve the last element, call getLast( ).
As:
Object getFirst( )
Object getLast( )
To remove the first element, removeFirst( );
To remove the last lement,removeLast()
They are shown here:
Object removeFirst( )
Object removeLast( )
405
The HashSet Class
HashSet extends AbstractSet and implements
the Set interface.
It creates a collection that uses a hash table
for storage.
In hashing, the informational content of a key
is used to determine a unique value, called its
hash code.
The hash code is then used as the index at
which the data associated with the key is
stored.
406
The HashSet Class
The transformation of the key into its hash
code is performed automatically—you never
see the hash code itself.
Also, your code can’t directly index the hash
table. The advantage of hashing is that it
allows the execution time of basic operations,
such as add( ),contains( ), remove( ), and
size( ), to remain constant even for large
sets.
407
The HashSet Class
The following constructors are defined:
HashSet( )
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
408
The HashSet Class
The first form constructs a default hash
set.
The second form initializes the hash
set by using the elements of c.
The third form initializes the capacity of
the hash set to capacity.
409
The HashSet Class
The fourth form initializes both the capacity
and the fill ratio (also called load capacity) of
the hash set from its arguments.
The fill ratio must be between 0.0 and
1.0,and it determines how full the hash set
can be before it is resized upward.
Eg: HashSetDemo.java
410
The HashSet Class
HashSet does not define any additional
methods beyond those provided by its
superclasses and interfaces.
Importantly, note that a hash set does not
guarantee the order of its elements,
because the process of hashing doesn’t
usually lend itself to the creation of sorted
sets.
If you need sorted storage, then another
collection, such as TreeSet, is a better choice
411
The LinkedHashSet Class
This class extends HashSet, but adds
no members of its own.
LinkedHashSet maintains a linked list of the
entries in the set, in the order in which they
were inserted.
This allows insertion-order iteration over the
set. That is, when cycling through a
LinkedHashSet using an iterator, the elements
will be returned in the order in which they
were inserted.
412
The LinkedHashSet Class
To see the effect of LinkedHashSet, try
substituting LinkedHashSet For HashSet
in the preceding program. The output
will be[B, A, D, E, C, F]
which is the order in which the
elements were inserted.
413
The TreeSet Class
TreeSet provides an implementation of the
Set interface that uses a tree for storage.
Objects are stored in sorted, ascending order.
Access and retrieval times are quite fast,
which makes TreeSet an excellent choice
when storing large amounts of sorted
information that must be found quickly.
414
The TreeSet Class
The following constructors are defined:
TreeSet( ): constructs an empty tree set
that will be sorted in ascending order
according to the natural order of its
elements.
TreeSet(Collection c): builds a tree set
that contains the elements of c.
415
The TreeSet Class
TreeSet(Comparator comp) : constructs an
empty tree set that will be sorted according
to the comparator specified by comp.
TreeSet(SortedSet ss):The fourth form
builds a tree set that contains the elements of
ss.
416
The TreeSet Class
stores its elements in a tree, they are
automatically arranged in sorted order,
as the output confirms.
Eg: TreeSetDemo.java
417
Accessing a Collection via an Iterator
Iterator enables you to cycle through a
collection, obtaining or removing
elements.
ListIterator extends Iterator to allow
bidirectional traversal of a list, and the
modification of elements.
418
Using an Iterator
Before you can access a collection through an
iterator, you must obtain one.
Each of the collection classes provides an
iterator( ) method that returns an iterator to
the start of the collection.
By using this iterator object, you can access
each element in the collection, one element
at a time.
419
Using an Iterator
In general, to use an iterator to cycle through
the contents of a collection, follow these
steps:



1. Obtain an iterator to the start of the collection
by calling the collection’s iterator( ) method.
2. Set up a loop that makes a call to hasNext( ).
Have the loop iterate as long as
hasNext( )
returns true.
3. Within the loop, obtain each element by calling
next( ).
420
Using an Iterator
Eg: IteratorDemo .java
421
Vector
Vector implements a dynamic array.
Vector is synchronized.
Here are the Vector constructors:
Vector( ):Creates a default vector, which has
an initial size of 10.
Vector(int size):Creates a vector whose initial
capacity is specified by size.
Vector(int size, int incr):creates a
vector whose initial capacity is specified by
size and whose increment is specified by
422
incr.
Vector
Vector(Collection c):Creates a vector that
contains the elements of collection c.
All vectors start with an initial capacity.
After this initial capacity is reached, the next
time that you attempt to store an object in
the vector, the vector automatically allocates
space for that object plus extra room for
additional objects.
By allocating more than just the required
memory, the vector reduces the number of
allocations that must take place.
423
Vector
Defines some protected data members:
int capacityIncrement;
int elementCount;
The increment value is stored in
capacityIncrement. The number of elements
currently in the vector is stored in
elementCount. The array that holds the
vector is stored in elementData.
424
Vector
Vector implements List,so you can use a
vector just like you use an ArrayList instance.
You can also manipulate one using its
methods.
For example, after you instantiate a Vector,
you can add an element to it by calling
addElement( ).
To obtain the element at a specific location,
call elementAt( ).
425
Vector
To obtain the first element in the vector, call
firstElement( ).
To retrieve the last element, call
lastElement( ).
You can obtain the index of an element by
using indexOf( ) and lastIndexOf( ).
To remove an element, call removeElement( )
or removeElementAt( ).
426
StringTokenizer
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 this parsing process, often called the
lexer (lexical analyzer) or scanner.
427
StringTokenizer
To use StringTokenizer, you specify an input
string and a string that contains delimiters.
Delimiters are characters that separate
tokens.
Each character in the delimiters string is
considered a valid delimiter—for example,
“,;:” sets the delimiters to a comma,
semicolon, and colon.
428
StringTokenizer
The default set of delimiters consists of the
whitespace characters:space, tab, newline,
and carriage return.
The StringTokenizer constructors are shown
here:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters,
boolean delimAsToken)
429
StringTokenizer
str is the string that will be tokenized.
In the first version, the default delimiters are
used.
In the second and third versions, delimiters is
a string that specifies the delimiters.
In the third version, if delimAsToken is true,
then the delimiters are also returned as
tokens when the string is parsed.
Otherwise, the delimiters are not returned.
430
StringTokenizer
Delimiters are not returned as tokens by
the first two forms.
431
Date
The Date class encapsulates the current date
and time.
Date supports the following constructors:
Date( ) :Initializes the object with the current
date and time.
Date(long millisec):constructor accepts one
argument that equals the number of
milliseconds that have elapsed since
midnight, January 1, 1970.
432
Calendar
The abstract Calendar class provides a set of
methods that allows you to convert a time
in milliseconds to a number of useful
components.
Calendar provides no public constructors.
Calendar defines several protected instance
variables. areFieldsSet is a boolean that
indicates if the time components have been
set.
433
Calendar
Fields is an array of ints that holds the
components of the time.
isSet is a boolean array that indicates if a
specific time component has been set. time is
a long that holds the current time for this
object.
isTimeSet is a boolean that indicates if the
current time has been set.
Eg:CalendarDemo.java
434
GregorianCalendar
GregorianCalendar is a concrete implementation
of a Calendar that implements the normal
Gregorian calendar with which you are familiar.
The getInstance( ) method of Calendar returns
a GregorianCalendar initialized with the current
date and time in the default locale and time
zone.
435
GregorianCalendar
GregorianCalendar defines two fields: AD and
BC. These represent the two eras defined by
the Gregorian calendar.
GregorianCalendar provides an
implementation of all the abstract methods in
Calendar.
It also provides some additional methods.
Perhaps the most interesting is isLeapYear( ),
which tests if the year is a leap year. Its form
is boolean isLeapYear(int year)
436
TimeZone
Another time-related class is TimeZone.
The TimeZone class allows you to work
with time zone offsets from Greenwich
mean time (GMT), also referred to as
Coordinated Universal Time (UTC).
437
Locale
The Locale class is instantiated to produce
objects that each describe a geographical or
cultural region.
It is one of several classes that provide you
with the ability to write programs that can
execute in several different international
environments.
438
Random
The Random class is a generator of
pseudorandom numbers.
These are called pseudorandom numbers
because they are simply uniformly distributed
sequences.
Random defines the following constructors:
Random( ) :The first version creates a
number generator that uses the current time
as the starting,or seed, value.
439
Random
Random(long seed):Allows you to specify a
seed value manually.
If you initialize a Random object with a seed,
you define the starting point for the random
sequence.
If you use the same seed to initialize another
Random object, you will extract the same
random sequence. If you want to generate
different sequences, specify different seed
values. The easiest way to do this is to use
the current time to seed a Random object
440
Currency
Encapsulates information about a currency.
import java.util.*;
class CurDemo {
public static void main(String args[]) {
Currency c;
c = Currency.getInstance(Locale.US);
System.out.println("Symbol: "+c.getSymbol());
System.out.println("Default fractional digits: "
+c.getDefaultFractionDigits());}}
The output is shown here.Symbol: $
Default fractional digits: 2
441
10. Stream Classes
442
I/O Basics
Streams
Java programs perform I/O through streams.
A stream is an abstraction that either
produces or consumes information.
A stream is linked to a physical device by the
Java I/O system.
All streams behave in the same manner,
even if the actual physical devices to which
they are linked differ.
443
I/O Basics
Streams
Thus, the same I/O classes and methods can
be applied to any type of device.
This means that an input stream can abstract
many different kinds of input: from a disk file,
a keyboard, or a network socket. Likewise, an
output stream may refer to the console, a
disk file, or a network connection.
444
I/O Basics
Streams
Reading information into a program
445
I/O Basics
Streams
Writing information out of a program.
446
Byte Streams and Character Streams
Java 2 defines two types of streams: byte and
character.
Byte streams provide a convenient means for
handling input and output of bytes.
Byte streams are used, for example, when
reading or writing binary data.
Character streams provide a convenient
means for handling input and output of
characters.
447
Byte Streams Classes
Defined by using two class hierarchies.
At the top are two abstract classes:
InputStream and OutputStream.
Remember, to use the stream classes,
you must import java.io.
448
Byte Streams Classes
The abstract classes InputStream and
OutputStream define several key methods
that the other stream classes implement.
Two of the most important are read( ) and
write( ), which, respectively, read and write
bytes of data.
Both methods are declared as abstract inside
InputStream and OutputStream.
They are overridden by derived stream classes.
449
Byte Streams Classes
Programs use byte streams to perform
input and output of 8-bit bytes. All byte
stream classes are descended from
InputStream and OutputStream.
450
The Character Stream Classes
Character streams are defined by using
two class hierarchies.
At the top are two abstract classes,
Reader and Writer. These abstract
classes handle Unicode character
streams.
Java has several concrete subclasses of
each of these.
451
Reader and Writer
The abstract classes Reader and Writer
define several key methods that the
other stream classes implement.
Two of the most important methods are
read( ) and write( ), which read and
write characters of data, respectively.
These methods are overridden by
derived stream classes.
452
The Predefined Streams
All Java programs automatically import the
java.lang package.
This package defines a class called System,
which encapsulates several aspects of the
run-time environment.
For example, using some of its methods, you
can obtain the current time and the settings
of various properties associated with the
system.
453
The Predefined Streams
System also contains three predefined stream
variables, in, out, and err. These fields are
declared as public and static within System.
This means that they can be used by
any other part of your program and without
reference to a specific System object.
454
The Predefined Streams
System.out refers to the standard
output stream. By default, this is the
console.
System.in refers to standard input,
which is the keyboard by default.
System.err refers to the standard error
stream, which also is the console by
default.
455
The Predefined Streams
System.in is an object of type
InputStream.
System.out and System.err are objects
of type PrintStream.
These are byte streams, even though
they typically are used to read and
write characters from and to the
console.
456
Reading Console Input
In Java, console input is accomplished by
reading from System.in.
To obtain a character-based stream that
is attached to the console, wrap
System.in in a BufferedReader object, to
create a character stream.
BuffereredReader supports a buffered
input stream.
457
Reading Console Input
Its most commonly used constructor is
shown here:
BufferedReader(Reader
inputReader)
Here, inputReader is the stream that is
linked to the instance of
BufferedReader that is being created.
Reader is an abstract class.
458
Reading Console Input
One of its concrete subclasses is
InputStreamReader, which converts
bytes to characters.
To obtain an InputStreamReader object
that is linked to System.in, use the
following constructor:
InputStreamReader(InputStream
inputStream)
459
Reading Console Input
Because System.in refers to an object of type
InputStream, it can be used for inputStream.
Putting it all together, the following line of
code creates a BufferedReader that is
connected to the keyboard:
BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
After this statement executes, br is a
character-based stream that is linked to the
console through System.in.
460
Reading Characters
To read a character from a BufferedReader,
use read( ).
The version of read( ) that we will be using is
int read( ) throws IOException.
Each time that read( ) is called, it reads a
character from the input stream and returns it
as an integer value.
It returns –1 when the end of the stream is
encountered and it can throw an
IOException.
461
Reading Strings
To read a string from the keyboard, use
the version of readLine( ) that is a
member of the BufferedReader class.
Its general form is shown here:
String readLine( ) throws IOException
you can see that it returns a String
object.
462
Writing Console Output
Console output is most easily accomplished
with print( ) and println( ),.
These methods are defined by the class
PrintStream (which is the type of the object
referenced by System.out).
Even though System.out is a byte stream,
using it for simple program output is still
acceptable.
Eg:WriteDemo.java
463
Writing Console Output
Because PrintStream is an output stream
derived from OutputStream, it also
implements the low-level method write( ).
Thus, write( ) can be used to write to the
console.
The simplest form of write( ) defined by
PrintStream is shown here:
void write(int byteval)
This method writes to the stream the byte
specified by byteval.
464
The PrintWriter Class
For real-world programs, the recommended
method of writing to the console when using
Java is through a PrintWriter stream.
PrintWriter is one of the character-based
classes.
Using a character-based class for console
output makes it easier to internationalize your
program.
465
The PrintWriter Class
Constructors: :
PrintWriter(OutputStream outputStream,
boolean flushOnNewline)
Here, outputStream is an object of type
OutputStream, and flushOnNewline controls
whether Java flushes the output stream every
time a println( ) method is called.
If flushOnNewline is true, flushing
automatically takes place. If false, flushing is
not automatic.
466
The PrintWriter Class
To write to the console by using a PrintWriter,
specify System.out for the output stream and
flush the stream after each newline.
For eg: this line of code creates a PrintWriter
that is connected to console output:
PrintWriter pw = new PrintWriter(System.out,
true);
// Demonstrate PrintWriter
import java.io.*;
467
The PrintWriter Class :example
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out,
true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);} }
468
Reading and Writing Files
Java provides a number of classes and
methods that allow you to read and write
files.
In Java, all files are byte-oriented, and Java
provides methods to read and write bytes
from and to a file.
Also, Java allows you to wrap a byte-oriented
file stream within a character-based object
Two of the most often-used stream classes
are FileInputStream and FileOutputStream,
which create byte streams linked to files.
469
Reading and Writing Files
To open a file, you simply create an object of
one of these classes, specifying the name of
the file as an argument to the constructor.
FileInputStream(String fileName) throws
FileNotFoundException
FileOutputStream(String fileName) throws
FileNotFoundException
Here, fileName specifies the name of the file
that you want to open.
470
Reading and Writing Files
When you create an input stream, if the file
does not exist, then FileNotFoundException is
thrown.
For output streams, if the file cannot be
created, then FileNotFoundException is
thrown.
When an output file is opened, any
preexisting file by the same name is
destroyed
471
Reading and Writing Files
When you are done with a file, you should
close it by calling close( ).
It is defined by both FileInputStream and
FileOutputStream, as shown here:
void close( ) throws IOException
To read from a file, you can use a version of
read( ) that is defined within FileInputStream.
Its general form is:
int read( ) throws IOException.
472
Reading and Writing Files
Each time that it is called, it reads a single
byte from the file and returns the byte as an
integer value.
read( ) returns –1 when the end of the file is
encountered. It can throw an IOException.
Eg: ShowFile.java
473
Reading and Writing Files
To write to a file, you will use the write( )
method defined by FileOutputStream.
Its simplest form is shown here:
void write(int byteval) throws
IOException
This method writes the byte specified by
byteval to the file. Although byteval is
declared as an integer, only the low-order
eight bits are written to the file. If an error
occurs during writing, an IOException is
thrown.
eg:CopyFile.java
474
The Java I/O Classes and Interfaces
IO_classes.txt
The following interfaces are defined
by java.io:
DataInput FilenameFilter ObjectOutput
DataOutput ObjectInput
ObjectStreamConstants
Externalizable ObjectInputValidation
Serializable FileFilter
475
File
Most of the classes defined by java.io operate
on streams, the File class does not.
It deals directly with files and the file system.
That is, the File class does not specify how
information is retrieved from or stored in
files; it describes the properties of a file itself.
A File object is used to obtain or manipulate
the information associated with a disk file,
such as the permissions, time, date, and
directory path, and to navigate subdirectory
hierarchies.
476
File
Files are a primary source and
destination for data within many
programs.
Although there are severe restrictions
on their use within applets for security
reasons,files are still a central resource
for storing persistent and shared
information.
477
File
:
constructors
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
Here, directoryPath is the path name of the
file, filename is the name of the file, dirObj is
a File object that specifies a directory, and
uriObj is a URI object that describes a file.
File defines many methods that obtain the
standard properties of a File object.
478
File
:
constructors
For eg: getName( ) returns the name of
the file, getParent( ) returns the name
of the parent directory, and exists( )
returns true if the file exists, false if it
does not.
Eg:FileDemo.java
479
File
isFile( ) returns true if called on a file and false if
called on a directory.
Also, isFile( ) returns false for some special files,
such as device drivers and named pipes, so this
method can be used to make sure the file will
behave as a file.
The isAbsolute( ) method returns true if the file
has an absolute path and false if its path is
relative.
480
File
File also includes two useful utility
methods. The first is renameTo( ) :
boolean renameTo(File newName)
Here, the filename specified by
newName becomes the new name of
the invoking File object.
It will return true upon success and
false if the file cannot be renamed.
481
File
The second utility method is delete( ), which
deletes the disk file represented by the path
of the invoking File object. boolean delete( )
You can also use delete( ) to delete a
directory if the directory is empty.
delete( ) returns true if it deletes the file and
false if the file cannot be removed.
Also, because File supports the Comparable
interface, the method compareTo( ) is
482
Directories
A directory is a File that contains a list of
other files and directories.
When you create a File object and it is a
directory, the isDirectory( ) method will return
true. Here,you can call list( ) on that object to
extract the list of other files and directories
inside.
It has two forms. One is String[ ] list( ) :The
list of files is returned in an array of String
objects.
Eg:DirList.java
483
Creating Directories
The mkdir( ) :creates a directory, returning
true on success and false on failure. Failure
indicates that the path specified in the File
object already exists, or that the directory
cannot be created because the entire path
does not exist yet.
To create a directory for which no path
exists, use the mkdirs( ) method. It creates
both a directory and all the parents of the
directory.
484
ByteArrayInputStream
ByteArrayInputStream is an implementation
of an input stream that uses a byte array as
the source.
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start,
int numBytes)
Here, array is the input source. The second
constructor creates an InputStream from a
subset of your byte array that begins with the
character at the index specified by start and
is numBytes long.
485
ByteArrayInputStream
Eg: ByteArrayInputStreamDemo.java
A ByteArrayInputStream implements both
mark( ) and reset( ).
If mark( ) has not been called, then reset( )
sets the stream pointer to the start of the
stream.
Eg: ByteArrayInputStreamReset
486
ByteArrayOutputStream
Implementation of an output stream that
uses a byte array as the destination.
Constructors:ByteArrayOutputStream( ) : a
buffer of 32 bytes is created.
ByteArrayOutputStream(int numBytes): A
buffer is created with a size equal to that
specified by numBytes. The buffer is held in
the protected buf field of
ByteArrayOutputStream. The buffer size will
be increased automatically, if needed.
Eg:ByteArrayOutputStreamDemo
487
Filtered Byte Streams
Filtered streams are simply wrappers around
underlying input or output streams that
transparently provide some extended level of
functionality.
These streams are typically accessed by
methods that are expecting a generic stream,
which is a superclass of the filtered streams.
Typical extensions are buffering, character
translation, and raw data translation. The
filtered byte streams are FilterInputStream
and FilterOutputStream.
488
Filtered Byte Streams
Their constructors are shown here:
FilterOutputStream(OutputStream os)
FilterInputStream(InputStream is)
The methods provided in these classes
are identical to those in InputStream
and OutputStream.
489
Buffered Byte Streams
For the byte-oriented streams, a buffered
stream extends a filtered stream class by
attaching a memory buffer to the I/O
streams.
This buffer allows Java to do I/O operations
on more than a byte at a time, hence
increasing performance.
Because the buffer is available, skipping,
marking, and resetting of the stream
becomes possible.
490
BufferedInputStream
Buffering I/O is a very common performance
optimization.
Java’s BufferedInputStream class allows you
to “wrap” any InputStream into a buffered
stream and achieve this performance
improvement.
Constructors:
BufferedInputStream(InputStream
inputStream): The first form creates a
buffered stream using a default buffer size.
491
BufferedInputStream
• BufferedInputStream(InputStream
inputStream, int bufSize) :size of the buffer is
passed in bufSize.
• Use of sizes that are multiples of memory
page, disk block, and so on can have a
significant positive impact on performance.
• Eg: BufferedInputStreamDemo.java
492
BufferedInputStream
Use of mark( ) is restricted to access
within the buffer. This means that you
can only
specify a parameter to mark( ) that is
smaller than the buffer size of the
stream.
493
BufferedOutputStream
Similar to any OutputStream with the
exception of an added flush( ) method that is
used to ensure that data buffers are
physically written to the actual output device.
Since the point of a BufferedOutputStream is
to improve performance by reducing the
number of times the system actually writes
data, you may need to call flush( ) to cause
any data that is in the buffer to get written.
494
BufferedOutputStream
Unlike buffered input, buffering output does
not provide additional functionality.Buffers for
output in Java are there to increase
performance.
constructors:
BufferedOutputStream(OutputStream
outputStream) :Creates a buffered stream
using a buffer of 512 bytes.
BufferedOutputStream(OutputStream
outputStream, int bufSize):The size of the
buffer is passed in bufSize
.
495
PushbackInputStream
One of the novel uses of buffering is the
implementation of pushback.
Pushback is used on an input stream to allow
a byte to be read and then returned (that is,
“pushed back”) to the stream.
The PushbackInputStream class implements
this idea.
It provides a mechanism to “peek” at what is
coming from an input stream without
disrupting it.
496
PushbackInputStream
Constructors:
PushbackInputStream(InputStream
inputStream) :Creates a stream object that
allows one byte to be returned to the input
stream.
PushbackInputStream(InputStream
inputStream, int numBytes): Creates a stream
that has a pushback buffer that is numBytes
long.
497
PushbackInputStream
Allows multiple bytes to be returned to the
input stream.Provides unread( ), shown here:
void unread(int ch) :Pushes back the loworder byte of ch. This will be the next byte
returned by a subsequent call to read( ).
void unread(byte buffer[ ]): returns the bytes
in buffer void unread(byte buffer, int offset,
int numChars): pushes back numChars bytes
beginning at offset from buffer.
An IOException will be thrown if there is an
attempt to return a byte when the pushback
buffer is full
498
PushbackInputStream
Eg: PushbackInputStreamDemo.java
PushbackInputStream has the side
effect of invalidating the mark( ) or
reset( ) methods of the InputStream
used to create it.
Use markSupported( ) to check any
stream on which you are going to use
mark( )/reset( ).
499
SequenceInputStream
The SequenceInputStream class allows you to
concatenate multiple InputStreams.
The construction of a SequenceInputStream
is different from any other InputStream.
500
PrintStream
The PrintStream class provides all of the
formatting capabilities.
PrintStream(OutputStream outputStream)
PrintStream(OutputStream outputStream,
boolean flushOnNewline)
where flushOnNewline controls whether Java
flushes the output stream every time a
newline (\n) character is output.
If flushOnNewline is true, flushing
automatically takes place.
501
PrintStream
If it is false, flushing is not automatic. The
first constructor does not automatically flush.
Java’s PrintStream objects support the
print( ) and println( ) methods for all types,
including Object.
If an argument is not a simple type, the
PrintStream methods will call the object’s
toString( ) method and then print the result.
502
RandomAccessFile
Encapsulates a random-access file.
It is not derived from InputStream or
OutputStream. Instead, it implements the
interfaces DataInput and DataOutput,which
define the basic I/O methods.
constructors:
RandomAccessFile(File fileObj, String
access)throws FileNotFoundException: fileObj
specifies the name of the file to open as a
File object
503
RandomAccessFile
In theRandomAccessFile(String filename,
String access) throws
FileNotFoundException:
The name of the file is passed in filename. In
both cases, access determines what type of
file access is permitted.
If it is “r”, then the file can be read, but not
written.
If it is “rw”, then the file is opened in readwrite mode.
504
RandomAccessFile
If it is “rws”, the file is opened for read-write
operations and every change to the file’s data
or metadata will be immediately written to
the physical device .
If it is “rwd”, the file is opened for read-write
operations and every change to the file’s data
will be immediately written to the physical
device.
505
RandomAccessFile
The method seek( ), is used to set the
current position of the file pointer within the
file:
void seek(long newPos) throws IOException.
Here, newPos specifies the new position, in
bytes, of the file pointer from the beginning
of the file.
After a call to seek( ), the next read or write
operation will occur at the new file position.
506
The Character Streams
While the byte stream classes provide
sufficient functionality to handle any type of
I/O operation, they cannot work directly with
Unicode characters.
Since one of the main purposes of Java is to
support the “write once, run anywhere”
philosophy, it was necessary to include direct
I/O support for characters.
507
Reader & Writer
Reader is an abstract class that defines Java’s
model of streaming character input.
All of the methods in this class will throw an
IOException on error conditions.
Writer is an abstract class that defines
streaming character output. All of the
methods in this class return a void value and
throw an IOException in the case of errors.
508
FileReader
The FileReader class creates a Reader that
you can use to read the contents of a file.
Constructors :
FileReader(String filePath)
FileReader(File fileObj)
Either can throw a FileNotFoundException.
Here, filePath is the full path name of a file,
and fileObj is a File object that describes the
file.
Eg:FileReaderDemo.java
509
FileWriter
Writer that can be used to write to a file.
Constructors: FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
They can throw an IOException. Here,
filePath is the full path name of a file, and
fileObj is a File object that describes the file.
If append is true, then output is appended to
the end of the file.
510
FileWriter
Creation of a FileWriter is not dependent on
the file already existing.
FileWriter will create the file before opening
it for output when you create the object.
In the case where you attempt to open a
read-only file, an IOException will be thrown.
Eg: FileWriterDemo.java
511
CharArrayReader
Implementation of an input stream that uses
a character array as the source.
Two Constructors, each of which requires a
character array to provide the data source:
CharArrayReader(char array[ ]):array is the
input source.
512
CharArrayReader
CharArrayReader(char array[ ], int start,
int numChars): Creates a Reader from a
subset of your character array that
begins with the character at the index
specified by start and is numChars long.
Eg:CharArrayReaderDemo.java
513
CharArrayWriter
Implementation of an output stream that
uses an array as the destination.
Two constructors: CharArrayWriter( ) a
buffer with a default size is created.
CharArrayWriter(int numChars)
A buffer is created with a size equal to that
specified by numChars. The buffer is held in
the buf field of CharArrayWriter.
Eg:
CharArrayWriter.java
514
Serialization
Process of writing the state of an object
to a byte stream. This is useful when
you want to save the state of your
program to a persistent storage area,
such as a file.
At a later time, you may restore these
objects by using the process of
deserialization.
515
Serialization
Serialization is also needed to implement
Remote Method Invocation (RMI).
RMI allows a Java object on one machine to
invoke a method of a Java object on a
different machine.
An object may be supplied as an argument to
that remote method.
The sending machine serializes the object
and transmits it. The receiving machine
deserializes it.
516
Serializable
Only an object that implements the
Serializable interface can be saved and
restored by the serialization facilities.
The Serializable interface defines no
members. It is simply used to indicate that a
class may be serialized. If a class is
serializable, all of its subclasses are also
serializable.
Variables that are declared as transient are
not saved by the serialization facilities.
Also, static variables are not saved.
517
Externalizable
Serialization and deserialization has been
designed so as to save and restore the state
of an object occurs automatically.
However, there are cases in which the
programmer may need to have control over
these processes.
For example, it may be desirable to use
compression or encryption techniques.
The Externalizable interface is designed for
these situations.
518
Externalizable
The Externalizable interface defines these two
methods:
void readExternal(ObjectInput inStream)
throws IOException, ClassNotFoundException
void writeExternal(ObjectOutput outStream)
throws IOException:
519
11. Applets
520
Applet Fundamentals
Applets are small applications that are
accessed on an Internet server, transported
over the Internet, automatically installed, and
run as part of a Web document.
After an applet arrives on the client, it has
limited access to resources, so that it can
produce an arbitrary multimedia user
interface and run complex computations
without introducing the risk of viruses or
breaching data integrity.
521
Sample Applet
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet{
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);}}
522
Sample Applet
This applet begins with two import
statements. The first imports the Abstract
Window Toolkit (AWT) classes. Applets
interact with the user through the AWT, not
through the console-based I/O classes. The
AWT contains support for a window-based,
graphical interface
The second import statement imports the
applet package, which contains the class
Applet. Every applet that you create must be
a subclass of Applet.
523
Sample Applet
The next line in the program declares the class
SimpleApplet. This class must be declared as
public, because it will be accessed by code that is
outside the program.
Inside SimpleApplet, paint( ) is declared. This
method is defined by the AWT and must be
overridden by the applet.
paint( ) is called each time that the applet must
redisplay its output. This situation can occur for
several reasons.
524
Sample Applet
For example,the window in which the applet
is running can be overwritten by another
window and then uncovered. Or, the applet
window can be minimized and then restored.
paint( ) is also called when the applet begins
execution.
The paint( ) method has one parameter of
type Graphics. This parameter contains the
graphics context, which describes the
graphics environment in which the applet is
running. This context is used whenever
output to the applet is required.
525
Inside paint( ) is a call to drawString( ),
which is a member of the Graphics
class.
This method outputs a string beginning
at the specified X,Y location. It has the
following general form:
void drawString(String message, int x,
int y)
526
Here, message is the string to be output
beginning at x,y. In a Java window, the upperleft corner is location 0,0.
The call to drawString( ) in the applet causes
the message “A Simple Applet” to be displayed
beginning at location 20,20.
Notice that the applet does not have a main( )
method. Unlike Java programs, applets do not
begin execution at main( ).
In fact, most applets don’t even have a main( )
method. Instead, an applet begins execution
when the name of its class is passed to an
applet viewer or to a network browser.
527
Compilation is same as before.But , running
SimpleApplet involves a different process. In
fact, there are two ways in which you can run
an applet:
Executing the applet within a Java-compatible
Web browser.
Using an applet viewer, such as the standard
SDK tool, appletviewer. An applet viewer
executes your applet in a window. This is
generally the fastest and easiest way to test
your applet.
528
To execute an applet in a Web browser, you
need to write a short HTML text file
that contains the appropriate APPLET tag.
Here is the HTML file that executes
SimpleApplet:
<applet code="SimpleApplet" width=200
height=60>
</applet>
529
The width and height statements specify the
dimensions of the display area used by the
applet. After you create this file, you can
execute your browser and then load this file,
which causes SimpleApplet to be executed.
To execute SimpleApplet with an applet
viewer, you may also execute the HTML file
shown earlier. For example, if the preceding
HTML file is called RunApp.html,then the
following command line will run SimpleApplet:
C:\>appletviewer RunApp.html
530
A more convenient method exists that you
can use to speed up testing.Simply include a
comment at the head of your Java source
code file that contains the APPLET tag.
By doing so, your code is documented with a
prototype of the necessary HTML
statements, and you can test your compiled
applet merely by starting the applet viewer
with your Java source code file. If you use
this method, the SimpleApplet source file
looks like this:
531
import java.awt.*;
import java.applet.*;
/*<applet code="SimpleApplet" width=200
height=60>
</applet>*/
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);}}
532
The three steps involved
1. Edit a Java source file.
2. Compile your program.
3. Execute the applet viewer, specifying the
name of your applet’s source file.
The applet viewer will encounter the APPLET
tag within the comment and execute your
applet.
533
Applet Basics
The Applet class is contained in the
java.applet package.
In addition, java.applet also defines three
interfaces: AppletContext, AudioClip, and
AppletStub.
Applet Basics All applets are subclasses of
Applet. Thus, all applets must import
java.applet. Applets must also import
java.awt
534
Applet Basics
Applets are not executed by the consolebased Java run-time interpreter.Rather, they
are executed by either a Web browser or an
applet viewer.
Execution of an applet does not begin at
main( ). Actually, few applets even have
main( ) methods.
Instead, execution of an applet is started and
controlled with an entirely different
mechanism.
535
Applet Basics
Output to your applet’s window is not
performed by System.out.println( ).
Rather, it is handled with various AWT
methods, such as drawString( ), which
outputs a string to a specified X,Y
location.
Input is also handled differently than in
an application.
536
Once an applet has been compiled, it is
included in an HTML file using the APPLET
tag.
The applet will be executed by a Javaenabled web browser when it encounters the
APPLET tag within the HTML file.
To view and test an applet more conveniently,
simply include a comment at the head of your
Java source code file that contains the
APPLET tag.
537
This way, your code is documented with the
necessary HTML statements needed by your
applet, and you can test the compiled applet
by starting the applet viewer with your Java
source code file specified as the target.
Here is an example of such a comment:
/*<applet code="MyApplet" width=200
height=60> </applet> */
538
The Applet Class
Applet class provides all necessary support
for applet execution,including methods that
load and display images, and methods that
load and play audio clips.
Applet extends the AWT class Panel. In turn,
Panel extends Container, which extends
Component.
These classes provide support for Java’s
window-based, graphical interface. Thus,
Applet provides all of the necessary support
for window-based activities.
539
Applet Architecture
An applet is a window-based program. As
such, its architecture is different from the socalled normal, console-based programs.
Remember,applets are event driven. Here is
how the process works. An applet waits until
an event occurs. The AWT notifies the applet
about an event by calling an event handler
that has been provided by the applet.
540
Once this happens, the applet must take
appropriate action and then quickly return
control to the AWT. This is a crucial point.
For the most part, your applet should not
enter a “mode” of operation in which it
maintains control for an extended period.
Instead, it must perform specific actions in
response to events and then return control to
the AWT run-time system.
541
An Applet Skeleton
Most trivial applets override a set of methods
that provides the basic mechanism by which
the browser or applet viewer interfaces to the
applet and controls its execution.
Four of these methods-init( ), start( ), stop( ),
and destroy( )—are defined by Applet.
Another, paint( ), is defined by the AWT
Component class. Default implementations for
all of these methods are provided.
Applets do not need to override those
methods they do not use.
542
An Applet skeleton.
import java.awt.*;
import java.applet.*;
/*<applet code="AppletSkel" width=300
height=100> </applet>*/
public class AppletSkel extends Applet {
// Called first.
public void init() { // initialization
}
/* Called second, after init(). Also called
whenever the applet is restarted. */
543
public void start()
{ // start or resume execution }
// Called when the applet is stopped.
public void stop() { //suspends execution }
/* Called when applet is terminated. This is
the last method executed. */
public void destroy(){//shutdown activities }
// Called when an applet's window must be
restored.public void paint(Graphics g) {
// redisplay contents of window }}
544
Although this skeleton does not do anything,
it can be compiled and run.
It is important to understand the order in
which the various methods shown in the
skeleton are called. When an applet begins,
the AWT calls the following methods, in
this sequence:1. init( ) 2. start( ) 3. paint( )
When an applet is terminated, the following
sequence of method calls takes place:
1. stop( ) 2. destroy( )
545
init( )
The init( ) method is the first method to
be called.
This is where you should initialize
variables.
This method is called only once during
the run time of your applet.
546
start( )
The start( ) method is called after init( ).
It is also called to restart an applet after it
has been stopped.
Whereas init( ) is called once—the first time
an applet is loaded—start( ) is called each
time an applet’s HTML document is displayed
onscreen.
So, if a user leaves a web page and comes
back,the applet resumes execution at start( ).
547
paint( )
Called each time your applet’s output must
be redrawn due to several reasons:
1. The window in which the applet is running
may be overwritten by another window and
then uncovered.
2. Or the applet window may be minimized and
then restored.
3. paint( ) is also called when the applet
begins execution.
548
paint( )
Whatever the cause, whenever the applet
must redraw its output, paint( ) is called.
The paint( ) method has one parameter of
type Graphics.
This parameter will contain the graphics
context, which describes the graphics
environment in which the applet is running.
This context is used whenever output to the
applet is required.
549
stop( )
Called when a web browser leaves the HTML
document containing the applet—when it
goes to another page, for example.
When stop( ) is called, the applet is probably
running.
You should use stop( ) to suspend threads
that don’t need to run when the applet is not
visible.
You can restart them when start( ) is called
if the user returns to the page
550
destroy( )
The destroy( ) method is called when the
environment determines that your applet
needs to be removed completely from
memory.
At this point, you should free up any
resources the applet may be using.
The stop( ) method is always called before
destroy( ).
551
Overriding update( )
In some situations, your applet may need to
override another method defined by the AWT,
called update( ).
This method is called when your applet has
requested that a portion of its window be
redrawn.
The default version of update( ) first fills an
applet with the default background color and
then calls paint( ).
552
Overriding update( )
If you fill the background using a different
color in paint( ), the user will experience a
flash of the default background each time
update( ) is called—that is, whenever the
window is repainted.
One way to avoid this problem is to override
the update( ) method so that it performs all
necessary display activities. Then have
paint( ) simply call update( ).
553
The applet skeleton will override paint( ) and
update( ), as shown here:
public void update(Graphics g) {
// redisplay your window, here.
}
public void paint(Graphics g) {
update(g);
}
554
To output a string to an applet, use
drawString( ), which is a member of the
Graphics class.
Typically, it is called from within either
update( ) or paint( ).
It has the following general form:
void drawString(String message, int x, int y)
Here, message is the string to be output
beginning at x,y.
555
In a Java window, the upper-left corner is
location 0,0. The drawString( ) method will
not recognize newline characters. If you want
to start a line of text on another line, you
must do so manually, specifying the precise
X,Y location where you want the line to
begin.)
556
To set the background color of an applet’s
window, use setBackground( ).
To set the foreground color (the color in
which text is shown, for example), use
setForeground( ).
These methods are defined by Component,
and they have the following general forms:
void setBackground(Color newColor)
void setForeground(Color newColor)
Here, newColor specifies the new color.
557
The class Color defines the constants shown
here that can be used to specify colors:
Color.black Color.magenta
Color.blue Color.orange
Color.cyan Color.pink
Color.darkGray Color.red
Color.gray Color.white
Color.green Color.yellow
Color.lightGray
558
Eg: this sets the background color to green and
the text color to red:
setBackground(Color.green);
setForeground(Color.red);
A good place to set the foreground and
background colors is in the init( ) method.
These colors can be changed as often as
necessary during the execution of yourapplet.
The default foreground color is black. The
default background color is light gray.
559
Requesting Repainting
As a general rule, an applet writes to its window
only when its update( ) or paint ( )method is
called by the AWT.
Whenever your applet needs to update the
information displayed in its window, it simply
calls repaint( ).
The repaint( ) method is defined by the AWT. It
causes the AWT run-time system to execute a
call to your applet’s update( ) method, which, in
its default implementation, calls paint( ).
560
repaint( )
The repaint( ) method has four forms. The
simplest version of repaint( ) is shown here:
void repaint( ):Causes the entire window to
be repainted.
The following version specifies a region that
will be repainted:
void repaint(int left, int top, int width, int
height)
561
repaint( )
Here, the coordinates of the upper-left corner
of the region are specified by left and
top, and the width and height of the region
are passed in width and height.
These dimensions are specified in pixels. If
you need to update only a small portion
of the window, it is more efficient to repaint
only that region.
562
Using the Status Window
In addition to displaying information in its
window, an applet can also output a message
to the status window of the browser or applet
viewer on which it is running.
To do so, call showStatus( ) with the string
that you want displayed. The status window
is a good place to give the user feedback
about what is occurring in the applet, suggest
options, or possibly report some types of
errors.
563
The status window also makes an
excellent debugging aid, because it
gives you an easy way to output
information about your applet.
564
showStatus( ):
The following applet demonstrates
// Using the Status Window.
import java.awt.*;
import java.applet.*;
/*<applet code="StatusWindow" width=300
height=50></applet>*/
public class StatusWindow extends Applet{
public void init(){setBackground(Color.cyan);}
565
// Display msg in applet window.
public void paint(Graphics g) {
g.drawString("This is in the applet
window.", 10, 20);
showStatus("This is shown in the status
window.");} }
566
The HTML APPLET Tag
The APPLET tag is used to start an applet
from both an HTML document and from an
applet viewer.
An applet viewer will execute each APPLET
tag that it finds in a separate window.
The syntax for the standard APPLET tag is
shown here. Bracketed items are optional.
567
The HTML APPLET Tag
< 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 =
AttributeName2 VALUE = AttributeValue>]
</APPLET>
568
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 (specified
by the CODE tag).
The HTML document’s URL directory is used
as the CODEBASE if this attribute is not
specified.
The CODEBASE does not have to be on the
host from which the HTML document was
read.
569
CODE: is a required attribute that gives
the name of the file containing your
applet’s compiled .class file.
This file is relative to the code base URL
of the applet, which is the directory that
the HTML file was in or the directory
indicated by CODEBASE if set.
570
ALT :Is an optional attribute used to
specify a short text message that
should be displayed if the browser
understands the APPLET tag but can’t
currently run Java applets.
This is distinct from the alternate HTML
you provide for browsers that don’t
support applets
571
NAME :is an optional attribute used to specify
a name for the applet instance.
Applets must be named in order for other
applets on the same page to find them by
name and communicate with them.
To obtain an applet by name,use
getApplet( ),which is defined by the
AppletContext interface.
572
WIDTH AND HEIGHT:Are required attributes
that give the size (in pixels) of the applet
display area.
ALIGN : is an optional attribute that specifies
the alignment of the applet.This attribute is
treated the same as the HTML IMG tag with
these possible values: LEFT, RIGHT, TOP,
BOTTOM, MIDDLE, BASELINE, TEXTTOP.
573
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.
They’re treated the same as the IMG
tag’s VSPACE and HSPACE attributes.
574
PARAM NAME AND VALUE: The PARAM
tag allows you to specify applet specific
arguments in an HTML page. Applets
access their attributes with the
getParameter( ) method.
575
Passing Parameters to Applets
The APPLET tag in HTML allows you to pass
parameters to your applet. To retrieve a
parameter, use the getParameter( ) method.
It returns the value of the specified
parameter in the form of a String object.
Thus, for numeric and boolean values, you
will need to convert their string
representations into their internal formats.
“ParamDemo.java”
576
If a parameter isn’t available, getParameter( )
will return null.
Also, conversions to numeric types must be
attempted in a try statement that catches
NumberFormatException.
Uncaught exceptions should never occur
within an applet. getDocumentBase( ) and
getCodeBase( ) Often, you will create applets
that will need to explicitly load media and
text.
577
Java will allow the applet to load data from
the directory holding the HTML file that
started the applet (the document base) and
the directory from which the applet’s class file
was loaded (the code base).
These directories are returned as URL objects
by getDocumentBase( ) and getCodeBase( ).
They can be concatenated with a string that
names the file you want to load.
578
To actually load another file, you
will use the showDocument( ) method
defined by the AppletContext interface.
Eg:Bases.java
579
AppletContext and showDocument( )
One application of Java is to use active
images and animation to provide a graphical
means of navigating the Web that is more
interesting than the underlined blue words
used by hypertext.
To allow your applet to transfer control to
another URL, you must use the
showDocument( ) method defined by the
AppletContext interface.
580
AppletContext is an interface that lets
you get information from the applet’s
execution environment.
The context of the currently executing
applet is obtained by a call to the
getAppletContext( ) method defined by
Applet.
581
Within an applet, once you have obtained the
applet’s context, you can bring another
document into view by calling
showDocument( ).
This method has no return value and throws
no exception if it fails, so use it carefully.
There are two showDocument( ) methods.
The method showDocument(URL) displays
the document at the specified URL.
582
The method showDocument(URL, where)
displays the specified document at the
specified location within the browser window.
Valid arguments for where are “_self” (show
in current frame), “_parent” (show in parent
frame), “_top”(show in topmost frame), and
“_blank” (show in new browser window).
You can also specify a name, which causes
the document to be shown in a new browser
window by that name.
583
Summary
An applet can react to major events in
the following ways:
It can initialize itself.
It can start running.
It can stop running.
It can perform a final cleanup, in
preparation for being unloaded.
584
What Applets Can and Can't Do
Every browser implements security
policies to keep applets from
compromising system security.
implementation of the security policies
differs from browser to browser. Also,
security policies are subject .
Current browsers impose the following
restrictions on
any applet that is
loaded over the network:
585
What Applets Can and Can't Do
1. An applet cannot load libraries or define
2.
3.
4.
5.
native methods.
It cannot ordinarily read or write files on the
host that's executing it.
It cannot make network connections except
to the host that it came from.
It cannot start any program on the host
that's executing it.
It cannot read certain system properties.
586
Applet Capabilities
The java.applet package provides an API that
gives applets some capabilities that
applications don't have.
1. applets can play sounds, which other
programs can't do yet.
2. Applets can usually make network connections
to the host they came from.
3. Applets running within a Web browser can
easily cause HTML documents to be
displayed.
4. Applets can invoke public methods of other
applets on the same page.
587
Summarizing...
The Basic Applet Life Cycle
1.
2.
3.
The browser reads the HTML page and finds
any <APPLET> tags.
The browser parses the <APPLET> tag to find
the CODE and possibly CODEBASE attribute.
The browser downloads the .class file for the
applet from the URL found in the last step.
588
4. The browser converts the raw bytes downloaded
into a Java class, that is a java.lang.Class object.
The browser instantiates the applet class to form
an applet object. This requires the applet to have a
noargs constructor.
6. The browser calls the applet's init() method.
7. The browser calls the applet's start() method.
589
While the applet is running, the browser passes
any events intended for the applet, e.g. mouse clicks,
key presses, etc., to the applet's handleEvent()
method.
Update events are used to tell the applet that it needs
to repaint itself.
9. The browser calls the applet's stop() method.
10. The browser calls the applet's destroy() method.
590
12. Event Handling
591
The Delegation Event Model
The modern approach to handling events is
based on the delegation event model, which
defines standard and consistent mechanisms
to generate and process events.
Its concept is quite simple: a source
generates an event and sends it to one or
more listeners.
In this scheme, the listener simply waits until
it receives an event.
592
Once received, the listener processes the
event and then returns.
The advantage of this design is that the
application logic that processes events is
cleanly separated from the user interface
logic that generates those events.
A user interface element is able to “delegate”
the processing of an event to a separate
piece of code.
593
In the delegation event model, listeners must
register with a source in order to receive an
event notification.
This provides an important benefit:
notifications are sent only to listeners that
want to receive them. This is a more efficient
way to handle events than the design used by
the old Java 1.0 approach.
Previously, an event was propagated up the
containment hierarchy until it was handled by
a component.
594
This required components to receive
events that they did not process, and it
wasted valuable time. The delegation
event model eliminates this overhead.
595
Events
In the delegation model, an event is an
object that describes a state change in a
source.
It can be generated as a consequence of a
person interacting with the elements in a
graphical user interface.
Some of the activities that cause events to be
generated are pressing a button, entering a
character via the keyboard, selecting an
item in a list, and clicking the mouse.
596
Event Sources
A source is an object that generates an
event. This occurs when the internal
state of that object changes in some way.
Sources may generate more than one type of
event.
A source must register listeners in order for
the listeners to receive notifications about a
specific type of event. Each type of event has
its own registration method.
597
General form
public void
addTypeListener(TypeListener el)
Here, Type is the name of the event and el is
a reference to the event listener.
For example,the method that registers a
keyboard event listener is called
addKeyListener( ).
The method that registers a mouse motion
listener is called addMouseMotionListener( ).
598
When an event occurs, all registered listeners
are notified and receive a copy of the event
object.
This is known as multicasting the event. In
all cases, notifications are sent only to
listeners that register to receive them.
Some sources may allow only one listener to
register.
599
The general form of such a method is this:
public void addTypeListener(TypeListener el)
throws java.util.TooManyListenersException
Here, Type is the name of the event and el is
a reference to the event listener.
When such an event occurs, the registered
listener is notified. This is known as
unicasting the event.
600
A source must also provide a method that allows
a listener to unregister an interest in a specific
type of event.
The general form of such a method is this:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event and el is a
reference to the event listener.
The methods that add or remove listeners are
provided by the source that generates events.
601
Event Listeners
A listener is an object that is notified when an
event occurs. It has two major requirements.
First, it must have been registered with one
or more sources to receive notifications about
specific types of events.
Second, it must implement methods to
receive and process these notifications.
602
Event Classes
The classes that represent events are at the core
of Java’s event handling mechanism.
At the root of the Java event class hierarchy is
EventObject, which is in java.util.
It is the superclass for all events. Its one
constructor is shown here:EventObject(Object src)
Here, src is the object that generates this event.
603
EventObject contains two methods:
getSource( ) and toString( ).
The getSource( )method returns the
source of the event. Its general form is
shown here:
Object getSource( )
As expected, toString( ) returns the
string equivalent of the event.
604
Main Event Classes in java.awt.event
1. ActionEvent :Generated when a button is
pressed, a list item is double-clicked, or a
menu item is selected.
2. AdjustmentEvent :Generated when a scroll bar
is manipulated.
3. ComponentEvent :Generated when a
component is hidden, moved, resized,or
becomes visible.
4. ContainerEvent :Generated when a component
is added to or removed from a container.
605
Main Event Classes
5. FocusEvent: Generated when a component
gains or loseskeyboard focus.
6. InputEvent:Abstract super class for all
component input event classes.
7. ItemEvent:Generated when a check box or
list item is clicked; also occurs when a choice
selection is made or a checkable menu item
is selected or deselected.
606
Main Event Classes
8. KeyEvent :Generated when input is
received from the keyboard.
9. MouseEvent: Generated when the
mouse is dragged, moved, clicked,
pressed, or released; also generated
when the mouse enters or exits a
component.
607
Main Event Classes
10.MouseWheelEvent :Generated when the
mouse wheel is moved.
11.TextEvent :Generated when the value of a
text area or text field is changed.
12.WindowEvent :Generated when a window is
activated,closed,deactivated, deiconified,
iconified, opened, or quit.
608
The ActionEvent Class
An ActionEvent is generated when a button is
pressed, a list item is double-clicked, or a
menu item is selected.
The ActionEvent class defines four integer
constants that can be used to identify any
modifiers associated with an action event:
ALT_MASK,CTRL_MASK, META_MASK, and
SHIFT_MASK.
In addition, there is an integer constant,
ACTION_PERFORMED, which can be used to
identify action events.
609
Three constructors
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd,
int modifiers)
ActionEvent(Object src, int type, String cmd,
long when, int modifiers)
Here, src is a reference to the object that
generated this event. The type of the eventis
specified by type, and its command string is
cmd..
610
The argument modifiers indicates
which modifier keys (ALT, CTRL, META,
and/or SHIFT) were pressed when the event
was generated. The when parameter specifies
when the event occurred .
You can obtain the command name for the
invoking ActionEvent object by usingthe
getActionCommand( ) method, shown here:
String getActionCommand( )
611
For example, when a button is pressed,
an action event is generated that has a
command name equal to the label on
that button.
The getModifiers( ) method returns a
value that indicates which modifier keys
(ALT, CTRL, META, and/or SHIFT) were
pressed when the event was generated.
612
The AdjustmentEvent Class
An AdjustmentEvent is generated by a scroll
bar.
There are five types of adjustmentevents.
The AdjustmentEvent class defines integer
constants that can be used to identify them.
1. BLOCK_DECREMENT The user clicked inside
the scroll bar to decrease its value.
2. BLOCK_INCREMENT The user clicked inside
the scroll bar to increase its value.
3. TRACK The slider was dragged.
613
4. UNIT_DECREMENT The button at the end
of the scroll bar was clicked to decrease its
value.
5. UNIT_INCREMENT The button at the end of
the scroll bar was clicked to increase its
value.
In addition, there is an integer constant,
ADJUSTMENT_VALUE_CHANGED,that
indicates that a change has occurred.
614
Constructors
AdjustmentEvent(Adjustable src, int id, int
type, int data)
Here, src is a reference to the object that
generated this event. The id equals
ADJUSTMENT_VALUE_CHANGED.
The type of the event is specified by type,and
its associated data is data.
The getAdjustable( ) method returns the
object that generated the event. Its form
is shown here:Adjustable getAdjustable( )
615
The type of the adjustment event may be
obtained by the getAdjustmentType( )
method.
It returns one of the constants defined by
AdjustmentEvent. The general form is
int getAdjustmentType( )
The amount of the adjustment can be
obtained from the getValue( ) method, shown
here:int getValue( )
Eg:, when a scroll bar is manipulated, this method returns the
value represented by that change
616
The ComponentEvent Class
A ComponentEvent is generated when the
size, position, or visibility of a component is
changed.
There are four types of component events.
The ComponentEvent class defines integer
constants that can be used to identify them.
The constants and their meanings are shown
here:
COMPONENT_HIDDEN The component was
hidden.
617
COMPONENT_MOVED The component
was moved.
COMPONENT_RESIZED The component
was resized.
COMPONENT_SHOWN The component
became visible.
618
constructor
ComponentEvent(Component src, int type)
Here, src is a reference to the object that
generated this event.
The type of the event is specified by type.
ComponentEvent is the superclass either
directly or indirectly of ContainerEvent,
FocusEvent, KeyEvent, MouseEvent, and
WindowEvent.
The getComponent( ) method returns the
component that generated the event.
Component getComponent( )
619
The ContainerEvent Class
A ContainerEvent is generated when a
component is added to or removed from a
container. There are two types of container
events.
The ContainerEvent class defines int
constants that can be used to identify them:
COMPONENT_ADDED and
COMPONENT_REMOVED.
They indicate that a component has been
added to or removed from the container.
620
ContainerEvent is a subclass of
ComponentEvent and has this constructor:
ContainerEvent(Component src, int type,
Component comp)
Here, src is a reference to the container that
generated this event.
The type of the event is specified by type,
and the component that has been added to
or removed from the container is comp.
621
You can obtain a reference to the container
that generated this event by using the
getContainer( ) method, shown here:
Container getContainer( )
The getChild( ) method returns a reference to
the component that was added to or removed
from the container. Its general form is shown
here: Component getChild( )
622
The FocusEvent Class
A FocusEvent is generated when a
component gains or loses input focus.
These events are identified by the integer
constants FOCUS_GAINED and FOCUS_LOST.
FocusEvent is a subclass of ComponentEvent
and has these constructors:
FocusEvent(Component src, int type)
FocusEvent(Component src, int type, boolean
temporaryFlag)
623
Here, src is a reference to the component
that generated this event. The type of the
event is specified by type.
The argument temporaryFlag is set to true if
the focus event is temporary. Otherwise, it is
set to false.
The isTemporary( ) method indicates if this
focus change is temporary. Its form is shown:
boolean isTemporary( )
The method returns true if the change is
temporary. Otherwise, it returns false.
624
The InputEvent Class
The abstract class InputEvent is a subclass of
ComponentEvent and is the superclass for
component input events. Its subclasses are
KeyEvent and MouseEvent.
InputEvent defines several integer constants
that represent any modifiers, such as the
control key being pressed, that might be
associated with the event.
625
The ItemEvent Class
An ItemEvent is generated when a check box
or a list item is clicked or when a checkable
menu item is selected or deselected.
There are two types of item events, which are
identified by the following integer constants:
DESELECTED The user deselected an item.
SELECTED The user selected an item.
626
The ItemEvent Class
In addition, ItemEvent defines one integer
constant, ITEM_STATE_CHANGED, that
signifies a change of state.
ItemEvent has this constructor:
ItemEvent(ItemSelectable src, int type,
Object entry, int state)
Here, src is a reference to the component
that generated this event.
627
The ItemEvent Class
The specific item that generated the item
event is passed in entry. The current state of
that item is in state.
The getItem( ) method can be used to obtain
a reference to the item that generated an
event.
Its signature : Object getItem( )
628
The KeyEvent Class
A KeyEvent is generated when keyboard input
occurs. There are three types
of key events, which are identified by these
integer constants: KEY_PRESSED,
KEY_RELEASED, and KEY_TYPED.
The first two events are generated when any
key is pressed or released. The last event
occurs only when a character is generated.
629
The KeyEvent Class
Remember, not all key presses result in
characters.
There are many other integer constants that
are defined by KeyEvent. For example,
VK_0 through VK_9 and VK_A through VK_Z
define the ASCII equivalents of the
numbers and letters. Here are some others:
VK_ENTER VK_ESCAPE VK_CANCEL VK_UP
VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN
630
The KeyEvent Class
KeyEvent is a subclass of InputEvent. Here
are two of its constructors:
KeyEvent(Component src, int type, long
when, int modifiers, int code)
KeyEvent(Component src, int type, long
when, int modifiers, int code, char ch)
Here, src is a reference to the component
that generated the event. The type of the
event is specified by type.
631
The KeyEvent Class
The KeyEvent class defines several methods,
but the most commonly used ones are :
char getKeyChar( ) :returns the character that
was entered,int getKeyCode( ) :returns the
key code.
If no valid character is available, then
getKeyChar( ) returns CHAR_UNDEFINED.
632
The MouseEvent Class
There are eight types of mouse events. This class
defines the following integer constants that can be
used to identify them:
MOUSE_CLICKED:The user clicked the mouse.
MOUSE_DRAGGED:The user dragged the mouse.
MOUSE_ENTERED:The mouse entered a component.
MOUSE_EXITED:The mouse exited from a
component.
633
The MouseEvent Class
MOUSE_MOVED :The mouse moved.
MOUSE_PRESSED: The mouse was pressed.
MOUSE_RELEASED: The mouse was released.
MouseEvent is a subclass of InputEvent. Here is
one of its constructors.
MouseEvent(Component src, int type, long
when, int modifiers, int x, int y, int clicks,
boolean triggersPopup)
634
The MouseEvent Class
Here, src is a reference to the component
that generated the event.
The type of the event is specified by type.
The system time at which the mouse event
occurred is passed in when.
The modifiers argument indicates which
modifiers were pressed when a mouse event
occurred.
The coordinates of the mouse are passed in
x and y. The click count is passed in clicks.
635
The MouseEvent Class
The triggersPopup flag indicates if this event
causes a pop-up menu to appear on this
platform.
The most commonly used methods in this
class are getX( ) and getY( ).
These return the X and Y coordinates of the
mouse when the event occurred. Their forms
are shown here: int getX( ),int getY( )
636
The MouseEvent Class
Alternatively, you can use the getPoint( )
method to obtain the coordinates of the
mouse. It is shown here: Point getPoint( )
It returns a Point object that contains the X, Y
coordinates in its integer members: x and y.
The translatePoint( ) method changes the
location of the event. Its form is shown here:
void translatePoint(int x, int y)
Here, the arguments x and y are added to the
coordinates of the event.
637
The getClickCount( ) method obtains the
number of mouse clicks for this event.
Its signature is shown here:
int getClickCount( )
The isPopupTrigger( ) method tests if this
event causes a pop-up menu to appear on
this platform. Its form is shown here:
boolean isPopupTrigger( )
int getButton( )
638
It returns a value that represents the
button that caused the event.
The return value will be one of these
constants defined by MouseEvent.
NO BUTTON BUTTON1 BUTTON2
BUTTON3
The NOBUTTON value indicates that no
button was pressed or released.
639
The MouseWheelEvent Class
The MouseWheelEvent class encapsulates a
mouse wheel event. It is a subclass of
MouseEvent .
If a mouse has a wheel, it is located between
the left and right buttons. Mouse wheels are
used for scrolling. MouseWheelEvent defines
these two integer constants.
WHEEL_BLOCK_SCROLL A page-up or pagedown scroll event occurred.
WHEEL_UNIT_SCROLL A line-up or line-down
scroll event occurred.
640
The WindowEvent Class
There are ten types of window events. The
WindowEvent class defines integer constants
that can be used to identify them. The
constants and their meanings are:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the
window be closed.
641
WINDOW_DEACTIVATED :The window was
deactivated.
WINDOW_DEICONIFIED The window was
deiconified.
WINDOW_GAINED_FOCUS The window gained
input focus.
WINDOW_ICONIFIED The window was iconified.
WindowEvent is a subclass of ComponentEvent.
642
WINDOW_LOST_FOCUS The window
lost input focus.
WINDOW_OPENED The window was
opened.
WINDOW_STATE_CHANGED The state
of the window changed.
643
Sources of Events
1. Button:Generates action events when the
button is pressed.
2. Checkbox:Generates item events when the
check box is selected or deselected.
3. Choice :Generates item events when the
choice is changed.
4. List :Generates action events when an item
is double-clicked; generates item events
when an item is selected or deselected.
644
Sources of Events
5. Menu Item :Generates action events when
a menu item is selected; generates item
events when a checkable menu item is
selected or deselected.
6. Scrollbar :Generates adjustment events
when the scroll bar is manipulated.
7. Text components :Generates text events
when the user enters a character.
8. Window :Generates window events when a
window is activated, closed,deactivated,
deiconified, iconified, opened, or quit.
645
Event Listener Interfaces
The delegation event model has two parts:
sources and listeners.
Listeners are created by implementing one or
more of the interfaces defined by the
java.awt.event package.
When an event occurs, the event source
invokes the appropriate method defined by
the listener and provides an event object as
its argument.
646
The ActionListener Interface
This interface defines the
actionPerformed( ) method that is
invoked when an actionevent occurs. Its
general form is shown here:
void actionPerformed(ActionEvent ae)
647
The AdjustmentListener Interface
This interface defines the
adjustmentValueChanged( ) method that is
invoked when an adjustment event occurs. Its
general form is shown here:
void adjustmentValueChanged
(AdjustmentEvent ae)
648
The ComponentListener Interface
This interface defines four methods that are
invoked when a component is resized,
moved, shown, or hidden. Their general
forms are shown here:
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
void componentHidden(ComponentEvent ce)
649
The AWT processes the resize and
move events.
The componentResized( ) and
componentMoved( ) methods are rovided
for notification purposes only.
650
The ContainerListener Interface
This interface contains two methods. When a
component is added to a container,
componentAdded( ) is invoked.
When a component is removed from a
container,componentRemoved( ) is invoked.
Their general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
651
The FocusListener Interface
This interface defines two methods. When a
component obtains keyboard focus,
focusGained( ) is invoked.
When a component loses keyboard focus,
focusLost( )is called.
Their general forms are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
652
ItemListener Interface
This interface defines the
itemStateChanged( ) method that is
invoked when the state of an item
changes.
Its general form is shown here:
void itemStateChanged(ItemEvent ie)
653
The KeyListener Interface
This interface defines three methods. The
keyPressed( ) and keyReleased( ) methods
are invoked when a key is pressed and
released, respectively.
The keyTyped( ) method is invoked when a
character has been entered.
The general forms of these methods are
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
654
The MouseListener Interface
This interface defines five methods.
void mouseClicked(MouseEvent me): Invoked
if the mouse is pressed and released at the
same point.
void mouseEntered(MouseEvent me):Called
when the mouse enters a component.
void mouseExited(MouseEvent me): Called
When it leaves.
655
The MouseListener Interface
void mousePressed(MouseEvent me) and
void mouseReleased(MouseEvent me): These
methods are invoked when the mouse is
pressed and released, respectively.
656
The MouseMotionListener Interface
This interface defines two methods. The
mouseDragged( ) method is called multiple
times as the mouse is dragged.
The mouseMoved( ) method is called multiple
times as the mouse is moved. Their general
forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
657
The MouseWheelListener Interface
This interface defines the
mouseWheelMoved( ) method that is
invoked when the mouse wheel is
moved. Its general form is shown here.
void mouseWheelMoved
(MouseWheelEvent mwe)
658
The WindowFocusListener Interface
This interface defines two methods:


windowGainedFocus( )
windowLostFocus( ).
These are called when a window gains or
losses input focus. Their general forms are
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
659
The WindowListener Interface
Defines 7 methods. The windowActivated( )
and windowDeactivated( ) methods are
invoked when a window is activated or
deactivated, respectively.
If a window is iconified,the windowIconified( )
method is called. When a window is
deiconified,the windowDeiconified( ) method is
called.
When a window is opened or closed, the
windowOpened( ) or windowClosed( ) methods
are called, respectively.
660
The general Forms
The windowClosing( ) method is called when
a window is being closed.
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
661
Using the delegation event model ..
Applet programming Using the delegation
event model actually quite easy. Just follow
these two steps:
1. Implement the appropriate interface in the
listener so that it will receive the type of
event desired.
2. Implement code to register and unregister (if
necessary) the listener as a recipient for the
event notifications.
662
Using the delegation event model ..
Remember that a source may generate
several types of events. Each event must be
registered separately.
Also, an object may register to receive several
types of events,but it must implement all of
the interfaces that are required to receive
these events.
663
Handling Mouse Events
To handle mouse events, you must
implement the MouseListener and the
MouseMotionListener interfaces.
Eg: MouseEvents.java
664
Handling Keyboard Events
Must implement the KeyListener interface.
There is one other requirement that your
program must meet before it can process
keyboard events: it must request input focus.
To do this, call requestFocus( ), which is
defined by Component.
If you don’t, then your program will not
receive any keyboard events.
Eg: SimpleKey.java, KeyEvents.java(for virtual keys)
665
Adapter Classes
Java provides a special feature, called an
adapter class, that can simplify the creation
of event handlers in certain situations.
An adapter class provides an empty
implementation of all methods in an event
listener interface.
Adapter classes are useful when you want to
receive and process only some of the events
that are handled by a particular event listener
interface.
666
Adapter Classes
You can define a new class to act as an event
listener by extending one of the adapter
classes and implementing only those events
in which you are interested.
For example, the MouseMotionAdapter class
has two methods, mouseDragged( )and
mouseMoved( ). The signatures of these
empty methods are exactly as defined in the
MouseMotionListener interface.
667
Adapter Classes
If you were interested in only mouse
drag events, then you could simply
extend MouseMotionAdapter and
implement mouseDragged( ).
The empty implementation of
mouseMoved( ) would handle the
mouse motion events for you.
Eg: AdapterDemo.java
668
Commonly Used Listener Interfaces
Implemented by Adapter Classes
Adapter Class
ComponentAdapter
ContainerAdapter
FocusAdapter
KeyAdapter
MouseAdapter
MouseMotionAdapter
WindowAdapter
Listener Interface
ComponentListener
ContainerListener
FocusListener
KeyListener
MouseListener
MouseMotionListener
WindowListener
669
13. AWT
Part I
670
The Abstract Window Toolkit (AWT)
The AWT contains numerous classes and
methods that allow you to create and
manage windows.
AWT Classes:
The AWT classes are contained in the
java.awt package. It is one of Java’s largest
packages. Fortunately, because it is logically
organized in a top-down, hierarchical fashion,
it is easier to understand and use than you
might at first believe.
671
Window Fundamentals
The AWT defines windows according to a
class hierarchy that adds functionality and
specificity with each level.
The two most common windows are those
derived from Panel, which is used by applets,
and those derived from Frame, which creates
a standard window. Much of the functionality
of these windows is derived from their parent
classes.
672
Component
At the top of the AWT hierarchy is the
Component class. Component is an abstract
class that encapsulates all of the attributes of
a visual component.
All user interface elements that are displayed
on the screen and that interact with the user
are subclasses of Component.
It defines over a hundred public methods that
are responsible for managing events, such as
mouse and keyboard input, positioning and
sizing the window, and repainting.
673
A Component object is
responsible for remembering
the current foreground and
background colors and the
currently selected text font.
674
Container
The Container class is a subclass of
Component. It has additional methods that
allow other Component objects to be nested
within it.
This makes for a multileveled containment
system. A container is responsible for laying
out (that is, positioning) any components that
it contains.
It does this through the use of various layout
managers.
675
Panel
The Panel class is a concrete subclass of
Container. It doesn’t add any new methods;
itsimply implements Container.
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.
676
Panel
Other components can be added to a
Panel object by its add( ) method
(inherited from Container).
Once these components have been
added, you can position and resize
them manually using the setLocation( ),
setSize( ), or setBounds( ) methods
defined by Component.
677
Window
This message warns users that the window they see
was started by an applet and not by software
running on their computer.
The Window class creates a top-level window. A toplevel window is not contained within any other
object; it sits directly on the desktop.
Generally, you won’t create Window objects directly.
Instead, you will use a subclass of Window called
Frame.
678
Frame
Frame encapsulates what is commonly
thought of as a “window.” It is a subclass of
Window and has a title bar, menu bar,
borders, and resizing corners.
If you create a Frame object from within an
applet, it will contain a warning message,
such as “Java Applet Window,” to the user
that an applet window has been created.
679
This message warns users that the
window they see was started by an
applet and not by software running on
their computer.
When a Frame window is created by a
program rather than an applet, a
normal window is created.
680
Working with Frame Windows
After the applet, the type of window you will
most often create is derived from Frame.
You will use it to create child windows within
applets, and top-level or child windows for
applications.
It creates a standard-style window.
Here are two of Frame’s constructors:
Frame( ) :The first form creates a standard
window that does not contain a title.
681
Frame(String title):The second form
creates a window with the title specified
by title.
Notice that you cannot specify the
dimensions of the window. Instead, you
must set the size of the window after it
has been created.
682
Setting the Window’s Dimensions
The setSize( ) method is used to set the
dimensions of the window.
Its signature is shown here:
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.
683
Setting the Window’s Dimensions
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 here:
Dimension getSize( )
This method returns the current size of the
window contained within the width and
height fields of a Dimension object.
684
Hiding and Showing a Window
After a frame window has been created,
it will not be visible until you call
setVisible( ). Its signature is shown
here:
void setVisible(boolean visibleFlag)
The component is visible if the
argument to this method is true.
Otherwise, it is hidden.
685
Setting a Window’s Title
You can change the title in a frame
window using setTitle( ), which has this
general form:
void setTitle(String newTitle):Here,
newTitle is the new title for the window.
686
Closing a Frame Window
When using a frame window, your program
must remove that window from the screen
when it is closed, by calling setVisible(false).
To intercept a window-close event, you must
implement the windowClosing( ) method of
the WindowListener interface.
Inside windowClosing( ), you must remove
the window from the screen.
Eg:AppletFrame.java
687
Handling Events in a Frame Window
Since Frame is a subclass of Component, it
inherits all the capabilities defined by
Component.
This means that you can use and manage a
frame window that you create just like you
manage your applet’s main window.
For example, you can override paint( ) to
display output, call repaint( ) when you need
to restore the window, and override all event
handlers.
688
Whenever an event occurs in a window, the
event handlers defined by that window will be
called.
Each window handles its own events. For
example, the following program creates a
window that responds to mouse events.
The main applet window also responds to
mouse events. When you experiment with
this program, you will see that mouse events
are sent to the window in which the event
occurs. eg:WindowEvents.java
689
Creating a Windowed Program
It is possible to create stand-alone
AWT-based applications.
To do this, simply create an instance of
the window or windows you need inside
main( ). For example, the following
program creates a frame window that
responds to mouse clicks and
keystrokes:
eg:AppWindow .java
690
Displaying Information Within a Window
In the most general sense, a window is
a container for information. Indeed,
much of the power of the AWT comes
from its support for these items..
691
Working with Graphics
The AWT supports a rich assortment of
graphics methods. All graphics are drawn
relative to a window. This can be the main
window of an applet, a child window of
an applet, or a stand-alone application
window.
The origin of each window is at the top-left
corner and is 0,0. Coordinates are specified in
pixels.
692
All output to a window takes place through a
graphics context. A graphics context is
encapsulated by the Graphics class and is
obtained in two ways:
It is passed to an applet when one of its
various methods, such as paint( ) or
update( ), is called.
It is returned by the getGraphics( ) method
of Component.
693
The Graphics class
Defines a number of drawing functions. Each
shape can be drawn edge-only or filled.
Objects are drawn and filled in the currently
selected graphics color, which is black by
default.
When a graphics object is drawn that exceeds
the dimensions of the window, output is
automatically clipped.
694
Drawing Lines
Different drawing methods are:
Lines are drawn by means of the drawLine( )
method, shown here:
void drawLine(int startX, int startY, int endX, int
endY)
drawLine( ) displays a line in the current
drawing color that begins at startX,startY and
ends at endX,endY.
695
Drawing Rectangles
The drawRect( ) and fillRect( ) methods
display an outlined and filled rectangle,
respectively. They are shown here:
void drawRect(int top, int left, int width, int
height)
void fillRect(int top, int left, int width, int
height)
The upper-left corner of the rectangle is at
top,left. The dimensions of the rectangle are
specified by width and height.
696
Drawing Rectangles
To draw a rounded rectangle, use
drawRoundRect( ) or fillRoundRect( ), both
shown here:
void drawRoundRect(int top, int left, int
width, int height,int xDiam, int yDiam)
void fillRoundRect(int top, int left, int width,
int height,int xDiam, int yDiam)
697
Drawing Rectangles
A rounded rectangle has rounded corners.
The upper-left corner of the rectangle is at
top,left. The dimensions of the rectangle are
specified by width and height.
The diameter of the rounding arc along the X
axis is specified by xDiam.
The diameter of the rounding arc along the Y
axis is specified by yDiam.
698
Drawing Ellipses and Circles
To draw an ellipse, use drawOval( ). To fill an
ellipse, use fillOval( ). General form is:
void drawOval(int top, int left, int width, int
height)
void fillOval(int top, int left, int width, int height)
The ellipse is drawn within a bounding
rectangle whose upper-left corner is specified
by top,left and whose width and height are
specified by width and height. To draw a circle,
specify a square as the bounding rectangle.
699
Drawing Arcs
Arcs can be drawn with drawArc( ) and fillArc(
), shown here:
void drawArc(int top, int left, int width, int
height, int startAngle,int sweepAngle)
void fillArc(int top, int left, int width, int height,
int startAngle,int sweepAngle)
The arc is bounded by the rectangle whose
upper-left corner is specified by top,left
and whose width and height are specified by
width and height.
700
Drawing Arcs
The arc is drawn from startAngle through the
angular distance specified by sweepAngle.
Angles are specified in degrees. Zero degrees
is on the horizontal, at the 3 o’clock position.
The arc is drawn counterclockwise if
sweepAngle is positive, and clockwise if
sweepAngle is negative.
Therefore, to draw an arc from 12 o’clock to
6 o’clock, the start angle would be 90 and the
sweep angle 180.
701
Drawing Polygons
To draw arbitrarily shaped figures use
drawPolygon( ) and fillPolygon( ),as shown.
void drawPolygon(int x[ ], int y[ ], int numPoints)
void fillPolygon(int x[ ], int y[ ], int numPoints).
The polygon’s endpoints are specified by the
coordinate pairs contained within the x & y arrays.
The number of points defined by x and y is
specified by numPoints.
702
Sizing Graphics
To size a graphics object to fit the current size
of the window in which it is drawn, first
obtain the current dimensions of the window
by calling getSize( ) on the window object.
It returns the dimensions of the window
encapsulated within a Dimension object.
Once you have the current size of the
window, you can scale your graphical output
accordingly.
703
Working with Color
Java supports color in a portable, deviceindependent fashion.
The AWT color system allows you to specify
any color you want. It then finds the best
match for that color,given the limits of the
display hardware currently executing your
program or applet.
Thus, your code does not need to be
concerned with the differences in the way
color is supported by various hardware
devices.
704
Working with Color
Color is encapsulated by the Color class.
Color defines several constants (for
example, Color.black) to specify a
number of common colors.
You can also create your own colors,
using one of the color constructors.
705
Working with Color
Color(int red, int green, int blue) :Takes three
integers that specify the color as a mix of red,
green,and blue. These values must be
between 0 and 255.Eg:
new Color(255, 100, 100); // light red.
Color(int rgbValue) :Takes a single integer
that contains the mix of red, green,and blue
packed into an integer. The integer is
organized with red in bits 16 to 23,green in
bits 8 to 15, and blue in bits 0 to 7.
706
Working with Color
Eg:
1. int newRed = (0xff000000 | (0xc0 << 16) |
(0x00 << 8) | 0x00);
2. Color(float red, float green, float blue):
3. Color darkRed = new Color(newRed);
Color(float, float, float), takes three float
values (between 0.0 and 1.0) that specify
the relative mix of red, green, and blue.
707
Once you have created a color, you can
use it to set the foreground and/or
background color by using the
setForeground( ) and setBackground( )
methods.
You can also select it as the current
drawing color.
708
Color Methods
The Color class defines several methods to p
manipulate colors. They are :.
Using Hue, Saturation, and Brightness
The hue-saturation-brightness (HSB) color
model is an alternative to red-green-blue
(RGB) for specifying particular colors.
Figuratively, hue is a wheel of color. The hue
is specified with a number between 0.0 and
1.0 (the colors are approximately: red,
orange,yellow, green, blue, indigo, and
violet).
709
Color Methods
Saturation is another scale ranging from 0.0
to 1.0, representing light pastels to intense
hues.
Brightness values also range from 0.0 to
1.0, where 1 is bright white and 0 is black.
Color supplies two methods that let you
convert between RGB and HSB.
1. static int HSBtoRGB(float hue, float
saturation, float brightness) HSBtoRGB( )
returns a packed RGB value compatible with
the Color(int) constructor
710
Color Methods
static float[ ] RGBtoHSB(int red, int green, int
blue, float values[ ])RGBtoHSB( ) returns a
float array of HSB values corresponding to
RGB integers.
If values is not null, then this array is given
the HSB values and returned.
Otherwise, a new array is created and the
HSB values are returned in it. In either case,
the array contains the hue at index 0,
saturation at index 1, and brightness at index
2.
711
getRed( ), getGreen( ), getBlue( )
You can obtain the red, green, and blue
components of a color independently using
getRed( ),getGreen( ),& getBlue( ),as shown:
int getRed( ),int getGreen( ),int getBlue( )
Each of these methods returns the RGB color
component found in the invoking Color object
in the lower 8 bits of an integer.
712
Int getRGB( ):To obtain a packed, RGB version
of a color, use getRGB( ).
Setting the Current Graphics Color:
By default, graphics objects are drawn in the
current foreground color.This may be changed
by calling the Graphics method setColor( ):
void setColor(Color newColor) :Here, newColor
specifies the new drawing color.
You can obtain the current color by calling
getColor( ):Color getColor( ); eg:ColorDemo.java
713
Working with Fonts
The AWT supports multiple type fonts. Fonts
have emerged from the domain of traditional
typesetting to become an important part of
computer-generated documents and displays.
The AWT provides flexibility by abstracting
font-manipulation operations and allowing for
dynamic selection of fonts.
Fonts have a family name, a logical font
name, and a face name.
714
Working with Fonts
The family name is the general name of
the font, such as Courier.
The logical name specifies a category
of font, such as Monospaced.
The face name specifies a specific
font,such as Courier Italic.
Fonts are encapsulated by the Font
class.
715
Working with Fonts
The Font class defines these variables:
Variable
Meaning
String name
Name of the font
float pointSize
Size of the font in
points
int size
Size of the font in
points
int style
Font style
716
Working with Fonts
Creating and Selecting a Font
To select a new font, you must first construct
a Font object that describes that font.
One Font constructor has this general form:
Font(String fontName, int fontStyle, int
pointSize): Here, fontName specifies the
name of the desired font. The name can be
specified using either the logical or face
name.
717
Working with Fonts
All Java environments will support the
following fonts:Dialog, DialogInput, Sans
Serif, Serif, Monospaced, and Symbol.
Dialog is the font used by your system’s
dialog boxes.
Dialog is also the default if you don’t explicitly
set a font.
You can also use any other fonts supported
by your particular environment, but these
other fonts may not be universally available.
718
Working with Fonts
The style of the font is specified by fontStyle.
It may consist of one or more of these three
constants: Font.PLAIN, Font.BOLD, and
Font.ITALIC. To combine styles, OR them
together.
For example, Font.BOLD | Font.ITALIC
specifies a bold, italics style.
The size, in points, of the font is specified by
pointSize.
719
Working with Fonts
To use a font that you have created, you
must select it using setFont( ), which is
defined by Component.
It has this general form:void setFont(Font
fontObj)
Here, fontObj is the object that contains the
desired font.
Eg:SampleFonts.java: The following program outputs a sample of each
standard font. Each time you click the mouse within its window, a new
font is selected and its name is displayed.
720
Obtaining Font Information
To obtain information about the currently
selected font you must first get the current
font by calling getFont( ).
This method is defined by the Font getFont( )
Once you have obtained the currently
selected font, you can retrieve information
about it using various methods defined by
Font.
721
14.AWT
Part II
722
Controls
Controls are components that allow a user to
interact with your application in various
ways—for example, a commonly used control
is the push button.
A layout manager automatically positions
components within a container.
Thus, the appearance of a window is
determined by a combination of the controls
that it contains and the layout manager used
to position them.
723
Control Fundamentals
The AWT supports the following types of
controls:
Labels
Push buttons
Check boxes
Choice lists
Lists
Scroll bars
Text editing
724
Adding and Removing Controls
To include a control in a window, you must
add it to the window.
To do this, you must first create an instance
of the desired control and then add it to a
window by calling add( ),which is defined by
Container.
The add( ) method has several forms.
Component add(Component compObj)Here,
compObj is an instance of the control that
you want to add. A reference to compObj is
returned.
725
Once a control has been added, it will
automatically be visible whenever its parent
window is displayed.
Sometimes you will want to remove a control
from a window when the control is no longer
needed. To do this, call remove( ).
This method is also defined by Container.
general form: void remove(Component
obj):Here, obj is a reference to the control you
want to remove. You can remove all controls by
calling removeAll( ).
726
Responding to Controls
Except for labels, which are passive controls,
all controls generate events when they are
accessed by the user.
For example, when the user clicks on a push
button, an event is sent that identifies the
push button.
In general, your program simply implements
the appropriate interface and then registers
an event listener for each control that you
need to monitor.
727
Labels
The easiest control to use is a label. A label is
an object of type Label, and it contains a
string, which it displays. Labels are passive
controls that do not support any interaction
with the user. Label defines the following
constructors:
Label( ):Label(String str) :The first version
creates a blank label Label(String str, int
how): The second version creates a label that
contains the string specified by str.
728
This string is left-justified. The third
version creates a label that contains the
string specified by str using the
alignment specified by how.
The value of how must be one of these
three constants: Label.LEFT,
Label.RIGHT, or Label.CENTER.
729
You can set or change the text in a label by
using the setText( ) method.
current label is obtained by calling getText( ).
These methods are :void setText(String str)
String getText( ):str specifies the new label.
You can set the alignment of the string within the
label by calling setAlignment( ).
730
To obtain the current alignment,
call getAlignment( ). The
methods are as follows:void
setAlignment(int how) int
getAlignment( ).
Eg:LabelDemo.java
731
Using Buttons
The most widely used control is the push button.
A push button is a component that contains a
label and that generates an event when it is
pressed. Push buttons are objects of type
Button.
2 constructors:
Button( ) :Creates an empty button.
Button(String str):Creates a button that contains
str as a label.
To set its label call setLabel( ).
To retrieve its label by call getLabel( ).
732
Handling Buttons
Each time a button is pressed, an action event is
generated. This is sent to any listeners that
previously registered an interest in receiving
action event notifications from that component.
Each listener implements the ActionListener
interface.
That interface defines the actionPerformed( )
method, which is called when an event occurs.
An ActionEvent object is supplied as the argument
to this method. It contains both a reference to
the button that generated the event and a
reference to the string that is the label of the
button.
733
Handling Buttons
Either value is used to identify the button.
Each time one is pressed, a message is
displayed that reports which button has been
pressed.
In this version, the label of the button is used
to determine which button has been pressed.
The label is obtained by calling the
getActionCommand( ) method on the
ActionEvent object passed to
actionPerformed( ). eg:ButtonDemo.java
734
We can also determine which button
has been pressed, by comparing the
object obtained from the getSource( ).
Method to the button objects that you
added to the window.
To do this, you must keep a list of the
objects when they are added.
Eg:ButtonList.java
735
Applying Check Boxes
A check box is a control that is used to turn
an option on or off.
It consists of a small box that can either
contain a check mark or not. There is a label
associated with each check box that describes
what option the box represents.
You change the state of a check box by
clicking on it. Check boxes can be used
individually or as part of a group. Check
boxes are objects of the Checkbox class.
736
Constructors
Checkbox( ) :Creates a check box whose label
is initially blank. The state of the check box is
unchecked.
Checkbox(String str) :The second form
creates a check box whose label is specified
by str.The state of the check box is
unchecked.
Checkbox(String str, boolean on): The third
form allows you to set the initial state of the
check box. If on is true, the check box is
initially checked; otherwise, it is cleared.
737
Constructors
Checkbox(String str, boolean on,
CheckboxGroup cbGroup)
Checkbox(String str, CheckboxGroup cbGroup,
boolean on)
Both create a check box whose label is
specified by str and whose group is specified
by cbGroup.
If this check box is not part of a group, then
cbGroup must be null.
738
Constructors
The value of on determines the initial
state of the check box.
To retrieve the current state of a check
box, call getState( ).
To set its state, call setState( ).
You can obtain the current label
associated with a check box by calling
getLabel( ).
To set the label, call setLabel( ).
739
Handling Check Boxes
Each time a check box is selected or
deselected, an item event is generated.
This is sent to any listeners that previously
registered an interest in receiving item event
notifications from that component.
Each listener implements the ItemListener
interface. That interface defines the
itemStateChanged( ) method.
740
Handling Check Boxes
An ItemEvent object is supplied as the
argument to this method. It contains
information about the event (for example,
whether it was a selection or deselection).
Eg: CheckboxDemo.java
741
CheckboxGroup
It is possible to create a set of mutually
exclusive check boxes in which one and only
one check box in the group can be checked at
any one time.
These check boxes are often called radio
buttons, because they act like the station
selector on a car radio—only one station can
be selected at any one time.
742
CheckboxGroup
To create a set of mutually exclusive check
boxes, you must first define the group to
which they will belong and then specify that
group when you construct the check boxes.
Check box groups are objects of type
CheckboxGroup. Only the default constructor
is defined, which creates an empty group.
You can determine which check box in a
group is currently selected by calling
getSelectedCheckbox( ).
743
CheckboxGroup
You can set a check box by calling
setSelectedCheckbox( ).
These methods are as follows:
Checkbox getSelectedCheckbox( )
void setSelectedCheckbox(Checkbox which):
Here, which is the check box that you want to
be selected. The previously selected check
box will be turned off.
Eg:CBGroup.java
744
Choice Controls
The Choice class is used to create a pop-up
list of items from which the user may choose.
Thus, a Choice control is a form of menu.
When inactive, a Choice component takes up
only enough space to show the currently
selected item.
When the user clicks on it, the whole list of
choices pops up, and a new selection can be
made. Each item in the list is a string that
appears as a left-justified label in the order it
is added to the Choice object.
745
Choice Controls
Choice only defines the default constructor,
which creates an empty list. To add a
selection to the list, call add( ). It has this
general form: void add(String name)
Here, name is the name of the item being
added. Items are added to the list in the
order in which calls to add( ) occur.
746
Choice Controls
To determine which item is currently selected,
you may call either getSelectedItem( ) or
getSelectedIndex( ). These methods are
shown here:
String getSelectedItem( ) :method returns a
string containing the name of the item.
int getSelectedIndex( ) returns the index of
the item. The first item is at index 0.
747
Choice Controls
By default, the first item added to the
list is selected.
To obtain the number of items in the
list, call getItemCount( ).
You can set the currently selected item
using the select( ) method with either a
zero-based integer index or a string
that will match a name in the list.
748
Choice Controls
These methods are shown here:
int getItemCount( ):
void select(int index)
void select(String name)
Given an index, you can obtain the name
associated with the item at that index by
calling getItem( ), which has this general form:
String getItem(int index) Here, index specifies
the index of the desired item.
749
Handling Choice Lists
Each time a choice is selected, an item event
is generated.
This is sent to any listeners that previously
registered an interest in receiving item event
notifications from that component.
Each listener implements the ItemListener
interface. That interface defines the
itemStateChanged( ) method.
An ItemEvent object is supplied as the
argument to this method.eg:
750
Using Lists
The List class provides a compact, multiplechoice, scrolling selection list.
Unlike the Choice object, which shows only
the single selected item in the menu, a List
object can be constructed to show any
number of choices in the visible window.
It can also be created to allow multiple
selections. List provides these constructors:
List( ): Creates a List control that allows only
one item to be selected at any one time.
751
Using Lists
List(int numRows) :Here the value of
numRows specifies the number of entries in
the list that will always be visible (others can
be scrolled into view as needed).
List(int numRows, boolean multipleSelect):
Here if multipleSelect is true, then the user
may select two or more items at a time.
If it is false, then only one item may be
selected.
752
Using Lists
To add a selection to the list, call add( ). It
has the following two forms:
void add(String name) :Adds items to the end
of the list.
void add(String name, int index) :Adds the
item at the index specified by index.
Here, name is the name of the item added to
the list.
Indexing begins at zero. You can specify –1
to add the item to the end of the list.
753
Handling Lists
To process list events, the ActionListener
interface is to be implemented.
Each time a List item is double-clicked, an
ActionEvent object is generated.
Its getActionCommand( ) method can be
used to retrieve the name of the newly
selected item.
Also, each time an item is selected or
deselected with a single click, an ItemEvent
object is generated.
754
Its getStateChange( ) method can be
used to determine whether a selection
or deselection triggered this event.
getItemSelectable( ) returns a reference
to the object that triggered this event.
Eg:ListDemo.java
755
Managing Scroll Bars
Scroll bars are used to select continuous
values between a specified minimum and
maximum. Scroll bars may be oriented
horizontally or vertically.
A scroll bar is actually a composite of several
individual parts. Each end has an arrow that
you can click to move the current value of the
scroll bar one unit in the direction of the
arrow.
756
The current value of the scroll bar relative to
its minimum and maximum values is indicated
by the slider box (or thumb) for the scroll bar.
The slider box can be dragged by the user to a
new position. The scroll bar will then reflect
this value.
In the background space on either side of the
thumb, the user can click to cause the thumb
to jump in that direction by some increment
larger than 1.
757
Typically, this action translates into some
form of page up and page down.
Scroll bars are encapsulated by the Scrollbar
class. Constructors Are:
Scrollbar( ) :creates a vertical scroll bar.
Scrollbar(int style): and
Scrollbar(int style, int initialValue, int
thumbSize, int min, int max)
The second and third forms allow you to
specify the orientation of the scroll bar.
758
If style is Scrollbar.VERTICAL, a vertical scroll
bar is created. If style is scrollbar.HORIZONTAL,
the scroll bar is horizontal.
In the third form of the constructor, the initial
value of the scroll bar is passed in initialValue.
The number of units represented by the height
of the thumb is passed in thumbSize.
The minimum and maximum values for the
scroll bar are specified by min and max.
759
If you construct a scroll bar by using one of
the first two constructors, then you need to
set its parameters by using setValues( ),
shown here, before it can be used:
void setValues(int initialValue, int thumbSize,
int min, int max)
760
Handling Scroll Bars
To process scroll bar events, you need to
implement the AdjustmentListener interface.
Each time a user interacts with a scroll bar, an
AdjustmentEvent object is generated.
Its getAdjustmentType( ) method can be used
to determine the type of the adjustment.
The types of adjustment events are as follows:
BLOCK_DECREMENT A page-down event has
been generated.
761
BLOCK_INCREMENT A page-up event has
been generated.
TRACK :An absolute tracking event has been
generated.
UNIT_DECREMENT The line-down button in a
scroll bar has been pressed.
UNIT_INCREMENT The line-up button in a
scroll bar has been pressed.
Eg:SBDemo.java
762
Using a TextField
The TextField class implements a single-line
text-entry area, usually called an edit control.
Text fields allow the user to enter strings and
to edit the text using the arrow keys, cut and
paste keys, and mouse selections.
TextField is a subclass of TextComponent.
Constructors are:
TextField( ):Creates a default text field.
TextField(int numChars): Creates a text field
that is numChars characters wide.
763
Using a TextField
TextField(String str):Initializes the text field
with the string contained in str.
TextField(String str, int numChars):Initializes
a text field and sets its width.
To obtain the string currently contained in the
text field, call getText( ). To set the text, call
setText( ).
Your program can obtain the currently
selected text by calling getSelectedText( ).
764
Using a TextField
These methods are:String getSelectedText( )
& void select(int startIndex, int endIndex)
getSelectedText( ) returns the selected text.
The select( ) method selects the characters
beginning at startIndex and ending at
endIndex–1.
You can control whether the contents of a
text field may be modified by the user by
calling setEditable( ).
765
Using a TextField
You can determine editability by calling
isEditable( ). These methods are :
boolean isEditable( ) :returns true if the text
may be changed and false if not.
void setEditable(boolean canEdit): if canEdit
is true, the text may be changed. If it is false,
the text cannot be altered.
You can disable the echoing of the characters
as they are typed by calling setEchoChar( ).
766
This method specifies a single character that the
TextField will display when characters are
entered(thus, the actual characters typed will not be
shown).
Echo character may be retrieved by calling the
getEchoChar( ) method.These methods are:
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( ) :Here, ch specifies the
character to be echoed. eg:TextFieldDemo.java
767
Using a TextArea
The AWT includes a simple multiline editor
called TextArea. Constructors for TextArea:
TextArea( )
TextArea(int numLines, int numChars)
TextArea(String str)
TextArea(String str, int numLines, int
numChars)
TextArea(String str, int numLines, int
numChars, int sBars)
768
Using a TextArea
Here, numLines specifies the height, in lines,
of the text area, and numChars specifies its
width, in characters.
Initial text can be specified by str. In the fifth
form you can specify the scroll bars that you
want the control to have. sBars must be one
of these values:
SCROLLBARS_BOTH SCROLLBARS_NONE
SCROLLBARS_HORIZONTAL_ONLY
SCROLLBARS_VERTICAL_ONLY
769
Using a TextArea
TextArea is a subclass of TextComponent.
Therefore, it supports the getText( ),setText( ),
getSelectedText( ), select( ), isEditable( ), and
setEditable( ).
TextArea adds the following methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, int
endIndex):
eg:TextAreaDemo.java
770
Understanding Layout Managers
A layout manager automatically arranges your
controls within a window by using some type
of algorithm.
Each Container object has a layout manager
associated with it.
A layout manager is an instance of any class
that implements the LayoutManager
interface.
The layout manager is set by the setLayout( )
method.
771
Understanding Layout Managers
If no call to setLayout( ) is made, then the
default layout manager is used.
Whenever a container is resized (or sized for
the first time), the layout manager is used to
position each of the components within it.
The setLayout( ) method has the following
general form:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired
layout manager.
772
To disable the layout manager and position
components manually, pass null for layoutObj.
If you do this, you will need to determine the
shape and position of each component
manually,using the setBounds( ) method
defined by Component. Each layout manager
keeps track of a list of components that are
stored by their names.
The layout manager is notified each time you
add a component to a container.
773
FlowLayout
It is the default layout manager. FlowLayout
implements a simple layout style, which is
similar to how words flow in a text editor.
Components are laid out from the upper-left
corner, left to right and top to bottom. When
no more components fit on a line, the next
one appears on the next line.
774
FlowLayout
A small space is left between each
component, above and below, as well as left
and right. Here are the constructors:
FlowLayout( ):Creates the default layout,
which centers components and leaves five
pixels of space between each component.
FlowLayout(int how): lets you specify how
each line is aligned. Valid values for how are
as follows: FlowLayout.LEFT,
FlowLayout.CENTER,FlowLayout.RIGHT
775
FlowLayout
These values specify left, center, and right
alignment, respectively.
FlowLayout(int how, int horz, int vert)
Allows you to specify the horizontal and
vertical space left between components in
horz and vert, respectively.
Eg:FlowLayoutDemo.java
776
BorderLayout
The BorderLayout class implements a
common layout style for top-level windows.
It has four narrow, fixed-width components
at the edges and one large area in the center.
The four sides are referred to as north, south,
east, and west. The middle area is called
the center. Here are the constructors defined
by BorderLayout:
777
BorderLayout( ):creates a default borderlayout.
BorderLayout(int horz, int vert):allows you to
specify the horizontal and vertical space left
between components in horz and vert,
respectively.
BorderLayout defines the following constants
that specify the regions:
BorderLayout.CENTER BorderLayout.SOUTH
BorderLayout.EAST BorderLayout.WEST
BorderLayout.NORTH. Eg:BorderLayoutDemo
778
Using Insets
Sometimes you will want to leave a small
amount of space between the container that
holds your components and the window that
contains it.
To do this, override the getInsets( ) method
that is defined by Container.
This function returns an Insets object that
contains the top, bottom, left, and right inset
to be used when the container is displayed.
These values are used by the layout manager
to inset the components when it lays out the
779
window.
GridLayout
GridLayout lays out components in a twodimensional grid.
When you instantiate a GridLayout, you define
the number of rows and columns. The
constructors are:
GridLayout(): creates a single-column grid layout.
GridLayout(int numRows, int numColumns )
:creates a grid layout with the specified
number of rows and columns.
780
GridLayout(int numRows, int numColumns,
int horz, int vert):allows you to specify the
horizontal and vertical space left between
components in horz and vert,respectively.
Either numRows or numColumns can be zero.
Specifying numRows as zero allows for
unlimited-length columns. Specifying
numColumns as zero allows for unlimitedlength rows.
781
Menu Bars and Menus
A top-level window can have a menu bar
associated with it. A menu bar displays a list of
top-level menu choices. Each choice is
associated with a drop-down menu.
This concept is implemented in Java by the
following classes: MenuBar, Menu, and
MenuItem.
Each Menu object in the menu bar contains a
list of MenuItem objects. Each MenuItem
object represents something that can be
selected by the user.
782
These are menu options of type
CheckboxMenuItem and will have a check
mark next to them when they are selected. To
create a menu bar, first create an instance of
MenuBar. This class only defines the default
constructor.
Next, create instances of Menu that will define
the selectionsdisplayed on the bar. Following
are the constructors for Menu:Menu(
),Menu(String optionName)
Menu(String optionName, boolean removable)
783
Here, optionName specifies the name of the
menu selection. If removable is true, the popup menu can be removed and allowed to float
free.
Otherwise, it will remain attached to the
menu bar. (Removable menus are
implementation-dependent.) The first form
creates an empty menu.
Individual menu items are of type MenuItem.
It defines these constructors:
784
MenuItem( )
MenuItem(String itemName)
MenuItem(String itemName, MenuShortcut
keyAccel)
Here, itemName is the name shown in the
menu, and keyAccel is the menu shortcut for
this item.
You can disable or enable a menu item by
using the setEnabled( ) method. Its form
is shown here:
785
void setEnabled(boolean enabledFlag)
If the argument enabledFlag is true, the
menu item is enabled. If false, the menu item
is disabled.
You can determine an item’s status by calling
isEnabled( ). This method is
shown here: boolean isEnabled( )
isEnabled( ) returns true if the menu item on
which it is called is enabled. Otherwise,
it returns false.
786
You can change the name of a menu item by
calling setLabel( ). You can retrieve the
current name by using getLabel( ).
These methods are as follows:
void setLabel(String newName)
String getLabel( ) Here, newName becomes
the new name of the invoking menu item.
getLabel( ) returns the current name.
787
Dialog Boxes
Dialog box is used to hold a set of related
controls.
Dialog boxes are primarily used to obtain user
input. They are similar to frame windows,
except that dialog boxes are always child
windows of a top-level window.
Also, dialog boxes don’t have menu bars. In
other respects, dialog boxes function like
frame windows.
788
Dialog boxes may be modal or modeless.
When a modal dialog box is active, all input is
directed to it until it is closed. This means
that you cannot access other parts of your
program until you have closed the dialog
box.
789
When a modeless dialog box is active, input
focus can be directed to another window in
your program.
Thus, other parts of your program remain
active and accessible. Dialog boxes are of
type Dialog.
790
15.SWING
791
AbstractButton
ButtonGroup
ImageIcon
JApplet
JButton
JCheckBox
JComboBox
list
Abstract superclass for Swing
buttons.
Encapsulates a mutually exclusive
set of buttons.
Encapsulates an icon.
The Swing version of Applet.
The Swing push button class.
The Swing check box class.
Encapsulates a combo box (an
combination of a drop-down
and text field).
792
JLabel
JRadioButton
JScrollPane
JTabbedPane
JTable
JTextField
JTree
The Swing version of a label.
The Swing version of a radio
button.
Encapsulates a scrollable window.
Encapsulates a tabbed window.
Encapsulates a table-based
control.
The Swing version of a text field.
Encapsulates a tree-based
control.
793
JApplet
Fundamental to Swing is the JApplet class,
which extends Applet. Applets that use Swing
must be subclasses of JApplet.
JApplet is rich with functionality that is not
found in Applet. For example, JApplet
supports various “panes,” such as the content
pane, the glass pane, and the root pane.
794
When adding a component to an instance of
JApplet, do not invoke the add( ) method of
the applet.
Instead, call add( ) for the content pane of
the JApplet object. The content pane can be
obtained via the method - Container
getContentPane( )
The add( ) method of Container can be used
to add a component to a content pane. void
add(comp):Here, comp is the component to
be added to the content pane.
795
Icons and Labels
In Swing, icons are encapsulated by the
ImageIcon class, which paints an icon from
an image.
Two of its constructors are shown here:
ImageIcon(String filename)
ImageIcon(URL url)
The first form uses the image in the file
named filename. The second form uses the
image in the resource identified by url.
796
ImageIcon
The ImageIcon class implements the Icon
interface that declares the methods:
int getIconHeight( ) :Returns the height of the icon
in pixels.
int getIconWidth( ) Returns the width of the icon
in pixels.
void paintIcon(Component comp, Graphics g,
int x, int y)
797
Paints the icon at position x, y on the
graphics context g.
Additional information about the paint
operation can be provided in comp.
Swing labels are instances of the JLabel class,
which extends JComponent. It can display
text and/or an icon. Some of its constructors
are shown here:
JLabel(Icon i),Label(String s)
JLabel(String s, Icon i, int align)
798
Here, s and i are the text and icon used for the
label. The align argument is either LEFT,RIGHT,
CENTER, LEADING, or TRAILING. These
constants are defined in the,SwingConstants
interface, along with several others used by the
Swing classes.
The icon and text associated with the label can
be read and written by the following
methods:Icon getIcon( ),String getText( ),void
setIcon(Icon i),void setText(String s),Here, i and
s are the icon and text, respectively.
799
Text Fields
The Swing text field is encapsulated by the
JTextComponent class, which extends
JComponent.
It provides functionality that is common to
Swing text components.
One of its subclasses is JTextField, which allows
you to edit one line of text.
JTextField( ) : Here, s is the string to be
presented, and cols is the number of columns in
the text field. JTextField(String s)
JTextField(int cols)
JTextField(String s, int cols)
800
Buttons
Swing buttons provide features that are not
found in the Button class defined by the AWT.
For example, you can associate an icon with a
Swing button. Swing buttons are subclasses of
the AbstractButton class, which extends
JComponent.
AbstractButton contains many methods that
allow you to control the behavior of buttons,
check boxes, and radio buttons.
For example, you can define different icons that
are displayed for the component when it is
disabled, pressed, or selected.
801
Buttons
The following are the methods that
control this behavior:
void setDisabledIcon(Icon di)
void setPressedIcon(Icon pi)
void setSelectedIcon(Icon si)
void setRolloverIcon(Icon ri)
Here, di, pi, si, and ri are the icons to
be used for these different conditions.
802
Buttons
The text associated with a button can be read
and written via the following methods:
String getText( ),void setText(String s)
Here, s is the text to be associated with the
button.
Concrete subclasses of AbstractButton generate
action events when they are pressed.
Listeners register and unregister for these
events via the methods shown here:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
803
Buttons
Here, al is the action listener.AbstractButton is
a superclass for push buttons, check boxes,
and radio buttons.
The JButton Class
The JButton class provides the functionality of
a push button. JButton allows an icon,a
string, or both to be associated with the push
button. constructors :
JButton(Icon i),JButton(String s)
JButton(String s, Icon i) Here, s and i are the
string and icon used for the button.
804
Check Boxes
The JCheckBox class, which provides the
functionality of a check box, is a concrete
implementation of AbstractButton.
Its immediate superclass is JToggleButton, which
provides support for two-state buttons.
constructors are :JCheckBox(Icon i),
JCheckBox(Icon i, boolean state)
JCheckBox(String s),JCheckBox(String s, boolean
state),JCheckBox(String s, Icon i)
JCheckBox(String s, Icon i, boolean state)
805
Check Boxes
Here, i is the icon for the button. The text is
specified by s. If state is true, the check box
is initially selected. Otherwise, it is not.
The state of the check box can be changed
via the following method:
void setSelected(boolean state)
Here, state is true if the check box should be
checked.
806
Radio Buttons
Radio buttons are supported by the
JRadioButton class, which is a concrete
implementation of AbstractButton.
Its immediate superclass is JToggleButton,
which provides support for two-state buttons.
constructors are :
JRadioButton(Icon i),
JRadioButton(Icon i, boolean state)
JRadioButton(String s),
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
807
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is
specified by s. If state is true, the button is
initially selected. Otherwise, it is not.
Radio buttons must be configured into a
group. Only one of the buttons in that
group can be selected at any time.
808
The ButtonGroup class is instantiated to
create a button group.
Its default constructor is invoked for this
purpose. Elements are then added to the
button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be
added to the group.
809
Combo Boxes
Swing provides a combo box (a combination
of a text field and a drop-down list) through
the JComboBox class, which extends
JComponent.
A combo box normally displays one entry.
However, it can also display a drop-down list
that allows a user to select a different entry.
You can also type your selection into the text
field. constructors are
JComboBox( )
810
JComboBox(Vector v)
Here, v is a vector that initializes the combo
box.
Items are added to the list of choices via the
addItem( ) method, whose signature is
shown here:
void addItem(Object obj)
Here, obj is the object to be added to the
combo box.
811
Tabbed Panes
A tabbed pane is a component that appears
as a group of folders in a file cabinet.
Each folder has a title. When a user selects
a folder, its contents become visible. Only one
of the folders may be selected at a time.
Tabbed panes are commonly used for setting
configuration options.
Tabbed panes are encapsulated by the
JTabbedPane class, which extends
JComponent.
812
Tabs are defined via the following method:
void addTab(String str, Component comp)
Here, str is the title for the tab, and comp is
the component that should be added to the
tab. Typically, a JPanel or a subclass of it is
added.
The general procedure to use a tabbed pane
in an applet is outlined here:1. Create a
JTabbedPane object.
813
2. Call addTab( ) to add a tab to
the pane. (The arguments to this
method define the title of the tab
and the component it contains.)
3. Repeat step 2 for each tab.
4. Add the tabbed pane to the
content pane of the applet.
814
Scroll Panes
Is a component that presents a rectangular area
in which a component may be viewed.
Horizontal and/or vertical scroll bars may be
provided if necessary.
Scroll panes are implemented in Swing by the
JScrollPane class, which extends
JScrollPane(Component comp)
JScrollPane(int vsb, int hsb)
JScrollPane(Component comp, int vsb, int hsb)
Here, comp is the component to be added to the
scroll pane. vsb and hsb are int
815
constants that define when vertical and
horizontal scroll bars for this scroll pane are
given next:
These constants are defined by the
ScrollPaneConstants interface. Some examples
of these constants are described as follows:
1.HORIZONTAL_SCROLLBAR_ALWAYS :Always
provide horizontal scroll bar
2.HORIZONTAL_SCROLLBAR_AS_NEEDED :
Provide horizontal scroll bar,if needed.
3.VERTICAL_SCROLLBAR_ALWAYS:Always
provide vertical scroll bar
816
4. VERTICAL_SCROLLBAR_AS_NEEDED Provide
vertical scroll bar.
if needed Here are the steps that you should
follow to use a scroll pane in an applet:
1. Create a JComponent object.
2. Create a JScrollPane object. (The
arguments to the constructor specify the
component and the policies for vertical and
horizontal scroll bars.)
3. Add the scroll pane to the content pane of
the applet
817
Trees
A tree is a component that presents a
hierarchical view of data. A user has the
ability to expand or collapse individual
subtrees in this display.
Trees are implemented in Swing by the JTree
class, which extends JComponent. Some of
its constructors are :
JTree(Hashtable ht): Creates a tree in which
each element of the hash table ht is a child
node.
818
JTree(Object obj[ ]): Each element of
the array obj is a child node Here.
JTree(TreeNode tn) :The tree node tn is
the root of the tree in this form.
JTree(Vector v):This form uses the
elements of vector v as child nodes.
819
A JTree object generates events when a node is
expanded or collapsed.
The addTreeExpansionListener( ) and
removeTreeExpansionListener( ) methods allow
listeners to register and unregister for these
notifications.
The signatures of these methods are shown : void
addTreeExpansionListener(TreeExpansionListener
tel)
Void
removeTreeExpansionListener(TreeExpansionListen
er tel)
Here, tel is the listener object.
820
The getPathForLocation( ) method is used to
translate a mouse click on a specific
point of the tree to a tree path.
Its signature is shown here:
TreePath getPathForLocation(int x, int y)
Here, x and y are the coordinates at which
the mouse is clicked. The return value is a
TreePath object that encapsulates information
about the tree node that was selected by the
user.
821
Tables
A table is a component that displays rows and
columns of data.
You can drag the cursor on column
boundaries to resize columns.
You can also drag a column to a new
position. Tables are implemented by the
JTable class, which extends JComponent.
One of its constructors is shown here:
JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the
information to be presented, and colHeads is
a one-dimensional array with the column
822
headings.
Here are the steps for using a table in an
applet:
1. Create a JTable object.
2. Create a JScrollPane object. (The
arguments to the constructor specify the
table
and the policies for vertical and horizontal
scroll bars.)
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of
the applet.
823
16. String Handling
824
String
Java implements strings as objects of type String.
when you create a String object, you are
creating a string that cannot be changed. That
is, once a String object has been created, you
cannot change the characters that comprise
that string.
Both the String and StringBuffer classes are
defined in java.lang. Thus, they are available to
all programs automatically. Both are declared
final, which means that neither of these classes
may be subclassed.
825
The String Constructors
The String class supports several
constructors. To create an empty String, you
call the default constructor. For example,
String s = new String();
will create an instance of String with no
characters in it.
Frequently, you will want to create strings
that have initial values.
826
The String class provides a variety of
constructors to handle this.
To create a String initialized by an array of
characters, use the constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string
“abc”.
827
You can specify a subrange of a character
array as an initializer using the following
constructor:
String(char chars[ ], int startIndex, int
numChars): Here, startIndex specifies the
index at which the subrange begins, and
numChars specifies the number of characters
to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
This initializes s with the characters cde.
828
You can construct a String object that
contains the same character sequence as
another String object using this constructor:
String(String strObj)
Here, strObj is a String object. Consider this
example:
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
829
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
830
String Length
The length of a string is the number of
characters that it contains. To obtain this
value, call the length( ) method, shown here:
int length( )
The following fragment 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());
831
Special String Operations
Because strings are a common and important
part of programming, Java has added
special support for several string operations
within the syntax of the language.
These operations include the automatic
creation of new String instances from string
literals,concatenation of multiple String
objects by use of the + operator, and the
conversion of other data types to a string
representation.
832
There are explicit methods available to
perform all of these functions, but Java
does them automatically as a
convenience for the programmer and to
add clarity.
833
String Literals
However, there is an easier way to do this
using to create a String instance from an
array of a string literal.
For each string literal in your program, Java
automatically constructs a String object.
Thus, you can 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
834
Because a String object is created for every
string literal, you can use a string literal any
place you can use a String object. For
example, you can call methods directly on a
quoted string as if it were an object
reference, as the following statement shows.
It calls the length( ) method on the string
“abc”. As expected, it prints “3”.
System.out.println("abc".length());
835
String Concatenation
In general, 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 you to chain together a series of
+ operations. For example, the following
fragment concatenates three strings:
String age = "9";
String s = "He is " + age + " years old.";
836
System.out.println(s);
This displays the string “He is 9 years old.”
One practical use of string concatenation is
found when you are creating very long
strings. Instead of letting long strings wrap
around within your source code, you can
break them into smaller pieces, using the +
to concatenate them
837
// Using concatenation to prevent long lines.
class ConCat {
public static void main(String args[]) {
String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation "
+
"prevents this.";
System.out.println(longStr);}}
838
String Concatenation with Other Data
Types
You can concatenate strings with other types
of data.
For example, consider this slightly different
version of the earlier 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.
839
This is because the int value in age is
automatically converted into its
string representation within a String object.
This string is 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.
Be careful when you mix other types of
operations with string concatenation
expressions, however.
840
String Conversion and toString( )
When Java converts data into its string
representation during concatenation, it does
so by calling one of the overloaded versions
of the string conversion method valueOf( )
defined by String.
valueOf( ) is overloaded for all the simple
types and for type Object. For the simple
types, valueOf( ) returns a string that
contains the human-readable equivalent of
the value with which it is called.
841
For objects, valueOf( ) calls the toString( )
method on the object.
Here, let’s examine the toString( ) method,
because it is the means by which you can
determine the string representation for
objects of classes that you create.
Every class implements toString( ) because it
is defined by Object. However, the
default implementation of toString( ) is
seldom sufficient.
842
For most important classes that you create,
you will want to override toString( ) and
provide your own string representations.
Fortunately, this is easy to do.
The toString( ) method has this general form:
String toString( ) To implement toString( ),
simply return a String object that contains the
humanreadable string that appropriately
describes an object of your class.
843
By overriding toString( ) for classes that
you create, you allow them to be fully
integrated into Java’s programming
environment. For example, they can be
used in
print( ) and println( ) statements and in
concatenation expressions.
844
Character Extraction
The String class provides a number of ways in
which characters can be extracted from
a String object.
Although the characters that comprise a
string within a String object cannot be
indexed as if they were a character array,
many of the String methods employ an index
(or offset) into the string for their operation.
Like arrays, the string indexes begin at zero.
845
charAt( )
To extract a single character from a String,
you can refer directly to an individual
character via the charAt( ) method. It has this
general form:char charAt(int where)
Here, where is the index of the character that
you want to obtain. The value of where
must be nonnegative and specify a location
within the string. charAt( ) returns the
character at the specified location.
846
For example,
char ch;
ch = "abc".charAt(1);
assigns the value “b” to ch
getChars( )
847
If you need to extract more than one
character at a time, you can use the
getChars( ) method.
It has this general form: void getChars(int
sourceStart, int sourceEnd, char target[ ], int
targetStart)
Here, sourceStart specifies the index of the
beginning of the substring, and sourceEnd
specifies an index that is one past the end of
the desired substring.
848
Thus, the substring contains the characters
from sourceStart through sourceEnd–1. The
array that will receive the characters is
specified by target.
The index within target at which the substring
will be copied is passed in targetStart. Care
must be taken to assure that the target array
is large enough to hold the number of
characters in the specified substring.
849
The following program demonstrates
getChars( ):
class getCharsDemo {
public static void main(String args[]) {String s
= "This is a demo of the getChars method.";
int start = 10;int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);}}
850
getBytes( ):
There is an alternative to getChars( ) that
stores the characters in an array of bytes.
This method is called getBytes( ), and it uses
the default character-to-byte conversions
provided by the platform. Here is its simplest
form: byte[ ] getBytes( )
Other forms of getBytes( ) are also available.
851
getBytes( ) is most useful when you are
exporting a String value into an environment
that does not support 16-bit Unicode
characters.
For example, most Internet protocols and text
file formats use 8-bit ASCII for all text
interchange. toCharArray( )
If you want to convert all the characters in a
String object into a character array, the
easiest way is to call toCharArray( ).
852
It returns an array of characters for the entire
string. It has this general form:
char[ ] toCharArray( )
This function is provided as a convenience,
since it is possible to use getChars( ) to
achieve the same result. String Comparison
The String class includes several methods
that compare strings or substrings within
strings.equals( ) and equalsIgnoreCase( )
853
To compare two strings for equality, use
equals( ). It has this general form:
boolean equals(Object str)
Here, str is the String object being compared
with the invoking String object.
It returns true if the strings contain the same
characters in the same order, and false
otherwise. The comparison is case-sensitive.
854
To perform a comparison that ignores case
differences, call equalsIgnoreCase( ).
When it compares two strings, it considers AZ to be the same as a-z. It has this
general form: boolean
equalsIgnoreCase(String str)
Here, str is the String object being compared
with the invoking String object. It, too,
returns true if the strings contain the same
characters in the same order, and false
otherwise.
855
regionMatches( ):The regionMatches( )
method compares a specific region inside a
string with another specific region in another
string.
There is an overloaded form that allows you
to ignore case in such comparisons. Here are
the general forms for these two methods:
boolean regionMatches(int startIndex, String
str2,int str2StartIndex, int numChars)
856
boolean regionMatches(boolean ignoreCase,
int startIndex, String str2, int str2StartIndex,
int numChars)
For both versions, startIndex specifies the
index at which the region begins within
the invoking String object. The String being
compared is specified by str2. The index
at which the comparison will start within str2
is specified by str2StartIndex.
857
The length of the substring being compared
is passed in numChars. In the second version,
if ignoreCase is true, the case of the
characters is ignored. Otherwise, case is
significant. startsWith( ) and endsWith( )
String defines two routines that are, more or
less, specialized forms of regionMatches( ).
The startsWith( ) method determines whether
a given String begins with a specified string.
858
Conversely, endsWith( ) determines whether
the String in question ends with a specified
string. They have the following general
forms:boolean startsWith(String str)
boolean endsWith(String str)
Here, str is the String being tested. If the
string matches, true is returned. Otherwise,
false is returned. For example,
"Foobar".endsWith("bar") and
"Foobar".startsWith("Foo")are both true.
859
A second form of startsWith( ), shown here,
lets you specify a starting point:
boolean startsWith(String str, int startIndex)
Here, startIndex specifies the index into the
invoking string at which point the search
will begin. For example,
"Foobar".startsWith("bar", 3)
returns true
equals( ) Versus ==
860
It is important to understand that the equals(
) method and the == operator perform
two different operations. As just explained,
the equals( ) method compares the
characters inside a String object. The ==
operator compares two object references to
see whether they refer to the same instance.
The following program shows how two
different String objects can contain the same
characters, but references to these objects
will not compare as equal:
861
// equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " > " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> "
+ (s1 == s2));} }
862
The variable s1 refers to the String instance
created by “Hello”. The object
referred to by s2 is created with s1 as an
initializer. Thus, the contents of the two
String objects are identical, but they are
distinct objects. This means that s1 and s2
do not refer to the same objects and are,
therefore, not ==, as is shown here by the
output of the preceding example:
Hello equals Hello -> true
Hello == Hello -> false
863
compareTo( ) Often, it is not enough to
simply know whether two strings are
identical.
For sorting applications, you need to know
which is less than, equal to, or greater than
the next.
A string is less than another if it comes before
the other in dictionary order. A string is
greater than another if it comes after the
other in dictionary order. The String method
compareTo( ) serves this purpose.
864
It has this general form:
int compareTo(String str)
Here, str is the String being compared with
the invoking String. The result of the
comparison is returned and is interpreted as
shown here:Value Meaning
Less than zero The invoking string is less than
str.Greater than zero The invoking string is
greater than str.Zero The two strings are
equal.Here is a sample program that sorts an
array of strings
865
If you want to ignore case differences
when comparing two strings, use
compareToIgnoreCase( ), shown here:
int compareToIgnoreCase(String str)
This method returns the same results as
compareTo( ), except that case
differences are ignored.
866
Searching Strings
The String class provides two methods that
allow you to search a string for a
specifiedcharacter or substring:
indexOf( ) Searches for the first occurrence of
a character or substring.
lastIndexOf( ) Searches for the last
occurrence of a character or substring.
These two methods are overloaded in several
different ways.
867
In all cases, the methods
return the index at which the character or
substring was found, or –1 on failure.
To search for the first occurrence of a
character, use int indexOf(int ch)
To search for the last occurrence of a
character, use int lastIndexOf(int ch)
Here, ch is the character being sought.
868
To search for the first or last occurrence of a
substring, use int indexOf(String str)
int lastIndexOf(String str)
Here, str specifies the substring.
You can specify a starting point for the search
using these forms:
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
869
Here, startIndex specifies the index at
which point the search begins. For
indexOf( ),
the search runs from startIndex to the
end of the string. For lastIndexOf( ),
the search
runs from startIndex to zero.
indexOfDemo.java
870
Modifying a String
Because String objects are immutable,
whenever you want to modify a String, you
must either copy it into a StringBuffer or use
one of the following String methods,
which will construct a new copy of the string
with your modifications complete.
substring( )
You can extract a substring using substring( ).
It has two forms. The first is
String substring(int startIndex)
871
Here, startIndex specifies the index at which
the substring will begin. This form returns a
copy of the substring that begins at
startIndex and runs to the end of the
invoking string.
The second form of substring( ) allows you to
specify both the beginning and
ending index of the substring:
String substring(int startIndex, int endIndex)
872
Here, startIndex specifies the beginning
index, and endIndex specifies the
stopping
point. The string returned contains all
the characters from the beginning
index, up to,
but not including, the ending index.
StringReplace.java
873
concat( ):You can concatenate two strings
using concat( ), shown here:
String concat(String str)
This method creates a new object that
contains the invoking string with the contents
of str appended to the end. concat( )
performs the same function as +. For
example, String s1 = "one";
String s2 = s1.concat("two"); puts the string
“onetwo” into s2.
874
It generates the same result as the following
sequence:String s1 = "one";
String s2 = s1 + "two";
replace( )
The replace( ) method replaces all
occurrences of one character in the invoking
string with another character. It has the
following general form:
String replace(char original, char
replacement)
875
Here, original specifies the character to be
replaced by the character specified by
replacement. The resulting string is returned.
For example,
String s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s.
trim( ):
The trim( ) method returns a copy of the
invoking string from which any leading and
trailing whitespace has been removed. It has
this general form:String trim( )
876
Here is an example:
String s = " Hello World ".trim();
This puts the string “Hello World” into s.
The trim( ) method is quite useful when you
process user commands.
For example,the following program prompts
the user for the name of a state and then
displays that state’s capital. It uses trim( ) to
remove any leading or trailing whitespace
that may have inadvertently been entered by
the user.eg:”UseTrim.java”
877
Data Conversion Using valueOf( )
The valueOf( ) method converts data from its
internal format into a human-readable
form.
It is a static method that is overloaded within
String for all of Java’s built-in types,so that
each type can be converted properly into a
string.
valueOf( ) is also overloaded for type Object, so
an object of any class type you create can
also be used as an argument.
878
Here are a few of its forms:
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(char chars[ ]):
valueOf( ) :is called when a string
representation of some other type of data is
needed—for example, during concatenation
operations.
879
You can call this method directly with any
data type and get a reasonable String
representation. All of the simple types are
converted to their common String
representation.
Any object that you pass to valueOf( ) will
return the result of a call to the object’s
toString( ) method. In fact, you could just call
toString( ) directly and get the same result.
880
Changing the Case of Characters
Within a String:
The method toLowerCase( ) converts all the
characters in a string from uppercase to
lowercase.
The toUpperCase( ) method converts all the
characters in a string from lowercase to
uppercase.
Nonalphabetical characters, such as digits,
are unaffected.
881
Here are the general forms of these methods:
String toLowerCase( )
String toUpperCase( )
Both methods return a String object that
contains the uppercase or lowercase
equivalent of the invoking String.
Here is an example that uses toLowerCase( )
and toUpperCase( ):
Eg:ChangeCase.java
882
StringBuffer
StringBuffer is a peer class of String that
provides much of the functionality of strings.
String represents fixed-length, immutable
character sequences.
In contrast,StringBuffer represents growable
and writeable character sequences.
StringBuffer may have characters and
substrings inserted in the middle or appended
to the end.
883
StringBuffer will automatically grow to make
room for such additions and often has more
characters preallocated than are actually
needed, to allow room for growth.
StringBuffer Constructors
StringBuffer( ) :reserves room for 16
characters without reallocation.
StringBuffer(int size) :Accepts an integer
argument that explicitly sets the size of the
buffer.
884
StringBuffer(String str):accepts a String
argument that sets the initial contents of the
StringBuffer object and reserves room for 16
more characters without reallocation.
StringBuffer allocates room for 16 additional
characters when no specific buffer length is
requested, because reallocation is a costly
process in terms of time.
Also, frequent reallocations can fragment
memory.
885
By allocating room for a few extra characters,
StringBuffer reduces the number of
reallocations that take place.
length( ) and capacity( )
The current length of a StringBuffer can be
found via the length( ) method, while the
total allocated capacity can be found through
the capacity( ) method.
They have the following general forms:
int length( )
int capacity( )
886
example:// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " +
sb.capacity());}}
887
Here is the output of this program, which
shows how StringBuffer reserves extra
space for additional manipulations:
buffer = Hello
length = 5
capacity = 21
Since sb is initialized with the string “Hello”
when it is created, its length is 5. Its
capacity is 21 because room for 16 additional
characters is automatically added.
888
ensureCapacity( ):If you want to preallocate
room for a certain number of characters after
a StringBuffer has been constructed, you can
use ensureCapacity( ) to set the size of the
buffer. General form:
void ensureCapacity(int capacity)
Here, capacity specifies the size of the buffer.
setLength( ):
To set the length of the buffer within a
StringBuffer object, use setLength( ).
889
Its general form is shown here:
void setLength(int len): Here, len specifies
the length of the buffer. This value must be
nonnegative.
When you increase the size of the buffer, null
characters are added to the end of the
existing buffer.
If you call setLength( ) with a value less than
the current value returned by length( ), then
the characters stored beyond the new length
will be lost.
890
The setCharAtDemo sample program in the
following section uses setLength( ) to
shorten a StringBuffer.
charAt( ) and setCharAt( )
The value of a single character can be
obtained from a StringBuffer via the charAt( )
method. You can set the value of a character
within a StringBuffer using setCharAt( ).
891
Their general forms are shown here:
char charAt(int where)
void setCharAt(int where, char ch)
For charAt( ), where specifies the index of the
character being obtained.
For setCharAt( ), where specifies the index of
the character being set, and ch specifies the
new value of that character. For both
methods, where must be nonnegative and
must not specify a location beyond the end of
the buffer.
892
// Demonstrate charAt() and setCharAt().
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " +
sb.charAt(1));
sb.setCharAt(1, 'i');sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " +
sb.charAt(1));}}
893
Here is the output generated by this
program:
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
894
getChars( )
To copy a substring of a StringBuffer into an
array, use the getChars( ) method. It has
this general form:
void getChars(int sourceStart, int sourceEnd,
char target[ ],int targetStart)
Here, sourceStart specifies the index of the
beginning of the substring, and sourceEnd
specifies an index that is one past the end of
the desired substring.
895
The substring contains the characters from
sourceStart through sourceEnd–1. The array
that will receive the characters is specified by
target.
The index within target at which the
substring will be copied is passed in
targetStart.
Care must be taken to assure that the target
array is large enough to hold the number of
characters in the specified substring.
896
append( )
The append( ) method concatenates the
string representation of any other type of
data to the end of the invoking StringBuffer
object.
String.valueOf( ) is called for each parameter
to obtain its string representation. The result
is appended to the current StringBuffer
object. The buffer itself is returned by each
version of append( ).
897
insert( )
The insert( ) method inserts one string into
another. It is overloaded to accept values of
all the simple types, plus Strings and Objects.
Like append( ), it calls String.valueOf( ) to
obtain the string representation of the value
it is called with. This string is then inserted
into the invoking StringBuffer object. These
are a few of its forms:
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
898
StringBuffer insert(int index, Object obj)
Here, index specifies the index at which
point the string will be inserted into the
invoking StringBuffer object.
reverse( )
You can reverse the characters within a
StringBuffer object using reverse( ),
shown here:StringBuffer reverse( )
899
delete( ) and deleteCharAt( )
StringBuffer delete(int startIndex, int
endIndex)
StringBuffer deleteCharAt(int loc)
The delete( ) method deletes a sequence of
characters from the invoking object.
Here, startIndex specifies the index of the
first character to remove, and endIndex
specifies an index one past the last character
to remove.
900
Thus, the substring deleted runs from
startIndex to endIndex–1. The resulting
StringBuffer object is returned.
The deleteCharAt( ) method deletes the
character at the index specified by loc.
It returns the resulting StringBuffer
object.
901
replace( ):It replaces one set of characters
with another set inside a StringBuffer object.
StringBuffer replace(int startIndex, int
endIndex, String str)
The substring being replaced is specified by
the indexes startIndex and endIndex. Thus,
the substring at startIndex through
endIndex–1 is replaced. The replacement
string is passed in str.
902
substring( ):
Returns a portion of a StringBuffer. It has the
following two forms:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
The first form returns the substring that
starts at startIndex and runs to the end of
the invoking StringBuffer object. The second
form returns the substring that starts at
startIndex and runs through endIndex–1.
903
17. JDBC
904
18. Networking
905
Thank You ...
906
Download