EC604A
EC604A
Course Objective:
Able to develop solution using object oriented concept to real life problems.
Course Outcomes:
Graduates will be able to understand the key concepts of object oriented programming and
have an ability to design OO programs and appreciate the techniques of good design;
Graduates will be able to program presciently in an OO programming language;
Graduates will be able to have an ability to use application libraries, in this case the use of thejava
API;
Graduates will be able to familiar with good programming practices such as testing, debugging,
documentation and version control;
Concepts of object oriented programming language, Major and minor elements, Object, Class,
relationships among objects, aggregation, links, relationships among classes-association, aggregation,
Generalization and Specialization. Difference between OOP and other conventional programming –
advantages and disadvantages. Class, object, message passing, inheritance, encapsulation, polymorphism
Structure of a Java program. Steps for executing a java program. JDK, JRE, JVM, API, byte code.
Basic concepts of java programming – advantages of java, data types, access specifiers, operators, control
statements & loops, array, creation of class, object, constructor, finalize and garbage collection, use of
method overloading, this keyword, use of objects as parameter & methods returning objects, call by value
& call by reference, static variables & methods, garbage collection, nested & inner classes, basic string
handling concepts- String (discuss charAt() , compareTo(), equals(), equalsIgnoreCase(), indexOf(),
length() , substring(), toCharArray() , toLowerCase(), toString(), toUpperCase() , trim() , valueOf()
methods) & StringBuffer classes (discuss append(), capacity(), charAt(), delete(), deleteCharAt(),
ensureCapacity(), getChars(), indexOf(), insert(), length(), setCharAt(), setLength(), substring(), toString()
methods), concept of mutable and immutable string, command line arguments, basics of I/O operations –
keyboard input using BufferedReader & Scanner classes.
EC604A
Reusability properties[8L] – Super class & subclasses including multilevel hierarchy, process of
constructor calling in inheritance, use of super and final keywords with super() method, dynamic method
dispatch, use of abstract classes & methods, interfaces, default and static method in interface, Creation of
packages, importing packages, member access for packages. Meta class.
Exception handling & Multithreading [6L] – Exception handling basics, different types of exception
classes, use of try & catch with throw, throws & finally, creation of user defined exception classes. Basics
of multithreading, main thread, thread life cycle, creation of multiple threads, thread priorities, thread
synchronization, inter-thread communication, deadlocks for threads, suspending & resuming threads.
Applet Programming (using swing) [4L] – Basics of applet programming, applet life cycle, difference
between application & applet programming, parameter passing in applets, concept of delegation event
model and listener, I/O in applets, use of repaint().
Module 1:
The object-oriented paradigm has gained great popularity in the recent decade. The primary and
most direct reason is undoubtedly the strong support of encapsulation and the logical grouping of
program aspects. These properties are very important when programs become larger and larger.
The underlying, and somewhat deeper reason to the success of the object-oriented paradigm is
probably the conceptual anchoring of the paradigm. An object-oriented program is constructed
with the outset in concepts, which are important in the problem domain of interest. In that way,
all the necessary technicalities of programming come in second row.
Objects belong to classes. Typically, all the objects in a given class will have the same kinds of
behavior.
Classes are usually arranged in some kind of class hierarchy. This hierarchy can be thought of as
representing a "kind of" relation. For example, a computational model of the University might
need a class person to represent the various people who make up the University. A sub-class of
person might be a student; students are a kind of person. Another sub-class might be professor.
Both students and professors can exhibit the same kinds of behaviour, since they are both people.
They both eat drink and sleep, for example. But there are kinds of behaviour that are distinctive:
professors pontificate for example.
• In 1970, Alan Kay and his research group at Xerox PARK created a personal computer named
Dynabook and the first pure object-oriented programming language (OOPL) - Smalltalk, for
programming the Dynabook.
• In the 1980s, Grady Booch published a paper titled Object Oriented Design that mainly
presented a design for the programming language, Ada. In the ensuing editions, he extended
his ideas to a complete object–oriented design method.
Object-oriented programming (OOP) is a programming paradigm based upon objects (having both
data and methods) that aims to incorporate the advantages of modularity and reusability. Objects,
which are usually instances of classes, are used to interact with one another to design applications
and computer programs.
1.4 Class
A class represents a collection of objects having same characteristic properties that exhibit
common behavior. It gives the blueprint or description of the objects that can be created from it.
Creation of an object as a member of a class is called instantiation. Thus, object is an instance of
a class.
• A set of attributes for the objects that are to be instantiated from the class. Generally, different
objects of a class have some difference in the values of the attributes.
Attributes are often referred as class data.
EC604A
• A set of operations that portray the behavior of the objects of the class. Operations are also
referred as functions or methods.
• State that determines the characteristic properties of an object as well as the values of the
properties that the object holds.
Objects can be modeled according to the needs of the application. An object may have a physical
existence, like a customer, a car, etc.; or an intangible conceptual existence, like a project, a
process, etc.
1.5 Relationship among Classes
1.5.1 Aggregation
Figure 1.2
Aggregation is whole-part relationship between an aggregate, the whole, and its parts. This
relationship is often known as a has-a relationship, because the whole has its parts. For example,
when you think of workers making up a team, you can say that a team has workers. Aggregation
is shown using a hollow diamond attached to the class that represents the whole. The filled-in
diamonds represent composition. As a UML rule, aggregation is used only with binary
associations.
Figure 1.3
EC604A
1.5.2 Link
A link represents a connection through which an object collaborates with other objects.
Rumbaugh has defined it as “a physical or conceptual connection between objects”. Through a
link, one object may invoke the methods or navigate through another object. A link depicts the
relationship between two or more objects.
A link is a specific relationship between objects. For example, the project management system
involves various specific relationships, including specific manage, lead, execute, input, output,
and other relationships between specific projects, managers, teams, work products,
requirements, systems, and so forth. A link is an instance of an association, and the UML
supports different types of links that correspond to the different types of associations.
The general rules for representing links in a UML diagram are as follows:
• Label links with their association names, and underline the names to show that they are
specific instances of their respective associations.
• Ensure that link ends are consistent with their corresponding association ends.
• Translate association multiplicity into one or more specific links between specific objects.
1.5.2.1 Binary links
A binary link, which is a specific relationship between two objects, is shown as a solid-line path
connecting the two objects in a UML object diagram. For example, a specific worker is related to
specific units of work and work products in the project management system. A link may have its
association name shown near the path (fully underlined), but links do not have instance names.
Figure 1.3
Figure 1.4
1.5.2.3 Link Objects
A link object is a specific instance of an association class, and thus has all the characteristics,
including structural and behavioral features, defined by the association class. Structural features
include attribute values and perhaps other links. Behavioral features include operations and
methods, which are shared by all the links of an association class. Whenever an association has a
related association class, each of its links has a corresponding link object. This link object defines
attribute values for the link's structural features. In addition, the behavioral features defined by
the link's association class apply to the link objects. In a UML object diagram, a link object is
shown as an object rectangle attached by a dashed-line path to its link path in a binary link, or
attached to its link diamond in an n-ary link. As with all UML elements representing specific
objects or links, link object names should be fully underlined.
1.5.2.4 Link Ends
A link end, similar to an association end, is an endpoint of a link and connects the link to an object.
A link end may show its association end's rolename, navigation arrow, aggregation or composition
symbol, and values for its association end's qualifiers.
a. Rolenames
A link end's rolename must match its association end's rolename. For example, Figure 1.4 shows
that a Worker is responsible for a WorkProduct. The specific association used is ResponsibleFor;
b. Navigation
Likewise, a link end's navigation must match its association end's navigation. For example, the
arrows on the two ResponsibleFor links point to instances of WorkProduct(Fig-1.8). c.
Multiplicity
Multiplicity is shown only on association ends. This is because an association describes the
multiplicity between two or more classes of objects. A link however, is between specific objects.
Thus, in an object diagram, multiplicity manifests itself in terms of a specific number of links
pointing to a specific number of discrete objects. (0..*) WorkProduct objects.
d. Aggregation
EC604A
Aggregation is shown using a hollow diamond,
Figure1.5 shows three teams named Eagle, Falcon, and Hawk. Jonathan, Andy, Nora, and
Phillip are on the Eagle team, while Nora and Phillip are also on the Hawk team.
Figure 1.5
e. Composition
Composition may be shown using a filled diamond or graphical nesting Figure shows that the two
teams, Falcon and Hawk, are subteams of the Eagle team. In addition, the filled-in diamond next
to the Organization class indicates that all the individuals on these teams belong to the same
organization, and that the Eagle team itself belongs to the organization.
.
Figure 1.6
EC604A
f. Qualifiers
Values for link qualifiers have the same notation as for object attribute values. Figure1.7 shows
how qualifier values associate a project with its problem statement (named Problem Statement)
and system (named PM-System).
Figure 1.7
Lecture 3
An association defines a type of link and is a general relationship between classes. For example,
the project management system involves various general relationships, including manage, lead,
execute, input, and output between projects, managers, teams, work products, requirements, and
systems. Consider, for example, how a project manager leads a team.
1.6.1 Binary associations
A binary association relates two classes. For example, one binary relationship in the project
management system is between individual workers and their units of work, and another binary
relationship is between individual workers and their work products.
In a UML class diagram, a binary association is shown as a solid-line path connecting the two
related classes. A binary association may be labeled with a name. The name is usually read from
left to right and top to bottom; otherwise, it may have a small black solid triangle next to it where
the point of the triangle indicates the direction in which to read the name, but the arrow is purely
descriptive, and the name of the association should be understood by the classes it relates.
Figure shows various associations within the project management system using the most basic
notation for binary associations. The associations in the figure are as follows:
• A worker is responsible for work products and performs units of work
EC604A
• Units of work consume work products as input and produce work products as output.
Figure 1.8
An n-ary association relates three or more classes. For example, in the project management
system, the use of a worker involves the worker, her units of work, and her associated work
products.
In a UML class diagram, an n-ary association is shown as a large diamond with solid-line paths
from the diamond to each class. An n-ary association may be labeled with a name. The name is
read in the same manner as for binary associations, described in the previous section.
Figure shows an n-ary association associated with the project management system using the most
basic notation for n-ary associations. This association states that utilization involves workers,
units of work, and work products. As with a binary association, an n-ary association is also
commonly named using a verb phrase. However, this is not always the case for example; the n-
ary Utilization association shown in Figure is described using a noun rather than a verb, because
it is named from our perspective rather than the perspective of one of the classes. That is, from
our perspective, we want to understand a worker's utilization relative to the other classes. From
the worker's perspective, a worker is responsible for work products and performs units of work.
Figure 1.9
1.6.3 Association Classes
Association classes may be applied to both binary and n-ary associations. Similar to how a class
defines the characteristics of its objects, including their structural features and behavioral features,
an association class may be used to define the characteristics of its links, including their structural
features and behavioral features. These types of classes are used when you need to maintain
information about the relationship itself.
EC604A
In a UML class diagram, an association class is shown as a class attached by a dashed-line path
to its association path in a binary association or to its association diamond in an n-ary association.
The name of the association class must match the name of the association.
The association classes track the following information:
• The reason a worker is responsible for a work product
• The reason a worker performs a unit of work
• A description of how a unit of work consumes a work product • A description of how a unit
of work produces a work product.
Figure 1.10
Figure 1.11
b. Navigation
Navigation is optional and indicates whether a class may be referenced from the other classes in
an association. Navigation is shown as an arrow attached to an association end pointing toward
the class in question. If no arrows are present, associations are assumed to be navigable in all
directions, and all classes involved in the association may reference one another.
For example, given a worker, you can determine his work products and units of workGiven a unit
of work, you can determine its input and output work products; but given a work product, you are
unable to identify which worker is responsible for it or which units of work reference it as input
or Given a worker, you can reference his work products and units of work to determine his
utilization, but given a work product or unit of work, you are unable to determine its utilization
by a worker.
Figure 1.12
c. Multiplicity
Multiplicity (which is optional) indicates how many objects of a class may relate to the other
classes in an association. Multiplicity is shown as a comma-separated sequence of the following:
Integer intervals
Literal integer values
EC604A
Intervals are shown as a lower-bound .. upper-bound string in which a single asterisk indicates an
unlimited range. No asterisks indicate a closed range. For example, 1 means one, 1..5 means one
to five, 1, 4 means one or four, 0..* and * mean zero or more (or many), and 0..1 and 0, 1mean
zero or one. There is no default multiplicity for association ends. Multiplicity is simply undefined,
unless you specify it. For example:
A single worker is responsible for zero or more work products.
A single work product is the responsibility of exactly one worker.
A single worker performs zero or more units of work.
A unit of work is performed by exactly one worker.
A unit of work may input as a consumer zero or more work products and output as a producer
zero or more work products.
A work product may be consumed as input by zero or more units of work and produced as
output by zero or more units of work.
To determine the multiplicity of a class, ask yourself how many objects may relate to a single
object of the class. The answer determines the multiplicity on the other end of the association. For
example, using Another way to determine multiplicity is to ask how many objects of a class may
relate to a single object of the class on the other end of an association, or to a single object of each
class on the other ends of an n-ary association. The answer determines the multiplicity for the
class.
d. Aggregation
Aggregation is whole-part relationship between an aggregate, the whole, and its parts. This
relationship is often known as a has-a relationship, because the whole has its parts. For example,
when you think of workers making up a team, you can say that a team has workers. Aggregation
is shown using a hollow diamond attached to the class that represents the whole.
Figure 1.13
c. Composition
Composition, also known as composite aggregation, is a whole-part relationship between a
composite (the whole) and its parts, in which the parts must belong only to one whole and the
whole is responsible for creating and destroying its parts when it is created or destroyed. This
relationship is often known as a contains-a relationship, because the whole contains its parts. For
example, an organization contains teams and workers, and if the organization ceases to exist, its
teams and workers also cease to exist. The specific individuals who represent the workers would
still exist, but they would no longer be workers of the organization, because the organization
EC604A
would no longer exist. Composition is shown using a filled diamond attached to the class that
represents the whole. As a UML rule, composition is used only with binary associations.
It shows that an organization may contain 0 to 20 teams and 0 to 1,000 workers. Furthermore,
each team has 2 to 5 workers and each worker may be a member of 0 to 2 teams. In addition, a
team may contain 0 to 3 subteams.
To determine if you should use an aggregation or composition, ask yourself a few questions. First,
if the classes are related to one another, use an association. Next, if one class is part of the other
class, which is the whole, use aggregation; otherwise, use an association. For example, Figure
shows that workers are part of a team and organization, teams are part of an organization, and
subteams are part of teams. Finally, if the part must belong to one whole only, and the whole is
responsible for creating and destroying its parts, use composition; otherwise, simply use
aggregation.
Composition also may be shown by graphically nesting classes, in which a nested class's
multiplicity is shown in its upper-right corner and its rolename is indicated in front of its class
name. Separate the rolename from the class name using a colon.
Figure 1.14
e. Qualifiers
A qualifier is an attribute of an association class that reduces the multiplicity across an association.
For example, The multiplicity between work products and units of work is zero or more for both
associations; that is, there may be many work products associated with a single unit of work and
there may be many units of work associated with a single work product. Rather than simply say
that there are "many" objects involved in the relationship, you can communicate a more finite
number.
You can reduce the multiplicity between work products and units of work by asking yourself what
you need to know about a unit of work so that you can define a more specific multiplicity one that
isn't unbounded on the high-end. Likewise, you can ask yourself the same question about the
association between work product and units of work. If you have a work product and the name of
a unit of work, you can determine whether a relationship exists between the two; likewise, if you
EC604A
have a unit of work and the name of a work product, you can determine whether a relationship
exists between those two. The trick is to document precisely what information is needed so you
can identify the objects on the other end of the relationship. This is where the qualifier comes into
play.
Essentially, a qualifier is a piece of information used as an index to find the objects on the other
end of an association. A qualifier is shown as a small rectangle attached to a class where an object
of the class, together with a value for the qualifier, reduces the multiplicity on the other end of the
association. Qualifiers have the same notation as attributes, have no initial values, and must be
attributes of the association or the class on the other end of the association.
Figure 1.15
1.7 Aggregation
Consider a situation; Employee object contains much information such as id, name, emailId etc.
It contains one more object named address, which contains its own informations such as city,
state, country, zipcode etc. as given below.
Figure 1.16
ordination
b. aggregation
c. segregation
EC604A
d. increment
A class is a blueprint or prototype from which objects are created. This section defines a class that
models the state and behavior of a real-world object. It intentionally focuses on the basics,
showing how even simple classes can cleanly model state and behavior.
An object is a software bundle of related state and behavior. Software objects are often used to
model the real-world objects that you find in everyday life. This lesson explains how state and
behavior are represented within an object, introduces the concept of data encapsulation, and
explains the benefits of designing your software in this manner.
We need to understand the relationship between class and its object. Let think about how we can
identify a cat , a dog or a bird?? We can identify them by recalling the image(definition) of the
entities(objects) mapped in our brain.
Message passing is a technique for invoking behavior (i.e., running a program) on a computer. In
contrast to the traditional technique of calling a program by name, message passing uses an object
model to distinguish the general function from the specific implementations. The invoking
program sends a message and relies on the object to select and execute the appropriate code. The
justifications for using an intermediate layer essentially falls into two categories: encapsulation
and distribution.
Asynchronous message passing is generally implemented so that all the complexities that
naturally occur when trying to synchronize systems and data are handled by an intermediary level
of software. Commercial vendors who develop software products to support these intermediate
levels usually call their software. One of the most common types of middleware to support
asynchronous messaging is called Message-oriented middleware (MOM).
1.7 Inheritance
Inheritance is the process by which one object acquires the properties of another object. This is
important because it supports the concept of hierarchical classification. As mentioned earlier,
most knowledge is made manageable by hierarchical (that is, top-down) classifications. For
example, a Golden Retriever is part of the classification dog, which in turn is part of the mammal
class, which is under the larger class animal. Without the use of hierarchies, each object would
need to define all of its characteristics explicitly. However, by use of inheritance, an object need
only define those qualities that make it unique within its class. It can inherit its general attributes
from its parent.
EC604A
1.8 Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be
used for a general class of actions. More generally, the concept of polymorphism is often
expressed by the phrase “one interface, multiple methods.” This means that it is possible to design
a generic interface to a group of related activities. This helps reduce complexity by allowing the
same interface to be used to specify a general class of action.
1.9 Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe
from outside interference and misuse. One way to think about encapsulation is as a protective wrapper
that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper.
Access to the code and data inside the wrapper is tightly controlled through a well-defined interface.
Inheritance interacts with encapsulation as well.
EC604A
Advantages
Source File
EC604A
a. Object
b. Method
c. Message
Class File
d. Class
Method 1 8. Polymorphism allows you to create clean, sensible, readable, and
resilient code
. a. TRUE
b. FALSE
9. Inheritance interacts with encapsulation as well.
a. TRUE
b. FALSE
10. Inheritance is the process by which one object acquires the properties of another object
a. TRUE
b. FALSE
Module 2
Figure 3.2
JRE:
JRE is an acronym for Java Runtime Environment. It is used to provide runtime environment. It
is the implementation of JVM. It physically exists. It contains set of libraries + other files that
JVM uses at runtime.
Implementation of JVMs is also actively released by other companies besides Sun Micro Systems.
EC604A
JVM:
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
public : public means that the method could be accessed from anywhere. To run a java
program the jvmrequire to access the main method and it may be that the jvm and the main
method is not in same folder then also jvm can access it because of public.
static :In object oriented concept every members other that static member need to be called
by creating theobject of the class.So if main method is not declared as static then jvm can
only call the main method after creating the object of the class, but it is not possible to create
object before execution starts so the main method is declared as static.
void : Return Type, It defined what this method can return. Which is void in this case it
means that this method will not return anything. main: Name of the method. This method
name is searched by JVM as starting point for an application.
String aa[] : Parameter to main method.
Why Java is a Platform Independent Language??
A platform is the hardware or software environment in which the program runs. This platform
in real-life is the laptop and the underlying operating system runs on that laptop
.
Any program that needs to be executed on a platform must be converted into machine
instructions understandable by that platform. When developers write Java programs and
compile it, the code is not directly converted into machine instructions but it is compiled
into Byte Code.
EC604A
Byte code is not machine instructions that any platform like Windows, Mac will
understand it directly. This Byte code is understood by Java made Virtual machines. Java
Virtual Machines (JVM) interprets the Bytec ode into machine specific instructions so that
platform can understand its.
Java Virtual Machine (JVM) plays a key role in making the Byte code understandable to
any underlying platform thus makes the Byte code platform independent. If JVM are not
pre-installed on any operating system then byte code will fail to execute on that machine.
This makes the Bytecode platform independent and Java Virtual Machine Platform (JVM)
platform dependent.
Java programming language does not dependent on any underlying platform and thus it
makes Java platform independent. That’s why it is said that Java programs are written
once and executed anywhere.
EC604A
Module 3
3.1 Tokens
A Java program is basically a set of classes. A class is defined by a set of declaration statements
and methods or functions. Most statements contain expressions, which express the actions
carried out on information or data. Smallest indivisual thing in a program are known as tokens.
The compiler recognizes them for building up expression and statements.
Tokens in Java:
There are five types of token as follows:
1. Literals
2. Identifiers 3. Keywords
4. Operators
5. Separators
EC604A
3.1.1 Literals: Literals in Java are a sequence of characters (digits, letters and other characters)
that characterize constant values to be stored in variables. Java language specifies five major
types of literals are as follows:
1. Integer literals
2. Floating point literals
3. Character literals
4. String literals
5. Boolean literals
3.1.2 Identifiers:
Identifiers are programmer-created tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a program. Java identifiers follow the
following rules:
1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not start with a digit.
3. Uppercase and lowercase letters are individual.
4. They can be of any length.
Identifier must be meaningful, easily understandable and descriptive.
For example:
Private and local variables like ―length.
Name of public methods and instance variables begin with lowercase letter like ―addition
3.1.3 Keywords:
Keywords are important part of Java. Java language has reserved 50 words as keywords.
Keywords have specific meaning in Java. We cannot use them as variable, classes and method.
Following table shows keywords.
Table 4.1
3.1.4 Operator:
Java carries a broad range of operators. An operator is symbols that specify operation to be
performed may be certain mathematical and logical operation. Operators are used in programs
to operate data and variables. They frequently form a part of mathematical or logical
expressions.
EC604A
Categories of operators are as follows:
1. Arithmetic operators
2. Logical operators
3. Relational operators
4. Assignment operators
5. Conditional operators
6. Increment and decrement operators
7. Bit wise operators
3.1.4.1 Arithmetic operators:
Arithmetic operators are used to make mathematical expressions and the working out as same in
algebra. Java provides the fundamental arithmetic operators. These can operate on built in data
type of Java.
Following table shows the details of operators.
Table 4.2
When both operands in the expression are integers then the expression is called Integer expression
and the operation is called Integer arithmetic.
When both operands in the expression are real then the expression is called Real expression and the
operation is called Real arithmetic.
When one operand in the expression is integer and other is float then the expression is called Mixed
Mode Arithmetic expression and the operation is called Mixed Mode Arithmetic operation.
EC604A
Table 4.3
The logical expression defers a value of true or false. Following table shows the truth table of
Logical – OR and Logical – AND.
Truth table for Logical – OR operator:
Table 4.4
T - True
F - False
Truth table for Logical – AND operator:
Table 4.5
T - True
F – False
Now the following program shows the use of Logical operators.
EC604A
When evaluation of two numbers is performed depending upon their relation, assured decisions are
made.
The value of relational expression is either true or false. If
A=7 and A < 10 is true while 10 < A is false.
Table 4.6
Table 4.7
Table 4.8
EC604A
Table 4.9
EC604A
3.1.5 Separator:
Separators are symbols. It shows the separated code. They describe function of our code.
Table 4.10
Table 4.11
Table 4.12
EC604A
int long We can make ineger long by adding ‗l‘ or ‗L‘ at the end of
the number. Floating point data type:
It is also called as Real number and when we require accuracy then we can use it.
There are two types of floating point data type.
float
double
It is represent single and double precision numbers. The float type is used for single precision
and it uses 4 bytes for storage space. It is very useful when we require accuracy with small
degree of precision. But in double type, it is used for double precision and uses 8 bytes of
starage space. It is useful for large degree of precision.
3.3 Variables:
Variables are labels that express a particular position in memory and connect it
with a data type.
The first way to declare a variable: This specifies its data type, and reserves memory for it.
It assigns zero to primitive types and null to objects. dataType variableName;
The second way to declare a variable: This specifies its data type, reserves memory for it,
and puts an initial value into that memory. The initial value must be of the correct data type.
dataType variableName = initialValue;
The first way to declare two variables: all of the same data type, reserves memory for each.
dataType variableNameOne, variableNameTwo;
The second way to declare two variables: both of the same data type, reserves
memory, and puts an initial value in each variable. dataType
variableNameI = initialValueI, variableNameII=initialValueII;
Variable name:
Use only the characters ‗a‘ through ‗z‘, ‗A‘ through ‗Z‘, ‗0‘ through ‗9‘, character ‗_‘, and
character ‗$‘.
EC604A
A name cannot include the space character.
Do not begin with a digit.
A name can be of any realistic length.
Upper and lower case count as different characters.
A name cannot be a reserved word (keyword).
A name must not previously be in utilized in this block of the program.
class Scope
{
public static void main(String args[]) {
int x; // known to all code within main x
= 10;
if(x == 10) { // start new scope int y
= 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}}
3.4 Constant:
Constant means fixed value which is not change at the time of execution of program. In Java, there
are two types of constant as follows:
Numeric Constants
Integer constant
Real constant
EC604A
Character Constants
Table 4.13
3.5 Comments:
A comment is a note written to a human reader of a program. The program compiles and runs
exactly the same with or without comments. Comments start with the two characters ―// (slash
slash). Those characters and everything that follows them on the same line are ignored by the
java compiler.
Everything between the two characters ―/*and the two characters ―*/ are unobserved by the
compiler. There can be many lines of comments between the ―/* and the ―*/.
3.6.2 Explicit typecasting: when the source type is larger than destination type
Constant value could not be changed, so we can store a constant bigger data type value to a smaller
data type variable without type casing.
EC604A
The most important thing to understand about a class is that it defines a new data type. Once
defined , this new type can be used to create objects of that type.
Class: A class is a user defined variable
A class can be defined as a template/blue print that describes the behaviors/states that object of its
type support.
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created.
class <class_name>{
data member; method;
}
3.7.2 Object: An entity that has state and behavior is known as an object. Object is an instance of
a class.
An object has three characteristics:
o state: represents data (value) of an object.
o behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
o identity: Object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. But, it is used internally by the JVM to identify each object
uniquely.
100
Figure 5.1
Figure 5.2
With primitive variables values are like: 1,2…1.1,’A’ etc. and for the reference value of the variable
is bits representing a way to get to a specific object.
A class can be defined as a template/blue print that describes the behaviors/states that object of its
type support.
Class Contains:
i. Member variable/constant ii.
Method
3.10 A class may contain any numbers of following types of variables: Local
variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any
method. These variables are instantiated when the class is loaded. Instance variables
EC604A
can be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside
any method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods.
Heap : Java Heap space is used by java runtime to allocate memory to Objects and JRE classes.
Whenever we create any object, it’s always created in the Heap space. Any object created in the
heap space has global access and can be referenced from anywhere of the application.
Dog
Cat Object
Object
Tiger
Object
Stack :Java Stack memory is used for execution of a thread. They contain method specific
values that are short-lived and references to other objects in the heap that are getting referred
from the method. Stack memory is always referenced in LIFO (Last-In-First-Out) order.
Whenever a method is invoked, a new block is created in the stack memory for the method to
EC604A
hold local primitive values and reference to other objects in the method. As soon as method ends,
the block becomes unused and become available for next method. Stack memory size is very less
compared to Heap memory.
m1() b
main()
EC604A
3.12Local Variables:
Local variables reside in stack. They are of two types one is primitive and other is reference.
The primitive local variables reside in stack and the reference local variable resides in stack
referred to a real object resided in heap.
3.13 Instance Variable: They reside in the heap along with the object. They can also be of two types
one in primitive and other is reference.
The primitive and reference instance variable resides in heap and the reference variable referred
to the real object resides in object.
• modifier − It defines the access type of the method and it is optional to use.
• nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.
EC604A
• Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the statements.
3.15 Constructor
Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler
builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked.
Features of Constructor:
• The name of constructor is same as class name where it is declared.
• It does not have any return type • It can not be called without new.
• It can not be static
• Constructors are called when we create object.
EC604A
Types of Constructor:
EC604A
Figure 5.3
2. Parameterized Constructor:
The constructor which has parameter is known as parameterized constructor.
3. Copy Constructor
It is a special type of parameterized constructor where the parameter is the object of the same
class. It is used to copy one object value to other object.
EC604A
Constructor Overloading
Constructor overloading is a feature by which a class can contain multiple constructors with
different signature (Parameters) and different purpose.
class Test{
Test(){
System.out.println("I am a Non Parameterized Constructor");
}
Test(int a){
System.out.println("I am a Parameterized Constructor");
}
public static void main(String[] a){
Test t1=new Test();
Test t2=new Test(10);
}
}
EC604A
class Test{
Test(int a){
System.out.println("int parameter");
}
Test(float a){
System.out.println("float parameter");
}
public static void main(String[] a){
Test t1=new Test(10);
Test t2=new Test(10.0f);
}}
Sequence of occurrence of parameters different
this() is something by which we can call the constructor of the same class. Suppose by accessing
one constructor, the programmer may require the functionality of other constructors also but by
creating one object only. For this, Java comes with this(). "this()" is used to access one
constructor from another "within the same class".
class Test{
Test(){
System.out.println("I am a Non Parameterized Constructor");
}
Test(int Calling the non parameterized constructor
a){
this();
EC604A
System.out.println("I am a Parameterized Constructor");
}
public static void main(String[] a){
Test t1=new Test();
Test t2=new Test(10);
}
}
Rules of using this()
1. If included, this() statement must be the first one in the constructor. You cannot write anything
before this() in the constructor.
2. With the above rule, there cannot be two this() statements in the same constructor (because
both cannot be the first).
3. this() must be used with constructors only, that too to call the same class constructor (but not
super class constructor).
Class Test_Const{
int a,b,c;
Test_Const(int a,int b){
this.a=a;
this.b=b; }
Test_Const(int a,int b, int c){
this(a,b); calling first constructor from the second one using this
this.c=c;
}}
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other
words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
EC604A
Advantage of Garbage Collection
• It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
• It is automatically done by the garbage collector (a part of JVM) so we don't need to
make extra efforts.
Disadvantages
Typically, garbage collection has certain disadvantages, including consuming additional
resources, performance impacts, possible stalls in program execution, and incompatibility with
manual resource management.
finalize() method :
The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object
class as:
System.gc() :
The java.lang.System.gc() method runs the garbage collector. Calling this suggests
that the Java Virtual Machine expend effort toward recycling unused objects in order
EC604A
to make the memory they currently occupy available for quick reuse. Following is the
declaration for java.lang.System.gc() method
3.18 Array
An array is a group of like-typed variables that are referred to by a common name. Arrays
of any type can be created and may have one or more dimensions. A specific element in an
array is accessed by its index. Arrays offer a convenient means of grouping related
information
Figure 5.4
Each item in an array is called an element, and each element is accessed by its numerical index.
As shown in the preceding
illustration, numbering begins with 0. The 9th element, for example, would therefore be
accessed at index 8.
Properties of Array in JAVA:
Not Homogeneous
Java Provides a final property ‘length’ that gives the length of array
Array is treated as object of type java.lang.Object class
Array has default values as:
0 int null
reference type at
creation time.
Creation of One dimensional array:
<datatype> [] <array name>= new <datatype> [<size>]
Followings are the way to create one dimensional array:
EC604A
Program on array:
Length : 2D array:
a.length: Numbers of rows in the array a[i].length:
Numbers of Columns in the ith row. Programme
on 2D array:
EC604A
Anonymous array:
In java it is possible to create an array without name.
System.out.println(new int[]{1,2,3,4}.length); //display 4.
Reusable array
In Java it is possible to reuse a already created array, i.e here x had initially size 3 but we
can create an array of size 90 with same name and initial values will be lost.
int[] x={1,2,3};
x=new int[90];
3.19 Method
EC604A
Method is the object oriented name of function. Method is a block of code having similar
functionality.
• modifier − It defines the access type of the method and it is optional to use.
• returnType − Method may return a value.
• nameOfMethod − This is the method name. The method signature consists of the method
name and the parameter list.
• Parameter List − The list of parameters, it is the type, order, and number of parameters of a
method. These are optional, method may contain zero parameters.
• method body − The method body defines what the method does with the statements.
Calling a Method:
Non static methods are called through the object of the class and static methods are called
through class name class Ret_Object{ A m(){
return new A();
}
static void s(){//}
public static void main(String[] aa){
Ret_Objcet r=new Ret_Object();
A o1=r.m(); //calling non static method
Ret_Object.s();// calling static method
}}
class
A{
//}
Method of java are always call by value.
//}
class AddArray{
int []a1=new int[3]; int
[]a2=new int[3]; void
setValues(){
System.out.println(“Initilizing two
arrays”); a1[0]=10; a1[1]=11; a1[2]=100;
a2[0]=12; a2[1]=11 a2[2]=101;} int[]
add(){ int[] r=new int[a1.length]; for(int
i=0;i<a1.length;i++){ r[i]=a1[i]+a2[i];
} return r; } void
display(int[] a){
System.out.print(“The result= ”);
for(int i=0;i<a.length;i++)
System.out.print(a[i]+” “);
} public static void main(string[]
aa){ AddArray a=new AddArray();
EC604A
a.setValues(); int b[]=a.add();
a.display(b);
}
}
Method Overloading
If a class has multiple methods by same name but different signature, it is known as Method
Overloading.
Condition of Method Overloading:
1. Number of Parameters should be different
2. Types of Parameters should be different
3. Sequence of occurrence of parameters should be different
In the above example there is no parameter with int parameter, so when we call show(10) , this
10 can be stored in a double value by implicit type casting so show(double) method
will be called.
3.20 Static
Static Key word in java is basically used as a modifier. We can apply java static keyword with
variables, methods, blocks and nested class. Static keyword is associated with class rather than object.
EC604A
Static Block:
A static block is a normal block of code enclosed in braces, { }, and preceded by the
static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the
class body. The runtime system guarantees that static initialization blocks are called in the order
that they appear in the source code.
EC604A
Whenever a class loaded into memory static block will execute in their order. This is only once
as class is loaded only once during running.
For each object creation the non static blocks will execute.
If we initialize any static variable that static block also execute as the class loaded.
EC604A
Static variable:
Static variables are the class level variables. All the instances of a class share the same copy of a
static variable, which in turn actually saves memory. Usually the common properties of a class
are stored in static variable. Static variables are initialized when a class is loaded, before any
object is created.
Static Method:
They are the class level method. Behavior of static method does not depend on value of instance
variables.
<classname>.<methodname>
Static method could not access the non static data directly. They are accessed with objects.
Static methods could not identify which value of instance variable is associated with that
method so it needs object to call it. It is true for the non static method also.
EC604A
Whenever a class loaded into memory static block will execute in their order. This is only once
as class is loaded only once during running.
For each object creation the non static blocks will execute.
If we initialize any static variable that static block also execute as the class loaded.
EC604A
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access
to other members of the enclosing class, even if they are declared private.
• It is a way of logically grouping classes that are only used in one place: If a class is
useful to only one other class, then it is logical to embed it in that class and keep the
two together. Nesting such "helper classes" makes their package more streamlined.
• It increases encapsulation: Consider two top-level classes, A and B, where B needs
access to members of A that would otherwise be declared private. By hiding class B within
class A, A's members can be declared private and B can access them. In
addition, B itself can be hidden from the outside world.
• It can lead to more readable and maintainable code: Nesting small classes within
top-level classes places the code closer to where it is used.
As with class methods and variables, a static nested class is associated with its outer class. And
like static class methods, a static nested class cannot refer directly to instance variables or
methods defined in its enclosing class: it can use them only through an object reference.
A static nested class interacts with the instance members of its outer class (and other classes) just
like any other top-level class. In effect, a static nested class is behaviorally a top-level class that
has been nested in another top-level class for packaging convenience.
class Outer{
private static int a=10;
void show_Outer(){
System.out.println(new Inner().aa);
System.out.println("Outer class method");
//show_Inner();
}
static class Nest{
private int aa=100;
static void show_Inner(){
System.out.println(a);
System.out.println("Nested class method");
}
}
}
class Nested{
public static void main(String[] aa){
new Outer().show_Outer();
Outer.Nest o=new Outer.Nest();
Outer.Nest.show_Inner();
}
EC604A
EC604A
Local Class:
Local classes are classes that are defined in a block, which is a group of zero or more statements
between balanced braces. You typically find local classes defined in the body of a method.
class
Test_Local{
public void s(){
class Local{ void
show(){
System.out.println(“LOCAL”);
}
Local l=new
Local(); l.show();
}
}
public static void main(String[]a
){ Test_Local t=new
Test_Local(); t.s();
}
}
Anonymous Class:
EC604A
Anonymous classes enable you to make your code more concise. They enable you to declare
and instantiate a class at the same time. They are like local classes except that they do not
have a name. Use them if you need to use a local class only once.
class A1{
interface
I{
void s();
}public void s1(){ I i =new I(){
public void s(){
System.out.println("Anonymous class");
}
};
i.s();
}
public static void main(String[]aa){
new A1().s1();
}
}
2. What will this code print? int arr[] = new int [5]; System.out.print(arr); a) 0
b) value stored in arr[0].
c) 00000
d) Class name@ hashcode in hexadecimal form
8. What is the return type of a method that does not returns any value? a) int
b) float
c) void
d) double
9. Which of the following is a method having same name as that of it’s class? a) finalize
b) delete
c) class
d) constructor
13. Which of the following is a method having same name as that of its class? a) finalize
b) delete
c) class
d) constructor
14. Which operator is used by Java run time implementations to free the memory of an
object when it is no longer needed? a) delete
b) free
c) new
d) None of the mentioned
15. Which function is used to perform some action when the object is to be destroyed? a)
finalize()
b) delete()
c) main()
d) None of the mentioned
18. What is the process of defining a method in terms of itself, that is a method that calls
itself?
a) Polymorphism
b) Abstraction
c) Encapsulation
d) Recursion
EC604A
19. void start() { A a = new A(); B b = new B(); a.s(b); b = null; /* Line 5 */ a =
null; /* Line 6 */
System.out.println("start completed"); /* Line 7 */
}
When is the B object, created in line 3, eligible for garbage collection?
1. After line 5
2. After line 6
3. After line 7
4. There is no way to be absolutely certain.
Module 4
Reusable Properties
4.1 Inheritance
Mammals
Dog
Inheritance
B
EC604A
C
EC604A
EC604A
Multiple Inheritance : Multiple Inheritance refers to the concept of one class extending (Or
inherits) more than one base class. The inheritance we learnt earlier had the concept of one base
class or parent. The problem with “multiple inheritance” is that the derived class will have to
manage the dependency on two base classes.
A B
Java supports single level and multi level inheritance. Keyword extends is used established
inheritance relationship among classes. Derived class can access all non private properties of base
class
EC604A
Derived class accessing Member Variable
4.3 super
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword
super. Super has two general forms. The first calls the superclass’ constructor. The second is used
to access a member of the super class that has been hidden by a member of a subclass .
new A()
new Object()
Output:
}
}
class B extends A { B() {
System.out.println("Inside B's constructor.");
}
}
class C extends B { C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons { public static void
main(String args[]) { C c = new C();
}
}
How Polymorphism actually works
Base class reference can store the parent class object.
Animal[] a=new Animal[4] a[0]=new Dog();
a[1]=new Cow(); a[2]=new Lion(); a[4]=new
Tiger();
Sometimes animal behaves like Dog, sometimes like Cow, sometimes like Lion and
sometimes like Tiger. It is the polymorphic behavior
Both Base class and Derived class have same named method. Method associated with the object
would be called.
show()
EC604A
4.11 Abstract Method: If a method does not have any definition then the method is abstract
method.
Abstract class: An abstract class is a class that is declared abstract—it may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be sub classed.
Lecture 4
4.12 Interface
Interface is a fully abstract class. An interface is a collection of abstract methods.
Features of Interface:
1. All the methods are by default public abstract
2. All the members are static and final
3. Interface cannot be instantiated
4. The child class which implements the interface should define all the methods of the interface.
5. One interface can extends other interface.
4.14 B C Similarities of
Interface and Class:
show() show() • An
interface can contain
any number of methods.
• An
interface is written in
a file D with a .java
extension, with the name of the
show() interface matching the name of the
file.
• The byte code of an
interface appears in a .class file.
• Interfaces appear in packages, and their corresponding byte code file must
be in a directory structure that matches the package name.
4.15 Dissimilarities of Interface and Class:
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can appear
in an interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a class.
• An interface can extend multiple interfaces.
4.17 Package
A Package can be defined as a grouping of related types (classes, interfaces, enumerations
and annotations ) providing access protection and name space management.
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is
a good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names
in other packages. Using packages, it is easier to provide access control and it is also easier
to locate the related classes.
To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the
specified package. The package statement defines a name space in which classes are stored
Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage.
package MyPackage;
You can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period. The general form of a multileveled package
statement is shown here:
package pkg1[.pkg2[.pkg3]];
package java.awt.image;
package jis1;
public class
T1{ public void
EC604A
s(){
System.out.println("Creating a package");
}
public static void main(String[]
a){ T1 t=new T1();
t.s();
}
Run:
D:\JP> java jis1.T1
import <packageName>.<subPackageName>.*
importing all the claases under the package.
or
import <packageName>.<subPackageName>.<class name>
importing specific under the package.
import java.util.*;
public class T1{
public static void main(String[] a){
Date d=new Date();
System.out.println(d.toString());
}
}
EC604A
If we are using import statement then we have to use fully qualified class name:
java.util.Date d=new java.util.Date()
package jis1;
public class
T1{ public
void s(){
System.out.println("Creating a package");
}
}
package jis2;
import jis1.*;
public class
T2{
public static void main(String[]
a){ T1 t=new T1();
t.s();
}
}
EC604A
To Compile
1. D:\JP\jis1>javac
T1.java <<Set class
path>>
D:\JP> set classpath=D:\JP
2. D:\JP\jis2>javac T2.java
Java's import statement doesn't include the file, as #include in C/C++ does, it just tells the compiler
where to look for its class references.
In order to access static members, it is necessary to qualify references with the class they
came from. For example, one must say: doub le r = Math.cos(Math.PI * theta);
In order to get around this, people sometimes put static members into an interface and inherit
from that interface. This is a bad idea. In fact, it's such a bad idea that there's a name for it:
the Constant Interface Antipattern . The problem is that a class's use of the static members of
another class is a mere implementation detail. When a class implements an interface, it
becomes part of the class's public API. Implementation details should not leak into public
APIs.
The static import construct allows unqualified access to static members without inheriting
from the type containing the static members. Instead, the program imports the members,
either individually:
The static import declaration is analogous to the normal import declaration. Where the normal
import declaration imports classes from packages, allowing them to be used without package
qualification, the static import declaration imports static members from classes, allowing them
to be used without class qualification.
Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse
inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent
access to static members from one or two classes. If you overuse the static import feature, it can
make your program unreadable and unmaintainable, polluting its namespace with all the static
members you import. Readers of your code (including you, a few months after you wrote it) will
not know which class a static member comes from. Importing all of the static members from a
class can be particularly harmful to readability; if you need only one or two members, import
them individually. Used appropriately, static import can make your program more readable, by
removing the boilerplate of repetition of class names.
Different NO NO NO YES
package non-
subclass
Classes and packages are both means of encapsulating and containing the name space and scope
of variables and methods. Packages act as containers for classes and other subordinate
packages. Classes act as containers for data and code. The class is Java’s smallest unit of
abstraction. Because of the interplay between classes and packages, Java addresses four
categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways
to produce the many levels of access required by these categories.
EC604A
5. Which of these keyword can be used in subclass to call the constructor of superclass? a)
super
b) this
c) extent
d) extends
6. What is the process of defining a method in subclass having same name & type
signature as a method in its superclass? a) Method overloading
b) Method overriding
c) Method hiding
d) None of the mentioned
11. Which of these is a mechanism for naming and visibility control of a class and its
content?
a) Object
b) Packages
c) Interfaces
d) None of the Mentioned.
12. Which of this access specifies can be used for a class so that its members can be
accessed by a different class in the same package? a) Public
b) Protected
c) No Modifier
d) All of the mentioned
13. Which of these access specifiers can be used for a class so that it’s members can be
accessed by a different class in the different package? a) Public
b) Protected
c) Private
d) No Modifier
14. Which of the following is correct way of importing an entire package ‘pkg’? a) import
pkg.
b) Import pkg.
c) import pkg.*
d) Import pkg.*
Module 5
Exception and Multithreading
5.1 Exception
The term exception is shorthand for the phrase "exceptional event."
An exception is an event, which occurs during the execution of a program, that disrupts the
normal flow of the program's instructions.
When an error occurs within a method, the method creates an object and hands it off to the
runtime system. The object, called an exception object, contains information about the error,
including its type and the state of the program when the error occurred. Creating an exception
object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle
it. The set of possible "something" to handle the exception is the ordered list of methods that
had been called to get to the method where the error occurred. The list of methods is known as
the call stack (see the next figure).
The exception handler chosen is said to catch the exception. If the runtime system exhaustively
searches all the methods on the call stack without finding an appropriate exception handler, as
shown in the next figure, the runtime system (and, consequently, the program) terminates.
Using exceptions to manage errors has some advantages over traditional error-management
techniques.
To understand how exception handling works in Java, you need to understand the three
categories of exceptions:
5.1.1 Checked exceptions: A checked exception is an exception that is typically a user error or
a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but
the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the
time of compilation.
5.1.2 Runtime exceptions: A runtime exception is an exception that occurs that probably could
have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions
are ignored at the time of compilation.
Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise.
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in
case of severe failures, which are not handled by the java programs. Errors are generated to
indicate errors generated by the runtime environment. Example : JVM is out of Memory.
Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
EC604A
Runtime Exception
EC604A
Exception Description
incompatible type.
Checked Exception
Exception Description
interface.
thread.
5.4.1 try-catch
If a exceptional condition occurs in code the code will terminate. But it it possible to handle the
exception so that rest of the code will execute properly:
EC604A
}catch(Exception e)
class Test_Exp{
public static void main(String[] aa){
int a=10;
try{
int c=a/0;
System.out.println(“Main method”); }catch(Exception e){ e.printStackTrace();}
System.out.println(“End of main”); }
}
catch(
Arith
meticE
xcepti
on
ae){
ae.prin
tStack
Trace(
);}
catch(
ArrayI
ndexO
utOfB
ounds
Except
ion
ae){
ae.prin
tStack
Trace(
);}
catch(
Except
ion e){
EC604A
e.print
StackT
race();
try{// }
ae){ ae.printStackTrace();}
EC604A
EC604A
catch(ArrayIndexOutOfBoundsException ae){
ae.printStackTrace();}class Test_Exp{ public static void
main(String[] aa){ int a=10; int b[]=new int[5]; try{ int c=a/0; int d=b[9];
System.out.println(“Main method”);
}catch(ArithmeticException ae){ ae.printStackTrace();}
catch(ArrayIndexOutOfBoundsException ae){ ae.printStackTrace();} catch(Exception e){
e.printStackTrace();}
System.out.println(“End of main”);
}}
class Test_Exp{
public static void main(String[] aa){
int a=10; int b[]=new int[5]; try{ int
c=a/0; int d=b[9];
System.out.println(“Main method”);
}catch(ArithmeticException ae){ ae.printStackTrace();}
catch(ArrayIndexOutOfBoundsException ae){ ae.printStackTrace();} catch(Exception e){
e.printStackTrace();}
System.out.println(“End of main”); }
Nested try-catch :
The try statement can be nested. That is, a try statement can be inside the block of another try.
Each time a try statement is entered, the context of that exception is pushed on the stack. If an
inner try statement does not have a catch handler for a particular exception, the stack is unwound
and the next try statement’s catch handlers are inspected for a match. This continues until one of
the catch statements succeeds, or until all of the nested try statements are exhausted.
EC604A
class Test_Exp{
public static void main(String[] aa){
int a=10;
int b[]=new int[5];
try{
int c=a/0;
try{
int d=b[9];
}catch(catch(ArrayIndexOutOfBoundsException ae){ ae.printStackTrace();}
System.out.println(“Main method”);
}catch(ArithmeticException ae){ ae.printStackTrace();}
System.out.println(“End of main”);
}
}
If inner block does not having a matching catch block it will look for the matching catch block in the
outer catch block, and if finds a matching catch exception will handle properly.
But if outer catch block does not have any matching catch block it cannot look for the inner catch block
so exception will not handle.
EC604A
5.5 throw:
class Test_Exp{
public static void main(String[] aa){
int a=10;
try{
throw new ArithmeticException()
System.out.println(“Main method”);
}catch(Exception e){ e.printStackTrace();}
System.out.println(“End of main”);
}
}
The chained exception feature allows you to associate another exception with an exception. This second
exception describes the cause of the first exception. For example, imagine a situation in which a method
throws an ArithmeticException because of an attempt to divide by zero. However, the actual cause of
the problem was that an I/O error occurred, which caused the divisor to be set improperly.
The chained exception methods added to Throwable are getCause( ) and initCause( ).
These methods are shown in Table 10-3 and are repeated here for the sake of discussion.
Throwable getCause( )
The getCause( ) method returns the exception that underlies the current exception. If there
EC604A
is no underlying exception, null is returned. The initCause( ) method associates causeExc with the invoking
exception and returns a reference to the exception. Thus, you can associate a cause with an exception after
the exception has been created. However, the cause exception can be set only once. Thus, you can call
initCause( ) only once for each exception object. Furthermore, if the cause exception was set by a
constructor, then you can’t set it again.
using initCause( ).
Ouput:
IOException
Computer execution unit is basically divided into two category Process and Thread.
5.9.1Process:
5.9.1Thread:
A thread is the basic unit to which the operating system allocates processor time. A thread can
execute any part of the process code, including parts currently being executed by another thread.
Threads have direct access to the data segment of its process
Processes are heavily dependent on system resources available while threads require minimal
amounts of resource, so a process is considered as heavyweight while a thread is termed as a
lightweight process.
5.10 Thread Life Cycle
Figure 8.3
New − A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this
state is considered to be executing its task.
EC604A
Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another
thread to perform a task. A thread transitions back to the runnable state only when another
thread signals the waiting thread to continue executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of
time. A thread in this state transitions back to the runnable state when that time interval expires
or when the event it is waiting for occurs.
Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
Current Thread: Every Java program works on a thread. If user dose not create any thread still
there is main thread.
class Test_Thread{
public static void main(String[] aa){
Thread t=Thread.currentThread();
System.out.println(t);
t.setName("JIS");
System.out.println(t);
}
}
Each thread maintains their separate call stack. When start method is called on a thread a
separate call stack creates.
m()
t.start()
run()
main()
EC604A
Figure 8.4
5.12 Important Methods used for developing Thread Application
void start() Causes this thread to begin execution; the Java Virtual Machine calls the run method
of this thread.
void run() If this thread was constructed using a separate Runnable run object, then that
Runnable object's run method is called; otherwise, this method does nothing and
returns.
void stop() Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has
locked (as a natural consequence of the unchecked
void sleep(long millis) Causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds, subject to the precision and accuracy of system
timers and schedulers.
void setName(name) Changes the name of this thread to be equal to the argument name.
static void yeild() A hint to the scheduler that the current thread is willing to yield its current use of a processor.
Table 8.3
Thread in a Java program can be created either by extending the thread class or implementing the
Runnable interface.
EC604A
EC604A
class MyThread1 extends Thread{
String name;
MyThread(String name){
this.name=name;
}
public void run(){
for(int i=0;i<5;i++){
System.out.println(name);
try{
Thread.sleep(2000);
}
}
}
}
Creating Multiple Thread by extending the Thread Class
System.out.println(s);
Java assigns to each thread a priority that determines how that thread should be treated with
respect to the others. Thread priorities are integers that specify the relative priority of one thread
to another. As an absolute value, a priority is meaningless; a higher-priority thread doesn’t run
any faster than a lower-priority thread if it is the only thread running. Instead, a thread’s priority
is used to decide when to switch from one running thread to the next. This is called a context
switch.
A thread can voluntarily relinquish control. This is done by explicitly yielding, sleeping, or
blocking on pending I/O. In this scenario, all other threads are examined, and the highestpriority
thread that is ready to run is given the CPU.
A thread can be preempted by a higher-priority thread. In this case, a lower-priority thread that
does not yield the processor is simply preempted—no matter what it is doing— by a
higherpriority thread. Basically, as soon as a higher-priority thread wants to run, it does. This is
called preemptive multitasking. In cases where two threads with the same priority are competing
for
CPU cycles, the situation is a bit complicated. For operating systems such as Windows, threads class
TestPriority{ public static void main(String[] a){ Mythread m=new Mythread();
m.start();
} } class Mythread extends Thread{
public void run(){ setPriority(2);
System.out.println(getPriority());
}
}
EC604A
of equal priority are time -sliced automatically in round -robin fashion. For other typ es of
operating systems, threads of equal priority must voluntarily yield control to their peers. If they
don’t, the other threads will not run.
When two or more threads need access to a shared resource, they need some way to ensure that
the resource will be used by only one thread at a time. The process by which this isachieved is
called synchronization. As you will see, Java pro vides unique, language -levelsupport for it.Key
to synchronization is the concept of the monitor (also called a semaphore). A monitor is an
object that is used as a mutually exclusive lock, or mutex. Only one thread can own amonitor at
a given time. When a thread acquires a lock, it is said to have entered the monitor.All other
threads attempting to enter the locked monitor wil l be suspended until the firstthread exits the
monitor. These other threads are said to be waiting for the monitor. A thread that own sa
monitor can reenter the same monitor if it so desires.
String s;
Test t;
MyThread (String s, Thread t){
this.s=s;
this.t=t;
}
public
5.16 void run(){
Synchronization
EC604A
Without Synchronization class
Test{
wait()
notify()
notifyAll()
wait() method
Causes current thread to release the lock and wait until either another thread invokes the notify()
method or the notifyAll() method for this object, or a specified amount of time has elapsed. The
current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
notify() method
Wakes up a single thread that is waiting on this object's monitor.
If any threads are waiting on this object, one of them is chosen to be awakened.
notifyAll() method
Wakes up all threads that are waiting on this object's monitor.
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
Example
6.1 Java I/O (Input and Output) is used to process the input and produce the output.Java I/O
(Input and Output) is used to process the input and produce the output.
6.2Byte Stream
EC604A
Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes
are descended from InputStream and OutputStream. There are many byte stream classes.
Figure 9.2
DataOutputStream An output stream that contain method for writing java standard data type
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
CopyBytes spends most of its time in a simple loop that reads the input stream and writes the
output stream, one byte at a time, as shown in the following figure.
EC604A
Closing a stream when it's no longer needed is very important — so important that CopyBytes
uses a finally block to guarantee that both streams will be closed even if an error occurs. This
practice helps avoid serious resource leaks.
One possible error is that CopyBytes was unable to open one or both files. When that happens,
the stream variable corresponding to the file never changes from its initial null value. That's why
CopyBytes makes sure that each stream variable contains an object reference before invoking
close.
CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that
you should avoid. There are also streams for more complicated data types. Byte streams should
only be used for the most primitive I/O.
The Java platform stores character values using Unicode conventions. Character stream I/O
automatically translates this internal format to and from the local character set. In Western locales,
the local character set is usually an 8-bit superset of ASCII.
For most applications, I/O with character streams is no more complicated than I/O with byte
streams. Input and output done with stream classes automatically translates to and from the local
character set. A program that uses character streams in place of byte streams automatically adapts
to the local character set and is ready for internationalization — all without extra effort by the
programmer.
If internationalization isn't a priority, you can simply use the character stream classes without
paying much attention to character set issues. Later, if internationalization becomes a priority,
your program can be adapted without extensive recoding.
EC604A
Figure 9.4
Need to convert the byte stream to character stream as from console bytes are read.
Example
6.9 Formatted IO
Stream objects that implement formatting are instances of either PrintWriter, a character stream
class, or PrintStream, a byte stream class.
Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a
standard set of write methods for simple byte and character output. In addition, both
PrintStream and PrintWriter implement the same set of methods for converting internal data into
formatted output. Two levels of formatting are provided:
Invoking print or println outputs a single value after converting the value using the
appropriate toString method. We can see this in the Root example:
i = 5;
r = Math.sqrt(i);
System.out.println("The square root of " + i + " is " + r + ".");
}}
The format method formats multiple arguments based on a format string. The format string
consists of static text embedded with format specifiers; except for the format specifiers, the
format string is output unchanged.
Format strings support many features. In this tutorial, we'll just cover some basics. For
a complete description, see format string syntax in the API specification. The Root2
example formats two values with a single format invocation:
Like the three used in this example, all format specifiers begin with a % and end with a 1- or
2character conversion that specifies the kind of formatted output being generated. The three
conversions used here are:
Except for %% and %n, all format specifiers must match an argument. If they don't, an
exception is thrown.
In the Java programming language, the \n escape always generates the linefeed character
(\u000A). Don't use \n unless you specifically want a linefeed character. To get the correct line
separator for the local platform, use %n.
EC604A
public class Format {
public static void main(String[] args) {
System.out.format("%f, %1$+020.10f %n", Math.PI);
}}
3.141593, +00000003.1415926536
The additional elements are all optional. The following figure shows how the longer specifier
breaks down into elements.
The elements must appear in the order shown. Working from the right, the optional elements
are: • Precision. For floating point values, this is the mathematical precision of the
formatted value. For s and other general conversions, this is the maximum width of the
formatted value; the value is right-truncated if necessary.
• Width. The minimum width of the formatted value; the value is padded if necessary. By
default the value is left-padded with blanks.
• Flags specify additional formatting options. In the Format example, the + flag specifies
that the number should always be formatted with a sign, and the 0 flag specifies that 0 is
the padding character. Other flags include - (pad on the right) and , (format number with
locale-specific thousands separators). Note that some flags cannot be used with certain
other flags or with certain conversions.
• The Argument Index allows you to explicitly match a designated argument. You can
also specify < to match the same argument as the previous specifier. Thus the example
could have said: System.out.format("%f, %<+020.10f %n", Math.PI);
6.12Scanner Class
The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace by default.
It provides many methods to read and parse various primitive values.
EC604A
6.12 Commonly used methods of Scanner class
Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and
returns the value as a string.
public byte nextByte() it scans the next token as a byte.
Example
6.13 File IO
On the far left of the diagram are the utility methods readAllBytes, readAllLines, and the write
methods, designed for simple, common cases. To the right of those are the methods used to iterate
EC604A
over a stream or lines of text, such as newBufferedReader, newBufferedWriter, then
newInputStream and newOutputStream. These methods are interoperable with the java.io
package. To the right of those are the methods for dealing with ByteChannels,
SeekableByteChannels, and ByteBuffers, such as the newByteChannel method.
Finally, on the far right are the methods that use FileChannel for advanced applications needing
file locking or memory-mapped I/O.
6.15 FileInputStream
Methods
Example
byte []b={1,2,3};
File f=new File("Test.txt");
OutputStream o=new FileOutputStream(f);
for(int i=0;i<b.length;i++) o.write(b);
InputStream is = new FileInputStream("Test.txt");
int size = is.available(); for(int i = 0; i < size; i++) {
System.out.print((char)is.read() + " ");
}
}
catch(Exception e){}
If you have a small-ish file and you would like to read its entire contents in one pass, you can use
the readAllBytes(Path) or readAllLines(Path, Charset) method. These methods take care
of most of the work for you, such as opening and closing the stream, but are not intended for
handling large files. The following code shows how to use the readAllBytes method:
You can use one of the write methods to write bytes, or lines, to a file.
Files.write(file, buf);
The java.nio.file package supports channel I/O, which moves data in buffers, bypassing
some of the layers that can bottleneck stream I/O.
The following code snippet shows how to create a file encoded in "US-ASCII" using this
method:
6.19 Methods for Unbuffered Streams and Interoperable with java.io APIs
To open a file for reading, you can use the newInputStream(Path, OpenOption...) method. This
method returns an unbuffered input stream for reading bytes from the file.
You can create a file, append to a file, or write to a file by using the newOutputStream(Path,
OpenOption...) method. This method opens or creates a file for writing bytes and returns an
unbuffered output stream.
The method takes an optional OpenOption parameter. If no open options are specified, and the
file does not exist, a new file is created. If the file exists, it is truncated. This option is equivalent
to invoking the method with the CREATE and TRUNCATE_EXISTING options.
The following example opens a log file. If the file does not exist, it is created. If the file exists, it
is opened for appending.
1. Which of these packages contain classes and interfaces used for input & output operations of a
program?
a)java.util
b)java.lang
c)java.io
d) All of the mentioned
2. Which of these class is not a member class of java.io package? a)String
b)StringReader
c)Writer
d) File
3. Which of these interface is not a member of java.io package? a)DataInput
b)ObjectInput
c)ObjectFilter
d) FileFilter
4. Which of these class is not related to input and output stream in terms of functioning? a)File
b)Writer
c)InputStream
d) Reader
EC604A
5. Which of these classes is used for input and output operation when working with bytes?
a)InputStream
b)Reader
c)Writer
d) All of the mentioned
6. Which of these class is used to read and write bytes in a file? a)FileReader
b)FileWriter
c)FileInputStream
d) InputStreamReader
7. Which of these method of InputStream is used to read integer representation of next available
byte input? a)read()
b)scanf()
c)get()
d) getInteger()
8. Which of these data type is returned by every method of OutputStream? a)int
b)float
c)byte
d) None of the mentioned
9. Which of these is a method to clear all the data present in output buffers? a)clear()
b)flush()
c)fflush()
d) close()
10.Which of these method(s) is/are used for writing bytes to an outputstream? a)put()
b)print() and write() c)printf()
d) write() and read()
Module 7
Applet Programming
7.1 Applet
Applet are small application 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 a
graphical user interface and run computation without introducing the risk of viruses or loss of
data integrity.
</applet>
*/
s+=”…call init()”;
}
All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand-alone
programs. Instead, they run within either a web browser or an applet viewer. The
illustrations shown in this chapter were created with the standard applet viewer, called
appletviewer, provided by the JDK
Compile :
java MyApplet.java
Run
appletviewer MyApplet.java
Execution of an applet does not begin at main( ). Actually, few applets even have main( )
EC604A
methods. Instead, execution of an applet is started and controlled with an entirely different
mechanism, which will be explained shortly. Output to your applet’s window is not performed
by System.out.println( ). Rather, in non-Swing applets, output is handled with various AWT
methods, such as drawString( ), which outputs a string to a specified X,Y location. Input is
also handled differently than in a console application.
To use an applet, it is specified in an HTMLfile. One way to do this is by using the APPLET
tag. The applet will be executed by a Java-enabled web browser when it encounters the
APPLET tag within the HTMLfile. To view and test an applet more conveniently, simply
include a comment at the head of your Java source code file that contains the APPLET tag.
This way, your code is documented with the necessary HTML
statements needed by your applet, and you can test the compiled applet by starting the applet
viewer with your Java source code file specified as the target.
/*
</applet>
*/
This comment contains an APPLET tag that will run an applet called MyApplet in a
window that is 200 pixels wide and 60 pixels high. Because the inclusion of an APPLET
command makes testing applets easier, all of the applets shown in this book will contain the
ALIGN ALIGN is an optional attribute that specifies the alignment of the applet. This attribute
is treated the same as the HTML IMG tag with these possible values: LEFT, RIGHT,
TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM.
VSPACE and HSPACE These attributes are optional. VSPACE specifies the space, in pixels,
above and below the applet. HSPACE specifies the space, in pixels, on each side of the applet.
EC604A
They’re treated the same as the IMG tag’s VSPACE and HSPACE attributes.
PARAM NAME and VALUE The PARAM tag allows you to specify applet-specific
arguments
in an HTML page. Applets access their attributes with the getParameter( ) method.
EC604A
Requesting Repainting
The repaint( ) method is defined by the AWT. It causes the AWT run-time system to execute a
call to your applet’s update( ) method, which, in its default implementation, calls paint( ). Thus,
for another part of your applet to output to its window, simply store the output and then call
repaint( ). The AWT will then execute a call to paint( ), which can display the stored
information. For example, if part of your applet needs to output a string, it can store this string
in a String variable and then call repaint( ). Inside paint( ), you will output the string using
drawString( ).
The repaint( ) method has four forms. Let’s look at each one, in turn. The simplest version
of repaint( ) is shown here:
void repaint( )
This version causes the entire window to be repainted. The following version specifies a region
that will be repainted:
void repaint(int left, int top, int width, int height)
Here, the coordinates of the upper-left corner of the region are specified by left and top, and
the width and height of the region are passed in width and height. These dimensions are
specified in pixels. You save time by specifying a region to repaint. Window updates are costly
in terms of time. If you need to update only a small portion of the window, it is more efficient
to repaint only that region.
EC604A
Calling repaint( ) is essentially a request that your applet be repainted sometime soon.
However, if your system is slow or busy, update( ) might not be called immediately. Multiple
requests for repainting that occur within a short time can be collapsed by the AWT in a manner
such that update( ) is only called sporadically
}
// Entry point for the thread that runs the banner. public void run() { char
ch;
// Display banner
for( ; ; ) { try { repaint();
Thread.sleep(250); ch = msg.charAt(0); msg =
msg.substring(1, msg.length()); msg += ch;
if(stopFlag) break;
} catch(InterruptedException e) {}
}
}
}
}
// Pause the banner. public void stop() { stopFlag =
true;
t = null;
}
// Display the banner.
public void paint(Graphics g) { g.drawString(msg, 50, 30);
}
}
EC604A
The same applet can work on “all” installed versions of Java at the same time, rather
than
just the latest plug-in version only. However, if an applet requires a later version of the
Java Runtime Environment (JRE) the client will be forced to wait during the large
download.
Most web browsers cache applets so will be quick to load when returning to a web
page. Applets also improve with use: after a first applet is run, the JVM is already
running and starts quickly (the JVM will need to restart each time the browser starts
afresh). It should be noted that JRE versions 1.5 and greater stop the JVM and restart it
when the browser navigates from one HTML page containing an applet to another
containing an applet.
It can move the work from the server to the client, making a web solution more scalable
with the number of users/clients.
If a standalone program (like Google Earth) talks to a web server, that server normally
needs to support all prior versions for users which have not kept their client software
updated. In contrast, a properly configured browser loads (and caches) the latest applet
version, so there is no need to support legacy versions.
The applet naturally supports the changing user state, such as figure positions on the
chessboard.
Developers can develop and debug an applet direct simply by creating a main routine
(either in the applet’s class or in a separate class) and calling init() and start() on the
applet, thus allowing for development in their favorite Java SE development
environment. All one has to do after that is re-test the applet in the AppletViewer
program or a web browser to ensure it conforms to security restrictions.
An untrusted applet has no access to the local machine and can only access the server it
came from. This makes such an applet much safer to run than a standalone executable
that it could replace. However, a signed applet can have full access to the machine it is
running on if the user agrees.
EC604A
Java applets are fast – and can even have similar performance to native installed
software.
Disadvantages:
Some browsers, notably mobile browsers running Apple iOS or Android do not run
Java applets at all.
Some organizations only allow software installed by the administrators. As a result,
some users can only view applets that are important enough to justify contacting the
administrator to request installation of the Java plug-in.
As with any client-side scripting, security restrictions may make it difficult or even
impossible for an untrusted applet to achieve the desired goals. However, simply
editing the java.policy file in the JAVA JRE installation, one can grant access to the
local filesystem or system clipboard for example, or to other network sources other than
the network source that served the applet to the browser.
Some applets require a specific JRE. This is
discouraged.
If an applet requires a newer JRE than available on the system, or a specific JRE, the user
running it the first time will need to wait for the large JRE download to complete. Java
automatic installation or update may fail if a proxy server is used to access the web. This makes
applets with specific requirements impossible to run unless Java is manually updated. The Java
automatic updater that is part of a Java installation also
may be complex to configure if it must work through a proxy.
Unlike the older applet tag, the object tag needs workarounds to write a cross-browser
HTML document.
There is no standard to make the content of applets available to screen readers.
Therefore, applets can harm the accessibility of a web site to users with special needs.
}
}
7.9 The Delegation Event Model
The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events. Its concept is quite simple: a
source generates an event and sends it to one or more listeners. In this scheme, the listener simply
waits until it receives an event. Once an event is 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. Auser interface element i s able
to “delegate” the processing of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want
to receive them. 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.
Events
In the delegation model, an event is an object that describes a state change in a source. It
can be generated as a consequence of a person interacting with the elements in a graphical
user interface.
Event Sources
Asource is an object that generates an event. This occurs when the internal state of that
object changes in some way
Event Listeners
Alistener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive
notifications about specific types of events. Second, it must implement methods to
receive and process these notifications.
import java.awt.*;
import
java.applet.*;
import
java.awt.event.*;
//import
javax.swing.*;
EC604A
/*<applet code="MyApp_Listn" height=100
width=100> </applet>
*/ public class MyApp_Listn extends Applet
implements
ActionListener{ Button b1;
Button b2;
Label l1;
TextField t;
public void
init(){
b1=new Button("RED");
b2=new Button("PINK");
l1=new Label("click on
button");
t=new
TextField(10);
add(b1);
add(b2);
add(l1);
add(t);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==b1){
setBackground(Color.red);
}
if(ae.getSource()==b2){
setBackground(Color.pink);
}
}
}
7.10 Layout Manager
Layout means the arrangement of components within the container. In other way we can say
that placing the components at a particular position within the container. The task of layouting
the controls is done automatically by the Layout Manager.
The layout manager automatically positions all the components within the container. If we do
not use layout manager then also the components are positioned by the default layout manager.
EC604A
It is possible to layout the controls by hand but it becomes very difficult because of the
following two reasons.
Java provide us with various layout manager to position the controls. The properties like
size,shape and arrangement varies from one layout manager to other layout manager. When
the size of the applet or the application window changes the size, shape and arrangement of
the components also changes in response i.e. the layout managers adapt to the dimensions of
appletviewer or the application window.
The layout manager is associated with every Container object. Each layout manager is an
object of the class that implements the LayoutManager interface.
BorderLayout
BoxLayout
EC604A
The BoxLayout class puts components in a single row or column. It respects the
components' requested maximum sizes and also lets you align components..
CardLayout
The CardLayout class lets you implement an area that contains different components at
different times. A CardLayout is often controlled by a combo box, with the state of the combo
box determining which panel (group of components) the CardLayout displays. An alternative
to using CardLayout is using a tabbed pane, which provides similar functionality but with a
pre-defined GUI
FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in
a single row, starting a new row if its container is not sufficiently wide. Both panels in
CardLayoutDemo, shown previously, use FlowLayout.
GridBagLayout
EC604A
GridLayout
GridLayout simply makes a bunch of components equal in size and displays them in the
requested number of rows and columns.
GroupLayout
GroupLayout is a layout manager that was developed for use by GUI builder tools, but it can
also be used manually. GroupLayout works with the horizontal and vertical layouts
separately. The layout is defined for each dimension independently. Consequently, however,
each component needs to be defined twice in the layout. The Find window shown above is an
example of a GroupLayout.
SpringLayout
EC604A
SpringLayout is a flexible layout manager designed for use by GUI builders. It lets you specify precise
relationships between the edges of components under its control. For example, you might define that
the left edge of one component is a certain distance (which can be dynamically calculated) from the
right edge of a second component. SpringLayout lays out the children of its associated container
according to a set of constraints.
Swing-based applets are similar to AWT-based applets, but with an important difference: A
Swing applet extends JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet
includes all of the functionality found in Applet and adds support for Swing. JApplet is a toplevel
Swing container, which means that it is not derived from JComponent. Because JApplet is a top-
level container, it includes the various panes described earlier. This means that all components
are added to JApplet’s content pane in the same way that components are added to
JFrame’s content pane.
Swing applets use the same four lifecycle methods init( ), start( ), stop( ), and destroy( ).
Of course, you need override only those methods that are needed by your applet. Painting
is accomplished differently in Swing than it is in the AWT, and a Swing applet will not
normally override the paint( ) method.
*/
try {
});
} catch(Exception exc) {
}
// This applet does not need to override start(), stop(),
// or destroy().
// Set up and initialize the GUI.
}
});
}
});
EC604A
// Add the buttons to the content pane. add(jbtnAlpha); add(jbtnBeta);
jlab = new JLabel("Press a button."); // Add the label to the content pane. add(jlab);
}
}
Lecture 4:
7.12 IO Applet
Applets work in graphical environment. Therefore applets treat input as text strings. We must
first create an area of the screen in which user can type and edit input items. We can do this by
using the TextField class of the applet package. The values of the fields can be given even editer
after the creation of input fields. Next step is to retrieve the items from the fields for display of
calculations.
}
public void paint(Graphics g){
int sum=0;
g.drawString("enter numbers",10,50);
try{
sum=Integer.parseInt(tf1.getText())+Integer.parseInt(tf2.getText());
}catch(Exception e)
EC604A
Multiple Choice Questions
1. Which of these functions is called to display the output of an applet? a)display()
b)paint()
c)displayApplet()
d)PrintApplet() View
Answer
2. Which of these methods can be used to output a sting in an applet? a)display()
b)print()
c)drawString()
d)transient()
View Answer
3. What does AWT stands for?
a)All Window Tools
b)All Writing Tools
c)Abstract Window Toolkit
d)Abstract Writing Toolkit
View Answer
4. Which of these methods is a part of Abstract Window Toolkit (AWT) ? a)display()
b)paint()
c)drawString()
d)transient()
View Answer
5. Which of these modifiers can be used for a variable so that it can be accessed from any
thread or parts of a program? a)transient
b)volatile
c)global
d)No modifier is needed
View Answer
6. Which of these operators can be used to get run time information about an object?
a)getInfo
b)Info
c)instanceof
d)getinfoof
7. Which of these functions is called to display the output of an applet?
a) display()
b) print()
c) displayApplet()
d) PrintApplet()
10. What is the length of the application box made by this program?
import java.awt.*; import java.applet.*;
public class myapplet extends Applet {
Graphic g;
g.drawString("A Simple Applet", 20, 20);
}
a). 20
b). Default value
c). Compilation Error
d). Runtime Error
EC604A