SlideShare a Scribd company logo
UNIT-1
B.TECH II YR II SEMESTER(TERM 08-09)
UNIT 1 PPT SLIDES
TEXT BOOKS:
1. Java: the complete reference, 7th editon, Herbert schildt,
TMH.Understanding
2. OOP with Java, updated edition, T. Budd, pearson eduction.
No. of slides: 24
S.NO. TOPIC LECTURE NO. PPTSLIDES
1 Need for oop paradigm, L1 L1.1TO L1.4
A way of viewing world – Agents
2 Responsibility, Messages, Methods L2 L2.1 TO L2.3
3 classes and instances, L3 L3.1 TO L3.6
class hierarchies, Inheritance
4 method binding L 4 L4.1 TO L4.5
overriding and exceptions
5 summary of oop concepts,
coping with complexity, L5 L5.1 TO 5.4
abstraction mechanisms
OOP is an approach to program organization and
development, which attempts to eliminate some of
the drawbacks of conventional programming
methods by incorporating the best of structured
programming features with several new concepts.
 OOP allows us to decompose a problem into
number of entities called objects and then build data
and methods (functions) around these entities.
The data of an object can be accessed only by the
methods associated with the object.
L 1.1
Some of the Object-Oriented Paradigm are:
1. Emphasis is on data rather than procedure.
2. Programs are divided into objects.
3. Data Structures are designed such that they
Characterize the objects.
4 Methods that operate on the data of an object
are tied together in the data structure.
5 Data is hidden and can not be accessed by
external functions.
6 Objects may communicate with each other
through methods.
L 1.2
OOP uses an approach of treating a real world
agent as an object.
Object-oriented programming organizes a
program around its data (that is, objects) and a set
of well-defined interfaces to that data.
An object-oriented program can be characterized
as data controlling access to code by switching the
controlling entity to data.
L 1.3
L 1.4
primary motivation is the need for a platform-
independent (that is, architecture- neutral) language
that could be used to create software to be
embedded in various consumer electronic devices,
such as microwave ovens and remote controls.
Objects with clear responsibilities
Each class should have a clear responsibility.
If you can't state the purpose of a class in a single,
clear sentence, then perhaps your class structure
needs some thought.
L 2.1
Messages
We all like to use programs that let us know
what's going on. Programs that keep us informed
often do so by displaying status and error
messages.
These messages need to be translated so they can
be understood by end users around the world.
The Section discusses translatable text messages.
Usually, you're done after you move a message
String into a ResourceBundle.
If you've embedded variable data in a message,
you'll have to take some extra steps to prepare it
for translation.
L 2.2
Methods
A method is a group of instructions that is given a name and can
be called up at any point in a program simply by quoting that
name.
Drawing a Triangle require draw of three straight lines. This
instruction three times to draw a simple triangle.
We can define a method to call this instruction three times and
draw the triangle(i.e. create a method drawLine() to draw lines
and this method is called repeatedly to achieve the needed task)
The idea of methods appears in all programming languages,
although sometimes it goes under the name functions and
sometimes under the name procedures.
The name methods is a throw-back to the language C++, from
which Java was developed.
In C++, there is an object called a class which can contain
methods. However, everything in Java is enclosed within a class
.so the functions within it are called methods
L 2.3
L 3.1
• Class is blue print or an idea of an Object
• From One class any number of Instances can be
created
• It is an encapsulation of attributes and methods
FIGURE
CIRCLE
RECTANGLE
SQUARE
Ob1
Ob2
Ob3
class
L 3.2
class <ClassName>
{
attributes/variables;
Constructors();
methods();
}
L 3.3
• Instance is an Object of a class which
is an entity with its own attribute
values and methods.
• Creating an Instance
ClassName refVariable;
refVariable = new Constructor();
or
ClassName refVariable = new Constructor();
L 3.4
• In Java, class “Object” is the base class to all
other classes
– If we do not explicitly say extends in a new
class definition, it implicitly extends Object
– The tree of classes that extend from Object and
all of its subclasses are is called the class
hierarchy
– All classes eventually lead back up to Object
– This will enable consistent access of objects of
different classes.
Methods allows to reuse a sequence of statements
Inheritance allows to reuse classes by deriving a
new class from an existing one
The existing class is called the parent class, or
superclass, or base class
The derived class is called the child class or
subclass.
The child class inherits characteristics of the
parent class(i.e the child class inherits the
methods and data defined for the parent class
L 3.5
Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
L 3.6
Animal
weight : int
+ getWeight() : int
Bird
+ fly() : void
Objects are used to call methods.
MethodBinding is an object that can be used to call an
arbitrary public method, on an instance that is acquired by
evaluatng the leading portion of a method binding
expression via a value binding.
It is legal for a class to have two or more methods with the
same name.
Java has to be able to uniquely associate the invocation of a
method with its definition relying on the number and types
of arguments.
Therefore the same-named methods must be distinguished:
1) by the number of arguments, or
2) by the types of arguments
Overloading and inheritance are two ways to implement
polymorphism.
L 4.1
 There may be some occasions when we want an object to
respond to the same method but have different behaviour
when that method is called.
 That means, we should override the method defined in the
superclass. This is possible by defining a method in a sub
class that has the same name, same arguments and same
return type as a method in the superclass.
 Then when that method is called, the method defined in
the sub class is invoked and executed instead of the one in
the superclass. This is known as overriding.
L 4.2
L 4.3
• Exception is an abnormal condition that arises in the code
sequence.
• Exceptions occur during compile time or run time.
• “throwable” is the super class in exception hierarchy.
• Compile time errors occurs due to incorrect syntax.
• Run-time errors happen when
– User enters incorrect input
– Resource is not available (ex. file)
– Logic error (bug) that was not fixed
In Java, exceptions are objects. When you throw an exception,
you throw an object. You can't throw just any object as an
exception, however -- only those objects whose classes descend
from Throwable.
Throwable serves as the base class for an entire family of classes,
declared in java.lang, that your program can instantiate and
throw.
Throwable has two direct subclasses, Exception and Error.
Exceptions are thrown to signal abnormal conditions that can
often be handled by some catcher, though it's possible they may
not be caught and therefore could result in a dead thread.
Errors are usually thrown for more serious problems, such as
OutOfMemoryError, that may not be so easy to handle. In
general, code you write should throw only exceptions, not errors.
Errors are usually thrown by the methods of the Java API, or by
the Java virtual machine itself.
L 4.4
L 4.5
The following are the basic oops concepts: They are as
follows:
1. Objects.
2. Classes.
3. Data Abstraction.
4. Data Encapsulation.
5. Inheritance.
6. Polymorphism.
7. Dynamic Binding.
8. Message Passing.
L 5.1
L 5.2
Abstraction in Object-Oriented Programming
Procedural Abstraction
• Procedural Abstractions organize instructions.
Function Power
Give me two numbers (base & exponent)
I’ll return baseexponent
Implementation
L 5.3
Data Abstraction
• Data Abstractions organize data.
Name (string)
Marks (num)
Grade (char)
Student Number (num)
StudentType
L 5.4
Behavioral Abstraction
• Behavioral Abstractions combine
procedural and data abstractions.
Data State
Enqueue
Is Full
Is Empty Dequeue
Initialize
Queue Object
UNIT-2
B.TECH II YR II SEMESTER(TERM 08-09)
UNIT 2 PPT SLIDES
TEXT BOOKS:
1. Java: the complete reference, 7th editon, Herbert schildt,
TMH.Understanding
2. OOP with Java, updated edition, T. Budd, pearson eduction.
No. of slides: 85
S.NO. TOPIC LECTURE NO. PPTSLIDES
1 History of Java, L1 L1.1TO L1.20
Java buzzwords, data types.
2 variables, scope and life time of variables,L2 L2.1 TO L2.20
arrays, operators, expressions
3 control statements, L3 L3.1 TO L3.9
type conversion and costing
4 simple java program, L 4 L4.1 TO L4.8
classes and objects – concepts of classes
5 objects, constructors, methods L5 L5.1 TO 5.6
6 Access control, this keyword, L6 L6.1 TO 6.8
garbage collection
7 overloading methods and constructors, L7 L7.1 TO 7.6
parameter passing
8 Recursion, string handling. L8 L 8.1 TO 8.6
Computer language innovation and development occurs
for two fundamental reasons:
1) to adapt to changing environments and uses
2) to implement improvements in the art of
programming
The development of Java was driven by both in equal
measures.
Many Java features are inherited from the earlier
languages:
B  C  C++  Java
L 1.1
Designed by Dennis Ritchie in 1970s.
Before C: BASIC, COBOL, FORTRAN, PASCAL
C- structured, efficient, high-level language that could
replace assembly code when creating systems programs.
Designed, implemented and tested by programmers.
L 1.2
Designed by Bjarne Stroustrup in 1979.
Response to the increased complexity of programs and
respective improvements in the programming
paradigms and methods:
1) assembler languages
2) high-level languages
3) structured programming
4) object-oriented programming (OOP)
OOP – methodology that helps organize complex
programs through the use of inheritance, encapsulation
and polymorphism.
C++ extends C by adding object-oriented features.
L 1.3
In 1990, Sun Microsystems started a project called Green.
Objective: to develop software for consumer electronics.
Project was assigned to James Gosling, a veteran of classic
network software design. Others included Patrick
Naughton, ChrisWarth, Ed Frank, and Mike Sheridan.
The team started writing programs in C++ for embedding
into
– toasters
– washing machines
– VCR’s
Aim was to make these appliances more “intelligent”.
L 1.4
C++ is powerful, but also dangerous. The power and popularity of
C derived from the extensive use of pointers. However, any
incorrect use of pointers can cause memory leaks, leading the
program to crash.
In a complex program, such memory leaks are often hard to
detect.
Robustness is essential. Users have come to expect that Windows
may crash or that a program running under Windows may crash.
(“This program has performed an illegal operation and will be
shut down”)
However, users do not expect toasters to crash, or washing
machines to crash.
A design for consumer electronics has to be robust.
Replacing pointers by references, and automating memory
management was the proposed solution.
L 1.5
Hence, the team built a new programming language called Oak,
which avoided potentially dangerous constructs in C++, such as
pointers, pointer arithmetic, operator overloading etc.
Introduced automatic memory management, freeing the
programmer to concentrate on other things.
Architecture neutrality (Platform independence)
Many different CPU’s are used as controllers. Hardware chips are
evolving rapidly. As better chips become available, older chips
become obsolete and their production is stopped. Manufacturers
of toasters and washing machines would like to use the chips
available off the shelf, and would not like to reinvest in compiler
development every two-three years.
So, the software and programming language had to be architecture
neutral.
L 1.6
 It was soon realized that these design goals of consumer electronics
perfectly suited an ideal programming language for the Internet and WWW,
which should be:
 object-oriented (& support GUI)
 – robust
 – architecture neutral
 Internet programming presented a BIG business opportunity. Much bigger
than programming for consumer electronics.
 Java was “re-targeted” for the Internet
 The team was expanded to include Bill Joy (developer of Unix), Arthur van
Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc.
 In 1994, an early web browser called WebRunner was written in Oak.
WebRunner was later renamed HotJava.
 In 1995, Oak was renamed Java.
 A common story is that the name Java relates to the place from where the
development team got its coffee. The name Java survived the trade mark
search.
L 1.7
Designed by James Gosling, Patrick Naughton, Chris
Warth, Ed Frank and Mike Sheridan at Sun
Microsystems in 1991.
The original motivation is not Internet: platform-
independent software embedded in consumer
electronics devices.
With Internet, the urgent need appeared to break the
fortified positions of Intel, Macintosh and Unix
programmer communities.
Java as an “Internet version of C++”? No.
Java was not designed to replace C++, but to solve a
different set of problems.
L 1.8
The key considerations were summed up by the Java
team in the following list of buzzwords:
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic
L 1.9
simple – Java is designed to be easy for the professional
programmer to learn and use.
object-oriented: a clean, usable, pragmatic approach to
objects, not restricted by the need for compatibility with
other languages.
Robust: restricts the programmer to find the mistakes early,
performs compile-time (strong typing) and run-time
(exception-handling) checks, manages memory
automatically.
Multithreaded: supports multi-threaded programming for
writing program that perform concurrent computations
L 1.10
Architecture-neutral: Java Virtual Machine provides
a platform independent environment for the
execution of Java byte code
Interpreted and high-performance: Java programs
are compiled into an intermediate representation –
byte code:
a) can be later interpreted by any JVM
b) can be also translated into the native machine
code for efficiency.
L 1.11
Distributed: Java handles TCP/IP protocols,
accessing a resource through its URL much like
accessing a local file.
Dynamic: substantial amounts of run-time type
information to verify and resolve access to objects
at run-time.
Secure: programs are confined to the Java
execution environment and cannot access other
parts of the computer.
L 1.12
Portability: Many types of computers and
operating systems are in use throughout the world
—and many are connected to the Internet.
For programs to be dynamically downloaded to all
the various types of platforms connected to the
Internet, some means of generating portable
executable code is needed. The same mechanism
that helps ensure security also helps create
portability.
Indeed, Java's solution to these two problems is
both elegant and efficient.
L 1.13
Java defines eight simple types:
1)byte – 8-bit integer type
2)short – 16-bit integer type
3)int – 32-bit integer type
4)long – 64-bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false
L 1.14
byte: 8-bit integer type.
Range: -128 to 127.
Example: byte b = -15;
Usage: particularly when working with data
streams.
short: 16-bit integer type.
Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the least used simple type.
L 1.15
int: 32-bit integer type.
Range: -2147483648 to 2147483647.
Example: int b = -50000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index arrays.
3) Expressions involving the byte, short and int values are
promoted to int before calculation.
L 1.16
long: 64-bit integer type.
Range: -9223372036854775808 to
9223372036854775807.
Example: long l = 10000000000000000;
Usage: 1) useful when int type is not large enough to hold
the desired value
float: 32-bit floating-point number.
Range: 1.4e-045 to 3.4e+038.
Example: float f = 1.5;
Usage:
1) fractional part is needed
2) large degree of precision is not required
L 1.17
double: 64-bit floating-point number.
Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many iterative calculations
2) manipulation of large-valued numbers
L 1.18
char: 16-bit data type used to store characters.
Range: 0 to 65536.
Example: char c = ‘a’;
Usage:
1) Represents both ASCII and Unicode character sets;
Unicode defines a
character set with characters found in (almost) all
human languages.
2) Not the same as in C/C++ where char is 8-bit and
represents ASCII only.
L 1.19
boolean: Two-valued type of logical values.
Range: values true and false.
Example: boolean b = (1<2);
Usage:
1) returned by relational operators, such as 1<2
2) required by branching expressions such as
if or for
L 1.20
declaration – how to assign a type to a variable
initialization – how to give an initial value to a variable
scope – how the variable is visible to other parts of the
program
lifetime – how the variable is created, used and destroyed
type conversion – how Java handles automatic type
conversion
type casting – how the type of a variable can be narrowed
down
type promotion – how the type of a variable can be
expanded
L 2.1
Java uses variables to store data.
To allocate memory space for a variable JVM
requires:
1) to specify the data type of the variable
2) to associate an identifier with the variable
3) optionally, the variable may be assigned an initial
value
All done as part of variable declaration.
L 2.2
datatype identifier [=value];
datatype must be
A simple datatype
User defined datatype (class type)
Identifier is a recognizable name confirm to identifier
rules
Value is an optional initial value.
L 2.3
We can declare several variables at the same time:
type identifier [=value][, identifier [=value] …];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';
L 2.4
Scope determines the visibility of program elements with respect
to other program elements.
In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
A scope is defined by a block:
{
…
}
A variable declared inside the scope is not visible outside:
{
int n;
}
n = 1;// this is illegal
L 2.5
Variables are created when their scope is entered by
control flow and destroyed when their scope is left:
A variable declared in a method will not hold its
value between different invocations of this method.
A variable declared in a block looses its value when
the block is left.
Initialized in a block, a variable will be re-initialized
with every re-entry. Variables lifetime is confined to
its scope!
L 2.6
An array is a group of liked-typed variables referred to
by a common
name, with individual variables accessed by their index.
Arrays are:
1) declared
2) created
3) initialized
4) used
Also, arrays can have one or several dimensions.
L 2.7
Array declaration involves:
1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
Two styles of array declaration:
type array-variable[];
or
type [] array-variable;
L 2.8
After declaration, no array actually exists.
In order to create an array, we use the new
operator:
type array-variable[];
array-variable = new type[size];
This creates a new array to hold size elements of
type type, which reference will be kept in the
variable array-variable.
L 2.9
Later we can refer to the elements of this array
through their indexes:
array-variable[index]
The array index always starts with zero!
The Java run-time system makes sure that all array
indexes are in the correct range, otherwise raises a
run-time error.
L 2.10
Arrays can be initialized when they are declared:
int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
Note:
1) there is no need to use the new operator
2) the array is created large enough to hold all specified
elements
L 2.11
Multidimensional arrays are arrays of arrays:
1) declaration: int array[][];
2) creation: int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
L 2.12
Java operators are used to build value expressions.
Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise
L 2.13
+= v += expr; v = v + expr ;
-= v -=expr; v = v - expr ;
*= v *= expr; v = v * expr ;
/= v /= expr; v = v / expr ;
%= v %= expr; v = v % expr ;
L 2.14
+ op1 + op2 ADD
- op1 - op2 SUBSTRACT
* op1 * op2 MULTIPLY
/ op1 / op2 DIVISION
% op1 % op2 REMAINDER
L 2.15
== Equals to Apply to any type
!= Not equals to Apply to any type
> Greater than Apply to numerical type
< Less than Apply to numerical type
>= Greater than or equal Apply to numerical type
<= Less than or equal Apply to numerical type
L 2.16
& op1 & op2 Logical AND
| op1 | op2 Logical OR
&& op1 && op2 Short-circuit
AND
|| op1 || op2 Short-circuit OR
! ! op Logical NOT
^ op1 ^ op2 Logical XOR
L 2.17
~ ~op Inverts all bits
& op1 & op2 Produces 1 bit if both operands are 1
| op1 |op2 Produces 1 bit if either operand is 1
^ op1 ^ op2 Produces 1 bit if exactly one operand is 1
>> op1 >> op2 Shifts all bits in op1 right by the value of
op2
<< op1 << op2 Shifts all bits in op1 left by the value of
op2
L 2.18
An expression is a construct made up of variables,
operators, and method invocations, which are
constructed according to the syntax of the language, that
evaluates to a single value.
Examples of expressions are in bold below:
int number = 0;
anArray[0] = 100;
System.out.println ("Element 1 at index 0: " +
anArray[0]);
int result = 1 + 2; // result is now 3 if(value1 ==
value2)
System.out.println("value1 == value2");
L 2.19
Expressions
The data type of the value returned by an expression depends on
the elements used in the expression.
 The expression number = 0 returns an int because the
assignment operator returns a value of the same data type as its
left-hand operand; in this case, number is an int.
As you can see from the other expressions, an expression can
return other types of values as well, such as boolean or String.
The Java programming language allows you to construct
compound expressions from various smaller expressions as long
as the data type required by one part of the expression matches
the data type of the other.
 Here's an example of a compound expression: 1 * 2 * 3
L 2.20
Java control statements cause the flow of execution to
advance and branch based on the changes to the state
of the program.
Control statements are divided into three groups:
1) selection statements allow the program to choose
different parts of the execution based on the outcome
of an expression
2) iteration statements enable program execution to
repeat one or more statements
3) jump statements enable your program to execute in
a non-linear fashion
L 3.1
Java selection statements allow to control the flow
of program’s execution based upon conditions
known only during run-time.
Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch
L 3.2
Java iteration statements enable repeated execution of
part of a program until a certain termination condition
becomes true.
Java provides three iteration statements:
1) while
2) do-while
3) for
L 3.3
Java jump statements enable transfer of control to
other parts of program.
Java provides three jump statements:
1) break
2) continue
3) return
In addition, Java supports exception handling that can
also alter the control flow of a program.
L 3.4
L 3.5
Type Conversion
• Size Direction of Data Type
– Widening Type Conversion (Casting down)
• Smaller Data Type  Larger Data Type
– Narrowing Type Conversion (Casting up)
• Larger Data Type  Smaller Data Type
• Conversion done in two ways
– Implicit type conversion
• Carried out by compiler automatically
– Explicit type conversion
• Carried out by programmer using casting
L 3.6
Type Conversion
• Widening Type Converstion
– Implicit conversion by compiler automatically
byte -> short, int, long, float, double
short -> int, long, float, double
char -> int, long, float, double
int -> long, float, double
long -> float, double
float -> double
byte -> short, int, long, float, double
short -> int, long, float, double
char -> int, long, float, double
int -> long, float, double
long -> float, double
float -> double
L 3.7
Type Conversion
• Narrowing Type Conversion
– Programmer should describe the conversion
explicitly
byte -> char
short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char, int
float -> byte, short, char, int, long
double -> byte, short, char, int, long, float
byte -> char
short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char, int
float -> byte, short, char, int, long
double -> byte, short, char, int, long, float
byte and short are always promoted to int
if one operand is long, the whole expression is
promoted to long
if one operand is float, the entire expression is
promoted to float
if any operand is double, the result is double
L 3.8
General form: (targetType) value
Examples:
1) integer value will be reduced module bytes
range:
int i;
byte b = (byte) i;
2) floating-point value will be truncated to
integer value:
float f;
int i = (int) f;
L 3.9
A class to display a simple message:
class MyProgram
{
public static void main(String[] args)
{
System.out.println(“First Java program.");
}
}
4.1
Real world objects are things that have:
1) state
2) behavior
Example: your dog:
state – name, color, breed, sits?, barks?, wages
tail?, runs?
behavior – sitting, barking, waging tail, running
A software object is a bundle of variables (state)
and methods (operations).
L 4.2
A class is a blueprint that defines the variables and
methods common to all objects of a certain kind.
Example: ‘your dog’ is a object of the class Dog.
An object holds values for the variables defines in the
class.
An object is called an instance of the Class
L 4.3
A variable is declared to refer to the objects of
type/class String:
String s;
The value of s is null; it does not yet refer to any
object.
A new String object is created in memory with
initial “abc” value:
String s = new String(“abc”);
Now s contains the address of this new object.
L 4.4
A program accumulates memory through its
execution.
Two mechanism to free memory that is no longer
need by the program:
1) manual – done in C/C++
2) automatic – done in Java
In Java, when an object is no longer accessible
through any variable, it is eventually removed from
the memory by the garbage collector.
Garbage collector is parts of the Java Run-Time
Environment.
L 4.5
A basis for the Java language.
Each concept we wish to describe in Java must be
included inside a class.
A class defines a new data type, whose values are
objects:
A class is a template for objects
An object is an instance of a class
L 4.6
A class contains a name, several variable declarations
(instance variables) and several method declarations. All
are called members of the class.
General form of a class:
class classname {
type instance-variable-1;
…
type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }
…
type method-name-m(parameter-list) { … }
}
L 4.7
class Box {
double width;
double height;
double depth;
}
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println ("Volume is " + vol);
} }
L 4.8
A constructor initializes the instance variables of an object.
It is called immediately after the object is created but before
the new operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default
return type of a class
constructor is the same class
When the class has no constructor, the default constructor
automatically initializes all its instance variables with zero.
L 5.1
class Box {
double width;
double height;
double depth;
Box() {
System.out.println("Constructing Box");
width = 10; height = 10; depth = 10;
}
double volume() {
return width * height * depth;
}
}
L 5.2
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
double volume()
{ return width * height * depth;
}
}
L 5.3
General form of a method definition:
type name(parameter-list) {
… return value;
…
}
Components:
1) type - type of values returned by the method. If a
method does not return any value, its return type must be
void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists
separated by commas
4) return value indicates what value is returned by the
method.
L 5.4
Classes declare methods to hide their internal data
structures, as well as for their own internal use: Within
a class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
L 5.5
Parameters increase generality and applicability
of a method:
1) method without parameters
int square() { return 10*10; }
2) method with parameters
int square(int i) { return i*i; }
Parameter: a variable receiving value at the time
the method is invoked.
Argument: a value passed to the method when it
is invoked.
L 5.6
L 6.1
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables
and methods.
• Encapsulation, safely sealing data within the capsule
of the class Prevents programmers from relying on
details of class implementation, so you can update
without worry
• Helps in protecting against accidental or wrong
usage.
• Keeps code elegant and clean (easier to maintain)
L 6.2
Access Modifiers: Public, Private,
Protected
• Public: keyword applied to a class, makes it
available/visible everywhere. Applied to a
method or variable, completely visible.
• Default(No visibility modifier is specified): it
behaves like public in its package and private
in other packages.
• Default Public keyword applied to a class,
makes it available/visible everywhere.
Applied to a method or variable, completely
visible.
Private fields or methods for a class only visible within
that class. Private members are not visible within
subclasses, and are not inherited.
Protected members of a class are visible within the
class, subclasses and also within all classes that are in
the same package as that class.
L 6.3
L 6.4
Visibility
public class Circle {
private double x,y,r;
// Constructor
public Circle (double x, double y, double r) {
this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r;}
public double area() { return 3.14 * r * r; }
}
L 6.5
Keyword this
• Can be used by any object to refer to itself
in any class method
• Typically used to
– Avoid variable name collisions
– Pass the receiver as an argument
– Chain constructors
Keyword this allows a method to refer to the
object that invoked it.
It can be used inside any method to refer to the
current object:
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
L 6.6
Garbage collection is a mechanism to remove objects from
memory when they are no longer needed.
Garbage collection is carried out by the garbage collector:
1) The garbage collector keeps track of how many
references an object has.
2) It removes an object from memory when it has no
longer any references.
3) Thereafter, the memory occupied by the object can be
allocated again.
4) The garbage collector invokes the finalize method.
L 6.7
A constructor helps to initialize an object just
after it has been created.
In contrast, the finalize method is invoked just
before the object is destroyed:
1) implemented inside a class as:
protected void finalize() { … }
2) implemented when the usual way of removing
objects from memory is insufficient, and some
special actions has to be carried out
L 6.8
It is legal for a class to have two or more
methods with the same name.
However, Java has to be able to uniquely
associate the invocation of a method with its
definition relying on the number and types of
arguments.
Therefore the same-named methods must be
distinguished:
1) by the number of arguments, or
2) by the types of arguments
Overloading and inheritance are two ways to
implement polymorphism. L 7.1
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a); return a*a;
}
}
L 7.2
class Box {
double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box() {
width = -1; height = -1; depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}
L 7.3
Two types of variables:
1) simple types
2) class types
Two corresponding ways of how the arguments
are passed to methods:
1) by value a method receives a cope of the
original value; parameters of simple types
2) by reference a method receives the memory
address of the original value, not the value itself;
parameters of class types
L 7.4
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.print("a and b before call: “);
System.out.println(a + " " + b);
ob.meth(a, b);
System.out.print("a and b after call: ");
System.out.println(a + " " + b);
}
}
L 7.5
As the parameter hold the same address as the argument,
changes to the object inside the method do affect the object used
by the argument:
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.print("ob.a and ob.b before call: “);
System.out.println(ob.a + " " + ob.b);
ob.meth(ob);
System.out.print("ob.a and ob.b after call: ");
System.out.println(ob.a + " " + ob.b);
}
}
L 7.6
A recursive method is a method that calls itself:
1) all method parameters and local variables are
allocated on the stack
2) arguments are prepared in the corresponding
parameter positions
3) the method code is executed for the new
arguments
4) upon return, all parameters and variables are
removed from the stack
5) the execution continues immediately after the
invocation point
L 8.1
class Factorial {
int fact(int n) {
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.print("Factorial of 5 is ");
System.out.println(f.fact(5));
} }
L 8.2
String is probably the most commonly used class in
Java's class library. The obvious reason for this is that
strings are a very important part of programming.
The first thing to understand about strings is that
every string you create is actually an object of type
String. Even string constants are actually String
objects.
For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
L 8.3
Java defines one operator for String objects: +.
It is used to concatenate two strings. For example, this
statement
String myString = "I" + " like " + "Java.";
results in myString containing
"I like Java."
L 8.4
The String class contains several methods that you can use.
Here are a few. You can
test two strings for equality by using
equals( ). You can obtain the length of a string by calling
the length( ) method. You can obtain the character at a
specified index within a string by calling charAt( ). The
general forms of these three methods are shown here:
// Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +
strOb1.length());
L 8.5
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
} }
This program generates the following output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
L 8.6
UNIT-3
B.TECH II YR II SEMESTER(TERM 08-09)
UNIT 3 PPT SLIDES
TEXT BOOKS:
1. Java: the complete reference, 7th edition, Herbert
schildt, TMH.Understanding
2. OOP with Java, updated edition, T. Budd, Pearson
education.
No. of slides:66
S.NO. TOPIC LECTURE NO. PPTSLIDES
1 Hierarchical abstractions L1 L1.1TO L1.9
Base class object.
2 subclass, subtype, substitutability. L2 L2.1 TO L2.8
3 forms of inheritance- specialization, L3 L3.1 TO L3.5 specification.
4 construction, extension, limitation, L4 L4.1 TO L4.9
combination.
5 Benefits of inheritance, costs of inheritance. L5 L5.1 TO 5.4
6 Member access rules, super uses, L6 L6.1 TO 6.17
using final with inheritance.
7 polymorphism- method overriding, L7 L7.1 TO 7.11
abstract classes.
An essential element of object-oriented programming
is abstraction.
Humans manage complexity through abstraction. For
example, people do not think of a car as a set of tens of
thousands of individual parts. They think of it as a
well-defined object with its own unique behavior.
This abstraction allows people to use a car without
being overwhelmed by the complexity of the parts that
form the car. They can ignore the details of how the
engine, transmission, and braking systems work.
Instead they are free to utilize the object as a whole.
L 1.1
A child class of one parent can be the parent of
another child, forming class hierarchies
L 1.2
Animal
Reptile Bird Mammal
Snake Lizard BatHorseParrot
 At the top of the hierarchy there’s a default class
called Object.
Good class design puts all common features as
high in the hierarchy as reasonable
The class hierarchy determines how methods
are executed
inheritance is transitive
An instance of class Parrot is also an
instance of Bird, an instance of Animal,
…, and an instance of class Object
L 1.3
In Java, all classes use inheritance.
If no parent class is specified explicitly, the base class
Object is implicitly inherited.
All classes defined in Java, is a child of Object class,
which provides minimal functionality guaranteed to e
common to all objects.
L 1.4
L 1.5
Methods defined in Object class are;
1.equals(Object obj) Determine whether the
argument object is the same as the receiver.
2.getClass() Returns the class of the receiver, an object
of type Class.
3.hashCode() Returns a hash value for this object. Should
be overridden when the equals method is changed.
4.toString() Converts object into a string value. This
method is also often overridden.
1) a class obtains variables and methods from another
class
2) the former is called subclass, the latter super-class
(Base class)
3) a sub-class provides a specialized behavior with
respect to its super-class
4) inheritance facilitates code reuse and avoids
duplication of data
L 1.6
One of the pillars of object-orientation.
A new class is derived from an existing class:
1) existing class is called super-class
2) derived class is called sub-class
A sub-class is a specialized version of its super-
class:
1) has all non-private members of its
super-class
2) may provide its own implementation of
super-class methods
Objects of a sub-class are a special kind of
objects of a super-class.
L 1.7
L 1.8
extends
 Is a keyword used to inherit a class from another class
 Allows to extend from only one class
