laboratory manual - mgm's jnec€¦ · 5. write a java program to implement multiple...
TRANSCRIPT
1
Laboratory Manual
PROGRAMMING IN JAVA
For
Third Year Students CSE Dept: Computer Science & Engineering
Author JNEC, Aurangabad
2
FORWORD
It is my great pleasure to present this laboratory manual for Third year engineering students for the subject of Programming in Java
As a student, many of you may be wondering with some of the questions in your mind regarding the subject and exactly what has been tried is to answer through
this manual.
As you may be aware that MGM has already been awarded with ISO 9001:2000 certification and it is our endure to technically equip our students taking the
advantage of the procedural aspects of ISO 9001:2000 Certification.
Faculty members are also advised that covering these aspects in initial stage itself, will greatly relived them in future as much of the load will be taken care by the
enthusiasm energies of the students once they are conceptually clear.
Dr. S.D.Deshmukh Principal
3
LABORATORY MANUAL CONTENTS
This manual is intended for the Third year students of Computer Science and
Engineering in the subject of Programming in Java. This manual typically contains practical/Lab Sessions related Programming in Java covering various aspects
related the subject to enhanced understanding.
Students are advised to thoroughly go through this manual rather than only topics mentioned in the syllabus as practical aspects are the key to understanding and
conceptual visualization of theoretical aspects covered in the books.
Good Luck for your Enjoyable Laboratory Sessions
Dr. Vijaya Musande Ms. Saroj S. Date HOD, CSE Asst. Prof. ,CSE Dept.
4
MGM’s
Jawaharlal Nehru Engineering College, Aurangabad
Department of Computer Science and Engineering
Vision of CSE Department:
To develop computer engineers with necessary analytical ability and human values who can
creatively design, implement a wide spectrum of computer systems for welfare of the society.
Mission of the CSE Department:
I. Preparing graduates to work on multidisciplinary platforms associated with their
professional position both independently and in a team environment.
II. Preparing graduates for higher education and research in computer science and
engineering enabling them to develop systems for society development.
Programme Educational Objectives:
Graduates will be able to I. To analyze, design and provide optimal solution for Computer Science & Engineering
and multidisciplinary problems.
II. To pursue higher studies and research by applying knowledge of mathematics and fundamentals of computer science.
III. To exhibit professionalism, communication skills and adapt to current trends by engaging in lifelong learning.
5
Programme Outcomes (POs):
Engineering Graduates will be able to: 1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems : Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development. 8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in multidisciplinary environments.
6
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
SUBJECT INDEX
1. Write a simple Java program based on basic syntactical constructs of
java.
1. a> Operators & Expressions
1. b> Looping Statement
1. c> Decision Making Statement.
2. Write a Java program to define a class, describe its constructor &
overload its constructor.
3. Write a Java program to implement Wrapper classes and their
methods.
4. Write Java programs for multilevel and hierarchical inheritance.
5. Write a Java program to implement Multiple Inheritance.
6. Write Java programs for: a) Command line arguments. b) String class
Methods.
7. Write a Java program to create a package & use it in another program.
8. Write Java programs to demonstrate use of exception and user defined
exception.
9. Write a Java program to implement concept of multithreading.
10. Write a Java program for database connectivity using JDBC.
11. Write a Java program to demonstrate Applet.
12. Write a Java program to implement Event Handling.
7
DOs and DON’Ts in Laboratory:
1. Make entry in the Log Book as soon as you enter the Laboratory.
2. All the students should sit according to their roll numbers starting from their left
to right.
3. All the students are supposed to enter the terminal number in the log book.
4. Do not change the terminal on which you are working.
5. All the students are expected to get at least the algorithm of the program/concept
to be implemented.
6. Strictly observe the instructions given by the teacher/Lab Instructor.
Instruction for Laboratory Teachers::
1. Submission related to whatever lab work has been completed should be done
during the next lab session. The immediate arrangements for printouts related to
submission on the day of practical assignments.
2. Students should be taught for taking the printouts under the observation of lab
teacher.
3. The promptness of submission should be encouraged by way of marking and evaluation patterns that will benefit the sincere students.
8
Experiment No. 1 Title:
Write a simple Java program based on basic syntactical constructs of java.
1.a> Operators & Expressions
1.b> Looping Statement
1.c> Decision Making Statement.
Objectives:
Understand fundamentals of programming such as variables, operators, loops.
Be able to use the Java SDK environment to create, debug and run simple Java programs.
Theory:
Java provides a rich operator environment. Most of its operators can be
divided into the following four groups: arithmetic, bitwise, relational and logical. Java also defines some additional operators that handle certain special situations.
Arithmetic Operators: Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:
Operator Result
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
_= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
Table 1.1 Arithmetic Operators
9
The operands of the arithmetic operators must be of a numeric type. You cannot use them on Boolean types, but you can use them on char types, since the char type
in Java is, essentially, a subset of int. The basic arithmetic operations are addition, subtraction, multiplication, and division. All behave as you would expect for all
numeric types. The minus operator also has a unary form which negates its single operand.
The Modulus Operator: The modulus operator, %, returns the remainder of a division operation. It
can be applied to floating-point types as well as integer types. (This differs from C/C++, in which the % can only be applied to integer types.)
Arithmetic Assignment Operators: Java provides special operators that can be used to combine an arithmetic operation with an assignment. As you probably know, statements like the following are quite
common in programming: a = a + 4;
c += a * b; c %= 6;
Increment and Decrement: The ++ and the – – are Java’s increment and decrement operators. The
increment operator increases its operand by one. The decrement operator decreases its operand by one.
For example, this statement: x = x + 1; can be rewritten like this by use of the increment operator: x++; Similarly, this statement: x = x - 1; is equivalent to x--;
The Bitwise Operators:
Java defines several bitwise operators. These operators act upon the individual bits of their operands. They are summarized in the following table:
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
Table 1.2 Bitwise Operators
10
Relational Operators: The relational operators determine the relationship that one operand has to
the other. Specifically, they determine equality and ordering. The relational operators are-
Operator Result
== Equal to
!= Not equal to
> Greater than
Table 1.3 Relational Operators
Boolean Logical Operators:
The Boolean logical operators shown here operate only on boolean operands. All of the binary logical operators combine two boolean values to form
a resultant Boolean value.
Operator Result
& Logical AND
| Logical OR
! Logical unary NOT
&= AND assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
Table 1.4 Boolean Logical operators
Expressions:
An arithmetic expression is a combination of variables, constants and operators arranged as per the syntax of the language.
Algebric Expression Java Expression
a b-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
ab/c a*b/c
Table 1.5 Expressions
Evaluation of Expression: Expression are evaluated using an assignment statement of the form
variable=expression;
11
Variable is any valid java variable name. An arithmetic expression without parenthesis will be evaluated from left to right using the rules of precedence. There
are priority levels of arithmetic operators in java. High level - * / %
Low level- + _
Type Conversion:
Java allows mixing of constants and variables of different types in an expression, but has during evaluation it applies rules of type conversion. If the
operands are of two different types the lower type is automatically converted to higher type before operation proceeds.
The following changes are introduced during assignment 1. float to int causes truncation of fractional part. 2. double to float causes rounding of digits.
3. long to int causes dropping of excess higher order bits.
Decision Making Statements and Looping :
A java program is a set of statements which are generally executed sequentially in order in which they appear.
1. if statement 2. switch statement
3. Conditional Operator.
1. if statement- It is powerful decision making statement & is used to control the flow of
execution of statements. The if statement may be implemented in different forms depending on the conditions to be tested.
a. Simple if b.if..else statement
c. Nested if..else statement d. else if ladder
a. if statement : It takes following form if(test expression)
b. if..else statement: if (condition) statement1;
else statement2; Here, each statement may be a single statement or a compound statement
enclosed in curly braces (that is, a block). The condition is any expression that returns a Boolean value. The else clause is optional. The if works like this: If the
12
condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed.
2. Switch Statement: The switch statement is Java’s multiway branch statement. Here is the
general form of a switch statement:
switch (expression)
{ case value1:
// statement sequence break; case value2:
// statement sequence break;
... case valueN:
// statement sequence break;
default: // default statement sequence
}
3. Conditional Operator (?):
The java language has an unusual operator useful in making two-way decisions.
The operator of ?: and takes three operands. This operator is usually known as
conditional operator. The general form is:
Conditional expression? expression1 : expression2
Looping Statements: The process of repeatedly executing a block of statement is known as
looping. The statement in the block may be executed any number of times from zero to infinite number.
The While statement: The while loop is an entry- control loop statement. It takes the following form:
Initialization;
13
while (test condition) { body of the loop;
}
The do statement:
The do statement takes the following type do {
body of the loop; }
while (test-condition);
The for statement: The for loop is another entry controlled loop that provides concise loop control
structure. It takes following form-
for(initialization; test condition ; iteration) {
body of the loop; }
Algorithm:
Declare and define a class. Define main method.
Declare variables and initialize variables.
Implement different operators in Java for e.g. Arithmetic, logical, conditional
etc. with the help of variables.
Print all the values of variables, by using basic syntax of Java language.
Output:
14
Conclusion:
Hence we have studied and implemented basic syntactical constructs of java.
15
Experiment No. 2 Title: Write a Java program to define a class, describe its constructor & overload
its constructor.
Objectives:
Understand fundamentals of object-oriented programming in Java, including
defining classes, creating objects, invoking methods.
To understand the concept of constructor overloading.
Theory:
Java is a true object oriented language and therefore the underlying structure
of all java programs is classes. Anything we wish to represent in a java program must be encapsulated in a class that defines the state and behavior of the basic
program components known as objects. Classes create object and object use methods to communicate between them.
In Java, the data items are called fields and the functions are called methods. The java program incorporates the basic OOP concepts such as encapsulation, inheritance and polymorphism.
Defining a Class: A class is a user defined data type with template that serves to define its
properties. Once the class has been defined, we can create “variables” of that type using declarations that are similar to the basic type declarations.
The basic definition is:
class classname {
[fields declarations;] [method declarations;]
}
Fields Declaration:
Data is encapsulated in a class by placing the data fields inside the body of the class definition. These variables are called instance variables because they are
created whenever an object of the class is instantiated. For example:
class Rectangle {
int length; int width;
16
} Remember these variables are only declared and therefore no storage space has
been created in the memory. Instance variables are also known as member variables.
Methods Declaration: The methods are declared inside the body of the class but immediately after
the declaration of instance variables. The general form of method declaration is:
type methodname (parameter-list) {
Method-body; }
Method declaration has four basic parts:
The name of the method(method name)
The type of the value the method returns(type)
A list of parameters (parameter-list)
The body of the method
Creating Objects:
An object in java is block of memory that contains space to store the
instance of variables. Creating a object is also known as instantiating an object.
Objects are created using a new operator.
For example:
Rectangle rect1; //declare the object
rect1 = new Rectangle () ; //instantiate the object Both statements can be
combined into one as shown below:
Rectangle rect1 = new Rectangle ();
The method Rectangle () is the default constructor of the class. We can create any
number of objects of Rectangle. Each object has its own copy of variables of its class.
17
Accessing Class Members: As we have created objects each containing its own set of variables, we
should assign values to these variables in order to use them in program. All variables must be assigned values before they are used. We must use the
concerned object and the dot operator as shown below:
objectname.variablename = value; objectname.methodname(parameter-list);
Constructors: A constructor initializes an object immediately upon creation. It has the
same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object
is created, before the new operator completes. Constructors look a little strange because they have no return type, not even void.
This is because the implicit return type of a class’ constructor is the class type itself. It is the constructor’s job to initialize the internal state of an object so that
the code creating an instance will have a fully initialized, usable object immediately.
Default Constructor:
The default constructor automatically initializes all instance variables to zero. The default constructor is often sufficient for simple classes, but it usually
won’t do for more sophisticated ones. Once you define your own constructor, the default constructor is no longer used.
Parameterized Constructors: For example consider Box( ) constructor it is not necessary—all boxes have
the same dimensions. What is needed is a way to construct Box objects of various dimensions. The easy solution is to add parameters to the constructor. Box defines a parameterized constructor that sets the dimensions of a box as
specified by those parameters. /* Here, Box uses a parameterized constructor to initialize the dimensions of a box.
*/ class Box {
double width; double height;
double depth; // this is the parameterized constructor for Box.
Box(double w, double h, double d) {
18
width = w; height = h;
depth = d; }
// compute and return volume double volume () {
return width * height * depth; }
}
Overloading Methods:
In Java it is possible to define two or more methods within the same class
that share the same name, as long as their parameter declarations are
different.
When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading.
When an overloaded method is invoked, Java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to actually call.
Thus, overloaded methods must differ in the type and/or number of their
parameters.
Table 2.1 Difference between Method Overloading & Method Overriding
Method Overloading Method Overriding
Method Overloading is used to increase
the readability of the program
Method Overriding is used to provide
the implementation of method that is already produced by super class
It is performed within the class It occurs in two classes i.e you can only override method in sub class
In case of method overloading
parameters must be different.
In case of method overriding parameter
must be same
Overloading occurs during run time. Overriding occurs during runtime
Private &final methods can be
overloaded
Private &final methods cannot be
overridden
Overloaded methods are fast Overridden methods are slow as compared to overloaded methods
19
Overloading Constructors: In addition to overloading normal methods, you can also overload
constructor. In fact, for most real-world classes that you create, overloaded constructors will be the norm, not the exception.
Algorithm:
Create any class, describe it’s constructor, define class variables, member
functions of class.
Initialize the class variables
Also overload the constructor.
Define main class, create object of above class.
Access members of above class in main class.
Print the result.
End of the Program.
Output:
20
Snapshot 2.1 Demo of Constructor Overloading
Conclusion:
Hence we have defined a class, descried its constructor & overloaded its constructor.
21
Experiment no. 3 Title:
Write a Java program to implement Wrapper classes and their methods.
Objectives:
To understand the concept of wrapper classes
To make use of various methods of Wrapper classes.
Theory:
In java vectors cannot handle primitive data types like int, float, long, char & double. Primitive data types may be converted into object types using the wrapper
classes contained in java.lang package. Java provides type wrappers, which are classes that encapsulate a primitive type within an object.
The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.
Wrapper Classes: Character
Character is a wrapper around a char. The constructor for Character is Character (char ch)
Here, ch specifies the character that will be wrapped by the Character object being created.
To obtain the char value contained in a Character object, call charValue( ), shown here:
char charValue ( ) It returns the encapsulated character.
Boolean
Boolean is a wrapper around Boolean values. It defines these constructors: Boolean (boolean boolValue)
Boolean (String boolString) In the first version, boolValue must be either true or false. In the second version, if
boolString contains the string “true” (in uppercase or lowercase), then the new Boolean object will be true. Otherwise, it will be false.
To obtain a boolean value from a Boolean object, use booleanValue( ), shown here:
boolean booleanValue ( )
22
It returns the boolean equivalent of the invoking object.
The Numeric Type Wrappers
By far, the most commonly used type wrappers are those that represent numeric values. These are Byte, Short, Integer, Long, Float, and Double. All of
the numeric type wrappers inherit the abstract class Number. Number declares methods that return the value of an object in each of the different number formats.
These methods are shown here: byte byteValue( )
double doubleValue( ) float floatValue( )
int intValue( ) long longValue( ) short shortValue( )
For example, doubleValue ( ) returns the value of an object as a double, floatValue ( ) returns the value as a float, and so on.
Table 3.1 Converting Primitive Numbers To Object Numbers
Method Calling Conversion Action
Integer IntVal = new Integer(i); Primitive integer to integer object
Float FloatVal = new Float(f) ; Primitive Float to Float object
Table 3.2 Converting String Objects to Numeric Objects Using static method
ValueOf() Method Calling Conversion Action
IntVal = Integer.ValueOf(str); Converts String to Integer object FloatVal = Float.ValueOf(str); Converts String to Float object.
` Algorithm:
Create any class.
Initialize variables.
Define & declare main method.
Use various methods of Wrapper classes.
Print the result.
End of the program.
23
Output:
Snapshot 3.1 Demo of use of wrapper class methods
Conclusion:
Hence we have implemented wrapper class methods.
24
Assignment No. 4 Title: Write Java programs for multilevel and hierarchical inheritance.
Objectives:
Discuss various types of inheritance.
Write Java classes which add extra methods to existing Java classes using
inheritance
Write Java classes which extend existing classes by changing the behavior of
their methods using inheritance
Understand the superclass-subclass relationship
Theory:
Reusability is yet another aspect of OOP paradigm. It is always nice if we could reuse something that already exists rather than creating the same all over
again. Java supports this concept i.e. java classes can be reused in several ways. This is basically done by creating new classes, reusing the properties of existing
ones. The mechanism of deriving a new class from an old one is called inheritance. The old class is known as base class or super class or parent class and
the new one is called the sub class or child class. The inheritance allows subclasses to inherit all variables and methods of their
parent classes. Inheritance may take different forms:
Single Inheritance(only one super class)
Multiple inheritance(several super classes)
Hierarchical inheritance(one super class, many sub classes)
Multilevel inheritance(Derived from a derived class)
Java does not directly implement multiple inheritance. It is implemented by using a
secondary inheritance path in form of interfaces.
Defining a Subclass:
A subclass is defined as follows:
Class subclassname extends superclassname { Variables declaration;
methods declaration; }
25
The keyword extends specifies that the properties of the superclassname are extended to the subclassname. The sub class now contains its own variables or
methods as well those of the super class
Subclass Constructor:
A subclass constructor is used to construct the instance variables of both the subclass and the superclass. The subclass constructor uses the keyword super to
invoke the constructor method of superclass
super may only be used within a subclass constructor method.
The call to superclass constructor must appear as first statement within
the sub class constructor.
The parameters in the super call must match the order and type of the
instance variables declared in super class.
Multilevel Inheritance: A common requirement in object oriented programming
is the use of a derived class as super class. Java supports the concept and uses it
extensively in building its class library.
Fig. 4.1 Multilevel inheritance
The class A serves as a base class for derived class B which in turn serves as a base class for the derived class C. The chain ABC is known as inheritance path.
A derived class with multilevel base classes is declared as follows. class A
{ ……….. ………..
} class B extends A // First level
{ ………..
26
……….. }
class C extends B //Second level { ………..
………..
}
Hierarchical Inheritance:
Deriving many subclasses from one super class is known as Hierarchical
Inheritance. Another interesting application of inheritance is to use it as a support
to hierarchical design of a program. Many programming problems can be cast into
hierarchy where certain features of one level are shared by many other below the
level.
For example:
Below diagram shows a hierarchical classification of accounts in a commercial bank. This is possible because all the accounts possess certain common features.
Fig. 4.2 Hierarchical classification of Bank Account
Algorithm:
Multilevel Inheritance:
Define base class/ Parent class , Define members of base class
Derive child class from base class with the help of extend keyword.
Derived another class from already derived one. (Derive more classes if
required).
27
Declare and define members of classes.
Define main class, create object of class which you want to access.
You can access members of base class in derived class just by creating object of
that class.
End of the program.
Hierarchical Inheritance:
Define base class/ Parent class , Define members of base class
Derive child class from base class with the help of extend keyword.
Derived another child class from already declared parent class with the help of
extends keywords.
Derived another child class from already declared parent class with the help of
extends keywords. (create as many child classes as you want)
Declare and define members of classes.
Define main class, create object of class which you want to access.
You can access members of base class in derived class just by creating object of
that class.
End of the program.
Output:
28
Snapshot 4.1 Demo of multilevel inheritance
Snapshot 4.2 Demo of hierarchical inheritance
29
Conclusion:
Thus we have implemented programs for multilevel inheritance &
hierarchical inheritance in java.
30
Experiment No: 5
Title: Write a Java program to implement Multiple Inheritance.
Objectives:
Understand the concept of interfaces.
Learn how to use interfaces to achieve multiple inheritance.
Theory:
Interface:
Java does not support multiple inheritance but it can be achieved using
interfaces. Interfaces are syntactically similar to classes, but they lack instance
variables, and their methods are declared without any body.
Once defined, any number of classes can implement an interface. Also, one class
can implement any number of interfaces.
Through the use of the interface keyword, Java allows you to fully abstract the
interface from its implementation. Using interface, you can specify a set of
methods that can be implemented by one or more classes. The interface, itself,
does not actually define any implementation. Although they are similar to abstract
classes, interfaces have an additional capability: A class can implement more than
one interface. By contrast, a class can only inherit a single superclass (abstract or
otherwise).To implement an interface; a class must create the complete set of
methods defined by the interface. However, each class is free to determine the
details of its own implementation. By providing the interface keyword, Java
allows you to fully utilize the “one interface, multiple methods” aspect of
polymorphism.
Defining an Interface:
An interface is defined much like a class. This is the general form of an interface:
31
access interface name {
return-type method-name1(parameter-list); return-type method-name2(parameter-list);
type final-varname1 = value; type final-varname2 = value; // ...
return-type method-nameN(parameter-list); type final-varnameN = value;
}
When no access specifier is included, then default access results, and the interface is only available to other members of the package in which it is declared. When it
is declared as public, the interface can be used by any other code.
Implementing Interfaces: Once an interface has been defined, one or more classes can implement that
interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form
of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface [,interface...]] {
// class-body }
If a class implements more than one interface, the interfaces are separated with a
comma.
Interfaces Can Be Extended:
One interface can inherit another by use of the keyword extends. The syntax is the same as for inheriting classes. When a class implements an interface that inherits another interface, it must provide implementations for all methods defined
within the interface inheritance chain.
Algorithm:
Define an interface along with its variables & methods
Define a class which implements the interface methods.
32
Define base class/ Parent class , Define members of base class.
Derive child class from base class with the help of extend keyword.
Declare and define members of classes.
Define main class, create object of class which you want to access.
Print the variable values.
End of the program.
Output:
Snapshot 5.1 Demo of multiple inheritance
Conclusion:
Hence we have implemented multiple inheritance in java.
33
Experiment No: 6 Title: Write Java programs for: a) Command line arguments. b) String class
Methods.
Objectives:
Understand how to pass parameters using command line arguments.
Learn & implement various methods of String class.
Theory:
Command line Arguments: Sometimes you will want to pass information into a program when you run
it. This is accomplished by passing command-line arguments to main ( ). A command-line argument is the information that directly follows the program’s
name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy— they are stored as strings in a
String array passed to the args parameter of main( ). The first command-line argument is stored at args[0], the second at args[1], and so on. For example, the following program displays all of the command-line arguments that it is called
with:
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " +args[i]);
} }
String Class & Methods:
Strings, which are widely used in Java programming, are a sequence of
characters. In the Java programming language, strings are objects. The Java
platform provides the String class to create and manipulate strings.
Creating Strings:
The most direct way to create a string is to write:
String greeting=”Hello World”;
34
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this case, "Hello world!'.
The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of
characters, then you should use String Buffer & String Builder Classes.
String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method,
which returns the number of characters contained in the string object.
Concatenating Strings:
The String class includes a method for concatenating two strings:
String1.concat(string2);.
String Methods:
Here is the list of methods supported by String class:
Table 6.1 String Class Methods
S.N. Methods with Description
1 char charAt(int index) Returns the character at the specified index.
2 int compareTo(Object o)
Compares this String to another Object.
3 int compareTo(String anotherString) Compares two strings lexicographically.
4 int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5 String concat(String str) Concatenates the specified string to the end of this string.
6 boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
7 boolean equals(Object anObject)
Compares this string to the specified object.
8 int length() Returns the length of this string.
9 String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar
35
in this string with newChar.
10 String replaceAll(String regex, String replacement Replaces each substring of this string that matches the given regular
expression with the given replacement.
11 String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular
expression with the given replacement.
12 String substring(int beginIndex) Returns a new string that is a substring of this string.
13 String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.
14 String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
15 String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
16 String toString()
This object (which is already a string!) is itself returned.
17 String toUpperCase() Converts all of the characters in this String to upper case using the rules
of the default locale.
18 String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules
of the given Locale.
19 String trim() Returns a copy of the string, with leading and trailing whitespace
omitted.
20 static String valueOf(primitive data type x) Returns the string representation of the passed data type argument.
Algorithm:
Declare a class
Define & declare main method.
Create an object of String class & initialize it.
Use various methods on the object.
Print the result.
36
End of the program.
Output:
Snapshot 6.1 Demo of using command line arguments
37
Snapshot 6.2 Demo of using various methods of String class
Conclusion:
Thus we have studied two programs.
How to use command line arguments in java.
What are the various methods of String class & how to use them in a
program.
38
Experiment No: 7
Title: Write a Java program to create a package & use it in another program.
Objectives:
Use of built-in packages in Java
To create user defined packages & use them in another program
Learn how to extend packages.
Use of various access protections with packages.
Theory:
Packages are containers for classes that are used to keep the class name space Compartmentalized. Packages are stored in a hierarchical manner and are
explicitly imported into new class definitions. Packages are Java’s way of grouping a variety of classes and/or interfaces together.
The grouping is usually done according to functionality. By organizing our classes into packages we can achieve the following benefits:
The classes contained in the packages can be easily reused.
Packages, classes can be unique compared with classes in other
packages. That is two classes in two different packages can have same name.
They may be referred by their fully qualified name, corresponding package name & the class name.
Packages provide a way to “hide” classes thus protecting other programs
or packages from accessing classes.
Java packages are therefore classified into two types. The first category is
known as Java API packages and second is user defined packages.
Java API Packages Java API provides a large number of classes grouped into different packages
according to functionality. Most of the time we use the packages available with Java API.
39
Fig. 7.1 Frequently used API packages
Package Name Contents
java.lang Language support classes. Java compiler itself uses classes & therefore they are automatically imported. They include classes
for primitive types, String, math functions, threads & exceptions.
java.util Language utility classes such as vectors, hash tables, random numbers, date etc.
java.io Input/output support classes. They provide facilities for input &
output of data. java.awt Set of classes for implementing graphical user interface.
java.net Classes for networking. They include classes for communicating with local computers as well as internet servers.
Java.applet Classes for creating & implementing applet.
Defining a Package: To create a package is quite easy: simply include a package command as the
first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in
which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package. For example, the following statement creates
a package called MyPackage.
40
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for
any classes you declare to be part of MyPackage must be stored in a directory called MyPackage.
You can create a hierarchy of packages. To do so, simply separate each package.. The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];
Here Myclass can directly accessed by using class name or its object.
Another approach is as follows:
Accessing a Package
Java system either using a fully qualified class name or system package can be accessed either using a fully qualified class name or using a shortcut approach through the import statement.
This same approach can be used with user defined package. The general form is:
Import package1[.package2][.package3].classname;
Here package1 is the name of top level package; package2 is the name of the package that is inside the package1 & so on. We can have any number of
hierarchies. Finally the explicit classname is specified. For example:
import firstpackage.secondpackage.Myclass;
Import packagename.*;
Here packagename may denote a single package or hierarchy of packages. The star indicates that the compiler should search this entire package hierarchy when it
encounters its class name.
Algorithm:
Create a package containing various classes & methods in it.
Define one more class & it’s members.
Import the classes & members of the package in the class under development.
41
Print the result.
End of the program.
Output:
Snapshot 7.1 Demo of package in java
Conclusion:
Hence we have studied and implemented how to create packages in java & use them in another programs.
42
Experiment No: 8
Title: Write Java programs to demonstrate use of exception and user defined
exception.
Objectives:
Learning various types of exception in java.
Learn how to handle exceptions using try-catch block.
Theory:
Java Exceptions:
The term exception is shorthand for the phrase "exceptional event". It can be
defined as follows: An exception is an event that occurs during the execution of a
program that disrupts the normal flow of instructions.
An exception is a condition that is caused by a run-time error in the program.
When the Java interpreter encounters an error such as dividing an integer by zero,
it creates an exception object & throws it. If the exception object is not caught &
handled properly, the interpreter will display an error and terminate the program. If
we want the program to continue with the execution of the remaining code, then
we should try to catch the exception object thrown by error condition & then
display the appropriate message for taking corrective actions. This task is known as
exception handling. The following error handling code has to be performed:
Find the problem(Hit the exception)
Inform that an error has occurred(Throw the exception)
Receive thatch the exception)
Take corrective actions(Handle the exception)
The error handling code basically consists of two segments, one to detect
errors & to throw exceptions & other to catch & to take appropriate actions.
Some common exceptions that we must watch out for catching are listed below:
43
Table 8.1 Some Common Exceptions
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type
EnumConstantNotPresentException An attempt is made to use an undefined enumeration value.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting
on an unlocked thread
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric format.
Syntax of Exception Handling Code
The basic concept of exception handling are throwing & catching it
The try Block:
The try block can have one or more statements that could generate an exception. If
any one statement generates an exception, the remaining statements in the block
are skipped & execution jumps to the catch block that is placed next to the try
block.
The catch Block(s):
The catch block too have one or more statements that are necessary to process the
exception. The catch statement works like a method definition. Every try statement
should have at least one catch statement otherwise compilation error will occur.
44
The catch statement is passed a single parameter, which is reference to the
exception object thrown by the try block.
{
. . .
}
catch (. . .)
{
. . .
}
catch (. . .)
{
. . .
} . . .
The finally Block:
Java supports another statement known as finally statement that can be used to
handle an exception that is not caught by any previous catch statements. Finally
block can be used to handle any exception generated within a try block. It may be
added immediately after try block or after the last catch block. When a finally
block is defined, this is guaranteed to execute, regardless of whether or not in
exception is thrown.
User Defined Exception
We can create our own exception by extending a Exception class. Then we can
throw instance of this class by using throw keyword.
throw new Throwable_subclass;
For e.g.: throw new MyException();
45
Here MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught.
Algorithm:
Define a class; define variables and members of class.
Write down the code which might throw an exception at a time of program execution in try block which throws exceptions.
The user defined exception class should extend from Exception class.
Write down multiple catch statements for handling all exceptions thrown by try
block.
End of the program.
Output:
46
Snapshot 8.1 Demo of Exception handling
Snapshot 8.2 Demo of user defined exception
Conclusion:
Hence we have studied types of exception and implemented it in java.
47
Experiment No: 9 Title: Write a Java program to implement concept of multithreading.
Objectives:
Understand the concept of multithreading & thread life cycle.
Using various methods of thread class.
Creating multi-threaded program.
Theory:
Java provides built-in support for multithreaded programming. A
multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.
Process: A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it
must be a part of a process. A process remains running until all of the non-daemon threads are done executing.
Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread
is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.
Fig. 9.1 Life cycle of thread
48
Above-mentioned stages are explained here:
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.
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: A runnable thread enters the terminated state when it completes
its task or otherwise terminates.
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very much platform
dependentant.
Creating a Thread:
Java defines two ways in which this can be accomplished:
You can implement the Runnable interface.
You can extend the Thread class itself.
Create Thread by Implementing Runnable:
The easiest way to create a thread is to create a class that implements the
Runnable interface.To implement Runnable, a class needs to only implement a single method called run ( ), which is declared like this: public void run ();
49
You will define the code that constitutes the new thread inside run() method. It is important to understand that run() can call other methods, use other classes, and
declare variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of
type Thread from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread (Runnable threadOb, String threadName);
Here, threadOb is an instance of a class that implements the Runnable interface
and the name of the new thread is specified by threadName. After the new thread is created, it will not start running until you call its start( )
method, which is declared within Thread. The start ( ) method is shown here: void start ();
Create Thread by Extending Thread:
The second way to create a thread is to create a new class that extends
Thread, and then to create an instance of that class.
The extending class must override the run( ) method, which is the entry point for
the new thread. It must also call start ( ) to begin execution of the new thread.
Thread Methods:
Following is the list of important methods available in the Thread class.
SN Methods with Description
1 public void start ()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2 public void run ()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
50
6 public final void join(long millisec) The current thread invokes this method on a second thread, causing
the current thread to block until the second thread terminates or the specified number of milliseconds passes.
7 public void interrupt ()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.
The previous methods are invoked on a particular Thread object. The
following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.
SN Methods with Description
1 public static void yield ()
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.
2 public static void sleep (long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds.
3 public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
4 public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method.
5 public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application
Algorithm:
Create thread by extending thread class.
Create as many threads as you want & declare their variables & methods
Declare a class which contains main thread.
From this class, start & control the execution of other threads by creating their
objects.
Print the result.
End of the program.
51
Output:
Snapshot 9.1 Demo of threads using Runnable interface
Snapshot 9.2demo of threads using Thread Class.
52
Conclusion:
Thus we have studied how to implement the concept of multithreading in
programming.
53
Assignment no: 10
Title: Write a Java program for database connectivity using JDBC.
Objectives:
Discussing various JDBC drivers.
Connect to Database using JDBC & perform simple query.
Theory:
A file system does not work well for data storage applications for e.g. Business
applications so we required power of database. Java provide file system access
with database connectivity called JDBC.
JDBC:
JDBC is a Java API for executing SQL statements. (As a point of interest,JDBC is
a trademarked name and is not an acronym; nevertheless, JDBC is often thought of
as standing for “Java Database Connectivity”.)
The JDBC (Java Database Connectivity) API defines interfaces and classes for
writing database applications in Java by making database connections. Using
JDBC, you can send SQL, PL/SQL statements to almost any relational database.
JDBC is a Java API for executing SQL statements and supports basic SQL
functionality. It provides RDBMS access by allowing you to embed SQL inside
Java code. Because Java can run on a thin client, applets embedded in Web pages
can contain downloadable JDBC code to enable remote database access.
JDBC Architecture:
54
Fig. 10.1 JDBC Architecture
Java application calls the JDBC library. JDBC loads a driver that talks to the
database. We can change database engines without changing database code.
JDBC Basics - Java Database Connectivity Steps
Before you can create a java jdbc connection to the database, you must first import
the java.sql package. import java.sql.*; The star (*) indicates that all of the classes
in the package java.sql are to be imported.
1. Loading a database driver,
In this step of the jdbc connection process, we load the driver class by calling
Class.forName() with the Driver class name as an argument. Once loaded, the
Driver class creates an instance of itself. A client can connect to Database Server
through JDBC Driver. Since most of the Database servers support ODBC driver
therefore JDBC-ODBC Bridge driver is commonly used.
The return type of the Class.forName (String ClassName) method is “Class”.
java.lang package.
Syntax:
try { Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
} catch (Exception x){
System.out.println (“Unable to load the driver class!”);
2. Creating an oracle jdbc Connection
The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager is considered the backbone of JDBC
architecture. DriverManager class manages the JDBC drivers that are installed on
55
the system. Its getConnection() method is used to establish a connection to a
database. It uses a username, password, and a jdbc url to establish a connection to
the database and returns a connection object. A jdbc Connection represents a
session/connection with a specific database.
3. Creating a jdbc Statement object
. To execute SQL statements, you need to instantiate a Statement object from your
connection object by using the createStatement() method.
Statement statement = dbConnection.createStatement();
A statement object is used to send and execute SQL statements to a database.
4. Executing a SQL statement with the Statement object, and returning a jdbc
resultSet.
Statement interface defines methods that are used to interact with database via the
execution of SQL statements. The Statement class has three methods
executeQuery(), executeUpdate(), and execute().
JDBC driversTypes:
JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type1:JDBC-ODBC Bridge driver (Bridge) Type 2: Native-API/partly Java driver (Native)
Type 3: All Java/Net-protocol driver (Middleware) Type 4: All Java/Native-protocol driver (Pure)
Type 1 JDBC Driver: JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the
ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge
56
Type 1: JDBC-ODBC Bridge
Type 2: Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers is that Type 2 drivers convert
JDBC calls into database-specific calls i.e. this driver is specific to a particular
database. Example: Oracle will have oracle native api.
Type 2: Native api/ Partly Java Driver
Type 3 JDBC Driver: All Java/Net-protocol driver
57
Type 3 database requests are passed through the network to the middle-tier server.
The middle-tier then translates the request to the database. If the middle-tier server
can in turn use Type1, Type 2 or Type 4 drivers.
Type 3: All Java/ Net-Protocol Driver
Type 4 JDBC Driver: Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the
database server.
Type 4: Native-protocol/all-Java driver
Algorithm:
1) Create a database table.
58
2) Write java program, Import java Packages in program.
3) Define class establish ODBC connection with the help of java code.
4) Insert record in to database with the help of SQL queries.
5) Execute program, see the output on console prompt.
6) End of the program.
Output:
Snapshot 10.1 JDBC Demo
Conclusion:
Hence, we studied how to implement Java Database Connectivity.
59
Assignment no: 11
Title: Write a Java program to demonstrate Applet.
Objectives:
Understand the difference between Java applet & Application.
Learning how to write & execute simple Applets.
Theory:
Applet:
A Java applet is a small executable program attached to a Web page.
Applets require that a JVM be installed on the client computer.
A JVM (Java Virtual Machine) is a platform-specific browser add-on that
makes it possible for Web browsers to execute Java applets.
Java is a full-fledged programming language.
Applets pose less of a risk than scripts do.
Applets can’t carry viruses since they can’t write to the local machine.
Programming Java Applets will require programming skill
You can find freely available applets online at applet sites
Life Cycle of Applet:
Every Applet can be said to be any of the following state
1. New Born state
2. Running state
3. Idle state (may or may not)
4. Dead state
The following figure represents the life cycle of the Applet
60
Fig. 10.1 Life cycle of an Applet
New Born State
The life cycle of an applet is begin on that time when the applet is first
loaded into the browser and called the init() method.
The init () method is called only one time in the life cycle on an applet.
The init() method is basically called to read the PARAM tag in the html file.
The init () method retrieve the passed parameter through the PARAM tag of
html file using get Parameter() method.
All the initialization such as initialization of variables and the objects like
image, sound file are loaded in the init () method.
After the initialization of the init() method user can interact with the Applet
Running State
After initialization, this state will automatically occur by invoking the start
method of applet class which again calls the run method and which calls the
paint method.
The running state also occurs from idle state when the applet is reloaded.
This method may be called multiples time when the Applet needs to be
started or restarted.
61
For Example if the user wants to return to the Applet, in this situation the
start Method() of an Applet will be called by the web browser and the user
will be back on the applet.
In the start method user can interact within the applet.
Idle State
The idle state will make the execution of the applet to be halted temporarily.
Applet moves to this state when the currently executed applet is minimized
or when the user switches over to another page.
At this point the stop method is invoked.
From the idle state the applet can move to the running state.
The stop() method can be called multiple times in the life cycle of applet Or
should be called at least one time.
For example the stop() method is called by the web browser on that time
When the user leaves one applet to go another applet
Dead State
When the applet programs terminate, the destroy function is invoked which
makes an applet to be in dead state.
The destroy() method is called only one time in the life cycle of Applet like
init() method.
Display State
The applet is said to be in display state when the paint method is called.
This method can be used when we want to display output in the screen.
This method can be called any number of times.
62
paint() method is must in all applets when we want to draw something on the
applet window.
paint() method takes Graphics object as argument
The HTML APPLET Tag
As mentioned earlier, Sun currently recommends that the APPLET tag be
used to start an applet from both an HTML document and from an applet viewer.
An applet viewer will execute each APPLET tag that it finds in a separate window,
while web browsers will allow many applets on a single page. So far, we have been
using only a simplified form of the APPLET tag. Now it is time to take a closer
look at it.
The syntax for a fuller form of the APPLET tag is shown here. Bracketed items are
optional.
< APPLET
CODE = appletFile
WIDTH = pixels HEIGHT = pixels
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
. . .
[HTML Displayed in the absence of Java]
</APPLET>
CODE
CODE is a required attribute that gives the name of the file containing your
applet’s compiled .class file. This file is relative to the code base URL of the
applet, which is the directory that the HTML file was in or the directory indicated
by CODE.
WIDTH and HEIGHT
63
WIDTH and HEIGHT are required attributes that give the size (in pixels)
of the applet display area.
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. APPLET tag should include only a CODE or an OBJECT attribute, but
not both.
Passing Parameters to Applets
As just discussed, the APPLET tag in HTML allows you to pass parameters to
your applet.
To retrieve a parameter, use the getParameter( ) method. It returns the value of
the specified parameter in the form of a String object.
Algorithm:
1) import applet packages in program e.g. import java.awt.Image
import java.applet.*;
import java.awt.*;
2) To draw images, import the class Image also use graphics class to draw various
shapes.
3) Invoke the methods of classes with the Object.
4) Write applet code
5) Compile the Applet using java compiler & run it using appletviewer.
6) End of the program.
Output:
64
Snapshot 11.1 Compiling & executing the applet
Snapshot 11.2 Using various methods of Graphics class.
Conclusion:
Thus we have studied the Applets.
65
Assignment no. 12
Title: Write a Java program to implement Event Handling.
Objectives:
Understanding delegation event model.
Handling various key events.
Handling various mouse events. Theory:
Event handling is fundamental to Java programming because it is integral to
the creation of applets and other types of GUI-based programs.Events are supported by a number of packages, including java.util, java.awt, and java.awt.event.
Most events to which your program will respond are generated when the user interacts with a GUI-based program. There are several types of events, including
those generated by the mouse, the keyboard, and various GUI controls, such as a push button, scroll bar, or check box.
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. 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.
Events: In the delegation model, an event is an object that describes a state change in a
source. Events may also occur that are not directly caused by interactions with a user
interface.
Event Sources: A source is an object that generates an event. This occurs when the internal state of
that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive
notifications about a specific type of event. Each type of event has its own registration method. Here is the general form:
66
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener
Event Listeners: A listener is an object that is notified when an event occurs. It has two major
requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement
methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For example, the MouseMotionListener interface defines two methods to receive
notifications when the mouse is dragged or moved.
Main Event Classes in java.awt.event:
KeyEvent: Generated when input is received from the keyboard. MouseEvent: Generated when the mouse is dragged, moved, clicked, also
pressed, or released; also generated when the mouse enters or exits a component
MouseWheelEvent Generated when the mouse wheel is moved.
The KeyEvent Class: A KeyEvent is generated when keyboard input occurs. There are three types of
key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED. The first two events are generated when
any key is pressed or released. The last event occurs only when a character is generated. Remember, not all keypresses result in characters. For example,
pressing SHIFT does not generate a character. There are many other integer constants that are defined by KeyEvent. For example, VK_0 through VK_9 and
VK_A through VK_Z define the ASCII equivalents of the numbers and letters. Here are some others:
VK_ALT VK_DOWN VK_LEFT VK_RIGHT VK_CANCEL VK_ENTER VK_PAGE_DOWN VK_SHIFT
VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt. KeyEvent is a subclass of InputEvent.
The MouseEvent Class: There are eight types of mouse events. The MouseEvent class defines the
following integer constants that can be used to identify them:
67
MOUSE_CLICKED The user clicked the mouse. MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component. MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved. MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MouseEvent is a subclass of InputEvent. Here is one of its constructors:
MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup)
Here, src is a reference to the component that generated the event. The type of the
event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed
when a mouse event occurred. The coordinates of the mouse are passed in x and y. Two commonly used methods
in this class are getX( ) and getY( ). These return the X and Y coordinates of the mouse within the component when the event occurred.
Algorithm:
1) Import java packages, which supports event handling e.g. event, awt.
2) Write java program by implementing different Listeners
3) Handle different events by creating objects of classes.
4) Access different controls through objects.
5) End of the program.
Output:
Snapshot 12.1 Compiling & executing key events
68
Snapshot 12.2 Output of key event handling
Snapshot 12.3 compiling & executing mouse events
Snapshot 12.4 Output of mouse events handling
Conclusion:
Thus we have studied how to handle various key & mouse events.