class One
{
int a=5;
}
class Two extends One
{
int b=10;
}
One baseobj;// base class object.
super class object baseobj can be used to refer its
sub class objects.
For example, Two subobj=new Two;
Baseobj=subobj // now its pointing to sub class
L 1.9
A subtype is a class that satisfies the principle of
substitutability.
A subclass is something constructed using
inheritance, whether or not it satisfies the principle of
substitutability.
The two concepts are independent. Not all subclasses
are subtypes, and (at least in some languages) you
can construct subtypes that are not subclasses.
L 2.1
Substitutability is fundamental to many of the
powerful software development techniques in OOP.
The idea is that, declared a variable in one type may
hold the value of different type.
Substitutability can occur through use of inheritance,
whether using extends, or using implements
keywords.
L 2.2
L 2.3
When new classes are constructed using inheritance, the
argument used to justify the validity of substitutability is as
follows;
• Instances of the subclass must possess all data fields
associated with its parent class.
• Instances of the subclass must implement, through
inheritance at least, all functionality defined for parent class.
(Defining new methods is not important for the argument.)
• Thus, an instance of a child class can mimic the behavior of
the parent class and should be indistinguishable from an
instance of parent class if substituted in a similar situation.
L 2.4
The term subtype is used to describe the relationship
between types that explicitly recognizes the principle of
substitution. A type B is considered to be a subtype of A
if an instances of B can legally be assigned to a variable
declared as of type A.
The term subclass refers to inheritance mechanism
made by extends keyword.
Not all subclasses are subtypes. Subtypes can also be
formed using interface, linking types that have no
inheritance relationship.
Methods allows to reuse a sequence of statements
Inheritance allows to reuse classes by deriving a new
class from an existing one
The existing class is called the parent class, or
superclass, or base class
The derived class is called the child class or subclass.
As the name implies, the child inherits characteristics of
the parent(i.e the child class inherits the methods and
data defined for the parent class
L 2.5
Inheritance relationships are often shown
graphically in a class diagram, with the arrow
pointing to the parent class
L 2.6
Animal
weight : int
+ getWeight() : int
Bird
+ fly() : void
In Java, we use the reserved word extends to
establish an inheritance relationship
class Animal
{
// class contents
int weight;
public void int getWeight() {…}
}
class Bird extends Animal
{
// class contents
public void fly() {…};
}
L 2.7
 A child class can override the definition of an inherited method
in favor of its own
 that is, a child can redefine a method that it inherits from its parent
 the new method must have the same signature as the parent's
method, but can have different code in the body
 In java, all methods except of constructors override the methods
of their ancestor class by replacement. E.g.:
 the Animal class has method eat()
 the Bird class has method eat() and Bird extends Animal
 variable b is of class Bird, i.e. Bird b = …
 b.eat() simply invokes the eat() method of the Bird class
 If a method is declared with the final modifier, it cannot be
overridden
L 2.8
L 3.1
Inheritance is used in a variety of way and for a variety of different
purposes .
• Inheritance for Specialization
• Inheritance for Specification
• Inheritance for Construction
• Inheritance for Extension
• Inheritance for Limitation
• Inheritance for Combination
One or many of these forms may occur in a single case.
L 3.2
Most commonly used inheritance and sub classification is for
specialization.
Always creates a subtype, and the principles of substitutability
is explicitly upheld.
It is the most ideal form of inheritance.
An example of subclassification for specialization is;
public class PinBallGame extends Frame {
// body of class
}
 By far the most common form of inheritance is for specialization.
 Child class is a specialized form of parent class
 Principle of substitutability holds
 A good example is the Java hierarchy of Graphical components in the
AWT:
• Component
 Label
 Button
 TextComponent
 TextArea
 TextField
 CheckBox
 ScrollBar
L 3.3
L 3.4
This is another most common use of inheritance. Two different
mechanisms are provided by Java, interface and abstract, to make
use of subclassification for specification. Subtype is formed and
substitutability is explicitly upheld.
Mostly, not used for refinement of its parent class, but instead is
used for definitions of the properties provided by its parent.
class FireButtonListener implements ActionListener {
// body of class
}
class B extends A {
// class A is defined as abstract specification class
}
The next most common form of inheritance
involves specification. The parent class specifies
some behavior, but does not implement the
behavior
Child class implements the behavior
Similar to Java interface or abstract class
When parent class does not implement actual behavior
but merely defines the behavior that will be implemented
in child classes
Example, Java 1.1 Event Listeners:
ActionListener, MouseListener, and so on specify
behavior, but must be subclassed.
L 3.5
L 4.1
Child class inherits most of its functionality from parent,
but may change the name or parameters of methods
inherited from parent class to form its interface.
This type of inheritance is also widely used for code
reuse purposes. It simplifies the construction of newly
formed abstraction but is not a form of subtype, and often
violates substitutability.
Example is Stack class defined in Java libraries.
The parent class is used only for its behavior,
the child class has no is-a relationship to the
parent.
Child modify the arguments or names of
methods
An example might be subclassing the idea of a
Set from an existing List class.
Child class is not a more specialized form of
parent class; no substitutability
L 4.2
L 4.3
Subclassification for extension occurs when a child
class only adds new behavior to the parent class and
does not modify or alter any of the inherited attributes.
Such subclasses are always subtypes, and
substitutability can be used.
Example of this type of inheritance is done in the
definition of the class Properties which is an
extension of the class HashTable.
The child class generalizes or extends the parent
class by providing more functionality
In some sense, opposite of subclassing for
specialization
The child doesn't change anything inherited from the
parent, it simply adds new features
Often used when we cannot modify existing base
parent class
Example, ColoredWindow inheriting from Window
Add additional data fields
Override window display methods
L 4.4
L 4.5
Subclassification for limitation occurs when the
behavior of the subclass is smaller or more
restrictive that the behavior of its parent class.
Like subclassification for extension, this form
of inheritance occurs most frequently when a
programmer is building on a base of existing
classes.
Is not a subtype, and substitutability is not
proper.
The child class limits some of the behavior of the
parent class.
Example, you have an existing List data type,
and you want a Stack
Inherit from List, but override the methods that
allow access to elements other than top so as to
produce errors.
L 4.6
L 4.7
This types of inheritance is known as multiple inheritance in
Object Oriented Programming.
Although the Java does not permit a subclass to be formed be
inheritance from more than one parent class, several
approximations to the concept are possible.
Example of this type is Hole class defined as;
class Hole extends Ball implements
PinBallTarget{
// body of class
}
Two or more classes that seem to be related, but
its not clear who should be the parent and who
should be the child.
Example: Mouse and TouchPad and JoyStick
Better solution, abstract out common parts to
new parent class, and use subclassing for
specialization.
L 4.8
• Specialization. The child class is a special case of the parent class; in other
words, the child class is a subtype of the parent class.
• Specification. The parent class defines behavior that is implemented in the
child class but not in the parent class.
• Construction. The child class makes use of the behavior provided by the
parent class, but is not a subtype of the parent class.
• Generalization. The child class modifies or overrides some of the methods of
the parent class.
• Extension. The child class adds new functionality to the parent class, but
does not change any inherited behavior.
• Limitation. The child class restricts the use of some of the behavior inherited
from the parent class.
• Variance. The child class and parent class are variants of each other, and
the class-subclass relationship is arbitrary.
• Combination. The child class inherits features from more than one parent
class. This is multiple inheritance and will be the subject of a later chapter.
L 4.9
Software Reusability (among projects)
Increased Reliability (resulting from reuse and
sharing of well-tested code)
Code Sharing (within a project)
Consistency of Interface (among related objects)
Software Components
Rapid Prototyping (quickly assemble from pre-
existing components)
Polymorphism and Frameworks (high-level reusable
components)
Information Hiding
L 5.1
Execution Speed
Program Size
Message-Passing Overhead
Program Complexity (in overuse of inheritance)
L 5.2
L 5.3
Types of inheritance
 Acquiring the properties of an existing Object
into newly creating Object to overcome the
redeclaration of properties in deferent classes.
 These are 3 types:
1.Simple Inheritance
SUPER
SUB
SUPER
SUB 1 SUB 2
extendsextends
L 5.4
2. Multi Level
Inheritance
3. Multiple
Inheritance
SUPER
SUB
SUB SUB
SUPER 1
SUPER 2
extends
extends
implements
SUB
SUPER 1 SUPER 2
implements
SUB
extends
Visibility modifiers determine which class
members are accessible and which do not
Members (variables and methods) declared with
public visibility are accessible, and those with
private visibility are not
Problem: How to make class/instance variables
visible only to its subclasses?
Solution: Java provides a third visibility modifier
that helps in inheritance situations: protected
L 6.1
Visibility Modifiers for class/interface:
public : can be accessed from outside the class definition.
protected : can be accessed only within the class definition
in which it appears, within other classess in the same
package, or within the definition of subclassess.
private : can be accessed only within the class definition in
which it appears.
default-access (if omitted) features accessible from inside the
current Java package
L 6.2
 The protected visibility modifier allows a member of a base
class to be accessed in the child
 protected visibility provides more encapsulation than
public does
 protected visibility is not as tightly encapsulated as
private visibility
L 6.3
Book
protected int pages
+ getPages() : int
+ setPages(): void
Dictionary
+ getDefinitions() : int
+ setDefinitions(): void
+ computeRatios() : double
class A {
int i;
void showi() {
System.out.println("i: " + i);
}
}
L 6.4
class B extends A {
int j;
void showj() {
System.out.println(“j: " + j);
}
void sum() {
System.out.println("i+j: " + (i+j));
}
}
L 6.5
class SimpleInheritance {
public static void main(String args[]) {
A a = new A();
B b = new B();
a.i = 10;
System.out.println("Contents of a: ");
a.showi();
b.i = 7; b.j = 8;
System.out.println("Contents of b: ");
subOb.showi(); subOb.showj();
System.out.println("Sum of I and j in b:");
b.sum();}}
L 6.6
The basic Box class:
class Box {
private double width, height, depth;
Box(double w, double h, double d) {
width = w; height = h; depth = d;
}
Box(Box ob) {
width = ob.width;
height = ob.height; depth = ob.depth;
}
double volume() {
return width * height * depth;
}
}
L 6.7
Adding the weight variable to the Box class:
class BoxWeight extends Box {
double weight;
BoxWeight(BoxWeight ob) {
super(ob); weight = ob.weight;
}
BoxWeight(double w, double h, double d, double
m) {
super(w, h, d); weight = m;
}
}
L 6.7
Adding the cost variable to the BoxWeight class:
class Ship extends BoxWeight {
double cost;
Ship(Ship ob) {
super(ob);
cost = ob.cost;
}
Ship(double w, double h,
double d, double m, double c) {
super(w, h, d, m); cost = c;
}}
L 6.8
class DemoShip {
public static void main(String args[]) {
Ship ship1 = new Ship(10, 20, 15, 10, 3.41);
Ship ship2 = new Ship(2, 3, 4, 0.76, 1.28);
double vol;
vol = ship1.volume();
System.out.println("Volume of ship1 is " + vol);
System.out.print("Weight of ship1 is”);
System.out.println(ship1.weight);
System.out.print("Shipping cost: $");
System.out.println(ship1.cost);
L 6.9
vol = ship2.volume();
System.out.println("Volume of ship2 is " + vol);
System.out.print("Weight of ship2 is “);
System.out.println(ship2.weight);
System.out.print("Shipping cost: $“);
System.out.println(ship2.cost);
}
}
L 6.10
L 6.11
“super” uses
 ‘super’ is a keyword used to refer to hidden variables
of super class from sub class.
super.a=a;
 It is used to call a constructor of super class from
constructor of sub class which should be first
statement.
super(a,b);
 It is used to call a super class method from sub class
method to avoid redundancy of code
super.addNumbers(a, b);
 Why is super needed to access super-class members?
 When a sub-class declares the variables or methods with the
same names and types as its super-class:
class A {
int i = 1;
}
class B extends A {
int i = 2;
System.out.println(“i is “ + i);
}
 The re-declared variables/methods hide those of the super-
class.
L 6.12
class A {
int i;
}
class B extends A {
int i;
B(int a, int b) {
super.i = a; i = b;
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
L 6.13
Although the i variable in B hides the i variable
in A, super allows access to the hidden variable
of the super-class:
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
L 6.14
 final keyword is used declare constants which can not change
its value of definition.
 final Variables can not change its value.
 final Methods can not be Overridden or Over Loaded
 final Classes can not be extended or inherited
L 6.15
 A method declared final cannot be overridden in any
sub-class:
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
This class declaration is illegal:
class B extends A {
void meth() {
System.out.println("Illegal!");
}
}
L 6.16
A class declared final cannot be inherited –
has no sub-classes.
final class A { … }
This class declaration is considered illegal:
class B extends A { … }
Declaring a class final implicitly declares all
its methods final.
It is illegal to declare a class as both abstract
and final.
L 6.17
Polymorphism is one of three pillars of object-
orientation.
Polymorphism: many different (poly) forms of
objects that share a common interface respond
differently when a method of that interface is
invoked:
1) a super-class defines the common interface
2) sub-classes have to follow this interface
(inheritance), but are also permitted to provide
their own implementations (overriding)
A sub-class provides a specialized behaviors
relying on the common elements defined by its
super-class.
L 7.1
 A polymorphic reference can refer to different types of objects at
different times
 In java every reference can be polymorphic except of
references to base types and final classes.
 It is the type of the object being referenced, not the reference
type, that determines which method is invoked
 Polymorphic references are therefore resolved at run-time,
not during compilation; this is called dynamic binding
 Careful use of polymorphic references can lead to elegant, robust
software designs
L 7.2
When a method of a sub-class has the same
name and type as a method of the super-class,
we say that this method is overridden.
When an overridden method is called from
within the sub-class:
1) it will always refer to the sub-class method
2) super-class method is hidden
L 7.3
class A {
int i, j;
A(int a, int b) {
i = a; j = b;
}
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
L 7.4
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
System.out.println("k: " + k);
}
}
L 7.5
When show() is invoked on an object of type B,
the version of show() defined in B is used:
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show();
}
}
The version of show() in A is hidden through
overriding.
L7.6
L 7.7
Overloading deals with
multiple methods in the
same class with the same
name but different
signatures
Overloading lets you
define a similar
operation in different
ways for different data
Overriding deals with two
methods, one in a parent
class and one in a child
class, that have the same
signature
o Overriding lets you define
a similar operation in
different ways for different
object types
Java allows abstract classes
 use the modifier abstract on a class header to declare an
abstract class
abstract class Vehicle
{ … }
An abstract class is a placeholder in a class hierarchy
that represents a generic concept
L 7.8
Vehicle
Car Boat Plane
public abstract class Vehicle
{
String name;
public String getName()
{ return name; }  method body
abstract public void move();
 no body!
}
L 7.9
 An abstract class often contains abstract methods,
though it doesn’t have to
 Abstract methods consist of only methods declarations,
without any method body
An abstract class often contains abstract methods, though
it doesn’t have to
 Abstract methods consist of only methods declarations, without
any method body
The non-abstract child of an abstract class must override
the abstract methods of the parent
An abstract class cannot be instantiated
The use of abstract classes is a design decision; it helps us
establish common elements in a class that is too general to
instantiate
L 7.10
 Inheritance allows a sub-class to override the methods
of its super-class.
 A super-class may altogether leave the implementation
details of a method and declare such a method abstract:
 abstract type name(parameter-list);
 Two kinds of methods:
1) concrete – may be overridden by sub-classes
2) abstract – must be overridden by sub-classes
 It is illegal to define abstract constructors or static
methods.
L 7.11
UNIT-4
B.TECH II YR II SEMESTER(TERM 08-09)
UNIT 4 PPT SLIDES
TEXT BOOKS:
1. Java: the complete reference, 7th edition, Herbert
schildt, TMH.Understanding
2. OOP with Java, updated edition, T. Budd, Pearson
education.
No. of slides: 56
S.NO. TOPIC LECTURE NO. PPTSLIDES
1 Defining, Creating and Accessing a Package L1 L1.1TO L1.11
2 Importing packages L2 L2.1 TO L2.5
3 Differences between classes and interfaces L3 L3.1 TO L3.2
4 Defining an interface L 4 L4.1 TO L4.2
5 Implementing interface L5 L5.1 TO 5.7
6 Applying interfaces L6 L6.1 TO 6.3
7 variables in interface and extending interfaces L7 L7.1 TO 7.9
8 Exploring packages – Java.io L8 L 8.1 TO 8.6
9 Exploring packages- java.util. L9 L 9.1 TO 9.9
A package is both a naming and a visibility control
mechanism:
1) divides the name space into disjoint subsets It is
possible to define classes within a package that
are not accessible by code outside the package.
2) controls the visibility of classes and their
members It is possible to define class members
that are only exposed to other members of the
same package.
Same-package classes may have an intimate
knowledge of each other, but not expose that
knowledge to other packages
L 1.1
A package statement inserted as the first line of
the source file:
package myPackage;
class MyClass1 { … }
class MyClass2 { … }
means that all classes in this file belong to the
myPackage package.
 The package statement creates a name space
where such classes are stored.
When the package statement is omitted, class
names are put into the default package which has
no name.
L 1.2
Other files may include the same package instruction:
1.package myPackage;
class MyClass1 { … }
class MyClass2 { … }
2. package myPackage;
class MyClass3{ … }
A package may be distributed through several source
files
L 1.3
Java uses file system directories to store packages.
Consider the Java source file:
package myPackage;
class MyClass1 { … }
class MyClass2 { … }
The byte code files MyClass1.class and
MyClass2.class must be stored in a directory
myPackage.
Case is significant! Directory names must match
package names exactly.
L 1.4
To create a package hierarchy, separate each package
name with a dot:
package myPackage1.myPackage2.myPackage3;
A package hierarchy must be stored accordingly in the
file system:
1) Unix myPackage1/myPackage2/myPackage3
2) Windows myPackage1myPackage2myPackage3
3) Macintosh myPackage1:myPackage2:myPackage3
You cannot rename a package without renaming its
directory!
L 1.5
As packages are stored in directories, how does the
Java run-time system know where to look for
packages?
Two ways:
1) The current directory is the default start point - if
packages are stored in the current directory or sub-
directories, they will be found.
2) Specify a directory path or paths by setting the
CLASSPATH environment variable.
L 1.6
CLASSPATH - environment variable that points
to the root directory of the system’s package
hierarchy.
Several root directories may be specified in
CLASSPATH,
e.g. the current directory and the C:rajumyJava
directory:
.;C:rajumyJava
Java will search for the required packages by
looking up subsequent directories described in
the CLASSPATH variable.
L 1.7
Consider this package statement:
package myPackage;
In order for a program to find myPackage, one of the
following must be true:
1) program is executed from the directory
immediately above myPackage (the parent of
myPackage directory)
2) CLASSPATH must be set to include the path to
myPackage
L 1.8
package MyPack;
class Balance {
String name;
double bal;
Balance(String n, double b) {
name = n; bal = b;
}
void show() {
if (bal<0) System.out.print("-->> ");
System.out.println(name + ": $" + bal);
} }
L 1.9
class AccountBalance {
public static void main(String args[]) {
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for (int i=0; i<3; i++) current[i].show();
}
}
L 1.10
Save, compile and execute:
1) call the file AccountBalance.java
2) save the file in the directory MyPack
3) compile; AccountBalance.class should be also
in MyPack
4) set access to MyPack in CLASSPATH variable,
or make the parent of MyPack your current
directory
5) run: java MyPack.AccountBalance
Make sure to use the package-qualified class
name.
L 1.11
Since classes within packages must be fully-qualified
with their package names, it would be tedious to
always type long dot-separated names.
The import statement allows to use classes or whole
packages directly.
Importing of a concrete class:
import myPackage1.myPackage2.myClass;
Importing of all classes within a package:
import myPackage1.myPackage2.*;
L 2.1
The import statement occurs immediately after the
package statement and before the class statement:
package myPackage;
import otherPackage1;otherPackage2.otherClass;
class myClass { … }
The Java system accepts this import statement by
default:
import java.lang.*;
This package includes the basic language functions.
Without such functions, Java is of no much use.
L 2.2
A package MyPack with one public class Balance.
The class has two same-package variables: public
constructor and a public show method.
package MyPack;
public class Balance {
String name;
double bal;
public Balance(String n, double b) {
name = n; bal = b;
}
public void show() {
if (bal<0) System.out.print("-->> ");
System.out.println(name + ": $" + bal);
}
}
L 2.3
The importing code has access to the public class
Balance of the MyPack package and its two public
members:
import MyPack.*;
class TestBalance {
public static void main(String args[]) {
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show();
}
}
L 2.4
Finally, a Java source file consists of:
1) a single package instruction (optional)
2) several import statements (optional)
3) a single public class declaration (required)
4) several classes private to the package (optional)
At the minimum, a file contains a single public class
declaration.
L 2.5
Interfaces are syntactically similar to classes, but they
lack instance variables, and their methods are
declared without any body.
One class can implement any number of interfaces.
Interfaces are designed to support dynamic method
resolution at run time.
L 3.1
Interface is little bit like a class... but interface is lack in
instance variables....that's u can't create object for it.....
Interfaces are developed to support multiple inheritance...
The methods present in interfaces r pure abstract..
The access specifiers public,private,protected are possible
with classes, but the interface uses only one spcifier
public.....
interfaces contains only the method declarations.... no
definitions.......
A interface defines, which method a class has to implement.
This is way - if you want to call a method defined by an
interface - you don't need to know the exact class type of an
object, you only need to know that it implements a specific
interface.
Another important point about interfaces is that a class can
implement multiple interfaces.
L 3.2
Using interface, we specify what a class must do, but
not how it does this.
An interface is syntactically similar to a class, but it
lacks instance variables and its methods are declared
without any body.
An interface is defined with an interface keyword.
L 4.1
 An interface declaration consists of modifiers, the keyword interface,
the interface name, a comma-separated list of parent interfaces (if any),
and the interface body. For example:
public interface GroupedInterface extends Interface1, Interface2,
Interface3 {
// constant declarations double E = 2.718282;
// base of natural logarithms //
//method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}
 The public access specifier indicates that the interface can be used by
any class in any package. If you do not specify that the interface is
public, your interface will be accessible only to classes defined in the
same package as the interface.
 An interface can extend other interfaces, just as a class can extend or
subclass another class. However, whereas a class can extend only one
other class, an interface can extend any number of interfaces. The
interface declaration includes a comma-separated list of all the
interfaces that it extends
L 4.2
General format:
access interface name {
type method-name1(parameter-list);
type method-name2(parameter-list);
…
type var-name1 = value1;
type var-nameM = valueM;
…
}
L 5.1
Two types of access:
1) public – interface may be used anywhere in a
program
2) default – interface may be used in the current
package only
Interface methods have no bodies – they end
with the semicolon after the parameter list.
They are essentially abstract methods.
An interface may include variables, but they
must be final, static and initialized with a
constant value.
In a public interface, all members are implicitly
public.
L 5.2
A class implements an interface if it provides a
complete set of methods defined by this interface.
1) any number of classes may implement an interface
2) one class may implement any number of interfaces
Each class is free to determine the details of its
implementation.
Implementation relation is written with the
implements keyword.
L 5.3
General format of a class that includes the
implements clause:
Syntax:
access class name extends super-class implements
interface1, interface2, …, interfaceN {
…
}
Access is public or default.
L 5.4
If a class implements several interfaces, they are
separated with a comma.
If a class implements two interfaces that declare the
same method, the same method will be used by the
clients of either interface.
The methods that implement an interface must be
declared public.
The type signature of the implementing method must
match exactly the type signature specified in the
interface definition.
L 5.5
Declaration of the Callback interface:
interface Callback {
void callback(int param);
}
Client class implements the Callback interface:
class Client implements Callback {
public void callback(int p) {
System.out.println("callback called with " + p);
}
}
L 5.6
An implementing class may also declare its own
methods:
class Client implements Callback {
public void callback(int p) {
System.out.println("callback called with " + p);
}
void nonIfaceMeth() {
System.out.println("Classes that implement “ +
“interfaces may also define ” +
“other members, too.");
}
}
L 5.7
A Java interface declares a set of method signatures
i.e., says what behavior exists Does not say how
the behavior is implemented
i.e., does not give code for the methods
• Does not describe any state (but may include
“final” constants)
L 6.1
A concrete class that implements an interface
Contains “implements InterfaceName” in the class
declaration
Must provide implementations (either directly or
inherited from a superclass) of all methods declared
in the interface
An abstract class can also implement an interface
Can optionally have implementations of some or all
interface methods
L 6.2
Interfaces and Extends both describe an “is- a”
relation
If B implements interface A, then B inherits the
(abstract) method signatures in A
If B extends class A, then B inherits everything in
A,
which can include method code and instance
variables as well as abstract method signatures
Inheritance” is sometimes used to talk about the
superclass/subclass “extends” relation only
L 6.3
Variables declared in an interface must be
constants.
A technique to import shared constants into
multiple classes:
1) declare an interface with variables initialized to
the desired values
2) include that interface in a class through
implementation
As no methods are included in the interface, the
class does not implement
anything except importing the variables as
constants.
L 7.1
An interface with constant values:
import java.util.Random;
interface SharedConstants {
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
}
L 7.2
Question implements SharedConstants, including all
its constants.
Which constant is returned depends on the generated
random number:
class Question implements SharedConstants {
Random rand = new Random();
int ask() {
int prob = (int) (100 * rand.nextDouble());
if (prob < 30) return NO;
else if (prob < 60) return YES;
else if (prob < 75) return LATER;
else if (prob < 98) return SOON;
else return NEVER;
}
}
L 7.3
AskMe includes all shared constants in the same way, using
them to display the result, depending on the value received:
class AskMe implements SharedConstants {
static void answer(int result) {
switch(result) {
case NO: System.out.println("No"); break;
case YES: System.out.println("Yes"); break;
case MAYBE: System.out.println("Maybe"); break;
case LATER: System.out.println("Later"); break;
case SOON: System.out.println("Soon"); break;
case NEVER: System.out.println("Never"); break;
}
}
L 7.4
The testing function relies on the fact that both
ask and answer methods,
defined in different classes, rely on the same
constants:
public static void main(String args[]) {
Question q = new Question();
answer(q.ask());
answer(q.ask());
answer(q.ask());
answer(q.ask());
}
}
L 7.5
One interface may inherit another interface.
The inheritance syntax is the same for classes and
interfaces.
interface MyInterface1 {
void myMethod1(…) ;
}
interface MyInterface2 extends MyInterface1 {
void myMethod2(…) ;
}
When a class implements an interface that
inherits another interface, it must provide
implementations for all methods defined within
the interface inheritance chain.
L 7.6
Consider interfaces A and B.
interface A {
void meth1();
void meth2();
}
B extends A:
interface B extends A {
void meth3();
}
L 7.7
MyClass must implement all of A and B methods:
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
} }
L 7.8
Create a new MyClass object, then invoke all
interface methods on it:
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
L 7.9
Provides for system input and output through data
streams, serialization and the file system.
Interface Summary
.DataInput The DataInput interface provides for reading
bytes from a binary stream and reconstructing from them
data in any of the Java primitive types.
DataOutputThe DataOutput interface provides for
converting data from any of the Java primitive types to a
series of bytes and writing these bytes to a binary stream
.Externalizable Only the identity of the class of an
Externalizable instance is written in the serialization
stream and it is the responsibility of the class to save and
restore the contents of its instances.
SerializableSerializability of a class is enabled by the class
implementing the java.io.Serializable interface.
L 8.1
 BufferedInputStream: A BufferedInputStream adds functionality
to another input stream-namely, the ability to buffer the input and
to support the mark and reset methods.
 BufferedOutputStream: The class implements a buffered output
stream.
 BufferedReader: Reads text from a character-input stream,
buffering characters so as to provide for the efficient reading of
characters, arrays, and lines.
 BufferedWriter: Writes text to a character-output stream,
buffering characters so as to provide for the efficient writing of
single characters, arrays, and strings
 ByteArrayInputStream: A ByteArrayInputStream contains an
internal buffer that contains bytes that may be read from the
stream.
 ByteArrayOutputStream: This class implements an output
stream in which the data is written into a byte array.
L 8.2
CharArrayReader: This class implements a character
buffer that can be used as a character-input stream
.CharArrayWriter: This class implements a character
buffer that can be used as an Writer
Console: Methods to access the character-based
console device, if any, associated with the current Java
virtual machine.
DataInputStream: A data input stream lets an
application read primitive Java data types from an
underlying input stream in a machine-independent
way.
DataOutputStream: A data output stream lets an
application write primitive Java data types to an
output stream in a portable way.
L 8.3
 File: An abstract representation of file and directory pathnames.
 FileInputStream: A FileInputStream obtains input bytes from a
file in a file system.
 FileOutputStream: A file output stream is an output stream for
writing data to a File or to a FileDescriptor.
 FileReader: Convenience class for reading character files.
 FileWriter: Convenience class for writing character files.
 FilterInputStream: A FilterInputStream contains some other
input stream, which it uses as its basic source of data, possibly
transforming the data along the way or providing additional
functionality.
 FilterOutputStream: This class is the superclass of all classes that
filter output streams
 .FilterReader: Abstract class for reading filtered character streams
 .FilterWriter: Abstract class for writing filtered character streams
 .InputStream: This abstract class is the superclass of all classes
representing an input stream of bytes.
 InputStreamReader: An InputStreamReader is a bridge from byte
streams to character streams: It reads bytes and decodes them into
characters using a specified charset.
L 8.4
 ObjectInputStream: An ObjectInputStream deserializes primitive
data and objects previously written using an ObjectOutputStream
 ObjectOutputStream: An ObjectOutputStream writes primitive
data types and graphs of Java objects to an OutputStream.
 OutputStream: This abstract class is the superclass of all classes
representing an output stream of bytes.
 OutputStreamWriter: An OutputStreamWriter is a bridge from
character streams to byte streams: Characters written to it are
encoded into bytes using a specified charset.
 PrintWriter: Prints formatted representations of objects to a text-
output stream.
 RandomAccessFile: Instances of this class support both reading
and writing to a random access file.
 StreamTokenizer: The StreamTokenizer class takes an input
stream and parses it into "tokens", allowing the tokens to be read
one at a time.
L 8.5
FileNotFoundException: Signals that an attempt to
open the file denoted by a specified pathname has
failed.
InterruptedIOException: Signals that an I/O
operation has been interrupted
InvalidClassException: Thrown when the
Serialization runtime detects one of the following
problems with a Class.
InvalidObjectException: Indicates that one or more
deserialized objects failed validation tests.
IOException: Signals that an I/O exception of some
sort has occurred.
L 8.6
Contains the collections framework, legacy collection
classes, event model, date and time facilities,
internationalization, and miscellaneous utility classes
(a string tokenizer, a random-number generator, and
a bit array).
L9.1
Collection<E>: The root interface in the collection
hierarchy.
Comparator<T>: A comparison function, which imposes
a total ordering on some collection of objects.
Enumeration<E>: An object that implements the
Enumeration interface generates a series of elements, one
at a time.
EventListener: A tagging interface that all event listener
interfaces must extend.
Iterator<E>: An iterator over a collection
List<E>An ordered collection (also known as a sequence).
ListIterator<E>: An iterator for lists that allows the
programmer to traverse the list in either direction, modify
the list during iteration, and obtain the iterator's current
position in the list.
L9.2
Map<K,V>: An object that maps keys to values.
Observer: A class can implement the Observer
interface when it wants to be informed of changes in
observable objects.
Queue<E>: A collection designed for holding
elements prior to processing.
Set<E>: A collection that contains no duplicate
elements.
SortedMap<K,V>: A Map that further provides a
total ordering on its keys.
SortedSet<E>: A Set that further provides a total
ordering on its elements.
L 9.3
 AbstractCollection<E>: This class provides a skeletal
implementation of the Collection interface, to minimize the effort
required to implement this interface.
 AbstractList<E>: This class provides a skeletal implementation of
the List interface to minimize the effort required to implement this
interface backed by a "random access" data store (such as an
array).
 AbstractMap<K,V>: This class provides a skeletal implementation
of the Map interface, to minimize the effort required to implement
this interface.
 AbstractQueue<E>: This class provides skeletal implementations
of some Queue operations.
 AbstractSequentialList<E>: This class provides a skeletal
implementation of the List interface to minimize the effort
required to implement this interface backed by a "sequential
access" data store (such as a linked list).
 AbstractSet<E>: This class provides a skeletal implementation of
the Set interface to minimize the effort required to implement this
interface.
L 9.4
ArrayList<E>: Resizable-array implementation
of the List interface
Arrays: This class contains various methods for
manipulating arrays (such as sorting and
searching).
BitSet: This class implements a vector of bits that
grows as needed
Calendar: The Calendar class is an abstract class
that provides methods for converting between a
specific instant in time and a set of calendar fields:
such as YEAR, MONTH, DAY_OF_MONTH,
HOUR, and so on, and for manipulating the
calendar fields, such as getting the date of the
next week
L 9.5
Collections: This class consists exclusively of
static methods that operate on or return
collections
Currency: Represents a currency.
Date: The class Date represents a specific instant
in time, with millisecond precision.
Dictionary<K,V>: The Dictionary class is the
abstract parent of any class, such as Hashtable,
which maps keys to values.
EventObject: The root class from which all event
state objects shall be derived.
L 9.6
 GregorianCalendar: GregorianCalendar is a concrete subclass of
Calendar and provides the standard calendar system used by most
of the world.
 HashMap<K,V>: Hash table based implementation of the Map
interface.
 HashSet<E>: This class implements the Set interface, backed by a
hash table (actually a HashMap instance)
 .Hashtable<K,V>: This class implements a hashtable, which maps
keys to values.
 LinkedList<E>: Linked list implementation of the List interface
 Locale: A Locale object represents a specific geographical,
political, or cultural region.
 Observable: This class represents an observable object, or "data"
in the model-view paradigm
 Properties: The Properties class represents a persistent set of
properties.
L 9.7
 Random: An instance of this class is used to generate a stream of
pseudorandom numbers.
 ResourceBundle: Resource bundles contain locale-specific
objects.
 SimpleTimeZone: SimpleTimeZone is a concrete subclass of
TimeZone that represents a time zone for use with a Gregorian
calendar.
 Stack<E>: The Stack class represents a last-in-first-out (LIFO)
stack of objects.
 StringTokenizer: The string tokenizer class allows an application
to break a string into tokens.
 TimeZone: TimeZone represents a time zone offset, and also
figures out daylight savings.
 TreeMap<K,V>: A Red-Black tree based NavigableMap
implementation.
 TreeSet<E>: A NavigableSet implementation based on a
TreeMap.UUIDA class that represents an immutable universally
unique identifier (UUID).
 Vector<E>: The Vector class implements a growable array of
objects
L 9.8
 EmptyStackException: Thrown by methods in the Stack class
to indicate that the stack is empty.
 InputMismatchException: Thrown by a Scanner to indicate that
the token retrieved does not match the pattern for the expected
type, or that the token is out of range for the expected type.
 InvalidPropertiesFormatException: Thrown to indicate that an
operation could not complete because the input did not conform
to the appropriate XML document type for a collection of
properties, as per the Properties specification.
 NoSuchElementException: Thrown by the nextElement method
of an Enumeration to indicate that there are no more elements in
the enumeration.
 TooManyListenersException: The TooManyListenersException
Exception is used as part of the Java Event model to annotate and
implement a unicast special case of a multicast Event Source.
 UnknownFormatConversionException: Unchecked exception
thrown when an unknown conversion is given.
L 9.9
UNIT-5
B.TECH II YR II SEMESTER(TERM 08-09)
UNIT 5 PPT SLIDES
TEXT BOOKS:
1. Java: the complete reference, 7th edition, Herbert
schildt, TMH.Understanding
2. OOP with Java, updated edition, T. Budd, Pearson
education.
No. of slides:75
Exceptions
Exception is an abnormal condition that arises when
executing a program.
In the languages that do not support exception
handling, errors must be checked and handled
manually, usually through the use of error codes.
In contrast, Java:
1) provides syntactic mechanisms to signal, detect and
handle errors
2) ensures a clean separation between the code
executed in the
absence of errors and the code to handle various kinds
of errors
3) brings run-time error management into object-
oriented programming
L 1.1
An exception is an object that describes an
exceptional condition (error) that has occurred
when executing a program.
Exception handling involves the following:
1) when an error occurs, an object (exception)
representing this error is created and thrown in the
method that caused it
2) that method may choose to handle the exception itself
or pass it on
3) either way, at some point, the exception is caught and
processed
L 1.2
Exceptions can be:
1) generated by the Java run-time system Fundamental errors
that violate the rules of the Java language or the constraints
of the Java execution environment.
2) manually generated by programmer’s code Such
exceptions are typically used to report some error
conditions to the caller of a method.
L 1.3
Five constructs are used in exception handling:
1) try – a block surrounding program statements to monitor
for exceptions
2) catch – together with try, catches specific kinds of
exceptions and handles them in some way
3) finally – specifies any code that absolutely must be executed
whether or not an exception occurs
4) throw – used to throw a specific exception from the
program
5) throws – specifies which exceptions a given method can
throw
L 1.4
General form:
try { … }
catch(Exception1 ex1) { … }
catch(Exception2 ex2) { … }
…
finally { … }
where:
1) try { … } is the block of code to monitor for exceptions
2) catch(Exception ex) { … } is exception handler for the
exception Exception
3) finally { … } is the block of code to execute before the try
block ends
L 1.5
Separating Error-Handling code from “regular”
business logic code
Propagating errors up the call stack
Grouping and differentiating error types
L 2.1
In traditional programming, error detection, reporting, and
handling often lead to confusing code
Consider pseudocode method here that reads an
entire file into memory
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
L 2.2
● In traditional programming, To handle such cases, the readFile
function must have more code to do error detection, reporting,
and handling.
errorCodeType readFile {
initialize errorCode = 0;
open the file;
if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
}
L 2.3
else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
L 2.4
Exceptions enable you to write the main flow of your code and to
deal with the exceptional cases elsewhere
readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
}
L 2.5
catch (sizeDeterminationFailed) {
doSomething;
}catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}
Note that exceptions don't spare you the effort of doing
the work of detecting, reporting, and handling errors,
but they do help you organize the work more
effectively.
L 2.6
 Suppose that the readFile method is the fourth method in a
series of nested method calls made by the main program:
method1 calls method2, which calls method3, which finally
calls readFile
 Suppose also that method1 is the only method interested in
the errors that might occur within readFile.
method1 {
call method2;
}
method2 {
call method3;
}
method3 {
call readFile;
}
L 2.7
L 2.8
method1 {
errorCodeType error;
error = call method2;
if (error)
doErrorProcessing;
else
proceed;
}
errorCodeType method2 {
errorCodeType error;
error = call method3;
if (error)
return error;
else
proceed;
}
errorCodeType method3 {
errorCodeType error;
error = call readFile;
if (error)
return error;
else
proceed;
}
Traditional error notification
Techniques force method2 and
method3 to propagate the error
codes returned by readFile up
the call stack until the error
codes finally reach method1—
the only method that is
interested in them.
L 2.9
method1 {
try {
call method2;
} catch (exception e) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}
 Any checked exceptions
that can be thrown within a
method must be specified in
its throws clause.
Because all exceptions thrown within a program are objects,
the grouping or categorizing of exceptions is a natural
outcome of the class hierarchy
An example of a group of related exception classes in the Java
platform are those defined in java.io.IOException and its
descendants
IOException is the most general and represents any type of
error that can occur when performing I/O
Its descendants represent more specific errors. For example,
FileNotFoundException means that a file could not be located
on disk.
L 2.10
 A method can write specific handlers that can
handle a very specific exception
The FileNotFoundException class has no
descendants, so the following handler can handle
only one type of exception.
catch (FileNotFoundException e) {
...
}
L 2.11
A method can catch an exception based on its group
or general type by specifying any of the exception's
super classes in the catch statement.
For example, to catch all I/O exceptions, regardless
of their specific type, an exception handler specifies
an IOException argument.
// Catch all I/O exceptions, including
// FileNotFoundException, EOFException, and so on.
catch (IOException e) {
...
}
L 2.12
There are two basic models in exception-handling theory.
In termination the error is so critical there’s no way to get
back to where the exception occurred. Whoever threw the
exception decided that there was no way to salvage the
situation, and they don’t want to come back.
The alternative is called resumption. It means that the
exception handler is expected to do something to rectify
the situation, and then the faulting method is retried,
presuming success the second time. If you want
resumption, it means you still hope to continue execution
after the exception is handled.
L 2.13
In resumption a method call that want resumption-
like behavior (i.e don’t throw an exception all a
method that fixes the problem.)
Alternatively, place your try block inside a while
loop that keeps reentering the try block until the
result is satisfactory.
Operating systems that supported resumptive
exception handling eventually ended up using
termination-like code and skipping resumption.
L 2.14
All exceptions are sub-classes of the build-in class
Throwable.
Throwable contains two immediate sub-classes:
1) Exception – exceptional conditions that programs should
catch
The class includes:
a) RuntimeException – defined automatically for
user programs to include: division by zero, invalid
array indexing, etc.
b) use-defined exception classes
2) Error – exceptions used by Java to indicate errors with the
runtime environment; user programs are not supposed to
catch them
L 3.1
L 3.2
Syntax:
try {
<code to be monitored for exceptions>
} catch (<ExceptionType1> <ObjName>) {
<handler if ExceptionType1 occurs>
} ...
} catch (<ExceptionTypeN> <ObjName>) {
<handler if ExceptionTypeN occurs>
}
L 3.3
class DivByZero {
public static void main(String args[]) {
try {
System.out.println(3/0);
System.out.println(“Please print me.”);
} catch (ArithmeticException exc) {
//Division by zero is an ArithmeticException
System.out.println(exc);
}
System.out.println(“After exception.”);
}
}
L 3.4
class MultipleCatch {
public static void main(String args[]) {
try {
int den = Integer.parseInt(args[0]);
System.out.println(3/den);
} catch (ArithmeticException exc) {
System.out.println(“Divisor was 0.”);
} catch (ArrayIndexOutOfBoundsException exc2) {
System.out.println(“Missing argument.”);
}
System.out.println(“After exception.”);
}
}
L 3.5
class NestedTryDemo {
public static void main(String args[]){
try {
int a = Integer.parseInt(args[0]);
try {
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println(“Div by zero error!");
} } catch (ArrayIndexOutOfBoundsException) {
System.out.println(“Need 2 parameters!");
} } }
L 3.6
class NestedTryDemo2 {
static void nestedTry(String args[]) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println("Div by zero error!");
} }
public static void main(String args[]){
try {
nestedTry(args);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Need 2 parameters!");
} } }
L 3.7
So far, we were only catching the exceptions thrown
by the Java system.
In fact, a user program may throw an exception
explicitly:
throw ThrowableInstance;
ThrowableInstance must be an object of type
Throwable or its subclass.
L 4.1
Once an exception is thrown by:
throw ThrowableInstance;
1) the flow of control stops immediately
2) the nearest enclosing try statement is inspected if it has a
catch statement that matches the type of exception:
1) if one exists, control is transferred to that statement
2) otherwise, the next enclosing try statement is examined
3) if no enclosing try statement has a corresponding catch
clause, the default exception handler halts the program
and prints the stack
L 4.2
Two ways to obtain a Throwable instance:
1) creating one with the new operator
All Java built-in exceptions have at least two Constructors:
One without parameters and another with one String
parameter:
throw new NullPointerException("demo");
2) using a parameter of the catch clause
try { … } catch(Throwable e) { … e … }
L 4.3
class ThrowDemo {
//The method demoproc throws a NullPointerException
exception which is immediately caught in the try block and
re-thrown:
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e;
}
}
L 4.4
The main method calls demoproc within the try block
which catches and handles the NullPointerException
exception:
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
L 4.5
If a method is capable of causing an exception that it
does not handle, it must specify this behavior by the
throws clause in its declaration:
type name(parameter-list) throws exception-list {
…
}
where exception-list is a comma-separated list of all
types of exceptions that a method might throw.
All exceptions must be listed except Error and
RuntimeException or any of their subclasses, otherwise
a compile-time error occurs.
L 4.6
The throwOne method throws an exception that it does
not catch, nor declares it within the throws clause.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
Therefore this program does not compile.
L 4.7
Corrected program: throwOne lists exception, main catches it:
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
} } }
L 4.8
When an exception is thrown:
1) the execution of a method is changed
2) the method may even return prematurely.
This may be a problem is many situations.
For instance, if a method opens a file on entry and
closes on exit; exception handling should not bypass
the proper closure of the file.
The finally block is used to address this problem.
L 4.9
The try/catch statement requires at least one catch or finally
clause, although both are optional:
try { … }
catch(Exception1 ex1) { … } …
finally { … }
Executed after try/catch whether of not the exception is
thrown.
Any time a method is to return to a caller from inside the
try/catch block via:
1) uncaught exception or
2) explicit return
the finally clause is executed just before the method returns.
L 4.10
Three methods to exit in various ways.
class FinallyDemo {
//procA prematurely breaks out of the try by throwing an
exception, the finally clause is executed on the way out:
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
} }
L4.11
// procB’s try statement is exited via a return statement,
the finally clause is executed before procB returns:
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
L 4.12
In procC, the try statement executes normally without
error, however the finally clause is still executed:
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
L 4.13
Demonstration of the three methods:
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
L 4.14
The default java.lang package provides several
exception classes, all sub-classing the
RuntimeException class.
Two sets of build-in exception classes:
1) unchecked exceptions – the compiler does not check
if a method handles or throws there exceptions
2) checked exceptions – must be included in the
method’s throws clause if the method generates but
does not handle them
L 5.1
 Methods that generate but do not handle those
exceptions need not declare them in the
throws clause:
1) ArithmeticException
2) ArrayIndexOutOfBoundsException
3) ArrayStoreException
4) ClassCastException
5) IllegalStateException
6) IllegalMonitorStateException
7) IllegalArgumentException
L 5.2
8. StringIndexOutOfBounds
9. UnsupportedOperationException
10. SecurityException
11. NumberFormatException
12. NullPointerException
13. NegativeArraySizeException
14. IndexOutOfBoundsException
15. IllegalThreadStateException
L 5.3
 Methods that generate but do not handle those
exceptions must declare them in the throws clause:
1. NoSuchMethodException NoSuchFieldException
2. InterruptedException
3. InstantiationException
4. IllegalAccessException
5. CloneNotSupportedException
6. ClassNotFoundException
L 5.4
Build-in exception classes handle some generic
errors.
For application-specific errors define your own
exception classes. How? Define a subclass of
Exception:
class MyException extends Exception { … }
MyException need not implement anything – its
mere existence in the type system allows to use its
objects as exceptions.
L 6.1
A new exception class is defined, with a private detail
variable, a one parameter constructor and an overridden
toString method:
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
L 6.2
class ExceptionDemo {
The static compute method throws the MyException
exception whenever its a argument is greater than 10:
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if (a > 10) throw new MyException(a);
System.out.println("Normal exit");
}
L 6.3
The main method calls compute with two arguments
within a try block that catches the MyException exception:
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
L 6.4
Multi-Tasking
 Two kinds of multi-tasking:
1) process-based multi-tasking
2) thread-based multi-tasking
 Process-based multi-tasking is about allowing several programs to
execute concurrently, e.g. Java compiler and a text editor.
 Processes are heavyweight tasks:
1) that require their own address space
2) inter-process communication is expensive and limited
3) context-switching from one process to another is expensive
and limited
L 7.1
Thread-based multi-tasking is about a single program
executing concurrently
several tasks e.g. a text editor printing and spell-
checking text.
Threads are lightweight tasks:
1) they share the same address space
2) they cooperatively share the same process
3) inter-thread communication is inexpensive
4) context-switching from one thread to another
is low-cost
Java multi-tasking is thread-based.
L 7.2
Multi-threading enables to write efficient programs that
make the maximum use of the CPU, keeping the idle
time to a minimum.
There is plenty of idle time for interactive, networked
applications:
1) the transmission rate of data over a network is much
slower than the rate at which the computer can
process it
2) local file system resources can be read and written at a
much slower rate than can be processed by the CPU
3) of course, user input is much slower than the
computer
L 7.3
Thread exist in several states:
1) ready to run
2) running
3) a running thread can be suspended
4) a suspended thread can be resumed
5) a thread can be blocked when waiting for a resource
6) a thread can be terminated
Once terminated, a thread cannot be resumed.
L 7.4
L 7.5
Born
Blocked
Runnable
Dead
stop()
start()
stop()
Active
block on I/O
I/O available
JVM
sleep(500)
wake up
suspend()
resume()
wait
notify
 New state – After the creations of Thread instance the thread is in
this state but before the start() method invocation. At this point, the
thread is considered not alive.
 Runnable (Ready-to-run) state – A thread start its life from
Runnable state. A thread first enters runnable state after the
invoking of start() method but a thread can return to this state after
either running, waiting, sleeping or coming back from blocked state
also. On this state a thread is waiting for a turn on the processor.
 Running state – A thread is in running state that means the thread
is currently executing. There are several ways to enter in Runnable
state but there is only one way to enter in Running state: the
scheduler select a thread from runnable pool.
 Dead state – A thread can be considered dead when its run()
method completes. If any thread comes on this state that means it
cannot ever run again.
 Blocked - A thread can enter in this state because of waiting the
resources that are hold by another thread.
L 7.6
To create a new thread a program will:
1) extend the Thread class, or
2) implement the Runnable interface
Thread class encapsulates a thread of execution.
The whole Java multithreading environment is based
on the Thread class.
L 8.1
Start: a thread by calling start its run method
Sleep: suspend a thread for a period of time
Run: entry-point for a thread
Join: wait for a thread to terminate
isAlive: determine if a thread is still running
getPriority: obtain a thread’s priority
getName: obtain a thread’s name
L 8.2
To create a new thread by implementing the Runnable
interface:
1) create a class that implements the run method (inside
this method, we define the code that constitutes the new
thread):
public void run()
2) instantiate a Thread object within that class, a possible
constructor is:
Thread(Runnable threadOb, String threadName)
3) call the start method on this object (start calls run):
void start()
L 8.3
A class NewThread that implements Runnable:
class NewThread implements Runnable {
Thread t;
//Creating and starting a new thread. Passing this to the
// Thread constructor – the new thread will call this
// object’s run method:
NewThread() {
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start();
}
L 8.4
//This is the entry point for the newly created thread – a five-iterations
loop
//with a half-second pause between the iterations all within try/catch:
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
L 8.5
class ThreadDemo {
public static void main(String args[]) {
//A new thread is created as an object of
// NewThread:
new NewThread();
//After calling the NewThread start method,
// control returns here.
L 8.6
//Both threads (new and main) continue concurrently.
//Here is the loop for the main thread:
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
L 8.7
The second way to create a new thread:
1) create a new class that extends Thread
2) create an instance of that class
Thread provides both run and start methods:
1) the extending class must override run
2) it must also call the start method
L 8.8
The new thread class extends Thread:
class NewThread extends Thread {
//Create a new thread by calling the Thread’s
// constructor and start method:
NewThread() {
super("Demo Thread");
System.out.println("Child thread: " + this);
start();
}
L 8.9
NewThread overrides the Thread’s run method:
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
8.10
class ExtendThread {
public static void main(String args[]) {
//After a new thread is created:
new NewThread();
//the new and main threads continue
//concurrently…
L 8.11
//This is the loop of the main thread:
try {
for (int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
L 8.12
 Multi-threading introduces asynchronous behavior to a
program.
 How to ensure synchronous behavior when we need it?
 For instance, how to prevent two threads from simultaneously
writing and reading the same object?
 Java implementation of monitors:
1) classes can define so-called synchronized methods
2) each object has its own implicit monitor that is
automatically entered when one of the object’s synchronized
methods is called
3) once a thread is inside a synchronized method, no other
thread can call any other synchronized method on the same
object
L 8.13
Language keyword: synchronized
Takes out a monitor lock on an object
Exclusive lock for that thread
If lock is currently unavailable, thread will block
L 8.14
Protects access to code, not to data
Make data members private
Synchronize accessor methods
Puts a “force field” around the locked object so no
other threads can enter
Actually, it only blocks access to other synchronizing
threads
L 8.15
 Any Java thread can be a daemon thread.
 Daemon threads are service providers for other threads running in
the same process as the daemon thread.
 The run() method for a daemon thread is typically an infinite loop
that waits for a service request. When the only remaining threads
in a process are daemon threads, the interpreter exits. This makes
sense because when only daemon threads remain, there is no other
thread for which a daemon thread can provide a service.
 To specify that a thread is a daemon thread, call the setDaemon
method with the argument true. To determine if a thread is a
daemon thread, use the accessor method isDaemon.
L 9.1
o Every Java thread is a member of a thread group.
o Thread groups provide a mechanism for collecting multiple threads into a
single object and manipulating those threads all at once, rather than
individually.
o For example, you can start or suspend all the threads within a group with a
single method call.
o Java thread groups are implemented by the “ThreadGroup” class in the
java.lang package.
 The runtime system puts a thread into a thread group during thread
construction.
 When you create a thread, you can either allow the runtime system to put the
new thread in some reasonable default group or you can explicitly set the new
thread's group.
 The thread is a permanent member of whatever thread group it joins upon its
creation--you cannot move a thread to a new group after the thread has been
created
L 9.2
The “ThreadGroup” class manages groups of threads for Java
applications.
A ThreadGroup can contain any number of threads.
The threads in a group are generally related in some way, such
as who created them, what function they perform, or when
they should be started and stopped.
ThreadGroups can contain not only threads but also other
ThreadGroups.
The top-most thread group in a Java application is the thread
group named main.
You can create threads and thread groups in the main group.
You can also create threads and thread groups in subgroups of
main.
L 9.3
 A thread is a permanent member of whatever thread group it joins when its
created--you cannot move a thread to a new group after the thread has been
created. Thus, if you wish to put your new thread in a thread group other than
the default, you must specify the thread group explicitly when you create the
thread.
 The Thread class has three constructors that let you set a new thread's group:
public Thread(ThreadGroup group, Runnable target) public
Thread(ThreadGroup group, String name) public
Thread(ThreadGroup group, Runnable target, String name)
 Each of these constructors creates a new thread, initializes it based on the
Runnable and String parameters, and makes the new thread a member of the
specified group.
For example:
ThreadGroup myThreadGroup = new ThreadGroup("My Group of Threads");
Thread myThread = new Thread(myThreadGroup, "a thread for my group");
L 9.4
UNIT-6
B.TECH II YR II SEMESTER(TERM 08-09)
UNIT 6 PPT SLIDES
TEXT BOOKS:
1. Java: the complete reference, 7th editon, Herbert schildt,
TMH.Understanding
2. OOP with Java, updated edition, T. Budd, pearson eduction.
No. of slides:53
S.NO. TOPIC LECTURE NO. PPTSLIDES
1 Events, Event sources, Event classes, L1 L1.1TO L1.10
2 Event Listeners, Delegation event model L2 L2.1 TO L2.3
3 Handling mouse and keyboard events, L3 L3.1 TO L3.5
Adapter classes, inner classes.
4 The AWT class hierarchy, L 4 L4.1 TO L4.4
5 user interface components- labels, button, L 5 L5.1 TO L5.8
canvas, scrollbars, text
6 components, check box, check box groups, L 6L6.1 TO L6.7
choices
7 lists panels – scrollpane, dialogs L 7 L7.1 TO L7.4
8 menubar, graphics L 8 L8.1 TO L8.3
9 layout manager – layout manager types – L 9 L9.1 TO L9.7
boarder, grid, flow, card and grib bag
For the user to interact with a GUI, the underlying
operating system must support event handling.
1) operating systems constantly monitor events such as
keystrokes, mouse clicks, voice command, etc.
2) operating systems sort out these events and report
them to the appropriate application programs
3) each application program then decides what to do in
response to these events
L 1.1
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.
L 1.2
Events may also occur that are not directly caused
by interactions with a user interface.
For example, an event may be generated when a
timer expires, a counter exceeds a value, a
software or hardware failure occurs, or an
operation is completed.
Events can be defined as needed and appropriate
by application.
L 1.3
 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.
 General form is:
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event
listener.
 For example,
1. The method that registers a keyboard event listener is called
addKeyListener().
2. The method that registers a mouse motion listener is called
addMouseMotionListener( ).
L 1.4
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. The general form is:
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.
L 1.5
A source must also provide a method that allows a
listener to unregister an interest in a specific type of
event.
The general form is:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event and el is a
reference to the event listener.
For example, to remove a keyboard listener, you
would call removeKeyListener( ).
The methods that add or remove listeners are
provided by the source that generates events.
For example, the Component class provides
methods to add and remove keyboard and mouse
event listeners.
L 1.6
The Event classes that represent events are at the core of
Java's event handling mechanism.
Super class of the Java event class hierarchy is
EventObject, which is in java.util. for all events.
Constructor is :
EventObject(Object src)
Here, src is the object that generates this event.
EventObject contains two methods: getSource( ) and
toString( ).
1. The getSource( ) method returns the source of the
event. General form is : Object getSource( )
2. The toString( ) returns the string equivalent of the
event.
L 1.7
EventObject is a superclass of all events.
AWTEvent is a superclass of all AWT events that are
handled by the delegation event model.
The package java.awt.event defines several types of
events that are generated by various user interface
elements.
L 1.8
ActionEvent: Generated when a button is pressed, a list
item is double clicked, or a menu item is selected.
AdjustmentEvent: Generated when a scroll bar is
manipulated.
ComponentEvent: Generated when a component is
hidden, moved, resized, or becomes visible.
ContainerEvent: Generated when a component is added to
or removed from a container.
FocusEvent: Generated when a component gains or loses
keyboard focus.
L 1.9
InputEvent: Abstract super class for all component input
event classes.
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.
KeyEvent: Generated when input is received from the
keyboard.
MouseEvent: Generated when the mouse is dragged,
moved, clicked, pressed, or released; also generated when
the mouse enters or exits a component.
TextEvent: Generated when the value of a text area or text
field is changed.
WindowEvent: Generated when a window is activated,
closed, deactivated, deiconified, iconified, opened, or quit.
L 1.10
 A listener is an object that is notified when an event occurs.
 Event has two major requirements.
1. It must have been registered with one or more sources to receive
notifications about specific types of events.
2. It must implement methods to receive and process these
notifications.
 The methods that receive and process events are defined in a set of
interfaces found in java.awt.event.
 For example, the MouseMotionListener interface defines two
methods to receive notifications when the mouse is dragged or
moved.
 Any object may receive and process one or both of these events if it
provides an implementation of this interface.
L 2.1
 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.
 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.
L 2.2
 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.
 This required components to receive events that they did not process,
and it wasted valuable time.The delegation event model eliminates
this overhead.
Note
 Java also allows you to process events without using the delegation
event model.
 This can be done by extending an AWT component.
L 2.3
 mouse events can be handled by implementing the
MouseListener and the MouseMotionListener
interfaces.
 MouseListener Interface defines five methods. The
general forms of these methods are:
1. void mouseClicked(MouseEvent me)
2. void mouseEntered(MouseEvent me)
3. void mouseExited(MouseEvent me)
4. void mousePressed(MouseEvent me)
5. void mouseReleased(MouseEvent me)
 MouseMotionListener Interface. This interface defines
two methods. Their general forms are :
1. void mouseDragged(MouseEvent me)
2. void mouseMoved(MouseEvent me)
L 3.1
 Keyboard events, can be handled by implementing the
KeyListener interface.
 KeyListner interface defines three methods. The general forms of
these methods are :
1. void keyPressed(KeyEvent ke)
2. void keyReleased(KeyEvent ke)
3. void keyTyped(KeyEvent ke)
 To implement keyboard events implementation to the above
methods is needed.
L 3.2
Java provides a special feature, called an adapter class, that
can simplify the creation of event handlers.
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.
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.
L 3.3
adapter classes in java.awt.event are.
Adapter Class Listener Interface
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
FocusAdapter FocusListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
WindowAdapter WindowListener
L 3.4
Inner classes, which allow one class to be defined within
another.
An inner class is a non-static nested class. It has access to
all of the variables and methods of its outer class and may
refer to them directly in the same way that other non-
static members of the outer class do.
An inner class is fully within the scope of its enclosing
class.
an inner class has access to all of the members of its
enclosing class, but the reverse is not true.
Members of the inner class are known only within the
scope of the inner class and may not be used by the outer
class
L 3.5
 The AWT classes are contained in the java.awt package.
It is one of Java's largest packages. some of the AWT
classes.
 AWT Classes
1. AWTEvent:Encapsulates AWT events.
2. AWTEventMulticaster: Dispatches events to multiple listeners.
3. BorderLayout: The border layout manager. Border layouts use
five components: North, South, East, West, and Center.
4. Button: Creates a push button control.
5. Canvas: A blank, semantics-free window.
6. CardLayout: The card layout manager. Card layouts emulate
index cards. Only the one on top is showing.
L 4.1
7. Checkbox: Creates a check box control.
8. CheckboxGroup: Creates a group of check box controls.
9. CheckboxMenuItem: Creates an on/off menu item.
10. Choice: Creates a pop-up list.
11. Color: Manages colors in a portable, platform-independent fashion.
12. Component: An abstract super class for various AWT components.
13. Container: A subclass of Component that can hold other
components.
14. Cursor: Encapsulates a bitmapped cursor.
15. Dialog: Creates a dialog window.
16. Dimension: Specifies the dimensions of an object. The width is
stored in width, and the height is stored in height.
17. Event: Encapsulates events.
18. EventQueue: Queues events.
19. FileDialog: Creates a window from which a file can be selected.
20. FlowLayout: The flow layout manager. Flow layout positions
components left to right, top to bottom.
L 4.2
21. Font: Encapsulates a type font.
22. FontMetrics: Encapsulates various information related to a font. This
information helps you display text in a window.
23. Frame: Creates a standard window that has a title bar, resize
corners, and a menu bar.
24. Graphics: Encapsulates the graphics context. This context is used
by various output methods to display output in a window.
25. GraphicsDevice: Describes a graphics device such as a screen or
printer.
26. GraphicsEnvironment: Describes the collection of available Font
and GraphicsDevice objects.
27. GridBagConstraints: Defines various constraints relating to the
GridBagLayout class.
28. GridBagLayout: The grid bag layout manager. Grid bag layout
displays components subject to the constraints
specified by GridBagConstraints.
29. GridLayout: The grid layout manager. Grid layout displays
components i n a two-dimensional grid.
L 4.3
30. Scrollbar: Creates a scroll bar control.
31. ScrollPane: A container that provides horizontal and/or
vertical scrollbars for another component.
32. SystemColor: Contains the colors of GUI widgets such
as windows, scrollbars, text, and others.
33. TextArea: Creates a multiline edit control.
34. TextComponent: A super class for TextArea and
TextField.
35. TextField: Creates a single-line edit control.
36. Toolkit: Abstract class implemented by the AWT.
37. Window: Creates a window with no frame, no menu
bar, and no title.
L 4.4
Labels: Creates a label that displays a string.
 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:
1. Label( )
2. Label(String str)
3. Label(String str, int how)
 The first version creates a blank label.
 The second version creates a label that contains the string specified by
str. 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.
L 5.1
 Set or change the text in a label is done by using the setText( ) method.
 Obtain the current label by calling getText( ).
 These methods are shown here:
void setText(String str)
String getText( )
 For setText( ), str specifies the new label. For getText( ), the current label is
returned.
 To set the alignment of the string within the label by calling setAlignment( ).
 To obtain the current alignment, call getAlignment( ).
 The methods are as follows:
void setAlignment(int how)
int getAlignment( )
Label creation: Label one = new Label("One");
L 5.2
 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. Button defines these two
constructors:
Button( )
Button(String str)
 The first version creates an empty button. The second creates a button that
contains str as a label.
 After a button has been created, you can set its label by calling setLabel( ).
 You can retrieve its label by calling getLabel( ).
 These methods are as follows:
void setLabel(String str)
String getLabel( )
Here, str becomes the new label for the button.
Button creation: Button yes = new Button("Yes");
L 5.3
It is not part of the hierarchy for applet or frame windows
Canvas encapsulates a blank window upon which you can
draw.
Canvas creation:
Canvas c = new Canvas();
Image test = c.createImage(200, 100);
This creates an instance of Canvas and then calls the
createImage( ) method to actually make an Image
object.
At this point, the image is blank.
L 5.4
 Scrollbar generates adjustment events when the scroll bar is
manipulated.
 Scrollbar creates a scroll bar control.
 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.
 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.
L 5.5
 Scrollbar defines the following constructors:
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
 The first form creates a vertical scroll bar.
 The second and third forms allow you to specify the orientation of the
scroll bar. 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.
 vertSB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, height);
 horzSB = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, width);
L 5.6
 Text is created by Using a TextField class
 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. TextField defines the
following constructors:
TextField( )
TextField(int numChars)
TextField(String str)
TextField(String str, int numChars)
L 5.7
 The first version creates a default text field.
 The second form creates a text field that is numChars characters wide.
 The third form initializes the text field with the string contained in
str.
 The fourth form initializes a text field and sets its width.
 TextField (and its superclass TextComponent) provides several
methods that allow you to utilize a text field.
 To obtain the string currently contained in the text field, call
getText().
 To set the text, call setText( ). These methods are as follows:
String getText( )
void setText(String str)
Here, str is the new string.
L 5.8
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 public methods that are responsible for
managing events, such as mouse and keyboard input,
positioning and sizing the window, and repainting.
A Component object is responsible for remembering the
current foreground and background colors and the
currently selected text font.
L 6.1
To add components
Component add(Component compObj)
Here, compObj is an instance of the control that you want
to add. A reference to compObj is returned.
Once a control has been added, it will automatically be
visible whenever its parent window is displayed.
To remove a control from a window when the control is no
longer needed call remove( ).
This method is also defined by Container. It has this
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( ).
L 6.2
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 can change the state of a check box by clicking on it.
Check boxes can be used individually or as part of a group.
Checkboxes are objects of the Checkbox class.
L 6.3
 Checkbox supports these constructors:
1. Checkbox( )
2. Checkbox(String str)
3. Checkbox(String str, boolean on)
4. Checkbox(String str, boolean on, CheckboxGroup cbGroup)
5. Checkbox(String str, CheckboxGroup cbGroup, boolean on)
 The first form creates a check box whose label is initially blank. The
state of the check box is unchecked.
 The second form creates a check box whose label is specified by str.
The state of the check box is unchecked.
 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.
 The fourth and fifth forms 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. (Check box groups
are described in the next section.) The value of on determines the
initial state of the check box.
L 6.4
 To retrieve the current state of a check box, call getState( ).
 To set its state, call setState( ).
 To obtain the current label associated with a check box by calling
getLabel( ).
 To set the label, call setLabel( ).
 These methods are as follows:
boolean getState( )
void setState(boolean on)
String getLabel( )
void setLabel(String str)
Here, if on is true, the box is checked. If it is false, the box is cleared.
Checkbox creation:
CheckBox Win98 = new Checkbox("Windows 98", null, true);
L 6.5
 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 oftenccalled radio buttons.
 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.
 To determine which check box in a group is currently selected by calling
getSelectedCheckbox( ).
 To 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 checkbox will be turned off.
 CheckboxGroup cbg = new CheckboxGroup();
 Win98 = new Checkbox("Windows 98", cbg, true);
 winNT = new Checkbox("Windows NT", cbg, false);
L 6.6
 The Choice class is used to create a pop-up list of items from which
the user may choose.
 A Choice control is a form of menu.
 Choice only defines the default constructor, which creates an empty
list.
 To add a selection to the list, call addItem( ) or add( ).
void addItem(String name)
void add(String name)
 Here, name is the name of the item being added.
 Items are added to the list in the order to determine which item is
currently selected, you may call either getSelectedItem( ) or
getSelectedIndex( ).
String getSelectedItem( )
int getSelectedIndex( )
L 6.7
 The List class provides a compact, multiple-choice, scrolling selection
list.
 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( )
List(int numRows)
List(int numRows, boolean multipleSelect)
 To add a selection to the list, call add( ). It has the following two
forms:
void add(String name)
void add(String name, int index)
Ex: List os = new List(4, true);
L 7.1
 The Panel class is a concrete subclass of Container.
 It doesn't add any new methods; it simply 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.
 Panel is a window that does not contain a title bar, menu bar, or border.
 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.
 Ex: Panel osCards = new Panel();
CardLayout cardLO = new CardLayout();
osCards.setLayout(cardLO);
L 7.2
 A scroll pane 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.
 constants are defined by the
ScrollPaneConstants interface.
1. HORIZONTAL_SCROLLBAR_ALWAYS
2. HORIZONTAL_SCROLLBAR_AS_NEEDED
3. VERTICAL_SCROLLBAR_ALWAYS
4. VERTICAL_SCROLLBAR_AS_NEEDED
L 7.3
Dialog class creates a dialog window.
constructors are :
Dialog(Frame parentWindow, boolean mode)
Dialog(Frame parentWindow, String title, boolean mode)
The dialog box allows you to choose a method that should be
invoked when the button is clicked.
Ex:
Fontf = new Font("Dialog", Font.PLAIN, 12);
L 7.4
MenuBar class creates a menu bar.
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.
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 selections
displayed on the bar.
Following are the constructors for Menu:
Menu( )
Menu(String optionName)
Menu(String optionName, boolean removable)
L 8.1
Once you have created a menu item, you must
add the item to a Menu object by using
MenuItem add(MenuItem item)
Here, item is the item being added. Items are
added to a menu in the order in which the calls to
add( ) take place.
Once you have added all items to a Menu object,
you can add that object to the menu bar by using
this version of add( ) defined by MenuBar:
Menu add(Menu menu)
L 8.2
 The AWT supports a rich assortment of graphics methods.
 All graphics are drawn relative to a window.
 A graphics context is encapsulated by the Graphics class
 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.
 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
 Ex:
Public void paint(Graphics g)
{
G.drawString(“welcome”,20,20);
}
L 8.3
 A layout manager automatically arranges your controls within a
window by using some type of algorithm.
 it is very tedious to manually lay out a large number of components
and sometimes the width and height information is not yet available
when you need to arrange some control, because the native toolkit
components haven't been realized.
 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. 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.
L 9.1
Layout manager class defines the
following types of layout managers
 Boarder Layout
 Grid Layout
 Flow Layout
 Card Layout
 GridBag Layout
L 9.2
 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.
 The constructors defined by BorderLayout:
BorderLayout( )
BorderLayout(int horz, int vert)
 BorderLayout defines the following constants that specify the regions:
BorderLayout.CENTER
B orderLayout.SOUTH
BorderLayout.EAST
B orderLayout.WEST
BorderLayout.NORTH
 Components can be added by
void add(Component compObj, Object region);
L 9.3
 GridLayout lays out components in a two-dimensional grid. When
you instantiate a
 GridLayout, you define the number of rows and columns. The
constructors are
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)
 The first form creates a single-column grid layout.
 The second form creates a grid layout
 with the specified number of rows and columns.
 The third form 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 unlimited-lengthrows.
L 9.4
 FlowLayout is the default layout manager.
 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. A small space is left between each component, above and below, as
well as left and right.
 The constructors are
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
 The first form creates the default layout, which centers components and leaves
five pixels of space between each component.
 The second form allows to specify how each line is aligned. Valid values for
are:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
These values specify left, center, and right alignment, respectively.
 The third form allows to specify the horizontal and vertical space left between
components in horz and vert, respectively
L 9.5
 The CardLayout class is unique among the other layout managers in that it
stores several different layouts.
 Each layout can be thought of as being on a separate index card in a deck that
can be shuffled so that any card is on top at a given time.
 CardLayout provides these two constructors:
CardLayout( )
CardLayout(int horz, int vert)
 The cards are held in an object of type Panel. This panel must have
CardLayout selected as its layout manager.
 Cards are added to panel using
void add(Component panelObj, Object name);
 methods defined by CardLayout:
void first(Container deck)
void last(Container deck)
void next(Container deck)
void previous(Container deck)
void show(Container deck, String cardName)
L 9.6
The Grid bag layout displays components subject to the
constraints specified by GridBagConstraints.
GridLayout lays out components in a two-dimensional
grid.
The constructors are
GridLayout( )
GridLayout(int numRows, int numColumns )
GridLayout(int numRows, int numColumns, int horz, int vert)
L 9.7
UNIT-7
B.TECH II YR II SEMESTER(TERM 08-09)
UNIT 7 PPT SLIDES
TEXT BOOKS:
1. Java: the complete reference, 7th editon, Herbert schildt,
TMH.Understanding
2. OOP with Java, updated edition, T. Budd, pearson eduction.
No. of slides:45
S.NO. TOPIC LECTURE NO. PPTSLIDES
1 Concepts of Applets, L1 L1.1TO L1.5
differences between applets and applications
2 Life cycle of an applet, types of applets L2 L2.1 TO L2.4
3 Creating applets, passing parameters to applets. L3 L3.1 TO L3.4
4 Introduction to swings, limitations of AWT L 4 L4.1 TO L4.5
5 MVC architecture, components, containers L 5 L5.1 TO L5.10
6 Exploring swing- JApplet, JFrame and JComponent, L 6 L6.1 TO L6.3
7 Icons and Labels, text fields, buttons L 7 L7.1 TO L7.4
8 Check boxes, Combo boxes,RadioButton,JButton L 8 L8.1 TO L8.4
9 Tabbed Panes, Scroll Panes, Trees, and Tables L 9 L9.1 TO L9.4
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.
L 1.1
applets – Java program that runs within a Java-enabled
browser, invoked through a “applet” reference on a web
page, dynamically downloaded to the client computer
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("A Simple Applet", 20, 20);
}
}
L 1.2
 There are two ways to run an applet:
1. Executing the applet within a Java-compatible
Web browser, such as NetscapeNavigator.
2. Using an applet viewer, such as the standard JDK tool,
appletviewer.
 An appletviewer executes your applet in a window. This
is generally the fastest and easiest way to test an applet.
 To execute an applet in a Web browser, you need to
write a short HTML text file that contains the
appropriate APPLET tag.
<applet code="SimpleApplet" width=200 height=60>
</applet>
L 1.3
Java can be used to create two types of programs:
applications and applets.
An application is a program that runs on your computer,
under the operating system of that Computer(i.e an
application created by Java is more or less like one created
using C or C++).
When used to create applications, Java is not much
different from any other computer language.
An applet is an application designed to be transmitted
over the Internet and executed by a Java-compatible Web
browser.
An applet is actually a tiny Java program, dynamically
downloaded across the network, just like an image, sound
file, or video clip.
L 1.4
The important difference is that an applet is an intelligent
program, not just an animation or media file(i.e an applet
is a program that can react to user input and dynamically
change—not just run the same animation or sound over
and over.
Applications require main method to execute.
Applets do not require main method.
Java's console input is quite limited
Applets are graphical and window-based.
L 1.5
 Applets life cycle includes the following methods
1. init( )
2. start( )
3. paint( )
4. stop( )
5. destroy( )
 When an applet begins, the AWT calls the following methods, in
this sequence:
init( )
start( )
paint( )
 When an applet is terminated, the following sequence of method
calls takes place:
stop( )
destroy( )
L 2.1
 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.
 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( ).
 paint( ): The paint( ) method is called each time applet's output must
be redrawn. paint( ) is also called when the applet begins execution.
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.
L 2.2
stop( ): The stop( ) method is 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. Applet uses stop( )
to suspend threads that don't need to run when the applet
is not visible. To restart start( ) is called if the user returns
to the page.
destroy( ): The destroy( ) method is called when the
environment determines that your applet needs to be
removed completely from memory. The stop( ) method is
always called before destroy( ).
L 2.3
Applets are two types
1.Simple applets
2.JApplets
Simple applets can be created by extending Applet class
JApplets can be created by extending JApplet class of
javax.swing.JApplet package
L 2.4
 Applets are created by extending the Applet class.
import java.awt.*;
import java.applet.*;
/*<applet code="AppletSkel" width=300 height=100></applet> */
public class AppletSkel extends Applet {
public void init() {
// initialization
}
public void start() {
// start or resume execution
}
public void stop() {
// suspends execution
}
public void destroy() {
// perform shutdown activities
}
public void paint(Graphics g) {
// redisplay contents of window
}
}
L 3.1
 APPLET tag in HTML allows you to pass parameters to applet.
 To retrieve a parameter, use the getParameter( ) method. It returns
the value of the specified parameter in the form of a String object.
// Use Parameters
import java.awt.*;
import java.applet.*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
L 3.2
public class ParamDemo extends Applet{
String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null) // if not found
fontSize = Integer.parseInt(param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
}
param = getParameter("leading");
L 3.3
try {
if(param != null) // if not found
leading = Float.valueOf(param).floatValue();
else
leading = 0;
} catch(NumberFormatException e) {
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)
active = Boolean.valueOf(param).booleanValue();
}
// Display parameters.
public void paint(Graphics g) {
g.drawString("Font name: " + fontName, 0, 10);
g.drawString("Font size: " + fontSize, 0, 26);
g.drawString("Leading: " + leading, 0, 42);
g.drawString("Account Active: " + active, 0, 58);
}
}
L 3.4
 Swing is a set of classes that provides more powerful and flexible
components than are possible with the AWT.
 In addition to the familiar components, such as buttons, check boxes,
and labels, Swing supplies several exciting additions, including tabbed
panes, scroll panes, trees, and tables.
 Even familiar components such as buttons have more capabilities in
Swing.
 For example, a button may have both an image and a text string
associated with it. Also, the image can be changed as the state of the
button changes.
 Unlike AWT components, Swing components are not implemented by
platform-specific code.
 Instead, they are written entirely in Java and, therefore, are platform-
independent.
 The term lightweight is used to describe such elements.
L 4.1
 The Swing component are defined in javax.swing
1. AbstractButton: Abstract superclass for Swing buttons.
2. ButtonGroup: Encapsulates a mutually exclusive set of buttons.
3. ImageIcon: Encapsulates an icon.
4. JApplet: The Swing version of Applet.
5. JButton: The Swing push button class.
6. JCheckBox: The Swing check box class.
7. JComboBox : Encapsulates a combo box (an combination of a
drop-down list and text field).
8. JLabel: The Swing version of a label.
9. JRadioButton: The Swing version of a radio button.
10. JScrollPane: Encapsulates a scrollable window.
11. JTabbedPane: Encapsulates a tabbed window.
12. JTable: Encapsulates a table-based control.
13. JTextField: The Swing version of a text field.
14. JTree: Encapsulates a tree-based control.
L 4.2
AWT supports limited number of GUI
components.
AWT components are heavy weight components.
AWT components are developed by using
platform specific code.
AWT components behaves differently in different
operating systems.
AWT component is converted by the native code
of the operating system.
L 4.3
Lowest Common Denominator
If not available natively on one Java platform, not
available on any Java platform
Simple Component Set
Components Peer-Based
Platform controls component appearance
Inconsistencies in implementations
Interfacing to native platform error-prone
L 4.4
L 4.5
L 5.1
Model consists of data and the functions that
operate on data
Java bean that we use to store data is a
model component
EJB can also be used as a model component
L 5.2
View is the front end that user interact.
View can be a
HTML
JSP
Struts ActionForm
L 5.3
 Controller component responsibilities
1. Receive request from client
2. Map request to specific business operation
3. Determine the view to display based on the result of
the business operation
L 5.4
Container
JComponent
AbstractButton
JButton
JMenuItem
 JCheckBoxMenuItem
 JMenu
 JRadioButtonMenuItem
JToggleButton
 JCheckBox
 JRadioButton
L 5.5
JComponent
JComboBox
JLabel
JList
JMenuBar
JPanel
JPopupMenu
JScrollBar
JScrollPane
L 5.6
JComponent
JTextComponent
JTextArea
JTextField
JPasswordField
JTextPane
JHTMLPane
L 5.7
Top-Level Containers
The components at the top of any Swing containment
hierarchy
L 5.8
Intermediate containers that can be used under many
different circumstances.
L 5.9
Intermediate containers that play specific roles in the
UI.
L 5.10
If using Swing components in an applet, subclass
JApplet, not Applet
JApplet is a subclass of Applet
Sets up special internal component event handling,
among other things
Can have a JMenuBar
Default LayoutManager is BorderLayout
L 6.1
public class FrameTest {
public static void main (String args[]) {
JFrame f = new JFrame ("JFrame Example");
Container c = f.getContentPane();
c.setLayout (new FlowLayout());
for (int i = 0; i < 5; i++) {
c.add (new JButton ("No"));
c.add (new Button ("Batter"));
}
c.add (new JLabel ("Swing"));
f.setSize (300, 200);
f.show();
}
}
L 6.2
 JComponent supports the following components.
 JComponent
 JComboBox
 JLabel
 JList
 JMenuBar
 JPanel
 JPopupMenu
 JScrollBar
 JScrollPane
 JTextComponent
 JTextArea
 JTextField
 JPasswordField
 JTextPane
 JHTMLPane
L 6.3
 In Swing, icons are encapsulated by the ImageIcon class,
which paints an icon from an image.
 constructors are:
ImageIcon(String filename)
ImageIcon(URL url)
 The ImageIcon class implements the Icon interface that
declares the methods
1. int getIconHeight( )
2. int getIconWidth( )
3. void paintIcon(Component comp,Graphics g,int x, int y)
L 7.1
 Swing labels are instances of the JLabel class, which extends
JComponent.
 It can display text and/or an icon.
 Constructors are:
JLabel(Icon i)
Label(String s)
JLabel(String s, Icon i, int align)
 Here, s and i are the text and icon used for the label. The align
argument is either LEFT, RIGHT, or CENTER. These constants are
defined in the SwingConstants interface,
 Methods are:
1. Icon getIcon( )
2. String getText( )
3. void setIcon(Icon i)
4. void setText(String s)
 Here, i and s are the icon and text, respectively.
L 7.2
The Swing text field is encapsulated by the
JTextComponent class, which extendsJComponent.
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.
Constructors are:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
Here, s is the string to be presented, and cols is the
number of columns in the text field.
L 7.3
 Swing buttons provide features that are not found in the Button class defined
by the AWT.
 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.
 Methods are:
1. void setDisabledIcon(Icon di)
2. void setPressedIcon(Icon pi)
3. void setSelectedIcon(Icon si)
4. void setRolloverIcon(Icon ri)
 Here, di, pi, si, and ri are the icons to be used for these different conditions.
 The text associated with a button can be read and written via the following
methods:
1. String getText( )
2. void setText(String s)
 Here, s is the text to be associated with the button.
L 7.4
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.
Some of its constructors are :
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
Here, s and i are the string and icon used for the button.
L 8.1
 The JCheckBox class, which provides the functionality of a check box,
is a concrete implementation of AbstractButton.
 Some of its constructors are shown here:
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)
 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.
L 8.2
 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.
 Two of JComboBox's constructors are :
JComboBox( )
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:
void addItem(Object obj)
 Here, obj is the object to be added to the combo box.
L 8.3
 Radio buttons are supported by the JRadioButton class, which is a
concrete implementation of AbstractButton.
 Some of its constructors are :
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
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.
 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.
L 8.4
 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. We will use its default constructor. 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.
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.
L 9.1
 A scroll pane 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
JComponent. Some of its constructors are :
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
constants that define when vertical and horizontal scroll bars for this scroll pane
areshown.
 These constants are defined by the ScrollPaneConstants interface.
1. HORIZONTAL_SCROLLBAR_ALWAYS
2. HORIZONTAL_SCROLLBAR_AS_NEEDED
3. VERTICAL_SCROLLBAR_ALWAYS
4. VERTICAL_SCROLLBAR_AS_NEEDED
 Here are the steps to 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
thecomponent and the policies for vertical and horizontal scroll bars.)
3. Add the scroll pane to the content pane of the applet.
L 9.2
Data Model - TreeModel
default: DefaultTreeModel
getChild, getChildCount, getIndexOfChild, getRoot,
isLeaf
Selection Model - TreeSelectionModel
View - TreeCellRenderer
getTreeCellRendererComponent
Node - DefaultMutableTreeNode
L 9.3
 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 :
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 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.
L 9.4
UNIT-8
B.TECH II YR II SEMESTER(TERM 08-09)
UNIT 8 PPT SLIDES
TEXT BOOKS:
1. Java: the complete reference, 7th editon, Herbert schildt,
TMH.Understanding
2. OOP with Java, updated edition, T. Budd, pearson eduction.
No. of slides:45
S.NO. TOPIC LECTURE NO. PPTSLIDES
1 Basics of network programming L1 L1.1TO L1.7
2 addresses L2 L2.1 TO L2.2
3 Ports L3 L3.1 TO L3.2
4 Sockets L 4 L4.1 TO L4.3
5 simple client server program L 5 L5.1 TO L5.5
6 Multiple clients L 6 L6.1 TO L6.5
7 java .net package L 7 L7.1 TO L7.2
8 java.util package L 8 L8.1 TO L8.3
9 Revision L 9
L 1.1
TCP/IP
java.net
RMI JDBC CORBA
Network OS
node
any device on the network
host
a computer on the network
address
computer-readable name for host
host name
human-readable name for host
L 1.2
datagram (or “packet”)
little bundle of information
sent from one node to another
protocol
roles, vocabulary, rules for communication
IP
the Internet Protocol
L 1.3
L 1.4
Physical Network
Transport Layer (TCP, UDP)
Internet Layer (IP)
Application Layer (HTTP, FTP, SMTP)
IP
raw packets
the “Internet Layer”
TCP
data stream
reliable, ordered
the “Transport Layer”
UDP
user datagrams (packets)
unreliable, unordered
the “Transport Layer”
L 1.5
internet
any IP-based network
Internet
the big, famous, world-wide IP network
intranet
a corporate LAN-based IP network
extranet
accessing corporate data across the Internet
L 1.6
Built into language
One of the 11 buzzwords
Network ClassLoader
java.net API
Based on TCP/IP, the Internet Protocol
L 1.7
Every computer on the Internet has an address.
An Internet address is a number that uniquely identifies
each computer on the Net.
There are 32 bits in an IP address, and often refer to them
as a sequence of four numbers between 0 and 255
separated by dots
The first few bits define which class of network, lettered A,
B,
C, D, or E, the address represents.
Most Internet users are on a class C network, since there
are over two million networks in class C.
L 2.1
The first byte of a class C network is between 192 and
224, with the last byte actually identifying an
individual computer among the 256 allowed on a
single class C network.
IP Address: identifies a host
DNS: converts host names / domain names into IP
addresses.
L 2.2
 Port: a meeting place on a host
1. one service per port
2. 1-1023 = well-known services
3. 1024+ = experimental services, temporary
L 3.1
20,21: FTP
23: telnet
25: SMTP
43: whois
80: HTTP
119: NNTP
1099: RMI
L 3.2
A network socket is a lot like an electrical socket.
Socket: a two-way connection
Internet Protocol (IP) is a low-level routing protocol that
breaks data into small packets and sends them to an
address across a network, which does not guarantee to
deliver said packets to the destination.
Transmission Control Protocol (TCP) is a higher-level
protocol that manages to robustly string together these
packets, sorting and retransmitting them as necessary to
reliably transmit your data.
A third protocol, User Datagram Protocol (UDP), sits next
to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets.
L 4.1
Socket(String host, int port)
InputStream getInputStream()
OutputStream getOutputStream()
void close()
Socket s = new Socket(“www.starwave.com”, 90);
L 4.2
L 4.3
Client
port 13
port 80
Time Service
Web Service
Socket
Server
Socket
Client - initiates connection
retrieves data,
displays data,
responds to user input,
requests more data
Examples:
Web Browser
Chat Program
PC accessing files
L 5.1
/** Client program using TCP */
public class Tclient {
final static String serverIPname = “starwave.com";// server IP name
final static int serverPort = 3456; // server port number
public static void main(String args[]) {
java.net.Socket sock = null; // Socket object for communicating
java.io.PrintWriter pw = null; // socket output to server
java.io.BufferedReader br = null; // socket input from server
try {
sock = new java.net.Socket(serverIPname,serverPort);// create socket
and connect
pw = new java.io.PrintWriter(sock.getOutputStream(), true); // create
reader and writer
br = new java.io.BufferedReader(new
java.io.InputStreamReader(sock.getInputStream()));
System.out.println("Connected to Server");
L 5.2
pw.println("Message from the client"); // send msg to the server
System.out.println("Sent message to server");
String answer = br.readLine(); // get data from the server
System.out.println("Response from the server >" + answer);
pw.close();
// close everything
br.close();
sock.close();
} catch (Throwable e) {
System.out.println("Error " + e.getMessage());
e.printStackTrace();
}
}
}
L 5.3
/** Server program using TCP */
public class Tserver {
final static int serverPort = 3456; //
server port number
public static void main(String args[]) {
java.net.ServerSocket sock = null;
// original server socket
java.net.Socket clientSocket = null; //
//socket created by accept
java.io.PrintWriter pw = null; //
//socket output stream
java.io.BufferedReader br = null;
// socket input stream
try {
sock = new java.net.ServerSocket(serverPort); //
create socket and bind to port
System.out.println("waiting for client to connect");
clientSocket = sock.accept();
L 5.4
// wait for client to connect
System.out.println("client has connected");
pw = new java.io.PrintWriter(clientSocket.getOutputStream(),true);
br = new java.io.BufferedReader(
new java.io.InputStreamReader(clientSocket.getInputStream()));
String msg = br.readLine();
// read msg from client
System.out.println("Message from the client >" + msg);
pw.println("Got it!"); // send msg to client
pw.close(); // close
everything
br.close();
clientSocket.close();
sock.close();
} catch (Throwable e) {
System.out.println("Error " + e.getMessage());
e.printStackTrace();
}
}
}
L 5.5
Multiple clients can connect to the same port on the server at
the same time.
Incoming data is distinguished by the port to which it is
addressed and the client host and port from which it came.
The server can tell for which service (like http or ftp) the data
is intended by inspecting the port.
It can tell which open socket on that service the data is
intended for by looking at the client address and port stored
with the data.
L 6.1
Incoming connections are stored in a queue until the
server can accept them.
On most systems the default queue length is between 5
and 50.
Once the queue fills up further incoming connections
are refused until space in the queue opens up.
L 6.2
The java.net.ServerSocket class represents a server
socket.
A ServerSocket object is constructed on a particular
local port. Then it calls accept() to listen for
incoming connections.
accept() blocks until a connection is detected. Then
accept() returns a java.net.Socket object that
performs the actual communication with the client.
L 6.3
There are three constructors that specify the port to bind
to, the queue length for incoming connections, and the IP
address to bind to:
public ServerSocket(int port) throws IOException
public ServerSocket(int port, int backlog) throws
IOException
public ServerSocket(int port, int backlog, InetAddress
networkInterface) throws IOException
L 6.4
specify the port number to listen :
try {
ServerSocket ss = new ServerSocket(80);
}
catch (IOException e) {
System.err.println(e);
}
L 6.5
The classes in java.net package are :
JarURLConnection (Java 2) URLConnection
DatagramSocketImpl ServerSocket
URLDecoder (Java 2) HttpURLConnection
Socket URLEncoder
InetAddress SocketImpl
URLStreamHandler SocketPermission
ContentHandler MulticastSocket
URL DatagramPacket
NetPermission URLClassLoader (Java 2)
DatagramSocket PasswordAuthentication(Java 2)
Authenticator (Java 2)
L 7.1
The java.net package's interfaces are
1. ContentHandlerFactory
2. SocketImplFactory
3. URLStreamHandlerFactory
4. FileNameMap
5. SocketOptions
L 7.2
 The java.util package defines the following classes:
1. AbstractCollection (Java2)
2. EventObject
3. PropertyResourceBundle
4. AbstractList (Java 2)
5. GregorianCalendar
6. Random
7. AbstractMap (Java 2)
8. HashMap(Java 2)
9. ResourceBundle
10.AbstractSequentialList(Java 2)
11. HashSet (Java2)
12.SimpleTimeZone
13. AbstractSet (Java 2)
14.Hashtable
15.Stack
L 8.1
16.ArrayList (Java 2)
17.LinkedList(Java 2)
18.StringTokenizer
19.Arrays (Java 2)
20.ListResourceBundle
21.TimeZone
22.BitSet
23.Locale
24.TreeMap (Java 2)
25.Calendar
26.Observable
27.TreeSet (Java 2)
28.Collections (Java 2)
29.Properties
30.Vector
31. Date
32.PropertyPermission(Java 2)
33.WeakHashMap (Java 2)
34.Dictionary
L 8.2
java.util defines the following interfaces.
1. Collection (Java 2)
2. List (Java 2)
3. Observer
4. Comparator (Java 2)
5. ListIterator(Java 2)
6. Set (Java 2)
7. Enumeration
8. Map (Java 2)
9. SortedMap (Java 2)
10.EventListener
11. Map.Entry(Java 2)
12.SortedSet (Java 2)
13. Iterator (Java 2)
L 8.3

More Related Content

PPTX
Geothermal power plant and its types
PPT
Artificial Intelligence : The Future of AI
PPTX
PPTX
OOSE-UNIT-1.pptx
PPTX
Basics of JAVA programming
PPT
Pre Encounter Lesson 7: Knowing Our Enemy
PPTX
Java program structure
PPTX
Project communication management
Geothermal power plant and its types
Artificial Intelligence : The Future of AI
OOSE-UNIT-1.pptx
Basics of JAVA programming
Pre Encounter Lesson 7: Knowing Our Enemy
Java program structure
Project communication management

What's hot (20)

PDF
Arrays in Java
PPTX
Python Functions
PPS
Wrapper class
PPS
Introduction to class in java
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPTX
Interface in java
PPTX
Introduction to java
PPTX
oops concept in java | object oriented programming in java
PPTX
Core java complete ppt(note)
PPTX
Introduction to java
PPTX
Introduction to java
PPTX
Constructor in java
PPT
Java interfaces
PPTX
Introduction to JAVA
PDF
Python exception handling
PPTX
Python: Modules and Packages
PPTX
Dynamic method dispatch
PPTX
Java swing
PPTX
QSpiders - Jdk Jvm Jre and Jit
Arrays in Java
Python Functions
Wrapper class
Introduction to class in java
Basic Concepts of OOPs (Object Oriented Programming in Java)
Interface in java
Introduction to java
oops concept in java | object oriented programming in java
Core java complete ppt(note)
Introduction to java
Introduction to java
Constructor in java
Java interfaces
Introduction to JAVA
Python exception handling
Python: Modules and Packages
Dynamic method dispatch
Java swing
QSpiders - Jdk Jvm Jre and Jit
Ad

Viewers also liked (10)

PDF
Core java complete notes - Contact at +91-814-614-5674
PPT
Core java slides
PPTX
More Little Wonders of C#/.NET
PPT
C#/.NET Little Wonders
PPT
Programming in c#
PPT
Core java concepts
PPTX
Java programming course for beginners
PDF
Java SE 8 best practices
PPT
Java tutorial PPT
PDF
Alphorm.com support de la formation programmer en C# 6
Core java complete notes - Contact at +91-814-614-5674
Core java slides
More Little Wonders of C#/.NET
C#/.NET Little Wonders
Programming in c#
Core java concepts
Java programming course for beginners
Java SE 8 best practices
Java tutorial PPT
Alphorm.com support de la formation programmer en C# 6
Ad

Similar to Java Notes (20)

PPT
JAVA_8_.ppt all introduction to java topics
PPT
VTU JAVA PPT BY DJ AND BEST PPT C ON JAVA
PPT
Unit 1 Java
PPT
Need of object oriented programming paradigam
PPTX
Object oriented programming in python
PPTX
INTRODUCTION TO JAVA
PDF
JAVA-PPT'S.pdf
PDF
MCA NOTES.pdf
DOC
My c++
PPTX
Suga java training_with_footer
PPT
Oop by edgar lagman jr
PDF
M.c.a. (sem iv)- java programming
PDF
Oop basic concepts
PDF
Programming in Java Unit 1 lesson Notes for Java
PPT
Oops ppt
PDF
12th ip CBSE chapter 4 oop in java notes complete
PDF
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
DOCX
Question and answer Programming
PPTX
Selenium Training .pptx
JAVA_8_.ppt all introduction to java topics
VTU JAVA PPT BY DJ AND BEST PPT C ON JAVA
Unit 1 Java
Need of object oriented programming paradigam
Object oriented programming in python
INTRODUCTION TO JAVA
JAVA-PPT'S.pdf
MCA NOTES.pdf
My c++
Suga java training_with_footer
Oop by edgar lagman jr
M.c.a. (sem iv)- java programming
Oop basic concepts
Programming in Java Unit 1 lesson Notes for Java
Oops ppt
12th ip CBSE chapter 4 oop in java notes complete
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Question and answer Programming
Selenium Training .pptx

More from Abhishek Khune (16)

PDF
07 java collection
PPT
Clanguage
PPT
PPT
PPT
Slide8appletv2 091028110313-phpapp01
PPT
Packages in java
PPT
Week0 introduction
PPT
Binary trees
PPT
PPT
Clanguage
PPT
06 abstract-classes
PDF
Java unit3
PDF
Java unit2
PPT
Linux introduction
PPT
Shared memory
PPT
Lecture 14 (inheritance basics)
07 java collection
Clanguage
Slide8appletv2 091028110313-phpapp01
Packages in java
Week0 introduction
Binary trees
Clanguage
06 abstract-classes
Java unit3
Java unit2
Linux introduction
Shared memory
Lecture 14 (inheritance basics)

Recently uploaded (20)

PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Pharma ospi slides which help in ospi learning
PDF
Basic Mud Logging Guide for educational purpose
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Institutional Correction lecture only . . .
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Complications of Minimal Access Surgery at WLH
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Cell Types and Its function , kingdom of life
PPH.pptx obstetrics and gynecology in nursing
Renaissance Architecture: A Journey from Faith to Humanism
Pharma ospi slides which help in ospi learning
Basic Mud Logging Guide for educational purpose
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
O7-L3 Supply Chain Operations - ICLT Program
Institutional Correction lecture only . . .
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
VCE English Exam - Section C Student Revision Booklet
Supply Chain Operations Speaking Notes -ICLT Program
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Pharmacology of Heart Failure /Pharmacotherapy of CHF
O5-L3 Freight Transport Ops (International) V1.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Complications of Minimal Access Surgery at WLH
Microbial disease of the cardiovascular and lymphatic systems
Cell Types and Its function , kingdom of life

Java Notes

  • 2. B.TECH II YR II SEMESTER(TERM 08-09) UNIT 1 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th editon, Herbert schildt, TMH.Understanding 2. OOP with Java, updated edition, T. Budd, pearson eduction. No. of slides: 24
  • 3. S.NO. TOPIC LECTURE NO. PPTSLIDES 1 Need for oop paradigm, L1 L1.1TO L1.4 A way of viewing world – Agents 2 Responsibility, Messages, Methods L2 L2.1 TO L2.3 3 classes and instances, L3 L3.1 TO L3.6 class hierarchies, Inheritance 4 method binding L 4 L4.1 TO L4.5 overriding and exceptions 5 summary of oop concepts, coping with complexity, L5 L5.1 TO 5.4 abstraction mechanisms
  • 4. OOP is an approach to program organization and development, which attempts to eliminate some of the drawbacks of conventional programming methods by incorporating the best of structured programming features with several new concepts.  OOP allows us to decompose a problem into number of entities called objects and then build data and methods (functions) around these entities. The data of an object can be accessed only by the methods associated with the object. L 1.1
  • 5. Some of the Object-Oriented Paradigm are: 1. Emphasis is on data rather than procedure. 2. Programs are divided into objects. 3. Data Structures are designed such that they Characterize the objects. 4 Methods that operate on the data of an object are tied together in the data structure. 5 Data is hidden and can not be accessed by external functions. 6 Objects may communicate with each other through methods. L 1.2
  • 6. OOP uses an approach of treating a real world agent as an object. Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code by switching the controlling entity to data. L 1.3
  • 8. primary motivation is the need for a platform- independent (that is, architecture- neutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. Objects with clear responsibilities Each class should have a clear responsibility. If you can't state the purpose of a class in a single, clear sentence, then perhaps your class structure needs some thought. L 2.1
  • 9. Messages We all like to use programs that let us know what's going on. Programs that keep us informed often do so by displaying status and error messages. These messages need to be translated so they can be understood by end users around the world. The Section discusses translatable text messages. Usually, you're done after you move a message String into a ResourceBundle. If you've embedded variable data in a message, you'll have to take some extra steps to prepare it for translation. L 2.2
  • 10. Methods A method is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name. Drawing a Triangle require draw of three straight lines. This instruction three times to draw a simple triangle. We can define a method to call this instruction three times and draw the triangle(i.e. create a method drawLine() to draw lines and this method is called repeatedly to achieve the needed task) The idea of methods appears in all programming languages, although sometimes it goes under the name functions and sometimes under the name procedures. The name methods is a throw-back to the language C++, from which Java was developed. In C++, there is an object called a class which can contain methods. However, everything in Java is enclosed within a class .so the functions within it are called methods L 2.3
  • 11. L 3.1 • Class is blue print or an idea of an Object • From One class any number of Instances can be created • It is an encapsulation of attributes and methods FIGURE CIRCLE RECTANGLE SQUARE Ob1 Ob2 Ob3 class
  • 13. L 3.3 • Instance is an Object of a class which is an entity with its own attribute values and methods. • Creating an Instance ClassName refVariable; refVariable = new Constructor(); or ClassName refVariable = new Constructor();
  • 14. L 3.4 • In Java, class “Object” is the base class to all other classes – If we do not explicitly say extends in a new class definition, it implicitly extends Object – The tree of classes that extend from Object and all of its subclasses are is called the class hierarchy – All classes eventually lead back up to Object – This will enable consistent access of objects of different classes.
  • 15. Methods allows to reuse a sequence of statements Inheritance allows to reuse classes by deriving a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass. The child class inherits characteristics of the parent class(i.e the child class inherits the methods and data defined for the parent class L 3.5
  • 16. Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class L 3.6 Animal weight : int + getWeight() : int Bird + fly() : void
  • 17. Objects are used to call methods. MethodBinding is an object that can be used to call an arbitrary public method, on an instance that is acquired by evaluatng the leading portion of a method binding expression via a value binding. It is legal for a class to have two or more methods with the same name. Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments. Therefore the same-named methods must be distinguished: 1) by the number of arguments, or 2) by the types of arguments Overloading and inheritance are two ways to implement polymorphism. L 4.1
  • 18.  There may be some occasions when we want an object to respond to the same method but have different behaviour when that method is called.  That means, we should override the method defined in the superclass. This is possible by defining a method in a sub class that has the same name, same arguments and same return type as a method in the superclass.  Then when that method is called, the method defined in the sub class is invoked and executed instead of the one in the superclass. This is known as overriding. L 4.2
  • 19. L 4.3 • Exception is an abnormal condition that arises in the code sequence. • Exceptions occur during compile time or run time. • “throwable” is the super class in exception hierarchy. • Compile time errors occurs due to incorrect syntax. • Run-time errors happen when – User enters incorrect input – Resource is not available (ex. file) – Logic error (bug) that was not fixed
  • 20. In Java, exceptions are objects. When you throw an exception, you throw an object. You can't throw just any object as an exception, however -- only those objects whose classes descend from Throwable. Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw. Throwable has two direct subclasses, Exception and Error. Exceptions are thrown to signal abnormal conditions that can often be handled by some catcher, though it's possible they may not be caught and therefore could result in a dead thread. Errors are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself. L 4.4
  • 21. L 4.5
  • 22. The following are the basic oops concepts: They are as follows: 1. Objects. 2. Classes. 3. Data Abstraction. 4. Data Encapsulation. 5. Inheritance. 6. Polymorphism. 7. Dynamic Binding. 8. Message Passing. L 5.1
  • 23. L 5.2 Abstraction in Object-Oriented Programming Procedural Abstraction • Procedural Abstractions organize instructions. Function Power Give me two numbers (base & exponent) I’ll return baseexponent Implementation
  • 24. L 5.3 Data Abstraction • Data Abstractions organize data. Name (string) Marks (num) Grade (char) Student Number (num) StudentType
  • 25. L 5.4 Behavioral Abstraction • Behavioral Abstractions combine procedural and data abstractions. Data State Enqueue Is Full Is Empty Dequeue Initialize Queue Object
  • 27. B.TECH II YR II SEMESTER(TERM 08-09) UNIT 2 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th editon, Herbert schildt, TMH.Understanding 2. OOP with Java, updated edition, T. Budd, pearson eduction. No. of slides: 85
  • 28. S.NO. TOPIC LECTURE NO. PPTSLIDES 1 History of Java, L1 L1.1TO L1.20 Java buzzwords, data types. 2 variables, scope and life time of variables,L2 L2.1 TO L2.20 arrays, operators, expressions 3 control statements, L3 L3.1 TO L3.9 type conversion and costing 4 simple java program, L 4 L4.1 TO L4.8 classes and objects – concepts of classes 5 objects, constructors, methods L5 L5.1 TO 5.6 6 Access control, this keyword, L6 L6.1 TO 6.8 garbage collection 7 overloading methods and constructors, L7 L7.1 TO 7.6 parameter passing 8 Recursion, string handling. L8 L 8.1 TO 8.6
  • 29. Computer language innovation and development occurs for two fundamental reasons: 1) to adapt to changing environments and uses 2) to implement improvements in the art of programming The development of Java was driven by both in equal measures. Many Java features are inherited from the earlier languages: B  C  C++  Java L 1.1
  • 30. Designed by Dennis Ritchie in 1970s. Before C: BASIC, COBOL, FORTRAN, PASCAL C- structured, efficient, high-level language that could replace assembly code when creating systems programs. Designed, implemented and tested by programmers. L 1.2
  • 31. Designed by Bjarne Stroustrup in 1979. Response to the increased complexity of programs and respective improvements in the programming paradigms and methods: 1) assembler languages 2) high-level languages 3) structured programming 4) object-oriented programming (OOP) OOP – methodology that helps organize complex programs through the use of inheritance, encapsulation and polymorphism. C++ extends C by adding object-oriented features. L 1.3
  • 32. In 1990, Sun Microsystems started a project called Green. Objective: to develop software for consumer electronics. Project was assigned to James Gosling, a veteran of classic network software design. Others included Patrick Naughton, ChrisWarth, Ed Frank, and Mike Sheridan. The team started writing programs in C++ for embedding into – toasters – washing machines – VCR’s Aim was to make these appliances more “intelligent”. L 1.4
  • 33. C++ is powerful, but also dangerous. The power and popularity of C derived from the extensive use of pointers. However, any incorrect use of pointers can cause memory leaks, leading the program to crash. In a complex program, such memory leaks are often hard to detect. Robustness is essential. Users have come to expect that Windows may crash or that a program running under Windows may crash. (“This program has performed an illegal operation and will be shut down”) However, users do not expect toasters to crash, or washing machines to crash. A design for consumer electronics has to be robust. Replacing pointers by references, and automating memory management was the proposed solution. L 1.5
  • 34. Hence, the team built a new programming language called Oak, which avoided potentially dangerous constructs in C++, such as pointers, pointer arithmetic, operator overloading etc. Introduced automatic memory management, freeing the programmer to concentrate on other things. Architecture neutrality (Platform independence) Many different CPU’s are used as controllers. Hardware chips are evolving rapidly. As better chips become available, older chips become obsolete and their production is stopped. Manufacturers of toasters and washing machines would like to use the chips available off the shelf, and would not like to reinvest in compiler development every two-three years. So, the software and programming language had to be architecture neutral. L 1.6
  • 35.  It was soon realized that these design goals of consumer electronics perfectly suited an ideal programming language for the Internet and WWW, which should be:  object-oriented (& support GUI)  – robust  – architecture neutral  Internet programming presented a BIG business opportunity. Much bigger than programming for consumer electronics.  Java was “re-targeted” for the Internet  The team was expanded to include Bill Joy (developer of Unix), Arthur van Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc.  In 1994, an early web browser called WebRunner was written in Oak. WebRunner was later renamed HotJava.  In 1995, Oak was renamed Java.  A common story is that the name Java relates to the place from where the development team got its coffee. The name Java survived the trade mark search. L 1.7
  • 36. Designed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike Sheridan at Sun Microsystems in 1991. The original motivation is not Internet: platform- independent software embedded in consumer electronics devices. With Internet, the urgent need appeared to break the fortified positions of Intel, Macintosh and Unix programmer communities. Java as an “Internet version of C++”? No. Java was not designed to replace C++, but to solve a different set of problems. L 1.8
  • 37. The key considerations were summed up by the Java team in the following list of buzzwords:  Simple  Secure  Portable  Object-oriented  Robust  Multithreaded  Architecture-neutral  Interpreted  High performance  Distributed  Dynamic L 1.9
  • 38. simple – Java is designed to be easy for the professional programmer to learn and use. object-oriented: a clean, usable, pragmatic approach to objects, not restricted by the need for compatibility with other languages. Robust: restricts the programmer to find the mistakes early, performs compile-time (strong typing) and run-time (exception-handling) checks, manages memory automatically. Multithreaded: supports multi-threaded programming for writing program that perform concurrent computations L 1.10
  • 39. Architecture-neutral: Java Virtual Machine provides a platform independent environment for the execution of Java byte code Interpreted and high-performance: Java programs are compiled into an intermediate representation – byte code: a) can be later interpreted by any JVM b) can be also translated into the native machine code for efficiency. L 1.11
  • 40. Distributed: Java handles TCP/IP protocols, accessing a resource through its URL much like accessing a local file. Dynamic: substantial amounts of run-time type information to verify and resolve access to objects at run-time. Secure: programs are confined to the Java execution environment and cannot access other parts of the computer. L 1.12
  • 41. Portability: Many types of computers and operating systems are in use throughout the world —and many are connected to the Internet. For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed. The same mechanism that helps ensure security also helps create portability. Indeed, Java's solution to these two problems is both elegant and efficient. L 1.13
  • 42. Java defines eight simple types: 1)byte – 8-bit integer type 2)short – 16-bit integer type 3)int – 32-bit integer type 4)long – 64-bit integer type 5)float – 32-bit floating-point type 6)double – 64-bit floating-point type 7)char – symbols in a character set 8)boolean – logical values true and false L 1.14
  • 43. byte: 8-bit integer type. Range: -128 to 127. Example: byte b = -15; Usage: particularly when working with data streams. short: 16-bit integer type. Range: -32768 to 32767. Example: short c = 1000; Usage: probably the least used simple type. L 1.15
  • 44. int: 32-bit integer type. Range: -2147483648 to 2147483647. Example: int b = -50000; Usage: 1) Most common integer type. 2) Typically used to control loops and to index arrays. 3) Expressions involving the byte, short and int values are promoted to int before calculation. L 1.16
  • 45. long: 64-bit integer type. Range: -9223372036854775808 to 9223372036854775807. Example: long l = 10000000000000000; Usage: 1) useful when int type is not large enough to hold the desired value float: 32-bit floating-point number. Range: 1.4e-045 to 3.4e+038. Example: float f = 1.5; Usage: 1) fractional part is needed 2) large degree of precision is not required L 1.17
  • 46. double: 64-bit floating-point number. Range: 4.9e-324 to 1.8e+308. Example: double pi = 3.1416; Usage: 1) accuracy over many iterative calculations 2) manipulation of large-valued numbers L 1.18
  • 47. char: 16-bit data type used to store characters. Range: 0 to 65536. Example: char c = ‘a’; Usage: 1) Represents both ASCII and Unicode character sets; Unicode defines a character set with characters found in (almost) all human languages. 2) Not the same as in C/C++ where char is 8-bit and represents ASCII only. L 1.19
  • 48. boolean: Two-valued type of logical values. Range: values true and false. Example: boolean b = (1<2); Usage: 1) returned by relational operators, such as 1<2 2) required by branching expressions such as if or for L 1.20
  • 49. declaration – how to assign a type to a variable initialization – how to give an initial value to a variable scope – how the variable is visible to other parts of the program lifetime – how the variable is created, used and destroyed type conversion – how Java handles automatic type conversion type casting – how the type of a variable can be narrowed down type promotion – how the type of a variable can be expanded L 2.1
  • 50. Java uses variables to store data. To allocate memory space for a variable JVM requires: 1) to specify the data type of the variable 2) to associate an identifier with the variable 3) optionally, the variable may be assigned an initial value All done as part of variable declaration. L 2.2
  • 51. datatype identifier [=value]; datatype must be A simple datatype User defined datatype (class type) Identifier is a recognizable name confirm to identifier rules Value is an optional initial value. L 2.3
  • 52. We can declare several variables at the same time: type identifier [=value][, identifier [=value] …]; Examples: int a, b, c; int d = 3, e, f = 5; byte g = 22; double pi = 3.14159; char ch = 'x'; L 2.4
  • 53. Scope determines the visibility of program elements with respect to other program elements. In Java, scope is defined separately for classes and methods: 1) variables defined by a class have a global scope 2) variables defined by a method have a local scope A scope is defined by a block: { … } A variable declared inside the scope is not visible outside: { int n; } n = 1;// this is illegal L 2.5
  • 54. Variables are created when their scope is entered by control flow and destroyed when their scope is left: A variable declared in a method will not hold its value between different invocations of this method. A variable declared in a block looses its value when the block is left. Initialized in a block, a variable will be re-initialized with every re-entry. Variables lifetime is confined to its scope! L 2.6
  • 55. An array is a group of liked-typed variables referred to by a common name, with individual variables accessed by their index. Arrays are: 1) declared 2) created 3) initialized 4) used Also, arrays can have one or several dimensions. L 2.7
  • 56. Array declaration involves: 1) declaring an array identifier 2) declaring the number of dimensions 3) declaring the data type of the array elements Two styles of array declaration: type array-variable[]; or type [] array-variable; L 2.8
  • 57. After declaration, no array actually exists. In order to create an array, we use the new operator: type array-variable[]; array-variable = new type[size]; This creates a new array to hold size elements of type type, which reference will be kept in the variable array-variable. L 2.9
  • 58. Later we can refer to the elements of this array through their indexes: array-variable[index] The array index always starts with zero! The Java run-time system makes sure that all array indexes are in the correct range, otherwise raises a run-time error. L 2.10
  • 59. Arrays can be initialized when they are declared: int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31}; Note: 1) there is no need to use the new operator 2) the array is created large enough to hold all specified elements L 2.11
  • 60. Multidimensional arrays are arrays of arrays: 1) declaration: int array[][]; 2) creation: int array = new int[2][3]; 3) initialization int array[][] = { {1, 2, 3}, {4, 5, 6} }; L 2.12
  • 61. Java operators are used to build value expressions. Java provides a rich set of operators: 1) assignment 2) arithmetic 3) relational 4) logical 5) bitwise L 2.13
  • 62. += v += expr; v = v + expr ; -= v -=expr; v = v - expr ; *= v *= expr; v = v * expr ; /= v /= expr; v = v / expr ; %= v %= expr; v = v % expr ; L 2.14
  • 63. + op1 + op2 ADD - op1 - op2 SUBSTRACT * op1 * op2 MULTIPLY / op1 / op2 DIVISION % op1 % op2 REMAINDER L 2.15
  • 64. == Equals to Apply to any type != Not equals to Apply to any type > Greater than Apply to numerical type < Less than Apply to numerical type >= Greater than or equal Apply to numerical type <= Less than or equal Apply to numerical type L 2.16
  • 65. & op1 & op2 Logical AND | op1 | op2 Logical OR && op1 && op2 Short-circuit AND || op1 || op2 Short-circuit OR ! ! op Logical NOT ^ op1 ^ op2 Logical XOR L 2.17
  • 66. ~ ~op Inverts all bits & op1 & op2 Produces 1 bit if both operands are 1 | op1 |op2 Produces 1 bit if either operand is 1 ^ op1 ^ op2 Produces 1 bit if exactly one operand is 1 >> op1 >> op2 Shifts all bits in op1 right by the value of op2 << op1 << op2 Shifts all bits in op1 left by the value of op2 L 2.18
  • 67. An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. Examples of expressions are in bold below: int number = 0; anArray[0] = 100; System.out.println ("Element 1 at index 0: " + anArray[0]); int result = 1 + 2; // result is now 3 if(value1 == value2) System.out.println("value1 == value2"); L 2.19 Expressions
  • 68. The data type of the value returned by an expression depends on the elements used in the expression.  The expression number = 0 returns an int because the assignment operator returns a value of the same data type as its left-hand operand; in this case, number is an int. As you can see from the other expressions, an expression can return other types of values as well, such as boolean or String. The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other.  Here's an example of a compound expression: 1 * 2 * 3 L 2.20
  • 69. Java control statements cause the flow of execution to advance and branch based on the changes to the state of the program. Control statements are divided into three groups: 1) selection statements allow the program to choose different parts of the execution based on the outcome of an expression 2) iteration statements enable program execution to repeat one or more statements 3) jump statements enable your program to execute in a non-linear fashion L 3.1
  • 70. Java selection statements allow to control the flow of program’s execution based upon conditions known only during run-time. Java provides four selection statements: 1) if 2) if-else 3) if-else-if 4) switch L 3.2
  • 71. Java iteration statements enable repeated execution of part of a program until a certain termination condition becomes true. Java provides three iteration statements: 1) while 2) do-while 3) for L 3.3
  • 72. Java jump statements enable transfer of control to other parts of program. Java provides three jump statements: 1) break 2) continue 3) return In addition, Java supports exception handling that can also alter the control flow of a program. L 3.4
  • 73. L 3.5 Type Conversion • Size Direction of Data Type – Widening Type Conversion (Casting down) • Smaller Data Type  Larger Data Type – Narrowing Type Conversion (Casting up) • Larger Data Type  Smaller Data Type • Conversion done in two ways – Implicit type conversion • Carried out by compiler automatically – Explicit type conversion • Carried out by programmer using casting
  • 74. L 3.6 Type Conversion • Widening Type Converstion – Implicit conversion by compiler automatically byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double float -> double byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double float -> double
  • 75. L 3.7 Type Conversion • Narrowing Type Conversion – Programmer should describe the conversion explicitly byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long double -> byte, short, char, int, long, float byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long double -> byte, short, char, int, long, float
  • 76. byte and short are always promoted to int if one operand is long, the whole expression is promoted to long if one operand is float, the entire expression is promoted to float if any operand is double, the result is double L 3.8
  • 77. General form: (targetType) value Examples: 1) integer value will be reduced module bytes range: int i; byte b = (byte) i; 2) floating-point value will be truncated to integer value: float f; int i = (int) f; L 3.9
  • 78. A class to display a simple message: class MyProgram { public static void main(String[] args) { System.out.println(“First Java program."); } } 4.1
  • 79. Real world objects are things that have: 1) state 2) behavior Example: your dog: state – name, color, breed, sits?, barks?, wages tail?, runs? behavior – sitting, barking, waging tail, running A software object is a bundle of variables (state) and methods (operations). L 4.2
  • 80. A class is a blueprint that defines the variables and methods common to all objects of a certain kind. Example: ‘your dog’ is a object of the class Dog. An object holds values for the variables defines in the class. An object is called an instance of the Class L 4.3
  • 81. A variable is declared to refer to the objects of type/class String: String s; The value of s is null; it does not yet refer to any object. A new String object is created in memory with initial “abc” value: String s = new String(“abc”); Now s contains the address of this new object. L 4.4
  • 82. A program accumulates memory through its execution. Two mechanism to free memory that is no longer need by the program: 1) manual – done in C/C++ 2) automatic – done in Java In Java, when an object is no longer accessible through any variable, it is eventually removed from the memory by the garbage collector. Garbage collector is parts of the Java Run-Time Environment. L 4.5
  • 83. A basis for the Java language. Each concept we wish to describe in Java must be included inside a class. A class defines a new data type, whose values are objects: A class is a template for objects An object is an instance of a class L 4.6
  • 84. A class contains a name, several variable declarations (instance variables) and several method declarations. All are called members of the class. General form of a class: class classname { type instance-variable-1; … type instance-variable-n; type method-name-1(parameter-list) { … } type method-name-2(parameter-list) { … } … type method-name-m(parameter-list) { … } } L 4.7
  • 85. class Box { double width; double height; double depth; } class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20; mybox.depth = 15; vol = mybox.width * mybox.height * mybox.depth; System.out.println ("Volume is " + vol); } } L 4.8
  • 86. A constructor initializes the instance variables of an object. It is called immediately after the object is created but before the new operator completes. 1) it is syntactically similar to a method: 2) it has the same name as the name of its class 3) it is written without return type; the default return type of a class constructor is the same class When the class has no constructor, the default constructor automatically initializes all its instance variables with zero. L 5.1
  • 87. class Box { double width; double height; double depth; Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } double volume() { return width * height * depth; } } L 5.2
  • 88. class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { return width * height * depth; } } L 5.3
  • 89. General form of a method definition: type name(parameter-list) { … return value; … } Components: 1) type - type of values returned by the method. If a method does not return any value, its return type must be void. 2) name is the name of the method 3) parameter-list is a sequence of type-identifier lists separated by commas 4) return value indicates what value is returned by the method. L 5.4
  • 90. Classes declare methods to hide their internal data structures, as well as for their own internal use: Within a class, we can refer directly to its member variables: class Box { double width, height, depth; void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } L 5.5
  • 91. Parameters increase generality and applicability of a method: 1) method without parameters int square() { return 10*10; } 2) method with parameters int square(int i) { return i*i; } Parameter: a variable receiving value at the time the method is invoked. Argument: a value passed to the method when it is invoked. L 5.6
  • 92. L 6.1 Access Control: Data Hiding and Encapsulation • Java provides control over the visibility of variables and methods. • Encapsulation, safely sealing data within the capsule of the class Prevents programmers from relying on details of class implementation, so you can update without worry • Helps in protecting against accidental or wrong usage. • Keeps code elegant and clean (easier to maintain)
  • 93. L 6.2 Access Modifiers: Public, Private, Protected • Public: keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. • Default(No visibility modifier is specified): it behaves like public in its package and private in other packages. • Default Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible.
  • 94. Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class. L 6.3
  • 95. L 6.4 Visibility public class Circle { private double x,y,r; // Constructor public Circle (double x, double y, double r) { this.x = x; this.y = y; this.r = r; } //Methods to return circumference and area public double circumference() { return 2*3.14*r;} public double area() { return 3.14 * r * r; } }
  • 96. L 6.5 Keyword this • Can be used by any object to refer to itself in any class method • Typically used to – Avoid variable name collisions – Pass the receiver as an argument – Chain constructors
  • 97. Keyword this allows a method to refer to the object that invoked it. It can be used inside any method to refer to the current object: Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; } L 6.6
  • 98. Garbage collection is a mechanism to remove objects from memory when they are no longer needed. Garbage collection is carried out by the garbage collector: 1) The garbage collector keeps track of how many references an object has. 2) It removes an object from memory when it has no longer any references. 3) Thereafter, the memory occupied by the object can be allocated again. 4) The garbage collector invokes the finalize method. L 6.7
  • 99. A constructor helps to initialize an object just after it has been created. In contrast, the finalize method is invoked just before the object is destroyed: 1) implemented inside a class as: protected void finalize() { … } 2) implemented when the usual way of removing objects from memory is insufficient, and some special actions has to be carried out L 6.8
  • 100. It is legal for a class to have two or more methods with the same name. However, Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments. Therefore the same-named methods must be distinguished: 1) by the number of arguments, or 2) by the types of arguments Overloading and inheritance are two ways to implement polymorphism. L 7.1
  • 101. class OverloadDemo { void test() { System.out.println("No parameters"); } void test(int a) { System.out.println("a: " + a); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } double test(double a) { System.out.println("double a: " + a); return a*a; } } L 7.2
  • 102. class Box { double width, height, depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width = -1; height = -1; depth = -1; } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } } L 7.3
  • 103. Two types of variables: 1) simple types 2) class types Two corresponding ways of how the arguments are passed to methods: 1) by value a method receives a cope of the original value; parameters of simple types 2) by reference a method receives the memory address of the original value, not the value itself; parameters of class types L 7.4
  • 104. class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.print("a and b before call: “); System.out.println(a + " " + b); ob.meth(a, b); System.out.print("a and b after call: "); System.out.println(a + " " + b); } } L 7.5
  • 105. As the parameter hold the same address as the argument, changes to the object inside the method do affect the object used by the argument: class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.print("ob.a and ob.b before call: “); System.out.println(ob.a + " " + ob.b); ob.meth(ob); System.out.print("ob.a and ob.b after call: "); System.out.println(ob.a + " " + ob.b); } } L 7.6
  • 106. A recursive method is a method that calls itself: 1) all method parameters and local variables are allocated on the stack 2) arguments are prepared in the corresponding parameter positions 3) the method code is executed for the new arguments 4) upon return, all parameters and variables are removed from the stack 5) the execution continues immediately after the invocation point L 8.1
  • 107. class Factorial { int fact(int n) { if (n==1) return 1; return fact(n-1) * n; } } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.print("Factorial of 5 is "); System.out.println(f.fact(5)); } } L 8.2
  • 108. String is probably the most commonly used class in Java's class library. The obvious reason for this is that strings are a very important part of programming. The first thing to understand about strings is that every string you create is actually an object of type String. Even string constants are actually String objects. For example, in the statement System.out.println("This is a String, too"); the string "This is a String, too" is a String constant L 8.3
  • 109. Java defines one operator for String objects: +. It is used to concatenate two strings. For example, this statement String myString = "I" + " like " + "Java."; results in myString containing "I like Java." L 8.4
  • 110. The String class contains several methods that you can use. Here are a few. You can test two strings for equality by using equals( ). You can obtain the length of a string by calling the length( ) method. You can obtain the character at a specified index within a string by calling charAt( ). The general forms of these three methods are shown here: // Demonstrating some String methods. class StringDemo2 { public static void main(String args[]) { String strOb1 = "First String"; String strOb2 = "Second String"; String strOb3 = strOb1; System.out.println("Length of strOb1: " + strOb1.length()); L 8.5
  • 111. System.out.println ("Char at index 3 in strOb1: " + strOb1.charAt(3)); if(strOb1.equals(strOb2)) System.out.println("strOb1 == strOb2"); else System.out.println("strOb1 != strOb2"); if(strOb1.equals(strOb3)) System.out.println("strOb1 == strOb3"); else System.out.println("strOb1 != strOb3"); } } This program generates the following output: Length of strOb1: 12 Char at index 3 in strOb1: s strOb1 != strOb2 strOb1 == strOb3 L 8.6
  • 112. UNIT-3
  • 113. B.TECH II YR II SEMESTER(TERM 08-09) UNIT 3 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th edition, Herbert schildt, TMH.Understanding 2. OOP with Java, updated edition, T. Budd, Pearson education. No. of slides:66
  • 114. S.NO. TOPIC LECTURE NO. PPTSLIDES 1 Hierarchical abstractions L1 L1.1TO L1.9 Base class object. 2 subclass, subtype, substitutability. L2 L2.1 TO L2.8 3 forms of inheritance- specialization, L3 L3.1 TO L3.5 specification. 4 construction, extension, limitation, L4 L4.1 TO L4.9 combination. 5 Benefits of inheritance, costs of inheritance. L5 L5.1 TO 5.4 6 Member access rules, super uses, L6 L6.1 TO 6.17 using final with inheritance. 7 polymorphism- method overriding, L7 L7.1 TO 7.11 abstract classes.
  • 115. An essential element of object-oriented programming is abstraction. Humans manage complexity through abstraction. For example, people do not think of a car as a set of tens of thousands of individual parts. They think of it as a well-defined object with its own unique behavior. This abstraction allows people to use a car without being overwhelmed by the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. Instead they are free to utilize the object as a whole. L 1.1
  • 116. A child class of one parent can be the parent of another child, forming class hierarchies L 1.2 Animal Reptile Bird Mammal Snake Lizard BatHorseParrot  At the top of the hierarchy there’s a default class called Object.
  • 117. Good class design puts all common features as high in the hierarchy as reasonable The class hierarchy determines how methods are executed inheritance is transitive An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object L 1.3
  • 118. In Java, all classes use inheritance. If no parent class is specified explicitly, the base class Object is implicitly inherited. All classes defined in Java, is a child of Object class, which provides minimal functionality guaranteed to e common to all objects. L 1.4
  • 119. L 1.5 Methods defined in Object class are; 1.equals(Object obj) Determine whether the argument object is the same as the receiver. 2.getClass() Returns the class of the receiver, an object of type Class. 3.hashCode() Returns a hash value for this object. Should be overridden when the equals method is changed. 4.toString() Converts object into a string value. This method is also often overridden.
  • 120. 1) a class obtains variables and methods from another class 2) the former is called subclass, the latter super-class (Base class) 3) a sub-class provides a specialized behavior with respect to its super-class 4) inheritance facilitates code reuse and avoids duplication of data L 1.6
  • 121. One of the pillars of object-orientation. A new class is derived from an existing class: 1) existing class is called super-class 2) derived class is called sub-class A sub-class is a specialized version of its super- class: 1) has all non-private members of its super-class 2) may provide its own implementation of super-class methods Objects of a sub-class are a special kind of objects of a super-class. L 1.7
  • 122. L 1.8 extends  Is a keyword used to inherit a class from another class  Allows to extend from only one class class One { int a=5; } class Two extends One { int b=10; }
  • 123. One baseobj;// base class object. super class object baseobj can be used to refer its sub class objects. For example, Two subobj=new Two; Baseobj=subobj // now its pointing to sub class L 1.9
  • 124. A subtype is a class that satisfies the principle of substitutability. A subclass is something constructed using inheritance, whether or not it satisfies the principle of substitutability. The two concepts are independent. Not all subclasses are subtypes, and (at least in some languages) you can construct subtypes that are not subclasses. L 2.1
  • 125. Substitutability is fundamental to many of the powerful software development techniques in OOP. The idea is that, declared a variable in one type may hold the value of different type. Substitutability can occur through use of inheritance, whether using extends, or using implements keywords. L 2.2
  • 126. L 2.3 When new classes are constructed using inheritance, the argument used to justify the validity of substitutability is as follows; • Instances of the subclass must possess all data fields associated with its parent class. • Instances of the subclass must implement, through inheritance at least, all functionality defined for parent class. (Defining new methods is not important for the argument.) • Thus, an instance of a child class can mimic the behavior of the parent class and should be indistinguishable from an instance of parent class if substituted in a similar situation.
  • 127. L 2.4 The term subtype is used to describe the relationship between types that explicitly recognizes the principle of substitution. A type B is considered to be a subtype of A if an instances of B can legally be assigned to a variable declared as of type A. The term subclass refers to inheritance mechanism made by extends keyword. Not all subclasses are subtypes. Subtypes can also be formed using interface, linking types that have no inheritance relationship.
  • 128. Methods allows to reuse a sequence of statements Inheritance allows to reuse classes by deriving a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass. As the name implies, the child inherits characteristics of the parent(i.e the child class inherits the methods and data defined for the parent class L 2.5
  • 129. Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class L 2.6 Animal weight : int + getWeight() : int Bird + fly() : void
  • 130. In Java, we use the reserved word extends to establish an inheritance relationship class Animal { // class contents int weight; public void int getWeight() {…} } class Bird extends Animal { // class contents public void fly() {…}; } L 2.7
  • 131.  A child class can override the definition of an inherited method in favor of its own  that is, a child can redefine a method that it inherits from its parent  the new method must have the same signature as the parent's method, but can have different code in the body  In java, all methods except of constructors override the methods of their ancestor class by replacement. E.g.:  the Animal class has method eat()  the Bird class has method eat() and Bird extends Animal  variable b is of class Bird, i.e. Bird b = …  b.eat() simply invokes the eat() method of the Bird class  If a method is declared with the final modifier, it cannot be overridden L 2.8
  • 132. L 3.1 Inheritance is used in a variety of way and for a variety of different purposes . • Inheritance for Specialization • Inheritance for Specification • Inheritance for Construction • Inheritance for Extension • Inheritance for Limitation • Inheritance for Combination One or many of these forms may occur in a single case.
  • 133. L 3.2 Most commonly used inheritance and sub classification is for specialization. Always creates a subtype, and the principles of substitutability is explicitly upheld. It is the most ideal form of inheritance. An example of subclassification for specialization is; public class PinBallGame extends Frame { // body of class }
  • 134.  By far the most common form of inheritance is for specialization.  Child class is a specialized form of parent class  Principle of substitutability holds  A good example is the Java hierarchy of Graphical components in the AWT: • Component  Label  Button  TextComponent  TextArea  TextField  CheckBox  ScrollBar L 3.3
  • 135. L 3.4 This is another most common use of inheritance. Two different mechanisms are provided by Java, interface and abstract, to make use of subclassification for specification. Subtype is formed and substitutability is explicitly upheld. Mostly, not used for refinement of its parent class, but instead is used for definitions of the properties provided by its parent. class FireButtonListener implements ActionListener { // body of class } class B extends A { // class A is defined as abstract specification class }
  • 136. The next most common form of inheritance involves specification. The parent class specifies some behavior, but does not implement the behavior Child class implements the behavior Similar to Java interface or abstract class When parent class does not implement actual behavior but merely defines the behavior that will be implemented in child classes Example, Java 1.1 Event Listeners: ActionListener, MouseListener, and so on specify behavior, but must be subclassed. L 3.5
  • 137. L 4.1 Child class inherits most of its functionality from parent, but may change the name or parameters of methods inherited from parent class to form its interface. This type of inheritance is also widely used for code reuse purposes. It simplifies the construction of newly formed abstraction but is not a form of subtype, and often violates substitutability. Example is Stack class defined in Java libraries.
  • 138. The parent class is used only for its behavior, the child class has no is-a relationship to the parent. Child modify the arguments or names of methods An example might be subclassing the idea of a Set from an existing List class. Child class is not a more specialized form of parent class; no substitutability L 4.2
  • 139. L 4.3 Subclassification for extension occurs when a child class only adds new behavior to the parent class and does not modify or alter any of the inherited attributes. Such subclasses are always subtypes, and substitutability can be used. Example of this type of inheritance is done in the definition of the class Properties which is an extension of the class HashTable.
  • 140. The child class generalizes or extends the parent class by providing more functionality In some sense, opposite of subclassing for specialization The child doesn't change anything inherited from the parent, it simply adds new features Often used when we cannot modify existing base parent class Example, ColoredWindow inheriting from Window Add additional data fields Override window display methods L 4.4
  • 141. L 4.5 Subclassification for limitation occurs when the behavior of the subclass is smaller or more restrictive that the behavior of its parent class. Like subclassification for extension, this form of inheritance occurs most frequently when a programmer is building on a base of existing classes. Is not a subtype, and substitutability is not proper.
  • 142. The child class limits some of the behavior of the parent class. Example, you have an existing List data type, and you want a Stack Inherit from List, but override the methods that allow access to elements other than top so as to produce errors. L 4.6
  • 143. L 4.7 This types of inheritance is known as multiple inheritance in Object Oriented Programming. Although the Java does not permit a subclass to be formed be inheritance from more than one parent class, several approximations to the concept are possible. Example of this type is Hole class defined as; class Hole extends Ball implements PinBallTarget{ // body of class }
  • 144. Two or more classes that seem to be related, but its not clear who should be the parent and who should be the child. Example: Mouse and TouchPad and JoyStick Better solution, abstract out common parts to new parent class, and use subclassing for specialization. L 4.8
  • 145. • Specialization. The child class is a special case of the parent class; in other words, the child class is a subtype of the parent class. • Specification. The parent class defines behavior that is implemented in the child class but not in the parent class. • Construction. The child class makes use of the behavior provided by the parent class, but is not a subtype of the parent class. • Generalization. The child class modifies or overrides some of the methods of the parent class. • Extension. The child class adds new functionality to the parent class, but does not change any inherited behavior. • Limitation. The child class restricts the use of some of the behavior inherited from the parent class. • Variance. The child class and parent class are variants of each other, and the class-subclass relationship is arbitrary. • Combination. The child class inherits features from more than one parent class. This is multiple inheritance and will be the subject of a later chapter. L 4.9
  • 146. Software Reusability (among projects) Increased Reliability (resulting from reuse and sharing of well-tested code) Code Sharing (within a project) Consistency of Interface (among related objects) Software Components Rapid Prototyping (quickly assemble from pre- existing components) Polymorphism and Frameworks (high-level reusable components) Information Hiding L 5.1
  • 147. Execution Speed Program Size Message-Passing Overhead Program Complexity (in overuse of inheritance) L 5.2
  • 148. L 5.3 Types of inheritance  Acquiring the properties of an existing Object into newly creating Object to overcome the redeclaration of properties in deferent classes.  These are 3 types: 1.Simple Inheritance SUPER SUB SUPER SUB 1 SUB 2 extendsextends
  • 149. L 5.4 2. Multi Level Inheritance 3. Multiple Inheritance SUPER SUB SUB SUB SUPER 1 SUPER 2 extends extends implements SUB SUPER 1 SUPER 2 implements SUB extends
  • 150. Visibility modifiers determine which class members are accessible and which do not Members (variables and methods) declared with public visibility are accessible, and those with private visibility are not Problem: How to make class/instance variables visible only to its subclasses? Solution: Java provides a third visibility modifier that helps in inheritance situations: protected L 6.1
  • 151. Visibility Modifiers for class/interface: public : can be accessed from outside the class definition. protected : can be accessed only within the class definition in which it appears, within other classess in the same package, or within the definition of subclassess. private : can be accessed only within the class definition in which it appears. default-access (if omitted) features accessible from inside the current Java package L 6.2
  • 152.  The protected visibility modifier allows a member of a base class to be accessed in the child  protected visibility provides more encapsulation than public does  protected visibility is not as tightly encapsulated as private visibility L 6.3 Book protected int pages + getPages() : int + setPages(): void Dictionary + getDefinitions() : int + setDefinitions(): void + computeRatios() : double
  • 153. class A { int i; void showi() { System.out.println("i: " + i); } } L 6.4
  • 154. class B extends A { int j; void showj() { System.out.println(“j: " + j); } void sum() { System.out.println("i+j: " + (i+j)); } } L 6.5
  • 155. class SimpleInheritance { public static void main(String args[]) { A a = new A(); B b = new B(); a.i = 10; System.out.println("Contents of a: "); a.showi(); b.i = 7; b.j = 8; System.out.println("Contents of b: "); subOb.showi(); subOb.showj(); System.out.println("Sum of I and j in b:"); b.sum();}} L 6.6
  • 156. The basic Box class: class Box { private double width, height, depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box(Box ob) { width = ob.width; height = ob.height; depth = ob.depth; } double volume() { return width * height * depth; } } L 6.7
  • 157. Adding the weight variable to the Box class: class BoxWeight extends Box { double weight; BoxWeight(BoxWeight ob) { super(ob); weight = ob.weight; } BoxWeight(double w, double h, double d, double m) { super(w, h, d); weight = m; } } L 6.7
  • 158. Adding the cost variable to the BoxWeight class: class Ship extends BoxWeight { double cost; Ship(Ship ob) { super(ob); cost = ob.cost; } Ship(double w, double h, double d, double m, double c) { super(w, h, d, m); cost = c; }} L 6.8
  • 159. class DemoShip { public static void main(String args[]) { Ship ship1 = new Ship(10, 20, 15, 10, 3.41); Ship ship2 = new Ship(2, 3, 4, 0.76, 1.28); double vol; vol = ship1.volume(); System.out.println("Volume of ship1 is " + vol); System.out.print("Weight of ship1 is”); System.out.println(ship1.weight); System.out.print("Shipping cost: $"); System.out.println(ship1.cost); L 6.9
  • 160. vol = ship2.volume(); System.out.println("Volume of ship2 is " + vol); System.out.print("Weight of ship2 is “); System.out.println(ship2.weight); System.out.print("Shipping cost: $“); System.out.println(ship2.cost); } } L 6.10
  • 161. L 6.11 “super” uses  ‘super’ is a keyword used to refer to hidden variables of super class from sub class. super.a=a;  It is used to call a constructor of super class from constructor of sub class which should be first statement. super(a,b);  It is used to call a super class method from sub class method to avoid redundancy of code super.addNumbers(a, b);
  • 162.  Why is super needed to access super-class members?  When a sub-class declares the variables or methods with the same names and types as its super-class: class A { int i = 1; } class B extends A { int i = 2; System.out.println(“i is “ + i); }  The re-declared variables/methods hide those of the super- class. L 6.12
  • 163. class A { int i; } class B extends A { int i; B(int a, int b) { super.i = a; i = b; } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } L 6.13
  • 164. Although the i variable in B hides the i variable in A, super allows access to the hidden variable of the super-class: class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } L 6.14
  • 165.  final keyword is used declare constants which can not change its value of definition.  final Variables can not change its value.  final Methods can not be Overridden or Over Loaded  final Classes can not be extended or inherited L 6.15
  • 166.  A method declared final cannot be overridden in any sub-class: class A { final void meth() { System.out.println("This is a final method."); } } This class declaration is illegal: class B extends A { void meth() { System.out.println("Illegal!"); } } L 6.16
  • 167. A class declared final cannot be inherited – has no sub-classes. final class A { … } This class declaration is considered illegal: class B extends A { … } Declaring a class final implicitly declares all its methods final. It is illegal to declare a class as both abstract and final. L 6.17
  • 168. Polymorphism is one of three pillars of object- orientation. Polymorphism: many different (poly) forms of objects that share a common interface respond differently when a method of that interface is invoked: 1) a super-class defines the common interface 2) sub-classes have to follow this interface (inheritance), but are also permitted to provide their own implementations (overriding) A sub-class provides a specialized behaviors relying on the common elements defined by its super-class. L 7.1
  • 169.  A polymorphic reference can refer to different types of objects at different times  In java every reference can be polymorphic except of references to base types and final classes.  It is the type of the object being referenced, not the reference type, that determines which method is invoked  Polymorphic references are therefore resolved at run-time, not during compilation; this is called dynamic binding  Careful use of polymorphic references can lead to elegant, robust software designs L 7.2
  • 170. When a method of a sub-class has the same name and type as a method of the super-class, we say that this method is overridden. When an overridden method is called from within the sub-class: 1) it will always refer to the sub-class method 2) super-class method is hidden L 7.3
  • 171. class A { int i, j; A(int a, int b) { i = a; j = b; } void show() { System.out.println("i and j: " + i + " " + j); } } L 7.4
  • 172. class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { System.out.println("k: " + k); } } L 7.5
  • 173. When show() is invoked on an object of type B, the version of show() defined in B is used: class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); } } The version of show() in A is hidden through overriding. L7.6
  • 174. L 7.7 Overloading deals with multiple methods in the same class with the same name but different signatures Overloading lets you define a similar operation in different ways for different data Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature o Overriding lets you define a similar operation in different ways for different object types
  • 175. Java allows abstract classes  use the modifier abstract on a class header to declare an abstract class abstract class Vehicle { … } An abstract class is a placeholder in a class hierarchy that represents a generic concept L 7.8 Vehicle Car Boat Plane
  • 176. public abstract class Vehicle { String name; public String getName() { return name; } method body abstract public void move(); no body! } L 7.9  An abstract class often contains abstract methods, though it doesn’t have to  Abstract methods consist of only methods declarations, without any method body
  • 177. An abstract class often contains abstract methods, though it doesn’t have to  Abstract methods consist of only methods declarations, without any method body The non-abstract child of an abstract class must override the abstract methods of the parent An abstract class cannot be instantiated The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate L 7.10
  • 178.  Inheritance allows a sub-class to override the methods of its super-class.  A super-class may altogether leave the implementation details of a method and declare such a method abstract:  abstract type name(parameter-list);  Two kinds of methods: 1) concrete – may be overridden by sub-classes 2) abstract – must be overridden by sub-classes  It is illegal to define abstract constructors or static methods. L 7.11
  • 179. UNIT-4
  • 180. B.TECH II YR II SEMESTER(TERM 08-09) UNIT 4 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th edition, Herbert schildt, TMH.Understanding 2. OOP with Java, updated edition, T. Budd, Pearson education. No. of slides: 56
  • 181. S.NO. TOPIC LECTURE NO. PPTSLIDES 1 Defining, Creating and Accessing a Package L1 L1.1TO L1.11 2 Importing packages L2 L2.1 TO L2.5 3 Differences between classes and interfaces L3 L3.1 TO L3.2 4 Defining an interface L 4 L4.1 TO L4.2 5 Implementing interface L5 L5.1 TO 5.7 6 Applying interfaces L6 L6.1 TO 6.3 7 variables in interface and extending interfaces L7 L7.1 TO 7.9 8 Exploring packages – Java.io L8 L 8.1 TO 8.6 9 Exploring packages- java.util. L9 L 9.1 TO 9.9
  • 182. A package is both a naming and a visibility control mechanism: 1) divides the name space into disjoint subsets It is possible to define classes within a package that are not accessible by code outside the package. 2) controls the visibility of classes and their members It is possible to define class members that are only exposed to other members of the same package. Same-package classes may have an intimate knowledge of each other, but not expose that knowledge to other packages L 1.1
  • 183. A package statement inserted as the first line of the source file: package myPackage; class MyClass1 { … } class MyClass2 { … } means that all classes in this file belong to the myPackage package.  The package statement creates a name space where such classes are stored. When the package statement is omitted, class names are put into the default package which has no name. L 1.2
  • 184. Other files may include the same package instruction: 1.package myPackage; class MyClass1 { … } class MyClass2 { … } 2. package myPackage; class MyClass3{ … } A package may be distributed through several source files L 1.3
  • 185. Java uses file system directories to store packages. Consider the Java source file: package myPackage; class MyClass1 { … } class MyClass2 { … } The byte code files MyClass1.class and MyClass2.class must be stored in a directory myPackage. Case is significant! Directory names must match package names exactly. L 1.4
  • 186. To create a package hierarchy, separate each package name with a dot: package myPackage1.myPackage2.myPackage3; A package hierarchy must be stored accordingly in the file system: 1) Unix myPackage1/myPackage2/myPackage3 2) Windows myPackage1myPackage2myPackage3 3) Macintosh myPackage1:myPackage2:myPackage3 You cannot rename a package without renaming its directory! L 1.5
  • 187. As packages are stored in directories, how does the Java run-time system know where to look for packages? Two ways: 1) The current directory is the default start point - if packages are stored in the current directory or sub- directories, they will be found. 2) Specify a directory path or paths by setting the CLASSPATH environment variable. L 1.6
  • 188. CLASSPATH - environment variable that points to the root directory of the system’s package hierarchy. Several root directories may be specified in CLASSPATH, e.g. the current directory and the C:rajumyJava directory: .;C:rajumyJava Java will search for the required packages by looking up subsequent directories described in the CLASSPATH variable. L 1.7
  • 189. Consider this package statement: package myPackage; In order for a program to find myPackage, one of the following must be true: 1) program is executed from the directory immediately above myPackage (the parent of myPackage directory) 2) CLASSPATH must be set to include the path to myPackage L 1.8
  • 190. package MyPack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b; } void show() { if (bal<0) System.out.print("-->> "); System.out.println(name + ": $" + bal); } } L 1.9
  • 191. class AccountBalance { public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for (int i=0; i<3; i++) current[i].show(); } } L 1.10
  • 192. Save, compile and execute: 1) call the file AccountBalance.java 2) save the file in the directory MyPack 3) compile; AccountBalance.class should be also in MyPack 4) set access to MyPack in CLASSPATH variable, or make the parent of MyPack your current directory 5) run: java MyPack.AccountBalance Make sure to use the package-qualified class name. L 1.11
  • 193. Since classes within packages must be fully-qualified with their package names, it would be tedious to always type long dot-separated names. The import statement allows to use classes or whole packages directly. Importing of a concrete class: import myPackage1.myPackage2.myClass; Importing of all classes within a package: import myPackage1.myPackage2.*; L 2.1
  • 194. The import statement occurs immediately after the package statement and before the class statement: package myPackage; import otherPackage1;otherPackage2.otherClass; class myClass { … } The Java system accepts this import statement by default: import java.lang.*; This package includes the basic language functions. Without such functions, Java is of no much use. L 2.2
  • 195. A package MyPack with one public class Balance. The class has two same-package variables: public constructor and a public show method. package MyPack; public class Balance { String name; double bal; public Balance(String n, double b) { name = n; bal = b; } public void show() { if (bal<0) System.out.print("-->> "); System.out.println(name + ": $" + bal); } } L 2.3
  • 196. The importing code has access to the public class Balance of the MyPack package and its two public members: import MyPack.*; class TestBalance { public static void main(String args[]) { Balance test = new Balance("J. J. Jaspers", 99.88); test.show(); } } L 2.4
  • 197. Finally, a Java source file consists of: 1) a single package instruction (optional) 2) several import statements (optional) 3) a single public class declaration (required) 4) several classes private to the package (optional) At the minimum, a file contains a single public class declaration. L 2.5
  • 198. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. One class can implement any number of interfaces. Interfaces are designed to support dynamic method resolution at run time. L 3.1
  • 199. Interface is little bit like a class... but interface is lack in instance variables....that's u can't create object for it..... Interfaces are developed to support multiple inheritance... The methods present in interfaces r pure abstract.. The access specifiers public,private,protected are possible with classes, but the interface uses only one spcifier public..... interfaces contains only the method declarations.... no definitions....... A interface defines, which method a class has to implement. This is way - if you want to call a method defined by an interface - you don't need to know the exact class type of an object, you only need to know that it implements a specific interface. Another important point about interfaces is that a class can implement multiple interfaces. L 3.2
  • 200. Using interface, we specify what a class must do, but not how it does this. An interface is syntactically similar to a class, but it lacks instance variables and its methods are declared without any body. An interface is defined with an interface keyword. L 4.1
  • 201.  An interface declaration consists of modifiers, the keyword interface, the interface name, a comma-separated list of parent interfaces (if any), and the interface body. For example: public interface GroupedInterface extends Interface1, Interface2, Interface3 { // constant declarations double E = 2.718282; // base of natural logarithms // //method signatures void doSomething (int i, double x); int doSomethingElse(String s); }  The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.  An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends L 4.2
  • 202. General format: access interface name { type method-name1(parameter-list); type method-name2(parameter-list); … type var-name1 = value1; type var-nameM = valueM; … } L 5.1
  • 203. Two types of access: 1) public – interface may be used anywhere in a program 2) default – interface may be used in the current package only Interface methods have no bodies – they end with the semicolon after the parameter list. They are essentially abstract methods. An interface may include variables, but they must be final, static and initialized with a constant value. In a public interface, all members are implicitly public. L 5.2
  • 204. A class implements an interface if it provides a complete set of methods defined by this interface. 1) any number of classes may implement an interface 2) one class may implement any number of interfaces Each class is free to determine the details of its implementation. Implementation relation is written with the implements keyword. L 5.3
  • 205. General format of a class that includes the implements clause: Syntax: access class name extends super-class implements interface1, interface2, …, interfaceN { … } Access is public or default. L 5.4
  • 206. If a class implements several interfaces, they are separated with a comma. If a class implements two interfaces that declare the same method, the same method will be used by the clients of either interface. The methods that implement an interface must be declared public. The type signature of the implementing method must match exactly the type signature specified in the interface definition. L 5.5
  • 207. Declaration of the Callback interface: interface Callback { void callback(int param); } Client class implements the Callback interface: class Client implements Callback { public void callback(int p) { System.out.println("callback called with " + p); } } L 5.6
  • 208. An implementing class may also declare its own methods: class Client implements Callback { public void callback(int p) { System.out.println("callback called with " + p); } void nonIfaceMeth() { System.out.println("Classes that implement “ + “interfaces may also define ” + “other members, too."); } } L 5.7
  • 209. A Java interface declares a set of method signatures i.e., says what behavior exists Does not say how the behavior is implemented i.e., does not give code for the methods • Does not describe any state (but may include “final” constants) L 6.1
  • 210. A concrete class that implements an interface Contains “implements InterfaceName” in the class declaration Must provide implementations (either directly or inherited from a superclass) of all methods declared in the interface An abstract class can also implement an interface Can optionally have implementations of some or all interface methods L 6.2
  • 211. Interfaces and Extends both describe an “is- a” relation If B implements interface A, then B inherits the (abstract) method signatures in A If B extends class A, then B inherits everything in A, which can include method code and instance variables as well as abstract method signatures Inheritance” is sometimes used to talk about the superclass/subclass “extends” relation only L 6.3
  • 212. Variables declared in an interface must be constants. A technique to import shared constants into multiple classes: 1) declare an interface with variables initialized to the desired values 2) include that interface in a class through implementation As no methods are included in the interface, the class does not implement anything except importing the variables as constants. L 7.1
  • 213. An interface with constant values: import java.util.Random; interface SharedConstants { int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5; } L 7.2
  • 214. Question implements SharedConstants, including all its constants. Which constant is returned depends on the generated random number: class Question implements SharedConstants { Random rand = new Random(); int ask() { int prob = (int) (100 * rand.nextDouble()); if (prob < 30) return NO; else if (prob < 60) return YES; else if (prob < 75) return LATER; else if (prob < 98) return SOON; else return NEVER; } } L 7.3
  • 215. AskMe includes all shared constants in the same way, using them to display the result, depending on the value received: class AskMe implements SharedConstants { static void answer(int result) { switch(result) { case NO: System.out.println("No"); break; case YES: System.out.println("Yes"); break; case MAYBE: System.out.println("Maybe"); break; case LATER: System.out.println("Later"); break; case SOON: System.out.println("Soon"); break; case NEVER: System.out.println("Never"); break; } } L 7.4
  • 216. The testing function relies on the fact that both ask and answer methods, defined in different classes, rely on the same constants: public static void main(String args[]) { Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); } } L 7.5
  • 217. One interface may inherit another interface. The inheritance syntax is the same for classes and interfaces. interface MyInterface1 { void myMethod1(…) ; } interface MyInterface2 extends MyInterface1 { void myMethod2(…) ; } When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain. L 7.6
  • 218. Consider interfaces A and B. interface A { void meth1(); void meth2(); } B extends A: interface B extends A { void meth3(); } L 7.7
  • 219. MyClass must implement all of A and B methods: class MyClass implements B { public void meth1() { System.out.println("Implement meth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implement meth3()."); } } L 7.8
  • 220. Create a new MyClass object, then invoke all interface methods on it: class IFExtend { public static void main(String arg[]) { MyClass ob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); } } L 7.9
  • 221. Provides for system input and output through data streams, serialization and the file system. Interface Summary .DataInput The DataInput interface provides for reading bytes from a binary stream and reconstructing from them data in any of the Java primitive types. DataOutputThe DataOutput interface provides for converting data from any of the Java primitive types to a series of bytes and writing these bytes to a binary stream .Externalizable Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances. SerializableSerializability of a class is enabled by the class implementing the java.io.Serializable interface. L 8.1
  • 222.  BufferedInputStream: A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.  BufferedOutputStream: The class implements a buffered output stream.  BufferedReader: Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.  BufferedWriter: Writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings  ByteArrayInputStream: A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.  ByteArrayOutputStream: This class implements an output stream in which the data is written into a byte array. L 8.2
  • 223. CharArrayReader: This class implements a character buffer that can be used as a character-input stream .CharArrayWriter: This class implements a character buffer that can be used as an Writer Console: Methods to access the character-based console device, if any, associated with the current Java virtual machine. DataInputStream: A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. DataOutputStream: A data output stream lets an application write primitive Java data types to an output stream in a portable way. L 8.3
  • 224.  File: An abstract representation of file and directory pathnames.  FileInputStream: A FileInputStream obtains input bytes from a file in a file system.  FileOutputStream: A file output stream is an output stream for writing data to a File or to a FileDescriptor.  FileReader: Convenience class for reading character files.  FileWriter: Convenience class for writing character files.  FilterInputStream: A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.  FilterOutputStream: This class is the superclass of all classes that filter output streams  .FilterReader: Abstract class for reading filtered character streams  .FilterWriter: Abstract class for writing filtered character streams  .InputStream: This abstract class is the superclass of all classes representing an input stream of bytes.  InputStreamReader: An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. L 8.4
  • 225.  ObjectInputStream: An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream  ObjectOutputStream: An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream.  OutputStream: This abstract class is the superclass of all classes representing an output stream of bytes.  OutputStreamWriter: An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.  PrintWriter: Prints formatted representations of objects to a text- output stream.  RandomAccessFile: Instances of this class support both reading and writing to a random access file.  StreamTokenizer: The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. L 8.5
  • 226. FileNotFoundException: Signals that an attempt to open the file denoted by a specified pathname has failed. InterruptedIOException: Signals that an I/O operation has been interrupted InvalidClassException: Thrown when the Serialization runtime detects one of the following problems with a Class. InvalidObjectException: Indicates that one or more deserialized objects failed validation tests. IOException: Signals that an I/O exception of some sort has occurred. L 8.6
  • 227. Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator, and a bit array). L9.1
  • 228. Collection<E>: The root interface in the collection hierarchy. Comparator<T>: A comparison function, which imposes a total ordering on some collection of objects. Enumeration<E>: An object that implements the Enumeration interface generates a series of elements, one at a time. EventListener: A tagging interface that all event listener interfaces must extend. Iterator<E>: An iterator over a collection List<E>An ordered collection (also known as a sequence). ListIterator<E>: An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. L9.2
  • 229. Map<K,V>: An object that maps keys to values. Observer: A class can implement the Observer interface when it wants to be informed of changes in observable objects. Queue<E>: A collection designed for holding elements prior to processing. Set<E>: A collection that contains no duplicate elements. SortedMap<K,V>: A Map that further provides a total ordering on its keys. SortedSet<E>: A Set that further provides a total ordering on its elements. L 9.3
  • 230.  AbstractCollection<E>: This class provides a skeletal implementation of the Collection interface, to minimize the effort required to implement this interface.  AbstractList<E>: This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array).  AbstractMap<K,V>: This class provides a skeletal implementation of the Map interface, to minimize the effort required to implement this interface.  AbstractQueue<E>: This class provides skeletal implementations of some Queue operations.  AbstractSequentialList<E>: This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "sequential access" data store (such as a linked list).  AbstractSet<E>: This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface. L 9.4
  • 231. ArrayList<E>: Resizable-array implementation of the List interface Arrays: This class contains various methods for manipulating arrays (such as sorting and searching). BitSet: This class implements a vector of bits that grows as needed Calendar: The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields: such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week L 9.5
  • 232. Collections: This class consists exclusively of static methods that operate on or return collections Currency: Represents a currency. Date: The class Date represents a specific instant in time, with millisecond precision. Dictionary<K,V>: The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values. EventObject: The root class from which all event state objects shall be derived. L 9.6
  • 233.  GregorianCalendar: GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.  HashMap<K,V>: Hash table based implementation of the Map interface.  HashSet<E>: This class implements the Set interface, backed by a hash table (actually a HashMap instance)  .Hashtable<K,V>: This class implements a hashtable, which maps keys to values.  LinkedList<E>: Linked list implementation of the List interface  Locale: A Locale object represents a specific geographical, political, or cultural region.  Observable: This class represents an observable object, or "data" in the model-view paradigm  Properties: The Properties class represents a persistent set of properties. L 9.7
  • 234.  Random: An instance of this class is used to generate a stream of pseudorandom numbers.  ResourceBundle: Resource bundles contain locale-specific objects.  SimpleTimeZone: SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar.  Stack<E>: The Stack class represents a last-in-first-out (LIFO) stack of objects.  StringTokenizer: The string tokenizer class allows an application to break a string into tokens.  TimeZone: TimeZone represents a time zone offset, and also figures out daylight savings.  TreeMap<K,V>: A Red-Black tree based NavigableMap implementation.  TreeSet<E>: A NavigableSet implementation based on a TreeMap.UUIDA class that represents an immutable universally unique identifier (UUID).  Vector<E>: The Vector class implements a growable array of objects L 9.8
  • 235.  EmptyStackException: Thrown by methods in the Stack class to indicate that the stack is empty.  InputMismatchException: Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.  InvalidPropertiesFormatException: Thrown to indicate that an operation could not complete because the input did not conform to the appropriate XML document type for a collection of properties, as per the Properties specification.  NoSuchElementException: Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.  TooManyListenersException: The TooManyListenersException Exception is used as part of the Java Event model to annotate and implement a unicast special case of a multicast Event Source.  UnknownFormatConversionException: Unchecked exception thrown when an unknown conversion is given. L 9.9
  • 236. UNIT-5
  • 237. B.TECH II YR II SEMESTER(TERM 08-09) UNIT 5 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th edition, Herbert schildt, TMH.Understanding 2. OOP with Java, updated edition, T. Budd, Pearson education. No. of slides:75
  • 238. Exceptions Exception is an abnormal condition that arises when executing a program. In the languages that do not support exception handling, errors must be checked and handled manually, usually through the use of error codes. In contrast, Java: 1) provides syntactic mechanisms to signal, detect and handle errors 2) ensures a clean separation between the code executed in the absence of errors and the code to handle various kinds of errors 3) brings run-time error management into object- oriented programming L 1.1
  • 239. An exception is an object that describes an exceptional condition (error) that has occurred when executing a program. Exception handling involves the following: 1) when an error occurs, an object (exception) representing this error is created and thrown in the method that caused it 2) that method may choose to handle the exception itself or pass it on 3) either way, at some point, the exception is caught and processed L 1.2
  • 240. Exceptions can be: 1) generated by the Java run-time system Fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. 2) manually generated by programmer’s code Such exceptions are typically used to report some error conditions to the caller of a method. L 1.3
  • 241. Five constructs are used in exception handling: 1) try – a block surrounding program statements to monitor for exceptions 2) catch – together with try, catches specific kinds of exceptions and handles them in some way 3) finally – specifies any code that absolutely must be executed whether or not an exception occurs 4) throw – used to throw a specific exception from the program 5) throws – specifies which exceptions a given method can throw L 1.4
  • 242. General form: try { … } catch(Exception1 ex1) { … } catch(Exception2 ex2) { … } … finally { … } where: 1) try { … } is the block of code to monitor for exceptions 2) catch(Exception ex) { … } is exception handler for the exception Exception 3) finally { … } is the block of code to execute before the try block ends L 1.5
  • 243. Separating Error-Handling code from “regular” business logic code Propagating errors up the call stack Grouping and differentiating error types L 2.1
  • 244. In traditional programming, error detection, reporting, and handling often lead to confusing code Consider pseudocode method here that reads an entire file into memory readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } L 2.2
  • 245. ● In traditional programming, To handle such cases, the readFile function must have more code to do error detection, reporting, and handling. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } L 2.3
  • 246. else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } L 2.4
  • 247. Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } L 2.5
  • 248. catch (sizeDeterminationFailed) { doSomething; }catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively. L 2.6
  • 249.  Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program: method1 calls method2, which calls method3, which finally calls readFile  Suppose also that method1 is the only method interested in the errors that might occur within readFile. method1 { call method2; } method2 { call method3; } method3 { call readFile; } L 2.7
  • 250. L 2.8 method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; } Traditional error notification Techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1— the only method that is interested in them.
  • 251. L 2.9 method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; }  Any checked exceptions that can be thrown within a method must be specified in its throws clause.
  • 252. Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy An example of a group of related exception classes in the Java platform are those defined in java.io.IOException and its descendants IOException is the most general and represents any type of error that can occur when performing I/O Its descendants represent more specific errors. For example, FileNotFoundException means that a file could not be located on disk. L 2.10
  • 253.  A method can write specific handlers that can handle a very specific exception The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception. catch (FileNotFoundException e) { ... } L 2.11
  • 254. A method can catch an exception based on its group or general type by specifying any of the exception's super classes in the catch statement. For example, to catch all I/O exceptions, regardless of their specific type, an exception handler specifies an IOException argument. // Catch all I/O exceptions, including // FileNotFoundException, EOFException, and so on. catch (IOException e) { ... } L 2.12
  • 255. There are two basic models in exception-handling theory. In termination the error is so critical there’s no way to get back to where the exception occurred. Whoever threw the exception decided that there was no way to salvage the situation, and they don’t want to come back. The alternative is called resumption. It means that the exception handler is expected to do something to rectify the situation, and then the faulting method is retried, presuming success the second time. If you want resumption, it means you still hope to continue execution after the exception is handled. L 2.13
  • 256. In resumption a method call that want resumption- like behavior (i.e don’t throw an exception all a method that fixes the problem.) Alternatively, place your try block inside a while loop that keeps reentering the try block until the result is satisfactory. Operating systems that supported resumptive exception handling eventually ended up using termination-like code and skipping resumption. L 2.14
  • 257. All exceptions are sub-classes of the build-in class Throwable. Throwable contains two immediate sub-classes: 1) Exception – exceptional conditions that programs should catch The class includes: a) RuntimeException – defined automatically for user programs to include: division by zero, invalid array indexing, etc. b) use-defined exception classes 2) Error – exceptions used by Java to indicate errors with the runtime environment; user programs are not supposed to catch them L 3.1
  • 258. L 3.2
  • 259. Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> } L 3.3
  • 260. class DivByZero { public static void main(String args[]) { try { System.out.println(3/0); System.out.println(“Please print me.”); } catch (ArithmeticException exc) { //Division by zero is an ArithmeticException System.out.println(exc); } System.out.println(“After exception.”); } } L 3.4
  • 261. class MultipleCatch { public static void main(String args[]) { try { int den = Integer.parseInt(args[0]); System.out.println(3/den); } catch (ArithmeticException exc) { System.out.println(“Divisor was 0.”); } catch (ArrayIndexOutOfBoundsException exc2) { System.out.println(“Missing argument.”); } System.out.println(“After exception.”); } } L 3.5
  • 262. class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args[0]); try { int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(“Div by zero error!"); } } catch (ArrayIndexOutOfBoundsException) { System.out.println(“Need 2 parameters!"); } } } L 3.6
  • 263. class NestedTryDemo2 { static void nestedTry(String args[]) { try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println("Div by zero error!"); } } public static void main(String args[]){ try { nestedTry(args); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Need 2 parameters!"); } } } L 3.7
  • 264. So far, we were only catching the exceptions thrown by the Java system. In fact, a user program may throw an exception explicitly: throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or its subclass. L 4.1
  • 265. Once an exception is thrown by: throw ThrowableInstance; 1) the flow of control stops immediately 2) the nearest enclosing try statement is inspected if it has a catch statement that matches the type of exception: 1) if one exists, control is transferred to that statement 2) otherwise, the next enclosing try statement is examined 3) if no enclosing try statement has a corresponding catch clause, the default exception handler halts the program and prints the stack L 4.2
  • 266. Two ways to obtain a Throwable instance: 1) creating one with the new operator All Java built-in exceptions have at least two Constructors: One without parameters and another with one String parameter: throw new NullPointerException("demo"); 2) using a parameter of the catch clause try { … } catch(Throwable e) { … e … } L 4.3
  • 267. class ThrowDemo { //The method demoproc throws a NullPointerException exception which is immediately caught in the try block and re-thrown: static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; } } L 4.4
  • 268. The main method calls demoproc within the try block which catches and handles the NullPointerException exception: public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } } L 4.5
  • 269. If a method is capable of causing an exception that it does not handle, it must specify this behavior by the throws clause in its declaration: type name(parameter-list) throws exception-list { … } where exception-list is a comma-separated list of all types of exceptions that a method might throw. All exceptions must be listed except Error and RuntimeException or any of their subclasses, otherwise a compile-time error occurs. L 4.6
  • 270. The throwOne method throws an exception that it does not catch, nor declares it within the throws clause. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne(); } } Therefore this program does not compile. L 4.7
  • 271. Corrected program: throwOne lists exception, main catches it: class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } L 4.8
  • 272. When an exception is thrown: 1) the execution of a method is changed 2) the method may even return prematurely. This may be a problem is many situations. For instance, if a method opens a file on entry and closes on exit; exception handling should not bypass the proper closure of the file. The finally block is used to address this problem. L 4.9
  • 273. The try/catch statement requires at least one catch or finally clause, although both are optional: try { … } catch(Exception1 ex1) { … } … finally { … } Executed after try/catch whether of not the exception is thrown. Any time a method is to return to a caller from inside the try/catch block via: 1) uncaught exception or 2) explicit return the finally clause is executed just before the method returns. L 4.10
  • 274. Three methods to exit in various ways. class FinallyDemo { //procA prematurely breaks out of the try by throwing an exception, the finally clause is executed on the way out: static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } } L4.11
  • 275. // procB’s try statement is exited via a return statement, the finally clause is executed before procB returns: static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally"); } } L 4.12
  • 276. In procC, the try statement executes normally without error, however the finally clause is still executed: static void procC() { try { System.out.println("inside procC"); } finally { System.out.println("procC's finally"); } } L 4.13
  • 277. Demonstration of the three methods: public static void main(String args[]) { try { procA(); } catch (Exception e) { System.out.println("Exception caught"); } procB(); procC(); } } L 4.14
  • 278. The default java.lang package provides several exception classes, all sub-classing the RuntimeException class. Two sets of build-in exception classes: 1) unchecked exceptions – the compiler does not check if a method handles or throws there exceptions 2) checked exceptions – must be included in the method’s throws clause if the method generates but does not handle them L 5.1
  • 279.  Methods that generate but do not handle those exceptions need not declare them in the throws clause: 1) ArithmeticException 2) ArrayIndexOutOfBoundsException 3) ArrayStoreException 4) ClassCastException 5) IllegalStateException 6) IllegalMonitorStateException 7) IllegalArgumentException L 5.2
  • 280. 8. StringIndexOutOfBounds 9. UnsupportedOperationException 10. SecurityException 11. NumberFormatException 12. NullPointerException 13. NegativeArraySizeException 14. IndexOutOfBoundsException 15. IllegalThreadStateException L 5.3
  • 281.  Methods that generate but do not handle those exceptions must declare them in the throws clause: 1. NoSuchMethodException NoSuchFieldException 2. InterruptedException 3. InstantiationException 4. IllegalAccessException 5. CloneNotSupportedException 6. ClassNotFoundException L 5.4
  • 282. Build-in exception classes handle some generic errors. For application-specific errors define your own exception classes. How? Define a subclass of Exception: class MyException extends Exception { … } MyException need not implement anything – its mere existence in the type system allows to use its objects as exceptions. L 6.1
  • 283. A new exception class is defined, with a private detail variable, a one parameter constructor and an overridden toString method: class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } } L 6.2
  • 284. class ExceptionDemo { The static compute method throws the MyException exception whenever its a argument is greater than 10: static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if (a > 10) throw new MyException(a); System.out.println("Normal exit"); } L 6.3
  • 285. The main method calls compute with two arguments within a try block that catches the MyException exception: public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } } L 6.4
  • 286. Multi-Tasking  Two kinds of multi-tasking: 1) process-based multi-tasking 2) thread-based multi-tasking  Process-based multi-tasking is about allowing several programs to execute concurrently, e.g. Java compiler and a text editor.  Processes are heavyweight tasks: 1) that require their own address space 2) inter-process communication is expensive and limited 3) context-switching from one process to another is expensive and limited L 7.1
  • 287. Thread-based multi-tasking is about a single program executing concurrently several tasks e.g. a text editor printing and spell- checking text. Threads are lightweight tasks: 1) they share the same address space 2) they cooperatively share the same process 3) inter-thread communication is inexpensive 4) context-switching from one thread to another is low-cost Java multi-tasking is thread-based. L 7.2
  • 288. Multi-threading enables to write efficient programs that make the maximum use of the CPU, keeping the idle time to a minimum. There is plenty of idle time for interactive, networked applications: 1) the transmission rate of data over a network is much slower than the rate at which the computer can process it 2) local file system resources can be read and written at a much slower rate than can be processed by the CPU 3) of course, user input is much slower than the computer L 7.3
  • 289. Thread exist in several states: 1) ready to run 2) running 3) a running thread can be suspended 4) a suspended thread can be resumed 5) a thread can be blocked when waiting for a resource 6) a thread can be terminated Once terminated, a thread cannot be resumed. L 7.4
  • 290. L 7.5 Born Blocked Runnable Dead stop() start() stop() Active block on I/O I/O available JVM sleep(500) wake up suspend() resume() wait notify
  • 291.  New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.  Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor.  Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.  Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.  Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread. L 7.6
  • 292. To create a new thread a program will: 1) extend the Thread class, or 2) implement the Runnable interface Thread class encapsulates a thread of execution. The whole Java multithreading environment is based on the Thread class. L 8.1
  • 293. Start: a thread by calling start its run method Sleep: suspend a thread for a period of time Run: entry-point for a thread Join: wait for a thread to terminate isAlive: determine if a thread is still running getPriority: obtain a thread’s priority getName: obtain a thread’s name L 8.2
  • 294. To create a new thread by implementing the Runnable interface: 1) create a class that implements the run method (inside this method, we define the code that constitutes the new thread): public void run() 2) instantiate a Thread object within that class, a possible constructor is: Thread(Runnable threadOb, String threadName) 3) call the start method on this object (start calls run): void start() L 8.3
  • 295. A class NewThread that implements Runnable: class NewThread implements Runnable { Thread t; //Creating and starting a new thread. Passing this to the // Thread constructor – the new thread will call this // object’s run method: NewThread() { t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); } L 8.4
  • 296. //This is the entry point for the newly created thread – a five-iterations loop //with a half-second pause between the iterations all within try/catch: public void run() { try { for (int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } L 8.5
  • 297. class ThreadDemo { public static void main(String args[]) { //A new thread is created as an object of // NewThread: new NewThread(); //After calling the NewThread start method, // control returns here. L 8.6
  • 298. //Both threads (new and main) continue concurrently. //Here is the loop for the main thread: try { for (int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } L 8.7
  • 299. The second way to create a new thread: 1) create a new class that extends Thread 2) create an instance of that class Thread provides both run and start methods: 1) the extending class must override run 2) it must also call the start method L 8.8
  • 300. The new thread class extends Thread: class NewThread extends Thread { //Create a new thread by calling the Thread’s // constructor and start method: NewThread() { super("Demo Thread"); System.out.println("Child thread: " + this); start(); } L 8.9
  • 301. NewThread overrides the Thread’s run method: public void run() { try { for (int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } 8.10
  • 302. class ExtendThread { public static void main(String args[]) { //After a new thread is created: new NewThread(); //the new and main threads continue //concurrently… L 8.11
  • 303. //This is the loop of the main thread: try { for (int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } L 8.12
  • 304.  Multi-threading introduces asynchronous behavior to a program.  How to ensure synchronous behavior when we need it?  For instance, how to prevent two threads from simultaneously writing and reading the same object?  Java implementation of monitors: 1) classes can define so-called synchronized methods 2) each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called 3) once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object L 8.13
  • 305. Language keyword: synchronized Takes out a monitor lock on an object Exclusive lock for that thread If lock is currently unavailable, thread will block L 8.14
  • 306. Protects access to code, not to data Make data members private Synchronize accessor methods Puts a “force field” around the locked object so no other threads can enter Actually, it only blocks access to other synchronizing threads L 8.15
  • 307.  Any Java thread can be a daemon thread.  Daemon threads are service providers for other threads running in the same process as the daemon thread.  The run() method for a daemon thread is typically an infinite loop that waits for a service request. When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.  To specify that a thread is a daemon thread, call the setDaemon method with the argument true. To determine if a thread is a daemon thread, use the accessor method isDaemon. L 9.1
  • 308. o Every Java thread is a member of a thread group. o Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. o For example, you can start or suspend all the threads within a group with a single method call. o Java thread groups are implemented by the “ThreadGroup” class in the java.lang package.  The runtime system puts a thread into a thread group during thread construction.  When you create a thread, you can either allow the runtime system to put the new thread in some reasonable default group or you can explicitly set the new thread's group.  The thread is a permanent member of whatever thread group it joins upon its creation--you cannot move a thread to a new group after the thread has been created L 9.2
  • 309. The “ThreadGroup” class manages groups of threads for Java applications. A ThreadGroup can contain any number of threads. The threads in a group are generally related in some way, such as who created them, what function they perform, or when they should be started and stopped. ThreadGroups can contain not only threads but also other ThreadGroups. The top-most thread group in a Java application is the thread group named main. You can create threads and thread groups in the main group. You can also create threads and thread groups in subgroups of main. L 9.3
  • 310.  A thread is a permanent member of whatever thread group it joins when its created--you cannot move a thread to a new group after the thread has been created. Thus, if you wish to put your new thread in a thread group other than the default, you must specify the thread group explicitly when you create the thread.  The Thread class has three constructors that let you set a new thread's group: public Thread(ThreadGroup group, Runnable target) public Thread(ThreadGroup group, String name) public Thread(ThreadGroup group, Runnable target, String name)  Each of these constructors creates a new thread, initializes it based on the Runnable and String parameters, and makes the new thread a member of the specified group. For example: ThreadGroup myThreadGroup = new ThreadGroup("My Group of Threads"); Thread myThread = new Thread(myThreadGroup, "a thread for my group"); L 9.4
  • 311. UNIT-6
  • 312. B.TECH II YR II SEMESTER(TERM 08-09) UNIT 6 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th editon, Herbert schildt, TMH.Understanding 2. OOP with Java, updated edition, T. Budd, pearson eduction. No. of slides:53
  • 313. S.NO. TOPIC LECTURE NO. PPTSLIDES 1 Events, Event sources, Event classes, L1 L1.1TO L1.10 2 Event Listeners, Delegation event model L2 L2.1 TO L2.3 3 Handling mouse and keyboard events, L3 L3.1 TO L3.5 Adapter classes, inner classes. 4 The AWT class hierarchy, L 4 L4.1 TO L4.4 5 user interface components- labels, button, L 5 L5.1 TO L5.8 canvas, scrollbars, text 6 components, check box, check box groups, L 6L6.1 TO L6.7 choices 7 lists panels – scrollpane, dialogs L 7 L7.1 TO L7.4 8 menubar, graphics L 8 L8.1 TO L8.3 9 layout manager – layout manager types – L 9 L9.1 TO L9.7 boarder, grid, flow, card and grib bag
  • 314. For the user to interact with a GUI, the underlying operating system must support event handling. 1) operating systems constantly monitor events such as keystrokes, mouse clicks, voice command, etc. 2) operating systems sort out these events and report them to the appropriate application programs 3) each application program then decides what to do in response to these events L 1.1
  • 315. 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. L 1.2
  • 316. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, a software or hardware failure occurs, or an operation is completed. Events can be defined as needed and appropriate by application. L 1.3
  • 317.  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.  General form is: public void addTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener.  For example, 1. The method that registers a keyboard event listener is called addKeyListener(). 2. The method that registers a mouse motion listener is called addMouseMotionListener( ). L 1.4
  • 318. 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. The general form is: 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. L 1.5
  • 319. A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form is: public void removeTypeListener(TypeListener el) Here, Type is the name of the event and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ). The methods that add or remove listeners are provided by the source that generates events. For example, the Component class provides methods to add and remove keyboard and mouse event listeners. L 1.6
  • 320. The Event classes that represent events are at the core of Java's event handling mechanism. Super class of the Java event class hierarchy is EventObject, which is in java.util. for all events. Constructor is : EventObject(Object src) Here, src is the object that generates this event. EventObject contains two methods: getSource( ) and toString( ). 1. The getSource( ) method returns the source of the event. General form is : Object getSource( ) 2. The toString( ) returns the string equivalent of the event. L 1.7
  • 321. EventObject is a superclass of all events. AWTEvent is a superclass of all AWT events that are handled by the delegation event model. The package java.awt.event defines several types of events that are generated by various user interface elements. L 1.8
  • 322. ActionEvent: Generated when a button is pressed, a list item is double clicked, or a menu item is selected. AdjustmentEvent: Generated when a scroll bar is manipulated. ComponentEvent: Generated when a component is hidden, moved, resized, or becomes visible. ContainerEvent: Generated when a component is added to or removed from a container. FocusEvent: Generated when a component gains or loses keyboard focus. L 1.9
  • 323. InputEvent: Abstract super class for all component input event classes. 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. KeyEvent: Generated when input is received from the keyboard. MouseEvent: Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component. TextEvent: Generated when the value of a text area or text field is changed. WindowEvent: Generated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit. L 1.10
  • 324.  A listener is an object that is notified when an event occurs.  Event has two major requirements. 1. It must have been registered with one or more sources to receive notifications about specific types of events. 2. It must implement methods to receive and process these notifications.  The methods that receive and process events are defined in a set of interfaces found in java.awt.event.  For example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved.  Any object may receive and process one or both of these events if it provides an implementation of this interface. L 2.1
  • 325.  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.  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. L 2.2
  • 326.  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.  This required components to receive events that they did not process, and it wasted valuable time.The delegation event model eliminates this overhead. Note  Java also allows you to process events without using the delegation event model.  This can be done by extending an AWT component. L 2.3
  • 327.  mouse events can be handled by implementing the MouseListener and the MouseMotionListener interfaces.  MouseListener Interface defines five methods. The general forms of these methods are: 1. void mouseClicked(MouseEvent me) 2. void mouseEntered(MouseEvent me) 3. void mouseExited(MouseEvent me) 4. void mousePressed(MouseEvent me) 5. void mouseReleased(MouseEvent me)  MouseMotionListener Interface. This interface defines two methods. Their general forms are : 1. void mouseDragged(MouseEvent me) 2. void mouseMoved(MouseEvent me) L 3.1
  • 328.  Keyboard events, can be handled by implementing the KeyListener interface.  KeyListner interface defines three methods. The general forms of these methods are : 1. void keyPressed(KeyEvent ke) 2. void keyReleased(KeyEvent ke) 3. void keyTyped(KeyEvent ke)  To implement keyboard events implementation to the above methods is needed. L 3.2
  • 329. Java provides a special feature, called an adapter class, that can simplify the creation of event handlers. 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. 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. L 3.3
  • 330. adapter classes in java.awt.event are. Adapter Class Listener Interface ComponentAdapter ComponentListener ContainerAdapter ContainerListener FocusAdapter FocusListener KeyAdapter KeyListener MouseAdapter MouseListener MouseMotionAdapter MouseMotionListener WindowAdapter WindowListener L 3.4
  • 331. Inner classes, which allow one class to be defined within another. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non- static members of the outer class do. An inner class is fully within the scope of its enclosing class. an inner class has access to all of the members of its enclosing class, but the reverse is not true. Members of the inner class are known only within the scope of the inner class and may not be used by the outer class L 3.5
  • 332.  The AWT classes are contained in the java.awt package. It is one of Java's largest packages. some of the AWT classes.  AWT Classes 1. AWTEvent:Encapsulates AWT events. 2. AWTEventMulticaster: Dispatches events to multiple listeners. 3. BorderLayout: The border layout manager. Border layouts use five components: North, South, East, West, and Center. 4. Button: Creates a push button control. 5. Canvas: A blank, semantics-free window. 6. CardLayout: The card layout manager. Card layouts emulate index cards. Only the one on top is showing. L 4.1
  • 333. 7. Checkbox: Creates a check box control. 8. CheckboxGroup: Creates a group of check box controls. 9. CheckboxMenuItem: Creates an on/off menu item. 10. Choice: Creates a pop-up list. 11. Color: Manages colors in a portable, platform-independent fashion. 12. Component: An abstract super class for various AWT components. 13. Container: A subclass of Component that can hold other components. 14. Cursor: Encapsulates a bitmapped cursor. 15. Dialog: Creates a dialog window. 16. Dimension: Specifies the dimensions of an object. The width is stored in width, and the height is stored in height. 17. Event: Encapsulates events. 18. EventQueue: Queues events. 19. FileDialog: Creates a window from which a file can be selected. 20. FlowLayout: The flow layout manager. Flow layout positions components left to right, top to bottom. L 4.2
  • 334. 21. Font: Encapsulates a type font. 22. FontMetrics: Encapsulates various information related to a font. This information helps you display text in a window. 23. Frame: Creates a standard window that has a title bar, resize corners, and a menu bar. 24. Graphics: Encapsulates the graphics context. This context is used by various output methods to display output in a window. 25. GraphicsDevice: Describes a graphics device such as a screen or printer. 26. GraphicsEnvironment: Describes the collection of available Font and GraphicsDevice objects. 27. GridBagConstraints: Defines various constraints relating to the GridBagLayout class. 28. GridBagLayout: The grid bag layout manager. Grid bag layout displays components subject to the constraints specified by GridBagConstraints. 29. GridLayout: The grid layout manager. Grid layout displays components i n a two-dimensional grid. L 4.3
  • 335. 30. Scrollbar: Creates a scroll bar control. 31. ScrollPane: A container that provides horizontal and/or vertical scrollbars for another component. 32. SystemColor: Contains the colors of GUI widgets such as windows, scrollbars, text, and others. 33. TextArea: Creates a multiline edit control. 34. TextComponent: A super class for TextArea and TextField. 35. TextField: Creates a single-line edit control. 36. Toolkit: Abstract class implemented by the AWT. 37. Window: Creates a window with no frame, no menu bar, and no title. L 4.4
  • 336. Labels: Creates a label that displays a string.  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: 1. Label( ) 2. Label(String str) 3. Label(String str, int how)  The first version creates a blank label.  The second version creates a label that contains the string specified by str. 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. L 5.1
  • 337.  Set or change the text in a label is done by using the setText( ) method.  Obtain the current label by calling getText( ).  These methods are shown here: void setText(String str) String getText( )  For setText( ), str specifies the new label. For getText( ), the current label is returned.  To set the alignment of the string within the label by calling setAlignment( ).  To obtain the current alignment, call getAlignment( ).  The methods are as follows: void setAlignment(int how) int getAlignment( ) Label creation: Label one = new Label("One"); L 5.2
  • 338.  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. Button defines these two constructors: Button( ) Button(String str)  The first version creates an empty button. The second creates a button that contains str as a label.  After a button has been created, you can set its label by calling setLabel( ).  You can retrieve its label by calling getLabel( ).  These methods are as follows: void setLabel(String str) String getLabel( ) Here, str becomes the new label for the button. Button creation: Button yes = new Button("Yes"); L 5.3
  • 339. It is not part of the hierarchy for applet or frame windows Canvas encapsulates a blank window upon which you can draw. Canvas creation: Canvas c = new Canvas(); Image test = c.createImage(200, 100); This creates an instance of Canvas and then calls the createImage( ) method to actually make an Image object. At this point, the image is blank. L 5.4
  • 340.  Scrollbar generates adjustment events when the scroll bar is manipulated.  Scrollbar creates a scroll bar control.  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.  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. L 5.5
  • 341.  Scrollbar defines the following constructors: Scrollbar( ) Scrollbar(int style) Scrollbar(int style, int initialValue, int thumbSize, int min, int max)  The first form creates a vertical scroll bar.  The second and third forms allow you to specify the orientation of the scroll bar. 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.  vertSB = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, height);  horzSB = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, width); L 5.6
  • 342.  Text is created by Using a TextField class  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. TextField defines the following constructors: TextField( ) TextField(int numChars) TextField(String str) TextField(String str, int numChars) L 5.7
  • 343.  The first version creates a default text field.  The second form creates a text field that is numChars characters wide.  The third form initializes the text field with the string contained in str.  The fourth form initializes a text field and sets its width.  TextField (and its superclass TextComponent) provides several methods that allow you to utilize a text field.  To obtain the string currently contained in the text field, call getText().  To set the text, call setText( ). These methods are as follows: String getText( ) void setText(String str) Here, str is the new string. L 5.8
  • 344. 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 public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting. A Component object is responsible for remembering the current foreground and background colors and the currently selected text font. L 6.1
  • 345. To add components Component add(Component compObj) Here, compObj is an instance of the control that you want to add. A reference to compObj is returned. Once a control has been added, it will automatically be visible whenever its parent window is displayed. To remove a control from a window when the control is no longer needed call remove( ). This method is also defined by Container. It has this 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( ). L 6.2
  • 346. 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 can change the state of a check box by clicking on it. Check boxes can be used individually or as part of a group. Checkboxes are objects of the Checkbox class. L 6.3
  • 347.  Checkbox supports these constructors: 1. Checkbox( ) 2. Checkbox(String str) 3. Checkbox(String str, boolean on) 4. Checkbox(String str, boolean on, CheckboxGroup cbGroup) 5. Checkbox(String str, CheckboxGroup cbGroup, boolean on)  The first form creates a check box whose label is initially blank. The state of the check box is unchecked.  The second form creates a check box whose label is specified by str. The state of the check box is unchecked.  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.  The fourth and fifth forms 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. (Check box groups are described in the next section.) The value of on determines the initial state of the check box. L 6.4
  • 348.  To retrieve the current state of a check box, call getState( ).  To set its state, call setState( ).  To obtain the current label associated with a check box by calling getLabel( ).  To set the label, call setLabel( ).  These methods are as follows: boolean getState( ) void setState(boolean on) String getLabel( ) void setLabel(String str) Here, if on is true, the box is checked. If it is false, the box is cleared. Checkbox creation: CheckBox Win98 = new Checkbox("Windows 98", null, true); L 6.5
  • 349.  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 oftenccalled radio buttons.  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.  To determine which check box in a group is currently selected by calling getSelectedCheckbox( ).  To 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 checkbox will be turned off.  CheckboxGroup cbg = new CheckboxGroup();  Win98 = new Checkbox("Windows 98", cbg, true);  winNT = new Checkbox("Windows NT", cbg, false); L 6.6
  • 350.  The Choice class is used to create a pop-up list of items from which the user may choose.  A Choice control is a form of menu.  Choice only defines the default constructor, which creates an empty list.  To add a selection to the list, call addItem( ) or add( ). void addItem(String name) void add(String name)  Here, name is the name of the item being added.  Items are added to the list in the order to determine which item is currently selected, you may call either getSelectedItem( ) or getSelectedIndex( ). String getSelectedItem( ) int getSelectedIndex( ) L 6.7
  • 351.  The List class provides a compact, multiple-choice, scrolling selection list.  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( ) List(int numRows) List(int numRows, boolean multipleSelect)  To add a selection to the list, call add( ). It has the following two forms: void add(String name) void add(String name, int index) Ex: List os = new List(4, true); L 7.1
  • 352.  The Panel class is a concrete subclass of Container.  It doesn't add any new methods; it simply 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.  Panel is a window that does not contain a title bar, menu bar, or border.  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.  Ex: Panel osCards = new Panel(); CardLayout cardLO = new CardLayout(); osCards.setLayout(cardLO); L 7.2
  • 353.  A scroll pane 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.  constants are defined by the ScrollPaneConstants interface. 1. HORIZONTAL_SCROLLBAR_ALWAYS 2. HORIZONTAL_SCROLLBAR_AS_NEEDED 3. VERTICAL_SCROLLBAR_ALWAYS 4. VERTICAL_SCROLLBAR_AS_NEEDED L 7.3
  • 354. Dialog class creates a dialog window. constructors are : Dialog(Frame parentWindow, boolean mode) Dialog(Frame parentWindow, String title, boolean mode) The dialog box allows you to choose a method that should be invoked when the button is clicked. Ex: Fontf = new Font("Dialog", Font.PLAIN, 12); L 7.4
  • 355. MenuBar class creates a menu bar. 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. 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 selections displayed on the bar. Following are the constructors for Menu: Menu( ) Menu(String optionName) Menu(String optionName, boolean removable) L 8.1
  • 356. Once you have created a menu item, you must add the item to a Menu object by using MenuItem add(MenuItem item) Here, item is the item being added. Items are added to a menu in the order in which the calls to add( ) take place. Once you have added all items to a Menu object, you can add that object to the menu bar by using this version of add( ) defined by MenuBar: Menu add(Menu menu) L 8.2
  • 357.  The AWT supports a rich assortment of graphics methods.  All graphics are drawn relative to a window.  A graphics context is encapsulated by the Graphics class  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.  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  Ex: Public void paint(Graphics g) { G.drawString(“welcome”,20,20); } L 8.3
  • 358.  A layout manager automatically arranges your controls within a window by using some type of algorithm.  it is very tedious to manually lay out a large number of components and sometimes the width and height information is not yet available when you need to arrange some control, because the native toolkit components haven't been realized.  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. 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. L 9.1
  • 359. Layout manager class defines the following types of layout managers  Boarder Layout  Grid Layout  Flow Layout  Card Layout  GridBag Layout L 9.2
  • 360.  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.  The constructors defined by BorderLayout: BorderLayout( ) BorderLayout(int horz, int vert)  BorderLayout defines the following constants that specify the regions: BorderLayout.CENTER B orderLayout.SOUTH BorderLayout.EAST B orderLayout.WEST BorderLayout.NORTH  Components can be added by void add(Component compObj, Object region); L 9.3
  • 361.  GridLayout lays out components in a two-dimensional grid. When you instantiate a  GridLayout, you define the number of rows and columns. The constructors are GridLayout( ) GridLayout(int numRows, int numColumns ) GridLayout(int numRows, int numColumns, int horz, int vert)  The first form creates a single-column grid layout.  The second form creates a grid layout  with the specified number of rows and columns.  The third form 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 unlimited-lengthrows. L 9.4
  • 362.  FlowLayout is the default layout manager.  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. A small space is left between each component, above and below, as well as left and right.  The constructors are FlowLayout( ) FlowLayout(int how) FlowLayout(int how, int horz, int vert)  The first form creates the default layout, which centers components and leaves five pixels of space between each component.  The second form allows to specify how each line is aligned. Valid values for are: FlowLayout.LEFT FlowLayout.CENTER FlowLayout.RIGHT These values specify left, center, and right alignment, respectively.  The third form allows to specify the horizontal and vertical space left between components in horz and vert, respectively L 9.5
  • 363.  The CardLayout class is unique among the other layout managers in that it stores several different layouts.  Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time.  CardLayout provides these two constructors: CardLayout( ) CardLayout(int horz, int vert)  The cards are held in an object of type Panel. This panel must have CardLayout selected as its layout manager.  Cards are added to panel using void add(Component panelObj, Object name);  methods defined by CardLayout: void first(Container deck) void last(Container deck) void next(Container deck) void previous(Container deck) void show(Container deck, String cardName) L 9.6
  • 364. The Grid bag layout displays components subject to the constraints specified by GridBagConstraints. GridLayout lays out components in a two-dimensional grid. The constructors are GridLayout( ) GridLayout(int numRows, int numColumns ) GridLayout(int numRows, int numColumns, int horz, int vert) L 9.7
  • 365. UNIT-7
  • 366. B.TECH II YR II SEMESTER(TERM 08-09) UNIT 7 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th editon, Herbert schildt, TMH.Understanding 2. OOP with Java, updated edition, T. Budd, pearson eduction. No. of slides:45
  • 367. S.NO. TOPIC LECTURE NO. PPTSLIDES 1 Concepts of Applets, L1 L1.1TO L1.5 differences between applets and applications 2 Life cycle of an applet, types of applets L2 L2.1 TO L2.4 3 Creating applets, passing parameters to applets. L3 L3.1 TO L3.4 4 Introduction to swings, limitations of AWT L 4 L4.1 TO L4.5 5 MVC architecture, components, containers L 5 L5.1 TO L5.10 6 Exploring swing- JApplet, JFrame and JComponent, L 6 L6.1 TO L6.3 7 Icons and Labels, text fields, buttons L 7 L7.1 TO L7.4 8 Check boxes, Combo boxes,RadioButton,JButton L 8 L8.1 TO L8.4 9 Tabbed Panes, Scroll Panes, Trees, and Tables L 9 L9.1 TO L9.4
  • 368. 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. L 1.1
  • 369. applets – Java program that runs within a Java-enabled browser, invoked through a “applet” reference on a web page, dynamically downloaded to the client computer import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); } } L 1.2
  • 370.  There are two ways to run an applet: 1. Executing the applet within a Java-compatible Web browser, such as NetscapeNavigator. 2. Using an applet viewer, such as the standard JDK tool, appletviewer.  An appletviewer executes your applet in a window. This is generally the fastest and easiest way to test an applet.  To execute an applet in a Web browser, you need to write a short HTML text file that contains the appropriate APPLET tag. <applet code="SimpleApplet" width=200 height=60> </applet> L 1.3
  • 371. Java can be used to create two types of programs: applications and applets. An application is a program that runs on your computer, under the operating system of that Computer(i.e an application created by Java is more or less like one created using C or C++). When used to create applications, Java is not much different from any other computer language. An applet is an application designed to be transmitted over the Internet and executed by a Java-compatible Web browser. An applet is actually a tiny Java program, dynamically downloaded across the network, just like an image, sound file, or video clip. L 1.4
  • 372. The important difference is that an applet is an intelligent program, not just an animation or media file(i.e an applet is a program that can react to user input and dynamically change—not just run the same animation or sound over and over. Applications require main method to execute. Applets do not require main method. Java's console input is quite limited Applets are graphical and window-based. L 1.5
  • 373.  Applets life cycle includes the following methods 1. init( ) 2. start( ) 3. paint( ) 4. stop( ) 5. destroy( )  When an applet begins, the AWT calls the following methods, in this sequence: init( ) start( ) paint( )  When an applet is terminated, the following sequence of method calls takes place: stop( ) destroy( ) L 2.1
  • 374.  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.  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( ).  paint( ): The paint( ) method is called each time applet's output must be redrawn. paint( ) is also called when the applet begins execution. 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. L 2.2
  • 375. stop( ): The stop( ) method is 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. Applet uses stop( ) to suspend threads that don't need to run when the applet is not visible. To restart start( ) is called if the user returns to the page. destroy( ): The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory. The stop( ) method is always called before destroy( ). L 2.3
  • 376. Applets are two types 1.Simple applets 2.JApplets Simple applets can be created by extending Applet class JApplets can be created by extending JApplet class of javax.swing.JApplet package L 2.4
  • 377.  Applets are created by extending the Applet class. import java.awt.*; import java.applet.*; /*<applet code="AppletSkel" width=300 height=100></applet> */ public class AppletSkel extends Applet { public void init() { // initialization } public void start() { // start or resume execution } public void stop() { // suspends execution } public void destroy() { // perform shutdown activities } public void paint(Graphics g) { // redisplay contents of window } } L 3.1
  • 378.  APPLET tag in HTML allows you to pass parameters to applet.  To retrieve a parameter, use the getParameter( ) method. It returns the value of the specified parameter in the form of a String object. // Use Parameters import java.awt.*; import java.applet.*; /* <applet code="ParamDemo" width=300 height=80> <param name=fontName value=Courier> <param name=fontSize value=14> <param name=leading value=2> <param name=accountEnabled value=true> </applet> */ L 3.2
  • 379. public class ParamDemo extends Applet{ String fontName; int fontSize; float leading; boolean active; // Initialize the string to be displayed. public void start() { String param; fontName = getParameter("fontName"); if(fontName == null) fontName = "Not Found"; param = getParameter("fontSize"); try { if(param != null) // if not found fontSize = Integer.parseInt(param); else fontSize = 0; } catch(NumberFormatException e) { fontSize = -1; } param = getParameter("leading"); L 3.3
  • 380. try { if(param != null) // if not found leading = Float.valueOf(param).floatValue(); else leading = 0; } catch(NumberFormatException e) { leading = -1; } param = getParameter("accountEnabled"); if(param != null) active = Boolean.valueOf(param).booleanValue(); } // Display parameters. public void paint(Graphics g) { g.drawString("Font name: " + fontName, 0, 10); g.drawString("Font size: " + fontSize, 0, 26); g.drawString("Leading: " + leading, 0, 42); g.drawString("Account Active: " + active, 0, 58); } } L 3.4
  • 381.  Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT.  In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.  Even familiar components such as buttons have more capabilities in Swing.  For example, a button may have both an image and a text string associated with it. Also, the image can be changed as the state of the button changes.  Unlike AWT components, Swing components are not implemented by platform-specific code.  Instead, they are written entirely in Java and, therefore, are platform- independent.  The term lightweight is used to describe such elements. L 4.1
  • 382.  The Swing component are defined in javax.swing 1. AbstractButton: Abstract superclass for Swing buttons. 2. ButtonGroup: Encapsulates a mutually exclusive set of buttons. 3. ImageIcon: Encapsulates an icon. 4. JApplet: The Swing version of Applet. 5. JButton: The Swing push button class. 6. JCheckBox: The Swing check box class. 7. JComboBox : Encapsulates a combo box (an combination of a drop-down list and text field). 8. JLabel: The Swing version of a label. 9. JRadioButton: The Swing version of a radio button. 10. JScrollPane: Encapsulates a scrollable window. 11. JTabbedPane: Encapsulates a tabbed window. 12. JTable: Encapsulates a table-based control. 13. JTextField: The Swing version of a text field. 14. JTree: Encapsulates a tree-based control. L 4.2
  • 383. AWT supports limited number of GUI components. AWT components are heavy weight components. AWT components are developed by using platform specific code. AWT components behaves differently in different operating systems. AWT component is converted by the native code of the operating system. L 4.3
  • 384. Lowest Common Denominator If not available natively on one Java platform, not available on any Java platform Simple Component Set Components Peer-Based Platform controls component appearance Inconsistencies in implementations Interfacing to native platform error-prone L 4.4
  • 385. L 4.5
  • 386. L 5.1
  • 387. Model consists of data and the functions that operate on data Java bean that we use to store data is a model component EJB can also be used as a model component L 5.2
  • 388. View is the front end that user interact. View can be a HTML JSP Struts ActionForm L 5.3
  • 389.  Controller component responsibilities 1. Receive request from client 2. Map request to specific business operation 3. Determine the view to display based on the result of the business operation L 5.4
  • 390. Container JComponent AbstractButton JButton JMenuItem  JCheckBoxMenuItem  JMenu  JRadioButtonMenuItem JToggleButton  JCheckBox  JRadioButton L 5.5
  • 393. Top-Level Containers The components at the top of any Swing containment hierarchy L 5.8
  • 394. Intermediate containers that can be used under many different circumstances. L 5.9
  • 395. Intermediate containers that play specific roles in the UI. L 5.10
  • 396. If using Swing components in an applet, subclass JApplet, not Applet JApplet is a subclass of Applet Sets up special internal component event handling, among other things Can have a JMenuBar Default LayoutManager is BorderLayout L 6.1
  • 397. public class FrameTest { public static void main (String args[]) { JFrame f = new JFrame ("JFrame Example"); Container c = f.getContentPane(); c.setLayout (new FlowLayout()); for (int i = 0; i < 5; i++) { c.add (new JButton ("No")); c.add (new Button ("Batter")); } c.add (new JLabel ("Swing")); f.setSize (300, 200); f.show(); } } L 6.2
  • 398.  JComponent supports the following components.  JComponent  JComboBox  JLabel  JList  JMenuBar  JPanel  JPopupMenu  JScrollBar  JScrollPane  JTextComponent  JTextArea  JTextField  JPasswordField  JTextPane  JHTMLPane L 6.3
  • 399.  In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image.  constructors are: ImageIcon(String filename) ImageIcon(URL url)  The ImageIcon class implements the Icon interface that declares the methods 1. int getIconHeight( ) 2. int getIconWidth( ) 3. void paintIcon(Component comp,Graphics g,int x, int y) L 7.1
  • 400.  Swing labels are instances of the JLabel class, which extends JComponent.  It can display text and/or an icon.  Constructors are: JLabel(Icon i) Label(String s) JLabel(String s, Icon i, int align)  Here, s and i are the text and icon used for the label. The align argument is either LEFT, RIGHT, or CENTER. These constants are defined in the SwingConstants interface,  Methods are: 1. Icon getIcon( ) 2. String getText( ) 3. void setIcon(Icon i) 4. void setText(String s)  Here, i and s are the icon and text, respectively. L 7.2
  • 401. The Swing text field is encapsulated by the JTextComponent class, which extendsJComponent. 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. Constructors are: JTextField( ) JTextField(int cols) JTextField(String s, int cols) JTextField(String s) Here, s is the string to be presented, and cols is the number of columns in the text field. L 7.3
  • 402.  Swing buttons provide features that are not found in the Button class defined by the AWT.  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.  Methods are: 1. void setDisabledIcon(Icon di) 2. void setPressedIcon(Icon pi) 3. void setSelectedIcon(Icon si) 4. void setRolloverIcon(Icon ri)  Here, di, pi, si, and ri are the icons to be used for these different conditions.  The text associated with a button can be read and written via the following methods: 1. String getText( ) 2. void setText(String s)  Here, s is the text to be associated with the button. L 7.4
  • 403. 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. Some of its constructors are : JButton(Icon i) JButton(String s) JButton(String s, Icon i) Here, s and i are the string and icon used for the button. L 8.1
  • 404.  The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of AbstractButton.  Some of its constructors are shown here: 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)  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. L 8.2
  • 405.  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.  Two of JComboBox's constructors are : JComboBox( ) 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: void addItem(Object obj)  Here, obj is the object to be added to the combo box. L 8.3
  • 406.  Radio buttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton.  Some of its constructors are : JRadioButton(Icon i) JRadioButton(Icon i, boolean state) JRadioButton(String s) JRadioButton(String s, boolean state) JRadioButton(String s, Icon i) 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.  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. L 8.4
  • 407.  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. We will use its default constructor. 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. 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. L 9.1
  • 408.  A scroll pane 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 JComponent. Some of its constructors are : 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 constants that define when vertical and horizontal scroll bars for this scroll pane areshown.  These constants are defined by the ScrollPaneConstants interface. 1. HORIZONTAL_SCROLLBAR_ALWAYS 2. HORIZONTAL_SCROLLBAR_AS_NEEDED 3. VERTICAL_SCROLLBAR_ALWAYS 4. VERTICAL_SCROLLBAR_AS_NEEDED  Here are the steps to 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 thecomponent and the policies for vertical and horizontal scroll bars.) 3. Add the scroll pane to the content pane of the applet. L 9.2
  • 409. Data Model - TreeModel default: DefaultTreeModel getChild, getChildCount, getIndexOfChild, getRoot, isLeaf Selection Model - TreeSelectionModel View - TreeCellRenderer getTreeCellRendererComponent Node - DefaultMutableTreeNode L 9.3
  • 410.  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 : 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 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. L 9.4
  • 411. UNIT-8
  • 412. B.TECH II YR II SEMESTER(TERM 08-09) UNIT 8 PPT SLIDES TEXT BOOKS: 1. Java: the complete reference, 7th editon, Herbert schildt, TMH.Understanding 2. OOP with Java, updated edition, T. Budd, pearson eduction. No. of slides:45
  • 413. S.NO. TOPIC LECTURE NO. PPTSLIDES 1 Basics of network programming L1 L1.1TO L1.7 2 addresses L2 L2.1 TO L2.2 3 Ports L3 L3.1 TO L3.2 4 Sockets L 4 L4.1 TO L4.3 5 simple client server program L 5 L5.1 TO L5.5 6 Multiple clients L 6 L6.1 TO L6.5 7 java .net package L 7 L7.1 TO L7.2 8 java.util package L 8 L8.1 TO L8.3 9 Revision L 9
  • 414. L 1.1 TCP/IP java.net RMI JDBC CORBA Network OS
  • 415. node any device on the network host a computer on the network address computer-readable name for host host name human-readable name for host L 1.2
  • 416. datagram (or “packet”) little bundle of information sent from one node to another protocol roles, vocabulary, rules for communication IP the Internet Protocol L 1.3
  • 417. L 1.4 Physical Network Transport Layer (TCP, UDP) Internet Layer (IP) Application Layer (HTTP, FTP, SMTP)
  • 418. IP raw packets the “Internet Layer” TCP data stream reliable, ordered the “Transport Layer” UDP user datagrams (packets) unreliable, unordered the “Transport Layer” L 1.5
  • 419. internet any IP-based network Internet the big, famous, world-wide IP network intranet a corporate LAN-based IP network extranet accessing corporate data across the Internet L 1.6
  • 420. Built into language One of the 11 buzzwords Network ClassLoader java.net API Based on TCP/IP, the Internet Protocol L 1.7
  • 421. Every computer on the Internet has an address. An Internet address is a number that uniquely identifies each computer on the Net. There are 32 bits in an IP address, and often refer to them as a sequence of four numbers between 0 and 255 separated by dots The first few bits define which class of network, lettered A, B, C, D, or E, the address represents. Most Internet users are on a class C network, since there are over two million networks in class C. L 2.1
  • 422. The first byte of a class C network is between 192 and 224, with the last byte actually identifying an individual computer among the 256 allowed on a single class C network. IP Address: identifies a host DNS: converts host names / domain names into IP addresses. L 2.2
  • 423.  Port: a meeting place on a host 1. one service per port 2. 1-1023 = well-known services 3. 1024+ = experimental services, temporary L 3.1
  • 424. 20,21: FTP 23: telnet 25: SMTP 43: whois 80: HTTP 119: NNTP 1099: RMI L 3.2
  • 425. A network socket is a lot like an electrical socket. Socket: a two-way connection Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends them to an address across a network, which does not guarantee to deliver said packets to the destination. Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably transmit your data. A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast, connectionless, unreliable transport of packets. L 4.1
  • 426. Socket(String host, int port) InputStream getInputStream() OutputStream getOutputStream() void close() Socket s = new Socket(“www.starwave.com”, 90); L 4.2
  • 427. L 4.3 Client port 13 port 80 Time Service Web Service Socket Server Socket
  • 428. Client - initiates connection retrieves data, displays data, responds to user input, requests more data Examples: Web Browser Chat Program PC accessing files L 5.1
  • 429. /** Client program using TCP */ public class Tclient { final static String serverIPname = “starwave.com";// server IP name final static int serverPort = 3456; // server port number public static void main(String args[]) { java.net.Socket sock = null; // Socket object for communicating java.io.PrintWriter pw = null; // socket output to server java.io.BufferedReader br = null; // socket input from server try { sock = new java.net.Socket(serverIPname,serverPort);// create socket and connect pw = new java.io.PrintWriter(sock.getOutputStream(), true); // create reader and writer br = new java.io.BufferedReader(new java.io.InputStreamReader(sock.getInputStream())); System.out.println("Connected to Server"); L 5.2
  • 430. pw.println("Message from the client"); // send msg to the server System.out.println("Sent message to server"); String answer = br.readLine(); // get data from the server System.out.println("Response from the server >" + answer); pw.close(); // close everything br.close(); sock.close(); } catch (Throwable e) { System.out.println("Error " + e.getMessage()); e.printStackTrace(); } } } L 5.3
  • 431. /** Server program using TCP */ public class Tserver { final static int serverPort = 3456; // server port number public static void main(String args[]) { java.net.ServerSocket sock = null; // original server socket java.net.Socket clientSocket = null; // //socket created by accept java.io.PrintWriter pw = null; // //socket output stream java.io.BufferedReader br = null; // socket input stream try { sock = new java.net.ServerSocket(serverPort); // create socket and bind to port System.out.println("waiting for client to connect"); clientSocket = sock.accept(); L 5.4
  • 432. // wait for client to connect System.out.println("client has connected"); pw = new java.io.PrintWriter(clientSocket.getOutputStream(),true); br = new java.io.BufferedReader( new java.io.InputStreamReader(clientSocket.getInputStream())); String msg = br.readLine(); // read msg from client System.out.println("Message from the client >" + msg); pw.println("Got it!"); // send msg to client pw.close(); // close everything br.close(); clientSocket.close(); sock.close(); } catch (Throwable e) { System.out.println("Error " + e.getMessage()); e.printStackTrace(); } } } L 5.5
  • 433. Multiple clients can connect to the same port on the server at the same time. Incoming data is distinguished by the port to which it is addressed and the client host and port from which it came. The server can tell for which service (like http or ftp) the data is intended by inspecting the port. It can tell which open socket on that service the data is intended for by looking at the client address and port stored with the data. L 6.1
  • 434. Incoming connections are stored in a queue until the server can accept them. On most systems the default queue length is between 5 and 50. Once the queue fills up further incoming connections are refused until space in the queue opens up. L 6.2
  • 435. The java.net.ServerSocket class represents a server socket. A ServerSocket object is constructed on a particular local port. Then it calls accept() to listen for incoming connections. accept() blocks until a connection is detected. Then accept() returns a java.net.Socket object that performs the actual communication with the client. L 6.3
  • 436. There are three constructors that specify the port to bind to, the queue length for incoming connections, and the IP address to bind to: public ServerSocket(int port) throws IOException public ServerSocket(int port, int backlog) throws IOException public ServerSocket(int port, int backlog, InetAddress networkInterface) throws IOException L 6.4
  • 437. specify the port number to listen : try { ServerSocket ss = new ServerSocket(80); } catch (IOException e) { System.err.println(e); } L 6.5
  • 438. The classes in java.net package are : JarURLConnection (Java 2) URLConnection DatagramSocketImpl ServerSocket URLDecoder (Java 2) HttpURLConnection Socket URLEncoder InetAddress SocketImpl URLStreamHandler SocketPermission ContentHandler MulticastSocket URL DatagramPacket NetPermission URLClassLoader (Java 2) DatagramSocket PasswordAuthentication(Java 2) Authenticator (Java 2) L 7.1
  • 439. The java.net package's interfaces are 1. ContentHandlerFactory 2. SocketImplFactory 3. URLStreamHandlerFactory 4. FileNameMap 5. SocketOptions L 7.2
  • 440.  The java.util package defines the following classes: 1. AbstractCollection (Java2) 2. EventObject 3. PropertyResourceBundle 4. AbstractList (Java 2) 5. GregorianCalendar 6. Random 7. AbstractMap (Java 2) 8. HashMap(Java 2) 9. ResourceBundle 10.AbstractSequentialList(Java 2) 11. HashSet (Java2) 12.SimpleTimeZone 13. AbstractSet (Java 2) 14.Hashtable 15.Stack L 8.1
  • 441. 16.ArrayList (Java 2) 17.LinkedList(Java 2) 18.StringTokenizer 19.Arrays (Java 2) 20.ListResourceBundle 21.TimeZone 22.BitSet 23.Locale 24.TreeMap (Java 2) 25.Calendar 26.Observable 27.TreeSet (Java 2) 28.Collections (Java 2) 29.Properties 30.Vector 31. Date 32.PropertyPermission(Java 2) 33.WeakHashMap (Java 2) 34.Dictionary L 8.2
  • 442. java.util defines the following interfaces. 1. Collection (Java 2) 2. List (Java 2) 3. Observer 4. Comparator (Java 2) 5. ListIterator(Java 2) 6. Set (Java 2) 7. Enumeration 8. Map (Java 2) 9. SortedMap (Java 2) 10.EventListener 11. Map.Entry(Java 2) 12.SortedSet (Java 2) 13. Iterator (Java 2) L 8.3