SlideShare a Scribd company logo
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
1
Unit I – Object Oriented Programming – Fundamentals
1.1 Review of OOP
1.2 Objects and Classes in Java
1.3 Defining Classes
1.4 Methods
1.5 Access Specifiers
1.6 Static Members
1.7 Constructors
1.8 Finalize method
1.9 Arrays
1.10 Strings
1.11 Package
1.12 JavaDoc Comments
Programming Paradigms:
A programming paradigm is a general approach, orientation, or philosophy of programming
that can be used when implementing a program. One paradigm may be generally better for certain
kinds of problems than other paradigms are for those problems, and a paradigm may be better for
certain kinds of problems than for other kinds of problems.
Four most common paradigms:
1. imperative (or procedural) - C
2. applicative (or functional) - ML
3. rule-based (or logic) - prolog
4. object oriented – small talk, C++, Java
1.1 Review of OOP
 Process oriented model:
 In Process oriented model code is written around what is happening.
 This approach characterizes a program as a series of linear steps i.e. the code.
 It is the code acting on data.
 In a conventional application we typically:
o decompose it into a series of functions,
o define data structures that those functions act upon
o there is no relationship between the two other than the functions act on the data
Steps in process oriented approach:
1. Procedure is determined i.e. Algorithm
2. Appropriate ways to store data i.e. Data Structure.
Algorithm + Data Structure = Programs
Disadvantage of process oriented model:
 As program grows larger the complexity increases.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
2
 Object Oriented Programming:
It organizes program around its data i.e. Objects and set of well defined interface to that data.
Object oriented programming is characterized as data controlling access to code.
• How is OOP different to conventional programming?
– Decompose the application into abstract data types by identifying some useful
entities/abstractions
– An abstract type is made up of a series of behaviours and the data that those
behaviours use.
Steps in Object Oriented Programming:
1. Puts the data first.
2. Looks for algorithm to operate on the data.
Benefits of OO programming
a. Easier to understand (closer to how we view the world)
b. Easier to maintain (localised changes)
c. Modular (classes and objects)
d. Good level of code reuse (aggregation and inheritance)
• Understanding OOP is fundamental to writing good Java applications
– Improves design of your code
– Improves understanding of the Java APIs
• There are several concepts underlying OOP:
 Object
 Abstract Types (Classes)
 Encapsulation (or Information Hiding)
 Aggregation
 Inheritance
 Polymorphism
 Dynamic binding
 Message passing
Object
 Objects are basic runtime entity in an object oriented system. It is a real world entity & an
bundle of related state and behaviour. Object is an instance of Class, We can access Class
Member using its Object.
e.g-Person, Place ,Book etc
Object in java are created using the new operator.
Eg:
Rectangle rec1; // Declare the object
Rec1 = new Rectangle //instantiate the object
The above statements can also be combined as follows
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
3
 Rectangle rec1 = new Rectangle;
Abstract Data Types
• Identifying abstract types is part of the modelling/design process
– The types that are useful to model may vary according to the individual application
– For example a payroll system might need to know about Departments, Employees,
Managers, Salaries, etc
– An E-Commerce application may need to know about Users, Shopping Carts,
Products, etc
• Object-oriented languages provide a way to define abstract data types, and then create
objects from them
– It‘s a template (or ‗cookie cutter‘) from which we can create new objects
– For example, a Car class might have attributes of speed, colour, and behaviours of
accelerate, brake, etc
– An individual Car object will have the same behaviours but its own values assigned
to the attributes (e.g. 30mph, Red, etc)
Classes
 A class is a prototype from which objects are created. The entire set of data and code of an
object can be made a user defined data-type with the help of a Class. In fact objects are
variables of the type class.
e.g-object ORANGE belongs to Class FRUIT
 Defining the Class:
A class is defined by the user is data type with the template that helps in defining the properties.
Once the class type has been defined we can create the variables of that type using declarations
that are similar to the basic type declarations. In java instances of the classes which are actual
objects
Eg:
classclassname [extends superclassname]
{
[fields declarations;]
[methods declaration;]
}
 Field Declaration
Data is encapsulated in a class by placing data fields inside the body of the class definition. These
variables are called as instance variables.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
4
Class Rectangle
{
int length;
int width;
}
 Method Declaration
A Class with only data fields has no life, we must add methods for manipulating the data contained
in the class. Methods are declared inside the class immediate after the instance variables
declaration.
Eg:
class Rectangle
{
int length; //instance variables
int width;
Void getData(int x, int y) // Method Declartion {
Length =x;
Width = y;
} }
Encapsulation
• The data (state) of an object is private – it cannot be accessed directly.
• The state can only be changed through its behaviour, otherwise known as its public interface
or contract
• This is called encapsulation
 Main benefit of encapsulation
o Internal state and processes can be changed independently of the public interface
o Limits the amount of large-scale changes required to a system
 Example: Automatic transmission on a car.
 It encapsulates hundreds of bit of information about engine such as how much
acceleration is given, pitch of surface, position of shift lever.
 All the information about engine is encapsulated.
 The method of affecting this complex encapsulation is by moving the gear shift lever.
 We can affect transmission only by using gear shift lever and can‘t affect transmission
by using the turn signal or windshield wiper.
 Thus gear shift lever is a well defined interface to the transmission.
 What occurs inside the transmission does not affect the objects outside the transmission.
o For example, shifting gear does not turn on the head lights.
Private Data
Public Interface
"The Doughnut Diagram"
Showing that an object has
private state and public
behaviour. State can only be
changed by invoking some
behaviour
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
5
Aggregation
• Aggregation is the ability to create new classes out of existing classes
– Treating them as building blocks or components
• Aggregation allows reuse of existing code
– ―Holy Grail‖ of software engineering
• Two forms of aggregation
• Whole-Part relationships
– Car is made of Engine, Chassis, Wheels
• Containment relationships
– A Shopping Cart contains several Products
– A List contains several Items
Inheritance
• Inheritance is the ability to define a new class in terms of an existing class
– The existing class is the parent, base or superclass
– The new class is the child, derived or subclass
• The child class inherits all of the attributes and behaviour of its parent class
– It can then add new attributes or behaviour
– Or even alter the implementation of existing behaviour
• Inheritance is therefore another form of code reuse
The bird 'robin ' is a part of the class 'flying bird' which is again a part of the class 'bird'.
Polymorphism
 Polymorphism means the ability to take more than one form.
 Subclasses of a class can define their own unique behaviors and yet share some of the same
functionality of the parent class.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
6
Dynamic Binding
 Binding refers to the linking of a procedure call to the code to be executed.
 Dynamic binding means that the code associated with a given procedure call is not known
until the time of the call at run-time.
Message Communication
 Objects communicate with one another by sending and receiving information. A message
for an object is a request for execution of a procedure. Message passing involves specifying
the name of the object, the name of the function (message) and the information to be sent.
Basics of Java
Java is a programming language and a platform.
Application of Java
According to sun Microsystems, 3 billion devices run java.
1. Desktop application such as acrobat reader, media player, antivirus,etc
2. Web application such as irctc.co.in,etc
3. Enterprise application such as banking applications
4. Mobile
5. Embedded systems
6. Smart card
7. Games and so on
Types of Java
Basically Java Applications can be 4 types
1. Standalone application(like Microsoft office) Technology: core java
2. Client Server application(like yahoo chat) Technology: core java and web technology
3. Web Application(like orkut, facebook etc) Technology: Servlet, JSP, Struts, Hibernate etc.
Any web server is required to run this application like TOMCAT
4. Distributed Application (like banking application) Technology: EJB application
History of java
 James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language in June
1991.
 Originally designed for small, embedded systems in electronic appliances like setup box.
 Initially called Oak, and was developed as a part of Green project.
 In 1995, Oak was renamed as Java.
Characteristics of Java
 Java is simple
 Java is object-oriented
 Java is distributed
 Java is interpreted
 Java is robust
 Java is secure
 Java is architecture-neutral
 Java is portable
 Java‘s performance
 Java is multithreaded
 Java is dynamic
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
7
JDK Versions
 JDK 1.02 (1995)
 JDK 1.1 (1996)
 Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)
 Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)
 Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)
 Java 2 SDK v 1.5 (a.k.a JDK 1.4, 2004)
 Java 2 SDK v 1.6 (a.k.a JDK 1.4, 2006)
 Java 2 SDK v 1.7 (a.k.a JDK 1.4, 2011)
JDK Editions
 Java Standard Edition (J2SE)
o J2SE can be used to develop client-side standalone applications or applets.
 Java Enterprise Edition (J2EE)
o J2EE can be used to develop server-side applications such as Java servlets and Java
ServerPages.
 Java Micro Edition (J2ME).
o J2ME can be used to develop applications for mobile devices such as cell phones.
Java IDE Tools
 Forte by Sun MicroSystems
 Borland JBuilder
 Microsoft Visual J++
 WebGain Cafe
 IBM Visual Age for Java
Basic Structure
Simple Example
1. Create a Java program using notepad and save with extension .java.
2. Install the JDK1.6 or higher, if not , download and install it
3. Set path of the bin directory under jdk.
4. Compile: javac filename.java
5. Run: java filename
First Java Program:
Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
8
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
Lets look at how to save the file, compile and run the program. Please follow the steps given
below:
 Open notepad and add the code as above.
 Save the file as : MyFirstJavaProgram.java.
 Open a command prompt window and go o the directory where you saved the class. Assume
its C:.
 Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no
errors in your code the command prompt will take you to the next line.( Assumption : The
path variable is set).
 Now type ' java MyFirstJavaProgram ' to run your program.
 You will be able to see ' Hello World ' printed on the window.
C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram
Hello World
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have
different meaning in Java.
 Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter should be
in Upper Case.
Example class MyFirstJavaClass
 Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter
should be in Upper Case.
Example public void myMethodName()
 Program File Name - Name of the program file should exactly match the class name.
When saving the file you should save it using the class name (Remember java is case
sensitive) and append '.java' to the end of the name. (if the file name and the class name do
not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
 public static void main(String args[]) - java program processing starts from the main()
method which is a mandatory part of every java program..
Java Basics
Java Identifiers:
All java components require names. Names used for classes, variables and methods are called
identifiers.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
9
In java there are several points to remember about identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an
underscore (_).
 After the first character identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers:age, $salary, _value, __1_value
 Examples of illegal identifiers : 123abc, -salary
Java Modifiers:
Like other languages it is possible to modify classes, methods etc by using modifiers. There are
two categories of modifiers.
 Access Modifiers : default(friend), public , protected, private
 Non-access Modifiers : final, abstract, strictfp
Java Variables:
We would see following type of variables in Java:
 Local Variables
 Class Variables (Static Variables)
 Instance Variables (Non static variables)
Java Keywords:
The following list shows the reserved words in Java. These reserved words may not be used as
constant or variable or any other identifier names.
1.2 Object and Classes in Java
The class is at the core of Java. It is the logical construct upon which the entire Java
language is built because it defines the shape and nature of an object. As such, the class forms the
basis for object-oriented programming in Java. The entire set of data and code of an object can be
made of a user defined data type with the help of a class. Thus, a class is a template for an object,
and an object is an instance of a class.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
10
1.3 The General Form of a Class
The class contains data and the code that operates on that data. A class is declared by use of
the class keyword. The data, or variables, defined within a class are called instance variables. The
code is contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. The general form of a class definition is shown here:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list){ //
body of method
}
type methodname2(parameter-list) { //
body of method
}
// ...
type methodnameN(parameter-list) { //
body of method
}
}
Here is a class called Box that defines three instance variables: width, height, and depth.
Currently, Box does not contain any methods (but some will be added soon).
class Box
{
double width;
double height;
double depth;
}
Instantiating a class
Class declaration only creates a template; it does not create an actual object. To create a Box
object, you will use a statement like the following:
Box mybox = new Box(); // create a Box object called mybox
 The new operator allocates space for the new object, calls a class constructor and returns a
reference to the object.
 It should be noted that the class and its constructor have the same name.
After this statement executes, mybox will be an instance of Box. Each time you create an
instance of a class, you are creating an object that contains its own copy of each instance variable
defined by the class. Thus, every Box object will contain its own copies of the instance variables
width, height, and depth. To access these variables, you will use the dot (.) operator. The dot
operator links the name of the object with the name of an instance variable. For example, to assign
the width variable of mybox the value 100, you would use the following statement:
mybox.width = 100;
This statement tells the compiler to assign the copy of width that is contained within the
mybox object the value of 100.
1.4 Methods
 A class with only data fields has no life. Objects created by such a class cannot respond to
any messages.
 Methods are declared inside the body of the class but immediately after the declaration of
data fields.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
11
 The general form of a method declaration is:
modifier returnValueType methodName(list of parameters)
{
// Method body;
}
 A method definition consists of a method header and a method body. Here are all the parts
of a method:
 Modifiers: The modifier, which is optional, tells the compiler how to call the method. This
defines the access type of the method.
 Return Type: A method may return a value. The returnValueType is the data type of the
value the method returns. Some methods perform the desired operations without returning a
value. In this case, the returnValueType is the keyword void.
 Method Name: This is the actual name of the method. The method name and the parameter
list together constitute the method signature.
 Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a method. Parameters are
optional; that is, a method may contain no parameters.
 Method Body: The method body contains a collection of statements that define what the
method does.
Creating a object:
 Declare the Circle class, have created a new data type – Data Abstraction
 Can define variables (objects) of that type:
Circle aCircle;
Circle bCircle;
 Objects are created dynamically using the new keyword.
 aCircle and bCircle refer to Circle objects
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Accessing Object/Circle Data
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
12
Example
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
program
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
1.5 Access Modifiers :
 An access modifier is a Java keyword that indicates how a field or method can be
accessed. Variables and methods in Java have access restrictions, described by the following
access modifiers:
 private:
• Used for most instance variables
• private variables and methods are accessible only to methods of the class in which they are
declared
• Declaring instance variables private is known as data hiding
• Example: private int x;
 default (friend/ this means no modifier is used):
• Access is limited to the package in which the member is declared
• Example: int x;
 protected:
• Access is limited to the package in which the member is declared, as well as all subclasses
of its class
• Example: protected void setName() { . . . }
 public:
• The member is accessible to all classes in all packages.
• Declaring public methods is knows as defining the class‘ public interface.
• Example: public String getName() { . . . }
Java Access Specifiers :
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
13
• Access specifiers indicates which members of a class can be used by other classes
• We use of public, protected and private for access specifications
• Package access is used when there is no access specifier
• Package access means that all classes in the same package can access the member
• But for all other classes the member is private
1.6 Static
Variables-class variable(static),instance variable(class member variable) and local variable(
variable in method definition)
The static keyword can be used in 3 scenarios
 static variables
 static methods
 static blocks of code.
static (Class) variable
 It is a variable which belongs to the class and not to object(instance)
 Static variables are initialized only once , at the start of the execution . These variables will
be initialized first, before the initialization of any instance variables
 A single copy to be shared by all instances of the class
 A static variable can be accessed directly by the class name and doesn‘t need any object
Syntax : <class-name>.<variable-name>
 Syntax:
accessSpecifier static dataType variableName;
 Example:
public static int countAutos = 0;
static method (Class Method)
 It is a method which belongs to the class and not to the object(instance)
 A static method can access only static data. It cannot access non-static data (instance
variables)
 A static method can call only other static methods and can not call a non-static method
from it.
 A static method can be accessed directly by the class name and doesn‘t need any object
Syntax : <class-name>.<method-name>
 A static method cannot refer to ―this‖ or ―super‖ keywords in anyway
Example
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
Student(){
//Constructor incrementing static variable b
b++;
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
14
}
public void showData(){
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
//public static void increment(){
//a++;
//}
}
class Demo{
public static void main(String args[]){
Student s1 = new Student();
s1.showData();
Student s2 = new Student();
s2.showData();
//Student.b++;
//s1.showData();
}
}
static block
 The static block, is a block of statement inside a Java class that will be executed when a
class is first loaded in to the JVM
class Test{
static {
//Code goes here
}
}
A static block helps to initialize the static data members, just like constructors help to
initialize instance members
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
15
1.7 Constructor
 A constructor is a special method that is used to initialize a newly created object and
is called just after the memory is allocated for the object .It can be used to initialize the
objects ,to required ,or default values at the time of object creation. It is not mandatory
for the coder to write a constructor for the class. If no user defined constructor is provided
for a class, compiler initializes member variables to its default values.
 numeric data types are set to 0
 char data types are set to null character(‗‘)
 reference variables are set to null
 The constructor is automatically called immediately after the object is created, before the
new operator completes.
Box mybox1 = new Box();
Features of constructor
 A constructor has the same name as the class.
 A class can have more than one constructor.
 A constructor may take zero, one, or more parameters.
 A constructor has no return value.
 A constructor is always called with the new operator.
Types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
 Below is an example of a cube class containing 2 constructors. (one default and one
parameterized constructor).
public class Cube1 {
int length; int breadth; int height;
public int getVolume() {
return (length * breadth * height); }
Cube1()
{ length = 10; breadth = 10; height = 10; }
Cube1(int l, int b, int h)
{ length = l; breadth = b; height = h; }
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
16
cubeObj2 = new Cube1(10, 20, 30); System.out.println("Volume of Cube1 is : " +
cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume()); } }
Copy Constructor in Java
 Like C++, Java also supports copy constructor. But, unlike C++, Java doesn‘t create a
default copy constructor if you don‘t write your own.
// filename: Main.java
class Complex {
private double re, im;
// A normal parametrized constructor
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
// Overriding the toString of Object class
@Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
// Following involves a copy constructor call
Complex c2 = new Complex(c1);
// Note that following doesn't involve a copy constructor call as
// non-primitive variables are just references.
Complex c3 = c2;
System.out.println(c2); // toString() of c2 is called here
}}
Output:
Copy constructor called
(10.0 + 15.0i)
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
17
a) “this” Keyword
this can be used inside any method to refer to the current object. this keyword has two
meanings:
 to denote a reference to the implicit parameter
 to call another constructor of the same class.
// A redundant use of this. Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
b) Garbage Collection
 The purpose of garbage collection is to identify and discard objects that are no longer
needed by a program so that their resources can be reclaimed and reused.
 A Java object is subject to garbage collection when it becomes unreachable to the program
in which it is used.
1.8 Finalize method
 Finalizer methods are like the opposite of constructor methods; whereas a constructor
method is used to initialize an object, finalizer methods are called just before the object is
garbage collected and its memory reclaimed.
 To create a finalizer method, include a method with the following signature in your class
definition:
void finalize()
{
...
}
 Inside the body of that finalize() method, include any cleaning up you want to do for that
object.
protected void finalize() throws Throwable {
try{
System.out.println("Finalize of Sub Class");
//release resources, perform cleanup ;
}catch(Throwable t){
throw t;
}finally{
System.out.println("Calling finalize of Super Class");
super.finalize();
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
18
1.9 Arrays
 Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
 Declaring Array Variables:
dataType[] arrayRefVar; // preferred way.
Or
dataType arrayRefVar[]; // works but not preferred way.
Creating Arrays:
dataType[] arrayRefVar = new dataType[arraySize];
The above statement does two things:
1. It creates an array using new dataType[arraySize];
2. It assigns the reference of the newly created array to the variable arrayRefVar.
 Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Multidimensional Arrays
 In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect,
look and act like regular multidimensional arrays.
int twoD[][] = new int[4][5];
The Arrays Class
 The java.util.Arrays class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements. These methods are overloaded for all primitive
types.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
19
1.10 String objects
The Java String class (java.lang.String) is a class of object that represents a character array
of arbitrary length. While this external class can be used to handle string objects, Java integrates
internal, built-in strings into the language.
An important attribute of the String class is that once a string object is constructed, its value
cannot change (note that it is the value of an object that cannot change, not that of a string variable,
which is just a reference to a string object). All String data members are private, and no string
method modifies the string‘s value.
String Methods
Although a string represents an array, standard array syntax cannot be used to inquire into it.
These are detailed in the below Table.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
20
String Comparison
String comparison methods listed in below Table.
String Searching
The String class also provides methods that search a string for the occurrence of a single
character or substring. These return the index of the matching substring or character if found, or - 1
if not found.

int indexOf (char ch)

int indexOf (char ch, int begin)

int lastIndexOf (char ch)

int lastIndexOf (char ch, int fromIndex)

int indexOf (String str)

int indexOf (String str, int begin)

int lastIndexOf (String str)

int lastIndexOf (String str, int fromIndex)
The following example shows the usage of these functions: if
(s1.indexOf (‘:‘) >= 0)
{
…
}
String suffix =
s1.substring (s1.lastIndexOf (‘.‘));
int spaceCount = 0;
int index = s1.indexOf (‘ ‘);
while (index >= 0)
{
++spaceCount;
index = s1.indexOf (‘ ‘, index + 1);
}
int index = s1.indexOf (―that‖);
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
21
String Concatenation
The String class provides a method for concatenating two strings:
String concat (String otherString)
The + and += String operators are more commonly used: The Java compiler recognizes the + and
+= operators as String operators. For each + expression, the compiler generates calls to methods
that carry out the concatentation. For each += expression, the compiler generates calls to methods
that carry out the concatenation and assignment.
Converting Objects To Strings
The String + operator accepts a non-string operand, provided the other operand is a string.
The action of the + operator on non-string operands is to convert the non-string to a string, then to
do the concatenation. Operands of native types are converted to string by formatting their values.
Operands of class types are converted to a string by the method toString() that is defined for all
classes. Any object or value can be converted to a string by explicitly using one of the static
valueOf() methods defined in class String:
String str = String.valueOf (obj);
If the argument to valueOf() is of class type, then valueOf() calls that object‘s toString() method.
Any class can define its own toString() method, or just rely on the default. The output produced by
toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text
representation of the object, nor is it meant to be parsed. These conversion rules also apply to the
right-hand side of the String += operator.
Converting Strings To Numbers
Methods from the various wrapper classes, such as Integer and Double, can be used to
convert numerical strings to numbers.
The wrapper classes contain static methods such as parseInt() which convert a string to its
own internal data type.
1.11 Packages
 Provides a mechanism for grouping a variety of classes and / or interfaces together.
 Grouping is based on functionality.
Benefits:
 The classes contained in the packages of other programs can be reused.
 In packages, classes can be unique compared with classes in other packages.
 Packages provides a way to hide classes.
 Two types of packages: 1. Java API packages 2. User defined packages
Java API Packages:
 A large number of classes grouped into different packages based on functionality.
Examples:
Package Categories of Classes
java.lang Basic functionality common to many programs, such as the String
class and Math class
java.awt Graphics classes for drawing and using colors
javax.swing User-interface components
java.text Classes for formatting numeric output
java.util The Scanner class and other miscellaneous classes
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
22
Included in the Java SDK are more than 2,000 classes that can be used to add functionality to
our programs
 APIs for Java classes are published on Sun Microsystems Web site:
www.java.sun.com
Accessing Classes in a Package
1. Fully Qualified class name:
Example:java.awt.Color
2. import packagename.classname;
Example: import java.awt.Color;
or
import packagename.*;
Example: import java.awt.*;
 Import statement must appear at the top of the file, before any class declaration.
Creating Your Own Package
1. Declare the package at the beginning of a file using the form
package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
Example:
package firstPackage;
Public class FirstClass
{
//Body of the class
}
Example1-Package
package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(―Class A‖);
}}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
23
Source file – ClassA.java
Subdirectory-p1
ClassA.Java and ClassA.class->p1
import p1.*;
Class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA();
obA.displayA();
}
}
Source file-testclass.java
testclass.java and testclass.class->in a directory of which p1 is subdirectory.
Creating Packages
 Consider the following declaration:
package firstPackage.secondPackage;
This package is stored in subdirectory named firstPackage.secondPackage.
 A java package can contain more than one class definitions that can be declared as public.
 Only one of the classes may be declared public and that class name with .java extension is
the source file name.
Example2-Package
package p2;
public class ClassB
{
protected int m =10;
public void displayB()
{
System.out.println(―Class B‖);
System.out.println(―m= ―+m);
}
}
import p1.*;
import p2.*;
class PackageTest2
{
public static void main(String str[])
{
ClassA obA=new ClassA();
Classb obB=new ClassB();
obA.displayA();
obB.displayB();
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
24
Example 3- Package
import p2.ClassB;
class ClassC extends ClassB
{
int n=20;
void displayC()
{
System.out.println(―Class C‖);
System.out.println(―m= ―+m);
System.out.println(―n= ―+n);
}
}
class PackageTest3
{
public static void main(String args[])
{
ClassC obC = new ClassC();
obC.displayB();
obC.displayC();
}
}
Default Package
 If a source file does not begin with the package statement, the classes contained in the
source file reside in the default package
 The java compiler automatically looks in the default package to find classes.
Finding Packages
 Two ways:
1.By default, java runtime system uses current directory as starting point and search all the
subdirectories for the package.
2.Specify a directory path using CLASSPATH environmental variable.
CLASSPATH Environment Variable
 The compiler and runtime interpreter know how to find standard packages such as java.lang
and java.util
 The CLASSPATH environment variable is used to direct the compiler and interpreter to
where programmer defined imported packages can be found
 The CLASSPATH environment variable is an ordered list of directories and files
1.12 Documentation Comments
The Java SDK contains a very useful tool, called javadoc, that generates HTML
documentation from your source files. If you add comments that start with the special delimiter /**
to your source code, you too can produce professional-looking documentation easily. This is a very
nice scheme because it lets you keep your code and documentation in one place. If you put your
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
25
documentation into a separate file, then you probably know that the code and comments tend to
diverge over time. But since the documentation comments are in the same file as the source code, it
is an easy matter to update both and run javadoc again.
How to Insert Comments
The javadoc utility extracts information for the following items:
• Packages
• Public classes and interfaces
• Public and protected methods
• Public and protected fields
You can (and should) supply a comment for each of these features. Each comment is placed
immediately above the feature it describes. A comment starts with a /** and ends with a */. Each
/** . . . */ documentation comment contains free-form text followed by tags. A tag starts with an @,
such as @author or @param. The first sentence of the free-form text should be a summary
statement. The javadoc utility automatically generates summary pages that extract these sentences.
In the free-form text, you can use HTML modifiers such as <em>...</em> for emphasis,
<code>...</code> for a monospaced ―typewriter‖ font, <strong>...</strong> for strong emphasis,
and even <img ...> to include an image. You should, however, stay away from heading <h1> or
rules <hr> since they can interfere with the formatting of the document.
Class Comments
The class comment must be placed after any import statements, directly before the class
definition. Here is an example of a class comment:
/**
A <code>Card</code> object represents a playing card, such as "Queen of Hearts". A
card has a suit (Diamond, Heart, Spade or Club) and a value (1 = Ace, 2 . . . 10, 11 =
Jack, 12 = Queen, 13 = King).
*/
public class Card
{
. . .
}
Method Comments
Each method comment must immediately precede the method that it describes. In addition
to the general-purpose tags, you can use the following tags:
@param variable description
This tag adds an entry to the ―parameters‖ section of the current method. The description can span
multiple lines and can use HTML tags. All @param tags for one method must be kept together.
@return description
This tag adds a ―returns‖ section to the current method. The description can span multiple lines and
can use HTML tags.
@throws class description
Field Comments
You only need to document public fields—generally that means static constants. For
example,
/**
The "Hearts" card suit */
public static final int HEARTS = 1;
General Comments
The following tags can be used in class documentation comments.
@author name
This tag makes an ―author‖ entry. You can have multiple @author tags, one for each author.
@version text
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
26
How to Extract Comments
Here, docDirectory is the name of the directory where you want the HTML files to go. Follow these
steps:
1. Change to the directory that contains the source files you want to document. If you have
nested packages to document, such as com.horstmann.corejava, you must be in the directory
that contains the subdirectory com. (This is the directory that contains the overview.html
file, if you supplied one.)
2. Run the command javadoc -d docDirectory nameOfPackage for a single package. Or run
javadoc -d docDirectory nameOfPackage1 nameOfPackage2... to document multiple
packages. If your files are in the default package, then run javadoc -d docDirectory *.java
instead. If you omit the -d docDirectory option, then the HTML files are extracted to the
current directory. That can get messy, and we don't recommend it. The javadoc program can
be fine-tuned by numerous command-line options. For example, you can use the - author
and -version options to include the @author and @version tags in the documentation. (By
default, they are omitted.)
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
1
Unit II – Object Oriented Programming – Inheritance
2.1 Inheritance
2.2 class hierarchy
2.3 polymorphism
2.4 dynamic binding
2.5 final keyword
2.6 abstract classes
2.7 interfaces
2.8 inner classes
2.9 the Object class
2.10 object cloning
2.11 proxies
2.12 Reflection
2.1Inheritance
 Inheritance is a process of making a new class that derives from an existing class. The existing class
is called the superclass, base class, or parent class. The new class is called the subclass, derived
class, or child class.
 Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables
and methods defined by the superclass and add its own, unique elements.
 Subclasses of a class can define their own unique behaviors and yet share some of the same
functionality of the parent class.
The following kinds of inheritance are there in java.
 Simple Inheritance
 Multilevel Inheritance
Simple Inheritance
When a subclass is derived simply from it's parent class then this mechanism is known as simple
inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single
inheritance or one level inheritance.
class A
{
int x;
int y;
int get(int p, int q)
{
x=p; y=q; return(0);
}
void Show()
{
System.out.println(x);
}
}
class B extends A
{
public static void main(String args[]){
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
2
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}
Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class
then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child
class for it's parent class and this parent class works as the child class for it's just above ( parent )
class. Multilevel inheritance can go up to any number of level.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}}
Multiple Inheritance
 The mechanism of inheriting the features of more than one base class into a single class is known as
multiple inheritance.
 Java does not support multiple inheritance but the multiple inheritance can be achieved by using the
interface.
 In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than
one interfaces in a class.
Member Access and Inheritance
A class member that has been declared as private will remain private to its class. It is not accessible by any
code outside its class, including subclasses.
Super keyword
Super is a special keyword that directs the compiler to invoke the super class method. super has two general
forms.
 to invoke a superclass constructor.
 to invoke a superclass members(variables &methods).
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
3
Invoke superclass constructor:
A subclass can call a constructor method defined by its superclass by use of the following form of super:
super(parameter-list);
 Here, parameter-list specifies any parameters needed by the constructor in the superclass.
 super( ) must always be the first statement executed inside a subclass constructor.
 The compiler implicitly calls the base class’s no-parameter constructor or default constructor.
 If the superclass has parameterized constructor and the subclass constructor does not call superclass
constructor explicitly, then the Java compiler reports an error.
Invoke superclass members:
Super always refers to the superclass of the subclass in which it is used. This usage has the following
general form:
super.member;
 Here, member can be either a method or an instance variable. This second form of super is most
applicable to situations in which member names of a subclass hide members by the same name in the
superclass.
 If a parent class contains a finalize() method, it must be called explicitly by the derived class’s
finalize() method.
super.finalize();
When Constructors are Called
Constructors are called in order of derivation, from superclass to subclass. Because a superclass has no
knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to
any initialization performed by the subclass. Therefore, it must be executed first.
Advantages
 Reusability -- facility to use public methods of base class without rewriting the same
 Extensibility -- extending the base class logic as per business logic of the derived class
 Data hiding -- base class can decide to keep some data private so that it cannot be altered by the
derived class
 Overriding--With inheritance, we will be able to override the methods of the base class so that
meaningful implementation of the base class method can be designed in the derived class.
Disadvantages:-
 Both classes (super and subclasses) are tightly-coupled.
 As they are tightly coupled (binded each other strongly with extends keyword), they cannot work
independently of each other.
 Changing the code in super class method also affects the subclass functionality.
 If super class method is deleted, the code may not work as subclass may call the super class method
with super keyword. Now subclass method behaves independently.
2.2 Class Hierarchy
 The collection of all classes extending from a common superclass is called an inheritance hierarchy;
the path from a particular class to its ancestors in the inheritance hierarchy is its inheritance chain.
 Simple class hierarchies consist of only a superclass and a subclass. But you can build hierarchies
that contain as many layers of inheritance as you like.
 For example, create three classes called A, B, and C, C can be a subclass of B, which is a subclass
of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its
superclasses. In this case, C inherits all aspects of B and A.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
4
2.3 Polymorphism
 Polymorphism means the ability of methods to behave differently based on the kinds of input.
Types of polymorphism
 Method Overloading
 Method overriding
Overloaded methods
 Overloaded methods are methods with the same name but different method signature (either a
different number of parameters or different types in the parameter list).
class A{
void display(){ System.out.println("Hai");
}
}
class B extends A{
void display(String s){
System.out.println(s);
}
}
public class Test{
public static void main(String arg[]){
A a=new A();
a.display();
B b=new B();
b.display("Hello");
}}
Output
Hai
Hello
Method Overriding
 The process of a subclass redefining a method contained in the superclass (with the same parameter
types) is called overriding the method.
 Overridden methods allow Java to support run time polymorphism. Whenever a method is called for
a subclass object, the compiler calls the overriding version instead of the superclass version. The
version of the method defined by the superclass will be hidden.
 Call to an overridden method is resolved at run time, rather than compile time.
Rules:
1. Method have same name as in a parent class
2. Method have same parameter as in a parent class
//Example of method overriding
class Vehicle{
void run()
{
System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
void run()
{System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}}
Output:Bike is running safely
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
5
2.4 Dynamic Binding
Binding - Connecting a method call to a method body
1. Static binding (Early binding)
2. Dynamic binding (Late binding)
STATIC BINDING OR EARLY BINDING
 If the compiler can resolve the binding at the compile time only then such a binding is called Static
Binding or Early Binding. Resolve the call and binding at compile time.
 If the method is private, static, final, or a constructor, then the compiler knows exactly which
method to call. This is called static binding.
 All the member variables in Java follow static binding.
 All the static method calls are resolved at compile time itself.
 All private methods are resolved at compile time itself.
class Dog{
private void eat()
{
System.out.println("dog is eating...");
}
public static void main(String args[])
{
Dog d1=new Dog();
d1.eat();
}}
In this example, during compilation, the compiler knows eat() method to be invoked from the class Dog.
Dynamic Binding or Late Binding
 Selecting the appropriate method at runtime is called dynamic binding. Dynamic Binding refers to
the case where compiler is not able to resolve the call and the binding is done at runtime only.
 All the instance methods in Java follow dynamic binding.
 It is important to understand what happens when a method call is applied to an object. Here are the
details:
 The compiler looks at the declared type of the object and the method name. The compiler
knows all possible candidates for the method to be called.
 Next, the compiler determines the types of the parameters that are supplied in the method
call. If among all the methods called fun there is a unique method whose parameter types are
a best match for the supplied parameters, then that method is chosen to be called. This
process is called overloading resolution.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
6
 If the method is private, static, final, or a constructor, then the compiler knows exactly
which method to call.
 When the program runs and uses dynamic binding to call a method, then the virtual machine
must call the version of the method that is appropriate for the actual type of the object. The
virtual machine precomputes a method table for each class that lists all method signatures
and the actual methods to be called. When a method is actually called, the virtual machine
simply makes a table lookup. This is used to reduce the time consumed by searching
process.
class Animal{
void eat(){
System.out.println("animal is eating...");
}}
class Dog extends Animal{
void eat(){
System.out.println("dog is eating...");
}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}}
Output:
Dog is eating…
2.5 FINAL KEYWORD
The final keyword in java used to restrict the user.
The keyword final has three uses.
1. Final Variables - Used to create the equivalent of a named constant.
2. Final Methods - Used to Prevent Overriding
3. Final Class -
Used to Prevent Inheritance
Final variables
 A variable can be declared as final.
 If you make any variable as final, you cannot change the value of variable at runtime. (It is similar to
constant)
final int a = 1;
 Variables declared as final do not occupy memory on a per-instance basis.
 Attempts to change it will generate either a compile-time error or an exception.
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}}
Output:
Compile – time error occurs.
 Since the variables speedlimit is restricted by the user, so it cannot be reinitialized in run() method.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
7
Final Method
 Methods declared as final cannot be overridden
 since final methods cannot be overridden, a call to one can be resolved at compile time. This is
called early binding.
class Bike{
final void run(){
System.out.println("running");}}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run(); }}
Output:
Compile – time error occurs.
Final class
 Declaring a class as final implicitly declares all of its methods as final.
 So it prevents a class from being inherited.
final class Bike{}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}}
Output:
Compile – time error occurs.
2.6 Abstract Classes
 When we define a class to be “final”, it cannot be extended. In certain situation, we want to
properties of classes to be always extended and used. Such classes are called Abstract Classes.
 Abstraction can achieved by
1. Abstract class (0-100%)
2. Interface (100%)
 An Abstract class is a conceptual class.
 An Abstract class cannot be instantiated – objects cannot be created.
Abstract Class Syntax
abstract class ClassName
{
...
…
abstract Type MethodName1();
…
…
Type Method2()
{
// method body
}}
 When a class contains one or more abstract methods, it should be declared as abstract class.
 The abstract methods of an abstract class must be defined in its subclass.
 We cannot declare abstract constructors or abstract static methods.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
8
Abstract Class –Example
 Shape is a abstract class.
The Shape Abstract Class
public abstract class Shape {
public abstract double area();
public void move() { // non-abstract method
// implementation
}
}
 Is the following statement valid?
 Shape s = new Shape();
 No. It is illegal because the Shape class is an abstract class, which cannot be instantiated to create its
objects.
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){
System.out.println("drawing rectangle");
}}
class Circle extends Shape{
void draw(){
System.out.println("drawing circle");
}}
class Test{
public static void main(String args[]){
Shape s=new Circle();//In real scenario, Object is provided through factory method
s.draw();}}
Output:
drawing circle
In the above example, Shape is an abstract class, its implementation is provided by Rectangle and Circle
classes. Mostly, we don’t know about the implementation class (ie hidden to the user) and object
implementation class is provided by Factory method.
A Factory method is the method returns the instance of the class.
Abstract Classes Properties
 A class with one or more abstract methods is automatically abstract and it cannot be instantiated.
 A class declared abstract, even with no abstract methods cannot be instantiated.
 A subclass of an abstract class can be instantiated if it overrides all abstract methods by
implementation them.
 A subclass that does not implement all of the superclass abstract methods is itself abstract; and it
cannot be instantiated.
 A private method can’t be abstract. All abstract methods must be public.
 A class can’t be both abstract and final.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
9
2.7 Interface
 In Java, only single inheritance is permitted. However, Java provides a construct called an interface
which can be implemented by a class.
 Interfaces are similar to abstract classes.
 A class can implement any number of interfaces. In effect using interfaces gives us the benefit of
multiple inheritances without many of its problems.
 Interfaces are compiled into bytecode just like classes.
 Interfaces cannot be instantiated.
 Can use interface as a data type for variables.
 Can also use an interface as the result of a cast operation.
 Interfaces can contain only abstract methods and constants.
Defining an Interface
An interface must be declared with the keyword interface.
access interface interface-name {
return-type method-name(parameter-list);
type final-varname = value;
}
 It is also possible to declare that an interface is protected so that it can only be implemented by
classes in a particular package. However this is very unusual.
 Rules for interface constants. They must always be
 public
 static
 final
 Once the value has been assigned, the value can never be modified. The assignment happens in the
interface itself (where the constant is declared), so the implementing class can access it and use it,
but as a read-only value.
 To make a class implement an interface, have to carry out two steps:
1. Declare that your class intends to implement the given interface.
2. Supply definitions for all methods in the interface.
 To declare that a class implements an interface, use the implements keyword:
access class classname implements interfacename
{
//definitions for all methods in the interface
}
interface printable
{
void print();
}
class A implements printable
{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A obj = new A();
obj.print();
}}
Multiple inheritance by interface
 A class cannot extend two classes but it can implement two interfaces.
interface printable{
void print();}
interface Showable{
void show();}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
10
class A implements printable,Showable
{
public void print(){
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}}
Output:
Hello
Welcome
Interface vs. abstract class
2.8 Inner Classes
 Inner classes are classes defined within other classes
 The class that includes the inner class is called the outer(NESTED) class
 There is no particular location where the definition of the inner class (or classes) must be
place within the outer class
 Placing it first or last, however, will guarantee that it is easy to find
 An inner class definition is a member of the outer class in the same way that the instance variables
and methods of the outer class are members
 An inner class is local to the outer class definition
 The name of an inner class may be reused for something else outside the outer class
definition
 If the inner class is private, then the inner class cannot be accessed by name outside the
definition of the outer class
public class Outer
{
private class Inner
{
// inner class instance variables
// inner class methods
} // end of inner class definition
// outer class instance variables
// outer class methods
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
11
 There are two main advantages to inner classes
 They can make the outer class more self-contained since they are defined inside a class
 Both of their methods have access to each other's private methods and instance variables
 Using an inner class as a helping class is one of the most useful applications of inner classes
 If used as a helping class, an inner class should be marked private
Types of nested (outer) classes
Regular Inner Class
 You define an inner class within the curly braces of the outer class, as follows:
class MyOuter
{
class MyInner { }
}
And if you compile it, %javac MyOuter.java , you’ll end up with two class files:
 MyOuter.class
 MyOuter$MyInner.class
 The inner class is still, in the end, a separate class, so a class file is generated. But the inner class file
isn’t accessible to you in the usual way. The only way you can access the inner class is through a live
instance of the outer class.
Instantiating an Inner Class
To instantiate an instance of an inner class, you must have an instance of the outer class. An inner class
instance can never stand alone without a direct relationship with a specific instance of the outer class.
Instantiating an Inner Class from Within Code in the Outer Class
From inside the outer class instance code, use the inner class name in the normal way:
class MyOuter {
private int x = 7;
MyInner mi = new MyInner();
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
} }
public static void main(String arg[]){
MyOuter mo=new MyOuter();
mo.mi.seeOuter();
} }
Output:
Outer x is 7
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
12
Method-Local Inner Classes
A method-local inner class is defined within a method of the enclosing class.
class MyOuter {
void inner()
{
final int c=9;
class MyInner {
int x=5;
public void display() {
System.out.println("Inner x is " + x);
System.out.println("Inner c is " + c);
}
}
MyInner mi = new MyInner();
mi.display();
}
public static void main(String arg[]){
MyOuter mo = new MyOuter();
mo.inner();
}}
Anonymous Inner Classes
 Anonymous inner classes have no name, and their type must be either a subclass of the named type
or an implementer of the named interface.
 An anonymous inner class is always created as part of a statement, so the syntax will end the class
definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a
semicolon to end the statement: });
 An anonymous inner class can extend one subclass, or implement one interface. It cannot both
extend a class and implement an interface, nor can it implement more than one interface.
class A{
void display(){
System.out.println("Hai");
}}
class B {
A ob=new A(){
void display(){
System.out.println("Hello");
} }}
public class Test{
public static void main(String arg[]){
B b=new B();
b.ob.display();
} }
Output: Hello
And if you compile it, %javac Test.java , you’ll end up with two class files: A.class
B.class
B$1.class
Test.class
Static Nested Classes
 Static nested classes are inner classes marked with the static modifier.
 Technically, a static nested class is not an inner class, but instead is considered a top-level nested
class
 Because the nested class is static, it does not share any special relationship with an instance of the
outer class. In fact, you don’t need an instance of the outer class to instantiate a static nested class.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
13
 Instantiating a static nested class requires using both the outer and nested class names as follows:
A.B b=new A.B();
 A static nested class cannot access nonstatic members of the outer class, since it does not have an
implicit reference to any outer instance (in other words, the nested class instance does not get an
outer this reference).
class A {
static class B {
int m=5;
void display(){
System.out.println("m="+m);
} }
}
public class Test{
public static void main(String arg[]){
A.B b=new A.B();
b.display();
}}
Output: m=5
2.9 Object class
 In Java, every class is a descendent of the class Object
 Every class has Object as its ancestor
 Every object of every class is of type Object, as well as being of the type of its own class
 If a class is defined that is not explicitly a derived class of another class, it is still automatically a
derived class of the class Object
 The class Object is in the package java.lang which is always imported automatically
 Having an Object class enables methods to be written with a parameter of type Object
 A parameter of type Object can be replaced by an object of any class whatsoever
 For example, some library methods accept an argument of type Object so they can be used
with an argument that is an object of any class
 The class Object has some methods that every Java class inherits
 For example, the equals and toString methods
 Every object inherits these methods from some ancestor class
 Either the class Object itself, or a class that itself inherited these methods (ultimately) from
the class Object
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
14
2.9 Object Cloning
 Object cloning is a way to create exact copy of an object.
 For this purpose, clone() method of Object class is used to clone an object.
 The method Object.clone() does a bit-by-bit copy of the object's data in storage
 The Cloneable interface is another unusual example of a Java interface
 It does not contain method headings or defined constants
 It is used to indicate how the method clone (inherited from the Object class) should be used
and redefined
Syntax:
protected Object clone() throws CloneNotSupportedException
class Student implements Cloneable{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException
{
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"amit");
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException c)
{}
}}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
15
2.11Proxy
 Proxy used to create new classes at runtime that implement a given set of interfaces. The proxy class
can create brand-new classes at runtime.
 The proxy class can create brand-new classes at runtime. Such a proxy class implements the
interfaces that you specify. In particular, the proxy class has the following methods:
 All methods required by the specified interfaces;
 All methods defined in the Object class (toString, equals, and so on).
 To create a proxy object, you use the newProxyInstance method of the Proxy class. The method has
three parameters:
 A class loader. As part of the Java security model, it is possible to use different class loaders
for system classes, classes that are downloaded from the Internet, and so on.
 An array of Class objects, one for each interface to be implemented.
 An invocation handler.
 Proxies can be used for many purposes, such as:
 Routing method calls to remote servers;
 Associating user interface events with actions in a running program;
 Tracing method calls for debugging purposes
2.12 Reflection
 Reflection is the ability of the software to analyze itself at runtime.
 Reflection is provided by the java.lang.reflect package and elements in class.
 The Reflection API is mainly used in:
 IDE (Integrated Development Environment) eg. Eclipse, NetBeans
 Debugger
 Test Tools
 This mechanism is helpful to tool builders, not application programmers. The reflection mechanism
is extremely used to
a. Analyze the capabilities of classes at run time
b. Inspect objects at run time
c. Implement generic array manipulation code
Analyze the capabilities of classes at run time - Examine the structure of class.
The java.lang.Class class performs mainly two tasks:
1. Provides methods to get the metadata of a class at runtime.
2. Provides methods to examine and change the runtime behavior of a class.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
16
Field
 Provide information about fields.
 The getFields() method returns an array containing Field objects for the public fields.
 The getDeclaredField() method returns an array of Field objects for all fields. The methods return
an array of length 0 if there are no such fields.
import java.lang.reflect.*;
class Test{
public int var1;
private int var2;
protected int var3;
int var4;}
public class FieldDemo{
public static void main(String args[])throws Exception{
Class c=Class.forName("Test");
Field f[]=c.getFields();
Field fdec[]=c.getDeclaredFields();
System.out.println("public Fields:");
for(int i=0;i<f.length;i++)
System.out.println(f[i]);
System.out.println("All Fields:");
for(int i=0;i<fdec.length;i++)
System.out.println(fdec[i]);
}}
Output:
public Fields:
public int Test.var1
All Fields:
public int Test.var1
private int Test.var2
protected int Test.var3
int Test.var4
Method
 Provides information about method
 The getMethods() method return an array containing Method objects that give you all the
public methods.
 The getDeclaredMethods () return all methods of the class or interface. This includes those
inherited from classes or interfaces above it in the inheritance chain.
import java.lang.reflect.*;
class Test{
public void method1() {}
protected void method2() {}
private void method3() {}
void method4() {}
}
public class MethodDemo{
public static void main(String args[])throws Exception{
Class c=Class.forName("Test");
Method m[]=c.getMethods();
Method mdec[]=c.getDeclaredMethods();
System.out.println("public Methods of class Test & its Super class:");
for(int i=0;i<m.length;i++)
System.out.println(m[i].getName());
System.out.println("All Methods:");
for(int i=0;i<mdec.length;i++) System.out.println(mdec[i].getName());
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
17
Output:
public Methods of class Test & its Super class:
method1 All Methods:
hashCode method1
getClass method2
wait method3
equals method4
notify
notifyAll
toString
Constructor
 Provide information about constructors
 getConstructors () method return an array containing Constructor objects that give you all
the public constructors
 getDeclaredConstructors () method return all constructors of the class represented by the
Class object.
Using Reflection to Analyze Objects at Run Time
 Look at the contents of the data fields. It is easy to look at the contents of a specific field of an
object whose name and type are known when you write a program. But reflection lets you look at
fields of objects that were not known at compile time.
 f.set(obj, value) sets the field represented by f of the object obj to the new value.
 f.get(obj) returns an object whose value is the current value of the field of obj.
import java.lang.reflect.*;
class A{
public int var1,var2; A(int i, int j){
var1=i;
var2=j;
} }
public class ConstructorDemo {
public static void main(String args[]) throws Exception{
A obj=new A(10,20);
System.out.println("Before n var1= "+obj.var1);
Field f1 = obj.getClass().getField("var1");
int v1 = f1.getInt(obj) + 1;
f1.setInt(obj, v1);
System.out.println("After n var1= "+v1);
System.out.println("Before n var2= "+obj.var2);
Field f2 = obj.getClass().getField("var2");
f2.set(obj,21);
System.out.println("After n var2= "+f2.get(obj));
} }
Output:
Before var1= 10
After var1= 11
Before var2= 20
After var2= 21
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
18
Using Reflection to implement generic array manipulation code
 The Array class in the java.lang.reflect package allows you to create arrays dynamically. First the
given array can be converted to an Object[] array. newInstance() method of Array class, constructs a
new array.
 Object newarray= Array.newInstance(ComponentType, newlength)
 newInstance() method needs two parameters
 Component Type of new array
 To get component type
 Get the class object using getClass() method.
 Confirm that it is really an array using isArray().
 Use getComponentType method of class Class, to find the right type for the array.
 Length of new array
 Length is obtained by getLength() method. It returns the length of any array(method is
static method, Array.getLengh(array name)).
import java.lang.reflect.*;
public class TestArrayRef {
static Object arrayGrow(Object a){
Class cl = a.getClass();
if (!cl.isArray()) return null;
Class componentType = cl.getComponentType();
int length = Array.getLength(a);
int newLength = length + 10;
Object newArray = Array.newInstance(componentType,newLength);
System.arraycopy(a, 0, newArray, 0, length);
return newArray;
}
public static void main(String args[]) throws Exception{
int arr[]=new int[10];
System.out.println(arr.length);
arr = (int[])arrayGrow(arr);
System.out.println(arr.length);
} }
Output:
10
20
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
1
Unit III – Event Driven Programming
3.1 Graphics programming
3.2 Frame
3.3 Components
3.4 working with 2D shapes
3.5 Using color, fonts, and images
3.6 Basics of event handling
3.7 event handlers
3.8 adapter classes
3.9 actions
3.10 mouse events
3.11 AWT event hierarchy
3.12 introduction to Swing
3.13 Model-View-Controller design pattern
3.14 buttons
3.15 layout management
3.16 Swing Components
3.1 Graphics Programming
 Java contains support for graphics that enable programmers to visually enhance applications
JFC
 JFC is a collection of APIs for developing graphical components in Java. It includes the following:
1. AWT (version 1.1 and beyond)
2. 2D API
3. Swing Components
4. Accessibility API
AWT
 AWT was original toolkit for developing graphical components. The JFC is based on the AWT
components.
 The Abstract Window Toolkit was a part of Java from the beginning
import java.awt.*;
 All AWT components must be mapped to platform specific components using peers
 The look and feel of these components is tied to the native components of the window
manager
 AWT components are considered to be very error prone and should not be used in modern Java
applications
Swing
 With the introduction to Swing, lightweight version of many of the AWT components (heavyweight)
are created with the prefix J. For example, JFrame for Frame, JButton for Button, etc.
 Since Swing was an extension to AWT, all Swing components are organized in javax.swing package
compared to java.awt for all AWT components.
 Swing also provides many components that AWT lacked.
 Some of the original method names have been changed to allow uniform naming for all components.
 When a method name will no longer be supported in future newer versions, it is said to be
deprecated.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
2
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
3
AWT vs Swing
 Java 1.0 was introduced with a class library called Abstract Window Toolkit (AWT)
 used for basic user interface
 delegated creation and behavior of interface elements to the native GUI tookit on the target
platform
 Windows vs. Solaris vs. Macintosh, etc
 Downside to AWT:
 Worked well for simple applications but difficult to write high-quality portable
graphics
 Limited graphics programming to the lowest common denominator.
 Different platforms had different bugs
 In 1996 Sun worked with Netscape to create Swing
 In Swing user interface elements are painted onto blank windows
 Swing is not a complete replacement of AWT. Instead it works with AWT.
 Swing simply gives you more capable user interface components.
 However, even though AWT components are still available, you will rarely use them.
 Reasons to choose Swing:
 much richer and more convenient set of user interface elements
 depends far less on the underlying platform so it is less vulnerable to platform-specific bugs
 gives a consistent user experience across platforms
 fullfill’s Java’s promise of ―Write Once, Run Anywhere‖
 Easier to use than AWT
How to Create Graphics in Java
 Here are the basic steps you need to take to include graphics in your program:
 Create a frame
 Create a panel
 Override the paintComponent() method in your panel
3.2 Frame
 Frame is a top-level window that has a title bar, menu bar, borders, and resizing corners. By default, a
frame has a size of 0 × 0 pixels and it is not visible.
 Frames are examples of containers. It can contain other user interface components such as buttons and
text fields.
Class hierarchy for Frame
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
4
Component & Window class Methods
java.awt.Component
 void setVisible(boolean b) - shows or hides the component depending on whether b is true
or false. 

 void setSize(int width, int height) - resizes the component to the specified width and height. 

 void setBounds(int x, int y, int width, int height) - moves and resizes this component. The
location of the top-left corner is given by x and y, and the new size is given by the width and
height parameters. 

 void setBackground(java.awt.Color) – set Background color to the window. 

 void setForeground(java.awt.Color)- set Foreground color to the window. 

 void repaint() - causes a repaint of the component ―as soon as possible
 void setTitle(String s) - sets the text in the title bar for the frame to the string s. 
Frame class constructors
 Frame() - Creates a new instance of Frame that is initially invisible.
 Frame(String title) - Creates a new instance of Frame that is initially invisible with the
specified title.
Frame class methods
 void setResizable(boolean resizable) - Sets whether or not a frame is resizable
 void setTitle(String title) - Sets the title of a frame
 void setVisible(boolean visible) - Sets whether or not a frame is visible
 void setSize(int width, int height) - Sets the width & height of a frame
 String getTitle() - Returns the title of a frame
There are two ways to create a frame
1.Create a frame by extending the Frame class
2.Create a frame by creating an instance of the Frame class
Create a frame by extending the Frame class
import java.awt.*;
class AFrame extends Frame{
public static void main(String[] args){
AFrame frame = new AFrame();
frame.setSize(200, 200);
frame.setVisible(true);
} }
Create a frame by creating an instance of the Frame class
import java.awt.*;
class AFrame{
public static void main(String[] args){
Frame aFrame = new Frame();
aFrame.setSize(200, 200);
aFrame.setVisible(true);
} }
Frame Positioning
 Most methods for working the size and position of a frame come from the various superclasses of
JFrame. Some important methods include:
 the dispose() method: closes the window and reclaims system resources.
 the setIconImage() method: takes an Image object to use as the icon when the window is
minimized
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
5
 the setTitle() method: changes the text in the title bar.
 the setResizable() method: takes a boolean to determine if a frame will be resizeable by the
user.
 the setLocation() method: repositions a frame
 the setBounds() method: both repositions and resizes a frame.
 the setExtendedState(Frame.MAXIMIZED_BOTH): maximizes the size of a frame
Note: If you don’t explicitly size the frame, it will default to being 0 by 0 pixels, which is invisible.
 In a professional application, you should check the resolution of the user’s screen to
determine the appropriate frame size.
Java screen coordinate system
 Upper-left corner of a GUI component has the coordinates (0, 0)
 Contains x-coordinate (horizontal coordinate) - horizontal distance moving right from the
left of the screen
 Contains y-coordinate (vertical coordinate) - vertical distance moving down from the top of
the screen
 Coordinate units are measured in pixels. A pixel is a display monitor’s smallest unit of resolution.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class SizedFrameTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
SizedFrame frame = new SizedFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class SizedFrame extends JFrame {
public SizedFrame() {
// get screen dimensions
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
// set frame width, height and let platform pick screen location
setSize(screenWidth / 2, screenHeight / 2);
setLocationByPlatform(true);
// set frame icon and title
Image img = kit.getImage("icon.gif");
setIconImage(img);
setTitle("SizedFrame");
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
6
Display information inside frame
 Frames in Java are designed to be containers for other components like button, menu bar, etc.
 You can directly draw onto a frame, but it’s not a good programming practice
 Normally draw on another component, called panel, using Jpanel
Before JDK5, get the content pane of frame first, then add component on it
Container contentPane = getContentPane();
Component c = …;
contentPane.add(c);
After JDK5, you can directly use frame.add(c);
import javax.swing.*;
import java.awt.*;
class NotHelloWorld
{
public static void main(String[] args)
{
NotHelloWorldFrame frame = new NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame that contains a message panel
*/
class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()
{ setTitle("NotHelloWorld");
setSize(300,300);
// add panel to frame
NotHelloWorldPanel panel = new NotHelloWorldPanel();
add(panel);
}
}
/**
A panel that displays a message.
*/
class NotHelloWorldPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("Not a Hello, World program", 75,100);
}
}
 paintComponent() is a method of JComponent class, which is superclass for all nonwindow Swing
components
 Never call paintComponent() yourself. It’s called automatically whenever a part of your application
needs to be drawn
 User increase the size of the window
 User drag and move the window
 Minimize then restore
 It takes a Graphics object, which collects the information about the display setting
3.3 Components
 The java.awt.Component is one of the cornerstones of AWT programming. It contains approximately
half of the classes in AWT. AWT is built on the Component class.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
7
 Component class – an abstract class for GUI components such as buttons, menus, labels,
lists, etc.
 Container – An abstract class that extends Component. Classes derived from the Container
class can contain multiple components. Examples are Panel, Applet, Window, Frame, etc.
 LayoutManager – An interface for positing and sizing Container objects. Java defines
several default implementations. You can also create your custom layout.
 Graphics class– An abstract class that defines methods for performing graphical operations.
Every component has an associated Graphics object.
 java.awt.Component subclasses (in java.awt package):
 java.awt.Container subclasses (in java.awt package):
 java.awt.LayoutManager interface implementations:
Label Displays text in a box
Button A clickable button, can generate event
Canvas Area for painting graphics
Checkbox A button that provides on/off toggle values. Can
be used for both Check box and radio buttons
(when contained in a CheckBoxGroup)
Choice Combo box where a list of items can be displayed
by clicking the button
List A component that displays a list of selectable items
Scrollbar A scrollable bar
TextComponent Superclass for TextField and TextArea
TextArea Multiple line text input box
TextField One line user input text box
Applet Superclass of all applets, an extension of Panel
Dialog Can be modal or non-modal. Extends Window
FileDialog Opens a regular file dialog
Frame All applications are contained in a Frame. Extends
Window. It can have a menubar unlike an applet
Panel A simple container of other components including Panels
Window It is rarely used directly, but useful for spash screen
when an app starts. No menu or border. Parent of
Frame and Dialog
BorderLayout Compoents are layed out in North/South,
East/West and Center
CardLayout Deck of panels where panels are displayed one at a
time
FlowLayout Component flow from left to right, top to bottom.
When there is no real estate to maneuvar on the
right, goes down. Widely used.
GridBagLayout Each componet location is defined using grid.
Most difficult to implement.
GridLayout Components are layed out in a grid. Component is
streched to fill the grid.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
8
3.4Working with 2D shapes
 To draw shapes in the Java 2D library, you need to obtain an object of the Graphics2D class. This
class is a subclass of the Graphics class. Ever since Java SE 2, methods such as paintComponent
automatically receive an object of the Graphics2D class. Simply use a cast, as follows:
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
. . .
}
 The Java 2D library organizes geometric shapes in an object-oriented fashion. In particular, there are
classes to represent lines, rectangles, and ellipses:
 Line2D
 Rectangle2D
 Ellipse2D
These classes all implement the Shape interface.
 To draw a shape, you first create an object of a class that implements the Shape interface and then
call the draw method of the Graphics2D class.
Drawing Rectangle
Rectangle 2D rect = . . .;
g2.draw(rect);
 There are two versions of each Shape class
 one with float coordinates (conserves memory)
 one with double coordinates (easier to use)
Rectangle2D.Float floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D.Double doubleRect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);
 Rectangles are simple to construct
 Requires four arguments
 x- and y-coordinates of the upper-left corner
 the width and the height
 The Rectangle2D class has over 20 useful methods including:
 get Width
 getHeight
 getCenterX
 getCenterY
 Sometimes you don’t have the top-left corner readily available.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
9
 It is possible to have two diagonal corners of a rectangle that are not the top-left corner and the
bottom-right corner.
 To create a rectangle in this case use the setFrameFromDiagonal method.
Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(px, py, qx, qy);
 If you have a Point2D object, you can also create a rectangle by calling
Rectangle2D rect = new Rectangle2D.Double(p1, p2);
Drawing Ellipse
 The class Ellipse2D is inherited from the same Rectangle class that Rectangle2D is.
 because of the bounding box surrounding the ellipse
 So, creating an Ellipse2D object is very similar to creating a Rectangle2D object.
Ellipse2D e = new Ellipse2D.Double(px, py, qx, qy)
where px, py are the x- and y-coordinates of the top-left corner
and qx, qy are the x- and y-coordinates of the bottom-right corner
of the bounding box of the ellipse
Drawing Line
 To construct a line, simple use the Line2D class.
 It too, requires 4 arguments (the x and y coordinates of the start and end positions)
 These coordinates can be 2 Point2D objects or 2 pairs of numbers.
Line2D line = new Line2D.Double(start, end)
or
Line2D line = new Line2D.Double(px, py, qx, qy)
Filling Shapes
 You can fill the interior of closed shape objects with a color.
 Simply call the fill instead of draw method on the Graphics object.
Rectangle2D rect = new Rectangle2D.Double(x, y, x2, y2);
g2.setPaint(Color.red);
g2.fill(rect);
/**
* A frame that contains a panel with drawings
*/
class DrawFrame extends JFrame
{
public DrawFrame()
{
setTitle("DrawTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add panel to frame
DrawComponent component = new DrawComponent();
add(component);
}
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
}
/**
* A component that displays rectangles and ellipses.
*/
class DrawComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// draw a rectangle
double leftX = 100;
double topY = 100;
double width = 200;
double height = 150;
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
10
// draw the enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
// draw a diagonal line
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
// draw a circle with the same center
double centerX = rect.getCenterX(); double centerY = rect.getCenterY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.draw(circle);
}
}
3.5 using colors
 Class Color declares methods and constants for manipulating colors in a Java
program(java.awt.Color)
 Every color is created from a red, a green and a blue component – RGB values
Common Constructors:
 Color (int Red, int Green, int Blue) Creates a color with the designated combination of red, green,
and blue (each 0-255).
 Color (float Red, float Green, float Blue) Creates a color with the designated combination of red,
green, and blue (each 0-1).
 Color (int rgb) Creates a color with the designated combination of red, green, and blue (each 0-255).
Common Methods:
 getBlue () Returns the blue component of the color.
 getGreen () Returns the green component of the color.
 getRed () Returns the red component of the color.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
class FillTest
{
public static void main(String[] args)
{
FillFrame frame = new FillFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}}
/**
A frame that contains a panel with drawings
Color constant Color RGB value
public final static Color RED red 255, 0, 0
public final static Color GREEN green 0, 255, 0
public final static Color BLUE blue 0, 0, 255
public final static Color ORANGE orange 255, 200, 0
public final static Color PINK pink 255, 175, 175
public final static Color CYAN cyan 0, 255, 255
public final static Color MAGENTA magenta 255, 0, 255
public final static Color YELLOW yellow 255, 255, 0
public final static Color BLACK black 0, 0, 0
public final static Color WHITE white 255, 255, 255
public final static Color GRAY gray 128, 128, 128
public final static Color LIGHT_GRAY lightgray 192, 192, 192
public final static Color DARK_GRAY darkgray 64, 64, 64
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
11
*/
class FillFrame extends JFrame
{
public FillFrame()
{
setTitle("FillTest");
setSize(400,400);
// add panel to frame
FillPanel panel = new FillPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
}
/**
A panel that displays filled rectangles and ellipses
*/
class FillPanel extends JPanel
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
// draw a rectangle
Rectangle2D rect = new Rectangle2D.Double(100,100,200,150);
g2.setPaint(Color.RED);
g2.fill(rect);
// draw the enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.setPaint(new Color(0, 128, 128)); // a dull blue-green
g2.fill(ellipse);
}}
3.5 using font
 Class Font
 Constructor takes three arguments—the font name, font style and font size
 Font name – any font currently supported by the system on which the program is
running
 Font style –Font.PLAIN, Font.ITALIC or Font.BOLD. Font styles can be used in
combination
 Font sizes – measured in points. A point is 1/72 of an inch.
 Methods getName, getStyle and getSize retrieve information about Font object
 Graphics methods getFont and setFont retrieve and set the current font, respectively
Method or constant Description
Font constants, constructors and methods
public final static int PLAIN
A constant representing a plain font style.
public final static int BOLD
A constant representing a bold font style.
public final static int ITALIC
A constant representing an italic font style.
public Font( String name, int style, int size )
Creates a Font object with the specified font name, style and
size.
public int getStyle()
Returns an integer value indicating the current font style.
public int getSize()
Returns an integer value indicating the current font size.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
12
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
class FontTest
{
public static void main(String[] args)
{
FontFrame frame = new FontFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/**
A frame with a text message panel
*/
class FontFrame extends JFrame
{
public FontFrame()
{
setTitle("FontTest");
setSize(300,200);
// add panel to frame
FontPanel panel = new FontPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
}
/**
A panel that shows a centered message in a box.
*/
class FontPanel extends JPanel
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
String message = "Hello, World!";
Font f = new Font("Serif", Font.BOLD, 36);
g.setFont(f);
g.drawString(message, 50,100);
Font f1 = new Font("Arial", Font.ITALIC, 30);
g.setFont(f1);
g.drawString(message, 50,150);
}
}
Method or
constant Description
public String getName()
Returns the current font name as a string.
public String getFamily()
Returns the font’s family name as a string.
public boolean isPlain()
Returns true if the font is plain, else false.
public boolean isBold()
Returns true if the font is bold, else false.
public boolean isItalic()
Returns true if the font is italic, else false.
Graphics methods for manipulating Fonts
public Font getFont()
Returns a Font object reference representing
the current font.
public void setFont( Font f )
Sets the current font to the font, style and
size specified by the Font object reference f.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
13
3.5 using images
 You can display images on the Graphics object.
 You can use images stored locally or someplace on the Internet.
Step1: Loading an image
java.awt.Toolkit
Toolkit getDefaultToolkit()- returns the default toolkit.
Image getImage(String filename) - returns an image that will read its pixel data from a file.
Toolkit object can only read GIF and JPEG files.
Step2: displaying an image
java.awt.Graphics
boolean drawImage(Image img, int x, int y, ImageObserver observer)- draws a scaled image.
boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) - draws a
scaled image. The system scales the image to fit into a region with the given width and height. Note:
This call may return before the image is drawn.
 If an image is stored locally call:
String filename = ―…‖;
Image image = ImageIO.read(new File(filename));
 If an image is on the Internet, use the url:
String filename = ―…‖;
Image image = ImageIO.read(new URL(url);
import java.awt.*;
class Demo extends Frame{
Demo(String s){
super(s);setSize(300,300);
setVisible(true);
}
public void paint(Graphics g) {
Toolkit tk = Toolkit.getDefaultToolkit();
Image img= tk.getImage("Sunset.jpg");
for (int i = 20; i <300-20; i=i+20)
for (int j = 40; j <300-20; j=j+20)
g.drawImage(img,i,j,20,20,null);
}
public static void main(String arg[]){
Demo ob=new Demo("Image Demo");
}
}
AWT Components
 All components are subclass of Component class 

 Components allow the user to interact with application. A layout manager
arranges components within a container (Frame/Applet/Panel). 
Adding and Removing Controls
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
14
 add(Component compObj)- add components to the conatainer. Once it is added, it will
automatically be visible whenever its parent window is displayed. Here, compObj is an
instance of the control that you want to add. 

 void remove(Component obj)- remove a control from a window 

 removeAll( )- remove all controls from a window 
Component Constructor Methods
Label Label( ) void setText(String str)
Label(String str) String getText( )
Label(String str, int how)
Button Button( ) void setLabel(String str)
Button(String str) String getLabel( )
List List( ) void add(String name)
List(int numRows) void add(String name, int
List(int numRows, boolean multipleSelect) index)
String getSelectedItem( )
int getSelectedIndex( )
String[ ] getSelectedItems( )
Choice Choice( ) void add(String name)
String getSelectedItem( )
int getSelectedIndex( )
Checkbox Checkbox( ) boolean getState( )
Checkbox(String str) void setState(boolean on)
Checkbox(String str, boolean on) String getLabel( )
Checkbox(String str, boolean on, CheckboxGroup cbGroup) void setLabel(String str)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
TextField TextField( ) String getText( )
TextField(int numChars) void setText(String str)
TextField(String str) void setEditable(boolean
TextField(String str, int numChars) canEdit)
TextArea TextArea( ) void append(String str)
TextArea(int numLines, int numChars) void insert(String str, int
TextArea(String str) index)
TextArea(String str, int numLines, int numChars)
Label
 Labels are components that hold text. 

 Labels don’t react to user input. It is used to identify components. 
Constructors
 Label(String str) - constructs a label with left-aligned text. 

 Label(String str, int how) - constructs a label with the alignment specified by how. 
Methods
 void setText(String str)- set the text in the label 

 String getText( )- return the text of label 
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
15
Example: The following example creates three labels and adds them to a frame..The labels are
organized in the frame by the flow layout manager.
import java.awt.*; Demo ob=new Demo("Label Demo");
public class Demo extends Frame{ }
Label lb1 = new Label("One"); }
Label lb2 = new Label("Two"); Output:
Label lb3 = new Label("Three");
FlowLayout flow= new FlowLayout();
Demo(String s){
super(s);
setSize(200,200);
setLayout(flow);
add(lb1);add(lb2);add(lb3);
setVisible(true);
}
public static void main(String arg[]){
Button
A push button is a component that contains a label and that generates an event when it is pressed.
Push buttons are objects of type Button.
Constructors
 Button( )- creates an empty button 

 Button(String str)- creates a button that contains str as a label. 
Methods
 void setLabel(String str) -set the label in the button 

 String getLabel( ) -return the label of button 
Example: The following example creates three buttons and adds them to a frame. The buttons are
organized in the frame by the flow layout manager.
public static void main(String arg[]){
import java.awt.*; Demo ob=new Demo("Button Demo");
public class Demo extends Frame{ } }
FlowLayout flow= new FlowLayout(); Output:
Button b=new Button();
Button b1=new Button();
Button b2=new Button("Button 2");
Demo(String s){
super(s);setSize(200,200);
setLayout(flow);
b1.setLabel("Button 1");
add(b);add(b1);add(b2);
setVisible(true);
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
16
List
The List class provides a compact, multiple-choice, scrolling selection list. List object can be
constructed to display any number of choices in the visible window. It allows the user to select
multiple items.
Constructors
 List( )- allows to select one item at any one time 

 List(int numRows)- the value of numRows specifies the number of entries in the list that 
will be visible always
 List(int numRows, boolean multipleSelect)- if multipleSelect is true, then the user may 
select two or more items at a time
Method
 void add(String name)- Here, name is the name of the item added to the list. The first
form adds items to the end of the list. 

 void add(String name, int index) -adds the item at the index specified by index 

 String getSelectedItem( )- return the selected item 

 String[ ] getSelectedItems( )- return the selected items. 
Example: The following example creates a list and adds it to a frame.
import java.awt.*; Demo ob=new
public class Demo extends Frame{ Demo("List Demo");
FlowLayout flow= new FlowLayout(); }
List l1=new List(2); }
List l2=new List(3);
List l3=new List(4,true);
Label lb1 = new Label("Dept");
Label lb2 = new Label("Dept");
Label lb3 = new Label("Dept");
Demo(String s){
super(s);
setSize(200,300);
setLayout(flow);
l1.add("CSE");l1.add("ECE");l1.add("EEE");l1.add("MECH");
l2.add("CSE");l2.add("ECE");l2.add("EEE");l2.add("MECH");
l3.add("CSE");l3.add("ECE");l3.add("EEE");l3.add("MECH");
add(lb1);add(l1);add(lb2);add(l2);add(lb3);add(l3);
setVisible(true);
}
public static void main(String arg[]){
CheckBox
A check box is a control that is used to turn an option on or off. It consists of a small box that can
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
17
either contain a check mark or not. There is a label associated with each check box that describes
what option the box represents.
Constructors
 Checkbox( )- check box whose label is initially blank 

 Checkbox(String str)- check box whose label is specified by str. 

 Checkbox(String str, boolean on) - allows you to set the initial state of the check box. If on
is true, the check box is initially checked 

 Checkbox(String str, boolean on, CheckboxGroup cbGroup)- group is specified by cbGroup 

 Checkbox(String str, CheckboxGroup cbGroup, boolean on) 
Methods
 boolean getState( ) 

 void setState(boolean on) 

 String getLabel( ) 

 void setLabel(String str) 
CheckboxGroup
Create a set of mutually exclusive check boxes in which one and only one check box in the group
can be checked at any one time. These check boxes are often called radio buttons. The default
constructor is defined, which creates an empty group.
Example: The following example creates a checkbox group (Gender) and checkboxes (Languages
Known).
import java.awt.*; Label l2=new Label("Languages Known");
public class Demo extends Frame{ CheckboxGroup cg=new CheckboxGroup();
FlowLayout flow= new FlowLayout(); Checkbox c1=new Checkbox("Male",cg,true);
Label l1=new Label("Gender"); Checkbox c2=new Checkbox("Female",cg,false);
Checkbox c3=new Checkbox("VisualBasic"); }
Checkbox c4=new Checkbox("C++"); }
Checkbox c5=new Checkbox("Java");
Checkbox c6=new Checkbox("C"); Output:
Demo(String s){
super(s);
setSize(200,200);
setLayout(flow);
add(l1);add(c1);add(c2);
add(l2);add(c3);add(c4);add(c5);add(c6);
setVisible(true);
}
public static void main(String arg[]){
Demo ob=new Demo("Checkbox Demo");
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
18
Choice
The Choice class is used to create a pop-up list of items from which the user may choose. It allows
the user to select single item at any time. Choice only defines the default constructor, which creates
an empty list.
To add a item to the list, call add( ). It has this general form:
 void add(String name) 

 To determine which item is currently selected, you may call either getSelectedItem( ) or
getSelectedIndex( ). 
import java.awt.*;
public class Demo extends Frame{ FlowLayout flow= new FlowLayout(); Label lb=new Label("City");
Choice c=new Choice(); Demo(String s){ super(s);
setSize(200,200);setLayout(flow);
c.add("Chennai");c.add("Coimbatore");
c.add("KanyaKumari");c.add("Madurai");
c.add("Tirunelveli");
add(lb);add(c);
setVisible(true);
}
public static void main(String arg[]){ Demo ob=new Demo("Checkbox Demo");
}
}
TextField
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste
keys, and mouse selections.
 TextField( )- creates a default text field 

 TextField(int numChars)- creates a text field that is numChars characters wide 

 TextField(String str)- initializes the text field with the string contained in str 

 TextField(String str, int numChars) 
Methods
 String getText( ) 

 void setText(String str) 
TextArea
Simple multiline editor allow the user to enter strings.
TextArea and TextField are subclass of TextComponent. Therefore, it supports the getText( ),
setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in
TextField class.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
19
import java.awt.*; TextArea ta=new TextArea(2,10);
public class Demo extends Frame{ Demo(String s){
FlowLayout flow= new FlowLayout(); super(s);
Label lb1=new Label("Name"); setSize(250,200);
Label lb2=new Label("No"); setLayout(flow);
Label lb3=new Label("Message"); add(lb1);add(t1);
TextField t1=new TextField(20); add(lb2);add(t2);
TextField t2=new TextField(15); add(lb3);add(ta);
setVisible(true);
}
public static void main(String arg[]){
Demo ob=new Demo("TextComponents Demo");
}
}
output:
3.7 Basics of Event Handling
 Event handling is a basic concept of graphical user interfaces.
 What is event handling?
-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.
Examples.
Pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking
the mouse, timer expires, counter, h/w or s/w failure.
The way event handling works is this:
 Any operating system that supports GUIs constantly monitors events such as
keystrokes and mouse clicks.
 The operating system reports these events to programs that are running.
 The programs decide what, if anything, they want to do with these events.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
20
 In Java, you control how to handle these events by setting up event source objects and
event listener objects.
Event Source
 A source is an object that generates an event.
 This occurs when the internal state of that object changes.
 A source must register listeners.
Event Source Description
Button Generates action events when the button is pressed.
Checkbox Generates item events when the check box is selected or deselected.
Choice Generates item events when the choice is changed.
List Generates action events when an item is double-clicked; generates item
events when an item is selected or deselected.
Mouse Generates Mouse events when Mouse input occurs.
Keyboard Generates Key events when keyboard input occurs.
Event Listeners
 Listener is an object that is notified when an event occurs. It has two major requirements.
 It must have been registered with one or more sources to receive notifications about specific
types of events.
 It must implement methods to receive and process these notifications.
 The package java.awt.event defines several types of events that are generated by various
user interface elements.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
21
How event handling in the AWT works
 A listener object is an instance of a class that implements a special interface called
(naturally enough) a listener interface.
 An event source is an object that can register listener objects and send them event
objects.
 The event source sends out event objects to all registered listeners when that event
occurs.
 The listener objects will then use the information in the event object to determine
their reaction to the event.
 You register the listener object with the source object by using lines of code that
follow the model:
eventSourceObject.addEventListener(eventListenerObject);
3.8 AWT Event Hierarchy
Source Event Class Class Methods Listener Interface Interface Methods
Button ActionEvent String ActionListener actionPerformed(ActionEvent ae)
getActionCommand( )
List, ItemEvent Object getItem( ) ItemListener itemStateChanged(ItemEvent ie)
Choice, ItemSelectable
Checkbox getItemSelectable( )
Keyboard KeyEvent char getKeyChar( ) KeyListener keyPressed(KeyEvent ke)
int getKeyCode( ) keyReleased(KeyEvent ke)
keyTyped(KeyEvent ke)
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
22
Mouse MouseEvent int getX( ) MouseListener mouseClicked(MouseEvent me)
int getY( ) mouseEntered(MouseEvent me)
mouseExited(MouseEvent me)
mousePressed(MouseEvent me)
mouseReleased(MouseEvent me)
MouseMotionListener mouseDragged(MouseEvent me)
mouseMoved(MouseEvent me)
Handling Keyboard Events
A KeyEvent is fired (to all its registered KeyListeners) when you pressed, released, and typed
(pressed followed by released) a key on the source object.
A KeyEvent listener must implement KeyListener interface, which declares three abstract methods:
public void keyTyped(KeyEvent e)
// Called-back when a key has been typed (pressed and released).
public void keyPressed(KeyEvent e)
public void keyReleased(KeyEvent e)
// Called-back when a key has been pressed/released.
Source: KeyBoard
Event Class: java.awt.event.KeyEvent
Listener Interface: java.awt.event.KeyListener
Example: The following program demonstrates keyboard input. When program receives keystrokes,
identifies the key and perform the corresponding actions specified by the program.
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
// An AWT GUI program inherits the top-level container java.awt.Frame
class KeyEventDemo extends Frame implements KeyListener {
// This class acts as KeyEvent Listener
private TextField tfInput; // single-line TextField to receive tfInput key
private TextArea taDisplay; // multi-line TextArea to taDisplay result
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
23
/** Constructor to setup the GUI */
public KeyEventDemo() {
setLayout(new FlowLayout()); // "this" frame sets to FlowLayout
add(new Label("Enter Text: "));
tfInput = new TextField(10);
add(tfInput);
taDisplay = new TextArea(5, 40); // 5 rows, 40 columns
add(taDisplay);
tfInput.addKeyListener(this);
// tfInput TextField fires KeyEvent to its registered KeyListener
// It adds "this" object as a KeyEvent listener
setTitle("KeyEvent Demo"); // "this" Frame sets title
setSize(400, 200); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}
/** The entry main() method */
public static void main(String[] args) {
new KeyEventDemo(); // Let the constructor do the job
}
/** KeyEvent handlers */
// Called back when a key has been typed (pressed and released)
@Override
public void keyTyped(KeyEvent e) {
taDisplay.append("You have typed " + e.getKeyChar() + "n");
}
// Not Used, but need to provide an empty body for compilation
@Override
public void keyPressed(KeyEvent e) { }
@Override
public void keyReleased(KeyEvent e) { }
}
In this example:
1. We identify the TextField (input) as the source object, which fires a KeyEvent when you
press/release/type a key onto it.
2. We select this object as the KeyEvent listener.
3. We register this object as the KeyEvent listener to the source TextField via method
input.addKeyListener(this).
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
24
4. The KeyEvent listener (this object) needs to implement the KeyListener interface, which
declares 3 abstract methods: keyTyped(), keyPressed(), keyReleased().
5. We override the keyTyped() to display key typed on the display TextArea. We ignore the
keyPressed() and keyReleased().
3.9 Handling Mouse Events
A MouseEvent is fired to all its registered listeners, when you press, release, or click (press
followed by release) a mouse-button (left or right button) at the source object; or position the
mouse-pointer at (enter) and away (exit) from the source object.
A MouseEvent listener must implement the MouseListener interface, which declares the following
five abstract methods:
public void mouseClicked(MouseEvent e)
// Called-back when the mouse-button has been clicked (pressed followed by released) on the
source.
public void mousePressed(MouseEvent e)
public void mouseReleased(MouseEvent e)
// Called-back when a mouse-button has been pressed/released on the source.
// A mouse-click invokes mousePressed(), mouseReleased() and mouseClicked().
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
// Called-back when the mouse-pointer has entered/exited the source.
public void mouseDragged(MouseEvent e)
// Called-back when a mouse-button is pressed on the source component and then dragged.
public void mouseMoved(MouseEvent e)
// Called-back when the mouse-pointer has been moved onto the source component but no buttons
have been pushed.
Source: Mouse
Event Class: java.awt.event.MouseEvent
Listener Interface: java.awt.event.MouseListener
java.awt.event.MouseMotionListener
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
// An AWT GUI program inherits the top-level container java.awt.Frame
class MouseMotionDemo extends JFrame
implements MouseListener, MouseMotionListener {
// This class acts as MouseListener and MouseMotionListener
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
25
// To display the (x, y) coordinates of the mouse-clicked
private JTextField tfMouseClickX;
private JTextField tfMouseClickY;
// To display the (x, y) coordinates of the current mouse-pointer position
private JTextField tfMousePositionX;
private JTextField tfMousePositionY;
/** Constructor to setup the GUI */
public MouseMotionDemo() {
setLayout(new FlowLayout()); // "this" frame sets to FlowLayout
add(new Label("X-Click: "));
tfMouseClickX = new JTextField(10);
tfMouseClickX.setEditable(false);
add(tfMouseClickX);
add(new JLabel("Y-Click: "));
tfMouseClickY = new JTextField(10);
tfMouseClickY.setEditable(false);
add(tfMouseClickY);
add(new JLabel("X-Position: "));
tfMousePositionX = new JTextField(10);
tfMousePositionX.setEditable(false);
add(tfMousePositionX);
add(new Label("Y-Position: "));
tfMousePositionY = new JTextField(10);
tfMousePositionY.setEditable(false);
add(tfMousePositionY);
addMouseListener(this);
addMouseMotionListener(this);
// "this" frame fires MouseEvent to all its registered MouseListener and MouseMotionListener
// "this" frame adds "this" object as MouseListener and MouseMotionListener
setTitle("MouseMotion Demo"); // "this" Frame sets title
setSize(200, 200); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}
/** The entry main() method */
public static void main(String[] args) {
new MouseMotionDemo(); // Let the constructor do the job
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
26
/** MouseListener handlers */
// Called back when a mouse-button has been clicked
@Override
public void mouseClicked(MouseEvent e) {
tfMouseClickX.setText(e.getX() + "");
tfMouseClickY.setText(e.getY() + "");
}
// Not Used, but need to provide an empty body for compilation
@Override
public void mousePressed(MouseEvent e) { }
@Override
public void mouseReleased(MouseEvent e) { }
@Override
public void mouseEntered(MouseEvent e) { }
@Override
public void mouseExited(MouseEvent e) { }
/** MouseMotionEvent handlers */
// Called back when the mouse-pointer has been moved
@Override
public void mouseMoved(MouseEvent e) {
tfMousePositionX.setText(e.getX() + "");
tfMousePositionY.setText(e.getY() + "");
}
// Not Used, but need to provide an empty body for compilation
@Override
public void mouseDragged(MouseEvent e) { }
}
In this example, we shall illustrate both the MouseListener and MouseMotionListener.
1. We identify this Frame as the source, which fires the MouseEvent to its registered
MouseListener and MouseMotionListener.
2. We select this object as the MouseListener and MouseMotionListner (for simplicity).
3. We register this object as the listener to this Frame via method this.addMouseListener(this)
and this.addMouseMotionListener(this).
4. The MouseMotionListener (this object) needs to implement 2 abstract methods:
mouseMoved() and mouseDragged() declared in the MouseMotionListener interface.
5. We override the mouseMoved() to display the (x, y) position of the mouse pointer. We
ignore the MouseDragged() handler by providing an empty body for compilation.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
27
Action Event
To handle Action events, class must implement the ActionListener interface. Source objects needs
to register action listener to receive events.
SourceObject.addActionListener(this);
Source: Button
Event Class: java.awt.event.ActionEvent
Listener Interface: java.awt.event.ActionListener
Example: The following program demonstrates Action event handling. Application window has 3
Text Fields and two buttons. Text fields are used to get user input and show the result to the user.
When the user presses Button, it will generate an action event. Listener receives the event and
performs the operation specified in the actionPerformed Method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Demo extends JFrame implements ActionListener{
FlowLayout flow=new FlowLayout();
JLabel lb1 = new JLabel("Number1");
JLabel lb2 = new JLabel("Number2");
JLabel lb3 = new JLabel("Result");
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JTextField t3=new JTextField(20);
JButton b1=new JButton("Add");
JButton b2=new JButton("Multiply");
Demo(String s){
super(s);
setLayout(flow);
add(lb1);add(t1);
add(lb2);add(t2);
add(b1);add(b2);
add(lb3);add(t3);
b1.addActionListener(this);
b2.addActionListener(this);
setSize(350,280);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
String s=ae.getActionCommand();
int n1,n2;
n1=Integer.parseInt(t1.getText());
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
28
n2=Integer.parseInt(t2.getText());
if(s.equals("Add")){
t3.setText(String.valueOf(n1+n2));
}
if(s.equals("Multiply")){
t3.setText(String.valueOf(n1*n2));
}}
public static void main(String arg[]){
Demo my=new Demo("Action event demo");
}}
Item Event
To handle Item events, class must implement the ItemListener interface. Source objects needs to
register action listener to receive events.
SourceObject.addActionListener(this);
Source: List, Choice, Checkbox
Event Class: java.awt.event.ItemEvent
Listener Interface: java.awt.event.ItemListener
Example: The following program demonstrates Item event handling. Application window has Text
Field, Checkbox, and Choice. Text fields are used to show the result to the user. When the user
select item from any component, then the selected item will be displayed in text field. A listener
receives the event and performs the operation specified in the itemStateChanged() Method.
import java.awt.*; TextField t=new TextField(20);
import java.awt.event.*; Demo(String s){
public class Demo extends Frame implements super(s);
ItemListener{ setLayout(flow);
String msg=""; c.add("Chennai");c.add("Coimbatore");
FlowLayout flow=new FlowLayout(); c.add("KanyaKumari");c.add("Madurai");
Label lb1 = new Label("City"); c.add("Tirunelveli");
Label lb2 = new Label("Qualification"); add(lb1);add(c);
Label lb3 = new Label("Languages Known"); add(lb2);add(c1);add(c2);
Choice c=new Choice(); add(lb3);add(c3);add(c4);add(c5);add(c6);
CheckboxGroup cg=new CheckboxGroup(); add(t);
Checkbox c1=new Checkbox("UG",cg,true); setSize(200,300);
Checkbox c2=new Checkbox("PG",cg,false); setVisible(true);
Checkbox c3=new Checkbox("Visual Basic"); c.addItemListener(this);
Checkbox c4=new Checkbox("C++"); c1.addItemListener(this);
Checkbox c5=new Checkbox("Java"); c2.addItemListener(this);
Checkbox c6=new Checkbox("dotnet"); c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);
c6.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie){
String msg=(String)ie.getItem();
t.setText(msg);
}
public static void main(String arg[]){ Demo
ob=new Demo("List event Demo");
}}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
29
Event Listener's Adapter Class
WindowListener/WindowAdapter
A WindowEvent listener is required to implement the WindowListener interface, which declares 7
abstract methods. Although we are only interested in windowClosing(), we need to provide an
empty body to the other 6 methods in order to compile the program. This is tedious. For example,
we can rewrite the WindowEventDemo using an inner class implementing ActionListener as
follows:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
class WindowEventDemoWithInnerClass extends JFrame {
private JTextField tfCount;
private int count = 0;
/** Constructor to setup the GUI */
public WindowEventDemoWithInnerClass () {
setLayout(new FlowLayout());
add(new JLabel("Counter"));
tfCount = new JTextField("0", 10);
tfCount.setEditable(false);
add(tfCount);
JButton btnCount = new JButton("Count");
add(btnCount);
btnCount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
++count;
tfCount.setText(count + "");
}
});
// Allocate an anonymous instance of an anonymous inner class
// that implements WindowListener.
// "this" Frame adds the instance as WindowEvent listener.
addWindowListener(new WindowListener() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0); // terminate the program
}
// Need to provide an empty body for compilation
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
30
@Override public void windowOpened(WindowEvent e) { }
@Override public void windowClosed(WindowEvent e) { }
@Override public void windowIconified(WindowEvent e) { }
@Override public void windowDeiconified(WindowEvent e) { }
@Override public void windowActivated(WindowEvent e) { }
@Override public void windowDeactivated(WindowEvent e) { }
});
setTitle("WindowEvent Demo");
setSize(250, 100);
setVisible(true);
}
/** The entry main method */
public static void main(String[] args) {
new WindowEventDemoWithInnerClass(); // Let the constructor do the job
}
}
3.10 Adapter class
An adapter class called WindowAdapter is therefore provided, which implements the
WindowListener interface and provides default implementations to all the 7 abstract methods. You
can then derive a subclass from WindowAdapter and override only methods of interest and leave
the rest to their default implementation. For example,
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
class WindowEventDemoAdapter extends JFrame {
private JTextField tfCount;
private int count = 0;
/** Constructor to setup the GUI */
public WindowEventDemoAdapter () {
setLayout(new FlowLayout());
add(new Label("Counter"));
tfCount = new JTextField("0", 10);
tfCount.setEditable(false);
add(tfCount);
JButton btnCount = new JButton("Count");
add(btnCount);
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
31
btnCount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
++count;
tfCount.setText(count + "");
}
});
// Allocate an anonymous instance of an anonymous inner class
// that extends WindowAdapter.
// "this" Frame adds the instance as WindowEvent listener.
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0); // Terminate the program
}
});
setTitle("WindowEvent Demo");
setSize(250, 100);
setVisible(true);
}
/** The entry main method */
public static void main(String[] args) {
new WindowEventDemoAdapter(); // Let the constructor do the job
}
}
Other Event-Listener Adapter Classes
 Similarly, adapter classes such as MouseAdapter, MouseMotionAdapter, KeyAdapter,
FocusAdapter are available for Mou seListener, MouseMotionListener, KeyListener, and
FocusListener, respectively.
 There is no ActionAdapter for ActionListener, because there is only one abstract method
(i.e. actionPerformed()) declared in the ActionListener interface. This method has to be
overridden and there is no need for an adapter
3.11 Layout Managers
A container has a so-called layout manager to arrange its components. The layout managers provide
a level of abstraction to map your user interface on all windowing systems, so that the layout can be
platform-independent.
AWT provides the following layout managers (in package java.awt): FlowLayout, GridLayout,
BorderLayout, GridBagLayout, BoxLayout, CardLayout, and others.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
32
Container's setLayout()
A container has a setLayout() method to set its layout manager:
// java.awt.Container
public void setLayout(LayoutManager mgr)
To set up the layout of a Container (such as Frame, JFrame, Panel, or JPanel), you have to:
1. Construct an instance of the chosen layout object, via new and constructor, e.g., new
FlowLayout())
2. Invoke the setLayout() method of the Container, with the layout object created as the
argument;
3. Place the GUI components into the Container using the add() method in the correct order; or
into the correct zones.
For example,
// Allocate a Panel (containter)
Panel p = new Panel();
// Allocate a new Layout object. The Panel container sets to this layout.
p.setLayout(new FlowLayout());
// The Panel container adds components in the proper order.
p.add(new JLabel("One"));
p.add(new JLabel("Two"));
p.add(new JLabel("Three"));
......
Container's getLayout()
You can get the current layout via Container's getLayout().
Panel awtPanel = new Panel();
System.out.println(awtPanel.getLayout());
// java.awt.FlowLayout[hgap=5,vgap=5,align=center]
Panel's Inital Layout
Panel (and Swing's JPanel) provides a constructor to set its initial layout manager. It is because a
primary function of Panel is to layout a group of component in a particular layout.
public void Panel (LayoutManager layout)
// Construct a Panel in the given layout
// By default, Panel (and JPanel) has FlowLayout
// For example, create a Panel in BorderLayout
Panel mainPanel = new Panel(new BorderLayout());
FlowLayout
In the java.awt.FlowLayout, components are arranged from left-to-right inside the container in the
order that they are added (via method aContainer.add(aComponent)). When one row is filled, a new
row will be started. The actual appearance depends on the width of the display window.
Constructors
public FlowLayout();
public FlowLayout(int align);
public FlowLayout(int align, int hgap, int vgap);
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
33
// align: FlowLayout.LEFT (or LEADING), FlowLayout.RIGHT (or TRAILING), or
FlowLayout.CENTER
// hgap, vgap: horizontal/vertical gap between the components
// By default: hgap=5, vgap=5, align=CENTER
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
class AWTFlowLayoutDemo extends JFrame {
private JButton btn1, btn2, btn3, btn4, btn5, btn6;
/** Constructor to setup GUI components */
public AWTFlowLayoutDemo () {
setLayout(new FlowLayout());
// "this" Frame sets layout to FlowLayout, which arranges the components
// from left-to-right, and flow from top-to-bottom.
btn1 = new JButton("Button 1");
add(btn1);
btn2 = new JButton("This is Button 2");
add(btn2);
btn3 = new JButton("3");
add(btn3);
btn4 = new JButton("Another Button 4");
add(btn4);
btn5 = new JButton("Button 5");
add(btn5);
btn6 = new JButton("One More Button 6");
add(btn6);
setTitle("FlowLayout Demo"); // "this" Frame sets title
setSize(280, 150); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
34
/** The entry main() method */
public static void main(String[] args) {
new AWTFlowLayoutDemo(); // Let the constructor do the job
}
}
GridLayout
In java.awt.GridLayout, components are arranged in a grid (matrix) of rows and columns inside the
Container. Components are added in a left-to-right, top-to-bottom manner in the order they are
added (via method aContainer.add(aComponent)).
Constructors
public GridLayout(int rows, int columns);
public GridLayout(int rows, int columns, int hgap, int vgap);
// By default: rows=1, cols=0, hgap=0, vgap=0
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
class AWTGridLayoutDemo extends JFrame {
private JButton btn1, btn2, btn3, btn4, btn5, btn6;
/** Constructor to setup GUI components */
public AWTGridLayoutDemo () {
setLayout(new GridLayout(3, 2, 3, 3));
// "this" Frame sets layout to 3x2 GridLayout, horizontal and verical gaps of 3 pixels
// The components are added from left-to-right, top-to-bottom
btn1 = new JButton("Button 1");
add(btn1);
btn2 = new JButton("This is Button 2");
add(btn2);
btn3 = new JButton("3");
add(btn3);
btn4 = new JButton("Another Button 4");
add(btn4);
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
35
btn5 = new JButton("Button 5");
add(btn5);
btn6 = new JButton("One More Button 6");
add(btn6);
setTitle("GridLayout Demo"); // "this" Frame sets title
setSize(280, 150); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}
/** The entry main() method */
public static void main(String[] args) {
new AWTGridLayoutDemo(); // Let the constructor do the job
}
}
If rows or cols is 0, but not both, then any number of components can be placed in that column or
row. If both the rows and cols are specified, the cols value is ingored. The actual cols is determined
by the actual number of components and rows.
BorderLayout
In java.awt.BorderLayout, the container is divided into 5 zones: EAST, WEST, SOUTH, NORTH,
and CENTER. Components are added using method aContainer.add(acomponent, aZone), where
azone is either BorderLayout.NORTH (or PAGE_START), BorderLayout.SOUTH (or
PAGE_END), BorderLayout.WEST (or LINE_START), BorderLayout.EAST (or LINE_END), or
BorderLayout.CENTER. The method aContainer.add(aComponent) without specifying the zone
adds the component to the CENTER.
You need not add components to all the 5 zones. The NORTH and SOUTH components may be
stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER
component may stretch both horizontally and vertically to fill any space left over.
Constructors
public BorderLayout();
public BorderLayout(int hgap, int vgap);
// By default hgap=0, vgap=0
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
36
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
class AWTBorderLayoutDemo extends JFrame {
private JButton btnNorth, btnSouth, btnCenter, btnEast, btnWest;
/** Constructor to setup GUI components */
public AWTBorderLayoutDemo () {
setLayout(new BorderLayout(3, 3));
// "this" Frame sets layout to BorderLayout,
// horizontal and vertical gaps of 3 pixels
// The components are added to the specified zone
btnNorth = new JButton("NORTH");
add(btnNorth, BorderLayout.NORTH);
btnSouth = new JButton("SOUTH");
add(btnSouth, BorderLayout.SOUTH);
btnCenter = new JButton("CENTER");
add(btnCenter, BorderLayout.CENTER);
btnEast = new JButton("EAST");
add(btnEast, BorderLayout.EAST);
btnWest = new JButton("WEST");
add(btnWest, BorderLayout.WEST);
setTitle("BorderLayout Demo"); // "this" Frame sets title
setSize(280, 150); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}
/** The entry main() method */
public static void main(String[] args) {
new AWTBorderLayoutDemo(); // Let the constructor do the job
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
37
Using Panels as Sub-Container to Organize Components
An AWT Panel is a retangular pane, which can be used as sub-container to organized a group of
related components in a specific layout (e.g., FlowLayout, BorderLayout). Panels are secondary
containers, which shall be added into a top-level container (such as Frame), or another Panel.
For example, the following figure shows a Frame (in BorderLayout) containing two Panels,
panelResult in FlowLayout and panelButtons in GridLayout. panelResult is added to the NORTH,
and panelButtons is added to the CENTER.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
class AWTPanelDemo extends JFrame {
private JButton[] btnNumbers = new JButton[10]; // Array of 10 numeric buttons
private JButton btnHash, btnStar;
private JTextField tfDisplay;
/** Constructor to setup GUI components */
public AWTPanelDemo () {
// Set up display panel
JPanel panelDisplay = new JPanel(new FlowLayout());
tfDisplay = new JTextField("0", 20);
panelDisplay.add(tfDisplay);
// Set up button panel
JPanel panelButtons = new JPanel(new GridLayout(4, 3));
btnNumbers[1] = new JButton("1");
panelButtons.add(btnNumbers[1]);
btnNumbers[2] = new JButton("2");
panelButtons.add(btnNumbers[2]);
btnNumbers[3] = new JButton("3");
panelButtons.add(btnNumbers[3]);
btnNumbers[4] = new JButton("4");
panelButtons.add(btnNumbers[4]);
btnNumbers[5] = new JButton("5");
panelButtons.add(btnNumbers[5]);
btnNumbers[6] = new JButton("6");
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
38
panelButtons.add(btnNumbers[6]);
btnNumbers[7] = new JButton("7");
panelButtons.add(btnNumbers[7]);
btnNumbers[8] = new JButton("8");
panelButtons.add(btnNumbers[8]);
btnNumbers[9] = new JButton("9");
panelButtons.add(btnNumbers[9]);
// Can use a loop for the above statements!
btnStar = new JButton("*");
panelButtons.add(btnStar);
btnNumbers[0] = new JButton("0");
panelButtons.add(btnNumbers[0]);
btnHash = new JButton("#");
panelButtons.add(btnHash);
setLayout(new BorderLayout()); // "this" Frame sets to BorderLayout
add(panelDisplay, BorderLayout.NORTH);
add(panelButtons, BorderLayout.CENTER);
setTitle("BorderLayout Demo"); // "this" Frame sets title
setSize(200, 200); // "this" Frame sets initial size
setVisible(true); // "this" Frame shows
}
/** The entry main() method */
public static void main(String[] args) {
new AWTPanelDemo(); // Let the constructor do the job
}
}
3.11 Model-View-Controller design pattern
Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each
of its components. Essentially, MVC breaks GUI components into three elements. Each of these
elements plays a crucial role in how the component behaves.
Model - (includes state data for each component)
The model encompasses the state data for each component. There are different models for different
types of components. Model has no user interface. Model data always exists independent of the
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
39
component's visual representation.
For example, model of a Choice list might contain the information about list of items and currently
selected item. This information remains the same no matter how the component is painted on the
screen.
View - (to display component on screen)
The view refers to how you see the component on the screen. It determines exactly where and how
to draw the choice list by the information offered by the model.
Controller- (handles user Input)
The controller decides the behavior of each component with respect to the events. Events come in
many forms (a mouse click, a keyboard event).The controller decides how each component will
react to the event—if it reacts at all.
MVC Interaction
In MVC, each of the three elements—the model, the view, and the controller—requires the
services of another element to keep itself continually updated.
Model-View-Controller Analysis of Swing Buttons
For most components, the model class implements an interface whose name ends in Model; thus the
interface called ButtonModel. Classes implementing that interface can define the state of the
various kinds of buttons. Actually, buttons aren’t all that complicated, and the Swing library
contains a single class, called DefaultButtonModel, that implements this interface.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
40
Each JButton object stores a button model object, which you can retrieve.
JButton button = new JButton("Blue");
ButtonModel model = button.getModel();
3.12 Swing
Swing is part of the so-called "Java Foundation Classes (JFC)" (have you heard of MFC?), which
was introduced in 1997 after the release of JDK 1.1. JFC was subsequently included as an integral
part of JDK since JDK 1.2. JFC consists of:
Swing API: for advanced graphical programming.
Accessibility API: provides assistive technology for the disabled.
Java 2D API: for high quality 2D graphics and images.
Pluggable look and feel supports.
Drag-and-drop support between Java and native applications.
The goal of Java GUI programming is to allow the programmer to build GUI that looks good on
ALL platforms. JDK 1.0's AWT was awkward and non-object-oriented (using many
event.getSource()). JDK 1.1's AWT introduced event-delegation (event-driven) model, much
clearer and object-oriented. JDK 1.1 also introduced inner class and JavaBeans – a component
programming model for visual programming environment (similar to Visual Basic and Dephi).
Swing appeared after JDK 1.1. It was introduced into JDK 1.1 as part of an add-on JFC (Java
Foundation Classes). Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI
components that can be dragged and dropped as "GUI builders" in visual programming
environment. Swing is now an integral part of Java since JDK 1.2.
Swing's Features
The main features of Swing are (extracted from the Swing website):
1. Swing is written in pure Java (except a few classes) and therefore is 100% portable.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
41
2. Swing components are lightweight. The AWT components are heavyweight (in terms of
system resource utilization). Each AWT component has its own opaque native display, and
always displays on top of the lightweight components. AWT components rely heavily on the
underlying windowing subsystem of the native operating system. For example, an AWT
button ties to an actual button in the underlying native windowing subsystem, and relies on
the native windowing subsystem for their rendering and processing. Swing components
(JComponents) are written in Java. They are generally not "weight-down" by complex GUI
considerations imposed by the underlying windowing subsystem.
3. Swing components support pluggable look-and-feel. You can choose between Java look-
and-feel and the look-and-feel of the underlying OS (e.g., Windows, UNIX or Mac). If the
later is chosen, a Swing button runs on the Windows looks like a Windows' button and feels
like a Window's button. Similarly, a Swing button runs on the UNIX looks like a UNIX's
button and feels like a UNIX's button.
4. Swing supports mouse-less operation, i.e., it can operate entirely using keyboard.
5. Swing components support "tool-tips".
6. Swing components are JavaBeans – a Component-based Model used in Visual
Programming (like Visual Basic). You can drag-and-drop a Swing component into a "design
form" using a "GUI builder" and double-click to attach an event handler.
7. Swing application uses AWT event-handling classes (in package java.awt.event). Swing
added some new classes in package javax.swing.event, but they are not frequently used.
8. Swing application uses AWT's layout manager (such as FlowLayout and BorderLayout in
package java.awt). It added new layout managers, such as Springs, Struts, and BoxLayout
(in package javax.swing).
9. Swing implements double-buffering and automatic repaint batching for smoother screen
repaint.
10. Swing introduces JLayeredPane and JInternalFrame for creating Multiple Document
Interface (MDI) applications.
11. Swing supports floating toolbars (in JToolBar), splitter control, "undo".
12. Others - check the Swing website.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
42
S.No AWT(Abstract Window Toolkit) Swing
1 AWT components are heavy weight, Swing components are light weight,
components are platform dependent. components are platform independent.
2 AWT components support Delegate Swing components support MVC (model,
Event Model. view, control architecture)
3 AWT components provide static look Swing components provide dynamic look
and feel. and feel
4 It does not provide Tooltip text for It provide Tooltip text for components
components
Writing Swing Applications
In summary, to write a Swing application, you have:
1. Use the Swing components with prefix "J" in package javax.swing.
2. A top-level container (such as JFrame or JApplet) is needed. The JComponents cannot be
added directly onto the top-level container. They shall be added onto the content-pane of the
top-level container. You can retrieve a reference to the content-pane by invoking method
getContentPane() from the top-level container, or set the content-pane to the main JPanel
created in your program
Swing Components
javax.swing
3.
Component Constructor Methods
JLabel JLabel() void setText(String str)
JLabel(String text) String getText( )
JLabel(String text, int horizontalAlignment)
JButton JButton( ) void setLabel(String str)
JButton(String str) String getLabel( )
JList JList() Object getSelectedValue( )
JList(String[] ) int getSelectedIndex( )
String[] getSelectedItems( )
JRadioButton JRadioButton()
JRadioButton(String text)
JRadioButton(String text, boolean selected)
JRadioButton(String text, Icon icon, boolean
selected)
JComboBox JComboBox() void add(String name)
JComboBox(Object items[]) String getSelectedItem( )
int getSelectedIndex( )
JCheckbox JCheckbox( ) boolean getState( )
JCheckbox(String str) void setState(boolean on)
JCheckbox(String str, boolean on) String getLabel( )
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
43
JCheckBox(String text, Icon icon) void setLabel(String str)
JTextField JTextField(int numChars) String getText( )
JTextField(String str, int numChars) void setText(String str)
void setEditable(boolean
canEdit)
JTextArea JTextArea(int numLines, int numChars) void append(String str)
JTextArea(String str, int numLines, int numChars) void insert(String str, int index)
JPasswordField JPasswordField(String text, int columns) void setEchoChar(char echo)
The JLabel Class
Swing allows you to create labels that can contain text, images, or both. Unlike java.awt.Label
objects, JLabel objects may consist of both text and graphics (icons).
Text Input
In Java, two components are used to get text input:
 JTextField 

 JTextArea. 
The difference between them is that a text field can accept only one line of text and a text area can
accept multiple lines of text. The classes are called JTextField for single-line input and JTextArea
for multiple lines of text.
The JPasswordField Class
Password fields are a special kind of text field. To avoid nosy bystanders being able to glance at a
password, the characters that the user entered are not actually displayed. Instead, each typed
character is represented by an echo character, typically an asterisk
(*). The Swing set supplies a JPasswordField class that implements such a text field.
The JButton Class
They are typically used much like java.awt.Buttons. JButtons fire ActionEvents when they are
clicked.
The JCheckBox Class
It is used to allow the user to turn a given feature on or off, or to make multiple selections from a set
of choices. A JCheckBox is usually rendered by showing a small box into which a "check" is placed
when selected. The user could check either, both, or none of the two check boxes.
The JRadioButton Class
JRadioButtons, allowing users to make a single selection from a set of options.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
44
The JList Class
A list is a graphical component from which the user can select choices. Lists typically display
several items at a time, allowing the user to make either a single selection or multiple
selections.AWT limited the contents of its List component to strings. The Swing JList component
lifts this restriction. List elements can now be strings, images.
The JComboBox Class
A combo box component is actually a combination of a Swing list and a text field. Unlike lists, a
combo box only allows the user one selection at a time, which is usually copied into an editable
component at the top, such as a text field. The user can be permitted, however, to manually enter in
a selection as well.
JComboBox is the Swing version of a combo box component. It is very similar to the AWT Choice
component.
The JPanel Class
JPanel is an extension of JComponent (which, remember, extends java.awt.Container) used for
grouping together other components. It gets most of its implementation from its superclasses.
Typically, using JPanel amounts to instantiating it, setting a layout manager (this can be set in the
constructor and defaults to a FlowLayout), and adding components to it using the add() methods
inherited from Container.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
1
Unit IV – Generic Programming
4.1. Motivation for generic programming
4.2. generic classes
4.3. generic methods
4.4. generic code and virtual machine
4.5. inheritance and generics
4.6. reflection and generics
4.7. exceptions
4.8. exception hierarchy
4.9. throwing and catching exceptions
4.10. Stack Trace Elements
4.11. assertions
4.12. logging
4.1 Background
• old version 1.4 Java collections were Object-based and required the use of ugly casts
– cannot specify the exact type of elements
– must cast to specific classes when accessing
Java generics
• Generic programming is a style of computer programming in which algorithms are written
in terms of to-be-specified-later types that are then instantiated when needed for specific
types provided as parameters.
• lets you write code that is safer and easier to read
• is especially useful for general data structures, such as ArrayList
• generic programming = programming with classes and methods parameterized with types
• generic types are a powerful tool to write reusable object-oriented components and libraries
• however, the generic language features are not easy to master and can be misused
• their full understanding requires the knowledge of the type theory of programming
languages
• especially covariant and contravariant typing
As per Java Language Specification:
 A type variable is an unqualified identifier. Type variables are introduced by generic class
declarations, generic interface declarations, generic method declarations, and by generic
constructor declarations. 

 A class is generic if it declares one or more type variables. These type variables are known
as the type parameters of the class. It defines one or more type variables that act as
parameters. A generic class declaration defines a set of parameterized types, one for each
possible invocation of the type parameter section. All of these parameterized types share the
same class at runtime. 

 An interface is generic if it declares one or more type variables. These type variables are
known as the type parameters of the interface. It defines one or more type variables that act
as parameters. A generic interface declaration defines a set of types, one for each possible
invocation of the type parameter section. All parameterized types share the same interface at
runtime. 

 A method is generic if it declares one or more type variables. These type variables are
known as the formal type parameters of the method. The form of the formal type parameter
list is identical to a type parameter list of a class or interface. 

 A constructor can be declared as generic, independently of whether the class the constructor
is declared in is itself generic. A constructor is generic if it declares one or more type
variables. These type variables are known as the formal type parameters of the constructor.
The form of the formal type parameter list is identical to a type parameter list of a generic
class or interface.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
2
Motivation for Generics:
 Overloaded methods are often used to perform similar operations on different types of data.
To motivate generic methods, let’s begin with an example that contains three overloaded
printArray methods. These methods print the string representations of the elements of an
Integer array, a Double array and a Character array, respectively. Note that we could have
used arrays of primitive types int, double and char in this example. We chose to use arrays
of type Integer, Double and Character to set up our generic method example, because only
reference types can be used with generic methods and classes
public class OverloadedMethods
{
// method printArray to print Integer array
public static void printArray( Integer[] inputArray )
{
// display array elements
for ( Integer element : inputArray )
System.out.printf( "%s ", element );
System.out.println();
} // end method printArray
// method printArray to print Double array
public static void printArray( Double[] inputArray )
{
// display array elements
for ( Double element : inputArray )
System.out.printf( "%s ", element );
System.out.println();
} // end method printArray
// method printArray to print Character array
public static void printArray( Character[] inputArray )
{
// display array elements
for ( Character element : inputArray )
System.out.printf( "%s ", element );
System.out.println();
} // end method printArray
public static void main( String args[] )
{
// create arrays of Integer, Double and Character
Integer[] integerArray = { 1, 2, 3, 4, 5, 6 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println( "Array integerArray contains:" );
printArray( integerArray ); // pass an Integer array
System.out.println( "nArray doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( "nArray characterArray contains:" );
printArray( characterArray ); // pass a Character array
} // end main
} // end class OverloadedMethods
OUTPUT:
Array integerArray contains:
1 2 3 4 5 6
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
3
Array doubleArray contains: 1.1
2.2 3.3 4.4 5.5 6.6 7.7
Array characterArray contains:
H E L L O
4.2 Generic class definitions
 Generic methods and generic classes (and interfaces) enable you to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively.
 A generic class can have more than one type variable.
 Generics also provide compile-time type safety that allows you to catch invalid types at
compile time.
Here is an example of a generic class:
public class Pair<T, S>
{
public Pair(T f, S s)
{
first = f; second = s;
}
public T getFirst()
{
return first;
}
public S getSecond()
{
return second;
}
public String toString()
{
return "(" + first.toString() + ", " + second.toString() + ")";
}
private T first;
private S second;
}
This generic class can be used in the following way:
Pair<String, String> grade440 = new Pair<String, String>("mike", "A");
Pair<String, Integer> marks440 = new Pair<String, Integer>("mike", 100);
System.out.println("grade:" + grade440.toString());
System.out.println("marks:" + marks440.toString());
Explanation
The Pair class introduces a type variable T, enclosed in angle brackets < >, after the class name.
A generic class can have more than one type variable.
For example, we could have defined the Pair class with separate types for the first and
second field:
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
4
public class Pair<T, U> { . . . }
The type variables are used throughout the class definition to specify method return types
and the types of fields and local variables.
For example:
private T first; // uses type variable
Type erasure
Generics were introduced to the Java language to provide tighter type checks at compile time
and to support generic programming. To implement generics, the Java compiler applies type
erasure to:
 Replace all type parameters in generic types with their bounds or Object if the type
parameters are unbounded. The produced bytecode, therefore, contains only ordinary
classes, interfaces, and methods.
 Insert type casts if necessary to preserve type safety.
 Generate bridge methods to preserve polymorphism in extended generic types.
Type erasure ensures that no new classes are created for parameterized types; consequently,
generics incur no runtime overhead.
4.3 Generic Methods
 All generic method declarations have a type-parameter section delimited by angle brackets
(< and >) that precedes the method’s return type (< E > in this example).
 Each type-parameter section contains one or more type parameters (also called formal type
parameters), separated by commas.
 A type parameter, also known as a type variable, is an identifier that specifies a generic type
name.
 Can be used to declare the return type, parameter types and local variable types in a generic
method, and act as placeholders for the types of the arguments passed to the generic method
(actual type arguments).
 A generic method’s body is declared like that of any other method.
 Type parameters can represent only reference types—not primitive types.
Example:
public class GenericMethodTest
{
// generic method printArray
public static < E > void printArray( E[] inputArray )
{
// display array elements
for ( E element : inputArray )
System.out.printf( "%s ", element );
System.out.println(); } // end method printArray
public static void main( String args[] )
{
// create arrays of Integer, Double and Character
Integer[] integerArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
System.out.println( "Array integerArray contains:" );
printArray( integerArray ); // pass an Integer array
System.out.println( "nArray doubleArray contains:" );
printArray( doubleArray ); // pass a Double array
System.out.println( "nArray characterArray contains:" );
printArray( characterArray ); // pass a Character array
} // end main
} // end class GenericMethodTest
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
5
Output:
Array integerArray contains: 1 2 3 4 5 6
Array doubleArray contains: 1.1 2.2 3.3 4.4
5.5 6.6 7.7
Array characterArray contains:
H E L L O
4.4 Generic Code and the Virtual Machine
The virtual machine does not have objects of generic types—all objects belong to ordinary
classes
Whenever you define a generic type, a corresponding raw type is automatically provided.
The name of the raw type is simply the name of the generic type, with the type parameters removed.
The type variables are erased and replaced by their bounding types (or Object for variables without
bounds.)
For example, the raw type for Pair<T> looks like this:
public class Pair
{
public Pair(Object first, Object second)
{
this.first = first;
this.second = second;
}
public Object getFirst() { return first; }
public Object getSecond() { return second; }
public void setFirst(Object newValue) { first = newValue; }
public void setSecond(Object newValue) { second = newValue; }
private Object first;
private Object second;
}
Because T is an unbounded type variable, it is simply replaced by Object.
The result is an ordinary class, just as you might have implemented it before generics were
added to the Java programming language.
Your programs may contain different kinds of Pair, such as Pair<String> or Pair<Gregorian-
Calendar>, but erasure turns them all into raw Pair types
Translating Generic Expressions
When you program a call to a generic method, the compiler inserts casts when the return
type has been erased.
For example, consider the sequence of statements
Pair<Employee> buddies = . . .;
Employee buddy = buddies.getFirst();
The erasure of getFirst has return type Object. The compiler automatically inserts the cast to
Employee. That is, the compiler translates the method call into two virtual machine instructions:
Translating Generic Methods
Type erasure also happens for generic methods. Programmers usually think of a generic
method such as
public static <T extends Comparable> T min(T[] a)
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
6
as a whole family of methods, but after erasure, only a single method is left:
public static Comparable min(Comparable[] a)
Note that the type parameter T has been erased, leaving only its bounding type Comparable.
In summary, you need to remember these facts about translation of Java generics:
1. There are no generics in the virtual machines, only ordinary classes and methods.
2. All type parameters are replaced by their bounds.
3. Bridge methods are synthesized to preserve polymorphism.
4. Casts are inserted as necessary to preserve type safety.
4.5 Generics and Inheritance
As you already know, it is possible to assign an object of one type to an object of another type
provided that the types are compatible. For example, you can assign an Integer to an Object, since
Object is one of Integer's supertypes:
Object someObject = new Object();
Integer someInteger = new Integer(10);
someObject = someInteger; // OK
In object-oriented terminology, this is called an "is a" relationship. Since an Integer is a kind of
Object, the assignment is allowed. But Integer is also a kind of Number, so the following code is
valid as well:
public void someMethod(Number n) { /* ... */ }
someMethod(new Integer(10)); // OK
someMethod(new Double(10.1)); // OK
The same is also true with generics. You can perform a generic type invocation, passing Number as
its type argument, and any subsequent invocation of add will be allowed if the argument is
compatible with Number:
Box<Number> box = new Box<Number>();
box.add(new Integer(10)); // OK
box.add(new Double(10.1)); // OK
Now consider the following method:
public void boxTest(Box<Number> n) { /* ... */ }
What type of argument does it accept? By looking at its signature, you can see that it accepts a
single argument whose type is Box<Number>. But what does that mean? Are you allowed to pass
in Box<Integer> or Box<Double>, as you might expect? The answer is "no", because Box<Integer>
and Box<Double> are not subtypes of Box<Number>.
This is a common misunderstanding when it comes to programming with generics, but it is an
important concept to learn.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
7
Box<Integer> is not a subtype of Box<Number> even though Integer is a subtype of Number.
Note: Given two concrete types A and B (for example, Number and Integer), MyClass<A> has no
relationship to MyClass<B>, regardless of whether or not A and B are related. The common parent
of MyClass<A> and MyClass<B> is Object.
Wildcards and Subtyping
Generic classes or interfaces are not related merely because there is a relationship between their
types. However, you can use wildcards to create a relationship between generic classes or
interfaces.
Given the following two regular (non-generic) classes:
class A { /* ... */ }
class B extends A { /* ... */ }
It would be reasonable to write the following code:
B b = new B();
A a = b;
This example shows that inheritance of regular classes follows this rule of subtyping: class B is a
subtype of class A if B extends A. This rule does not apply to generic types:
List<B> lb = new ArrayList<>();
List<A> la = lb; // compile-time error
Given that Integer is a subtype of Number, what is the relationship between List<Integer> and
List<Number>?
The common parent is List<?>.
Although Integer is a subtype of Number, List<Integer> is not a subtype of List<Number> and, in
fact, these two types are not related. The common parent of List<Number> and List<Integer> is
List<?>.
In order to create a relationship between these classes so that the code can access Number's methods
through List<Integer>'s elements, use an upper bounded wildcard:
List<? extends Integer> intList = new ArrayList<>();
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
8
List<? extends Number> numList = intList; // OK.
List<? extends Integer> is a subtype of List<? extends Number>
Because Integer is a subtype of Number, and numList is a list of Number objects, a relationship
now exists between intList (a list of Integer objects) and numList. The following diagram shows the
relationships between several List classes declared with both upper and lower bounded wildcards.
A hierarchy of several generic List class declarations.
4.6 Reflection and Generics
1. The Generics Reflection Rule of Thumb
2. Generic Method Return Type
3. Generic Method Parameter Types
4. Generic Field Types
The Generics Reflection Rule of Thumb
Using Java Generics typically falls into one of two different situations:
1. Declaring a class/interface as being parameterizable.
2. Using a parameterizable class.
When you write a class or interface you can specify that it should be paramerizable. This is the case
with the java.util.List interface. Rather than create a list of Object you can parameterize
java.util.List to create a list of say String.
When runtime inspecting a parameterizable type itself, like java.util.List, there is no way of
knowing what type is has been parameterized to. This makes sense since the type can be
parameterized to all kinds of types in the same application. But, when you inspect the method or
field that declares the use of a parameterized type, you can see at runtime what type the
paramerizable type was parameterized to. In short:
You cannot see on a type itself what type it is parameterized to a runtime, but you can see it in
fields and methods where it is used and parameterized. Its concrete parameterizations in other
words.
The following sections take a closer look at these situations.
Generic Method Return Types
If you have obtained a java.lang.reflect.Method object it is possible to obtain information about its
generic return type. This cannot be any of the Method objects in the parameterized type, but in the
class that uses the parameterized type. You can read how to obtain Method objects in the text "Java
Generics: Methods". Here is an example class with a method having a parameterized return type:
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;
public class MethodReturnType {
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
9
List mRaw() { return null; }
List<String> mTypeString() { return null; }
List<?> mWildcard() { return null; }
List<? extends Number> mBoundedWildcard() { return null; }
<T extends List<String>> List<T> mTypeLiteral() { return null; }
public static void main(String[] args) {
for (Method method : MethodReturnType.class.getDeclaredMethods()) {
Type type = method.getGenericReturnType();
System.out.println(method.getName() + " - " + Generics.typeToString(type));
}
}
}
Output:
mRaw - java.util.List
mTypeString - java.util.List<java.lang.String>
mWildcard - java.util.List<? extends java.lang.Object>
mBoundedWildcard - java.util.List<? extends java.lang.Number>
mTypeLiteral - java.util.List<T extends java.util.List<java.lang.String>>
Generic Method Parameter Types
You can also access the generic types of parameter types at runtime via Java Reflection. Here is an
example class with a method taking a parameterized List as parameter:
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.List;
public class MethodParameterType {
<T extends List<T>> void m(String p1, T p2, List<?> p3, List<T> p4) { }
public static void main(String[] args) {
for (Method method : MethodParameterType.class.getDeclaredMethods()) {
for (Type type : method.getGenericParameterTypes()) {
System.out.println(method.getName() + " - " + Generics.typeToString(type));
}
}
}
}
Output:
m - java.lang.String
m - T extends java.util.List<T>
m - java.util.List<? extends java.lang.Object>
m - java.util.List<T extends java.util.List<T>>
Generic Field Types
It is also possible to access the generic types of public fields. Fields are class member variables -
either static or instance variables. You can read about obtaining Field objects in the text "Java
Generics: Fields". Here is the example from earlier, with an instance field called stringList.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
10
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class FieldType<K extends Number, V extends List<String> & Collection<String>> {
List fRaw;
List<Object> fTypeObject;
List<String> fTypeString;
List<?> fWildcard;
List<? super List<String>> fBoundedWildcard;
Map<String, List<Set<Long>>> fTypeNested;
Map<K, V> fTypeLiteral;
K[] fGenericArray;
public static void main(String[] args) {
for (Field field : FieldType.class.getDeclaredFields()) {
Type type = field.getGenericType();
System.out.println(field.getName() + " - " + Generics.typeToString(type));
}
}
}
Output:
fRaw - java.util.List
fTypeObject - java.util.List<java.lang.Object>
fTypeString - java.util.List<java.lang.String>
fWildcard - java.util.List<? extends java.lang.Object>
fBoundedWildcard - java.util.List<? super java.util.List<java.lang.String>>
fTypeNested - java.util.Map<java.lang.String>, <java.util.List<java.util.Set<java.lang.Long>>>
fTypeLiteral - java.util.Map<K extends java.lang.Number>, <V extends
java.util.List<java.lang.String> & java.util.Collection<java.lang.String>>
fGenericArray - K[]
4.7 Java exception handling:
Exception is a run-time error which arises during the execution of java program. The term exception
in java stands for an “exceptional event”.
So Exceptions are nothing but some abnormal and typically an event or conditions that arise during
the execution which may interrupt the normal flow of program.
An exception can occur for many different reasons, including the following:
· A user has entered invalid data.
· A file that needs to be opened cannot be found.
· A network connection has been lost in the middle of communications, or the JVM has run out
of memory.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
11
―If the exception object is not handled properly, the interpreter will display the error and will
terminate the program.
Now if we want to continue the program with the remaining code, then we should write the part of
the program which generate the error in the try{} block and catch the errors using catch() block..
Exception turns the direction of normal flow of the program control and send to the related catch()
block and should display error message for taking proper action. This process is known as
Exception handling.‖
The purpose of exception handling is to detect and report an exception so that proper action can be
taken and prevent the program which is automatically terminate or stop the execution because of
that exception.
Java exception handling is managed by using five keywords: try, catch, throw, throws and finally.
Try:
Piece of code of your program that you want to monitor for exceptions are contained within a try
block. If an exception occurs within the try block, it is thrown.
Catch:
Catch block can catch this exception and handle it in some logical manner.
Throw:
System-generated exceptions are automatically thrown by the Java run-time system. Now if we
want to manually throw an exception, we have to use the throw keyword.
Throws:
If a method is capable of causing an exception that it does not handle, it must specify this behavior
so that callers of the method can guard themselves against that exception.
You do this by including a throws clause in the method’s declaration. Basically it is used for
IOException. A throws clause lists the types of exceptions that a method might throw.
This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their
subclasses.
All other exceptions that a method can throw must be declared in the throws clause. If they are not,
a compile-time error will result.
Finally:
Any code that absolutely must be executed before a method returns, is put in a finally block.
General form:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 e1) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 e2) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
4.8 Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
12
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 :
These are not normally trapped form the Java programs.
Errors are typically ignored in your code because you can rarely do anything about an error.
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.
For Example :
(1) JVM is out of Memory. Normally programs cannot recover from errors.
(2) If a stack overflow occurs then an error will arise. They are also ignored at the time of
compilation.
The Exception class has two main subclasses:
(1) IOException or Checked Exceptions class and
(2) RuntimeException or Unchecked Exception class
(1) IOException or Checked Exceptions :
Exceptions that must be included in a method’s throws list if that method can generate one of these
exceptions and does not handle it itself. These are called checked exceptions.
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.
Java’s Checked Exceptions Defined in java.lang
(2) RuntimeException or Unchecked Exception :
Exceptions need not be included in any method’s throws list. These are called unchecked
exceptions because the compiler does not check to see if a method handles or throws these
exceptions.
As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
Java’s Unchecked RuntimeException Subclasses
BUILT-IN ECEPTIONS
1. ArithmeticException (Divide by zero)
2. ArrayIndexOutOfBoundsException(array index)
3. ArrayStoreException (incompatible type element)
4. ClassCastException(Invalid cast)
5. IllegalArgumentException (Illegal argument to a method)
6. IllegalMonitorStateException (waiting on an unlocked thread)
7. IllegalStateException (incorrect state)
8. IllegalThreadStateException (operation not compatible with current state)
9. IndexOutOfBoundsException (index exceding)
10. Negative ArrayStoreException (negative index)
11. NullPointerException (null pointer)
12. NumberFormatException (Invalid conversion of String to number)
13. SecurityException (Attempts to violate the security)
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
13
14. StringIndexOutOfBounds (index exceeds)
15. UnsupportedOperationException (unsupported operation encountered)
16. ClassNotFoundException (Class not Found)
17. CloneNotSupportedException (attempts to clone object where Clonable not implemented)
18. IllegalAccessException (Access to a class is denied)
19. InstantiationException (creating object from abstract class)
20. InterruptedException (when thread has been interrupted)
21. NoSuchFieldException (when Field does not exist)
22. NoSuchMethodException (when Method does not exist)
Try and catch with example in java:
Now here is the some examples of try and catch block.
EX :
public class TC_Demo
{
public static void main(String[] args)
{
int a=10;
int b=5,c=5;
int x,y;
try
{
x = a / (b-c);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
y = a / (b+c);
System.out.println("y = " + y);
}
}
Output :
Divide by zero
y = 1
Note that program did not stop at the point of exceptional condition. It catches the error condition,
prints the error message, and continues the execution, as if nothing has happened.
If we run same program without try catch block we will not gate the y value in output. It displays
the following message and stops without executing further statements.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Thrw_Excp.TC_Demo.main(TC_Demo.java:10)
Here we write ArithmaticException in catch block because it caused by math errors such as divide
by zero.
Now how to display description of an exception ?
You can display the description of thrown object by using it in a println() statement by simply
passing the exception as an argument. For example;
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
14
catch (ArithmeticException e)
{
system.out.pritnln(―Exception:‖ +e);
}
Multiple catch blocks :
It is possible to have multiple catch blocks in our program.
EX :
public class MultiCatch
{
public static void main(String[] args)
{
int a [] = {5,10};
int b=5;
try
{
int x = a[2] / b - a[1];
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y = a[1]/a[0];
System.out.println("y = " + y);
}
}
Output :
Array index error
y = 2
Note that array element a[2] does not exist. Therefore the index 2 is outside the array boundry.
When exception in try block is generated, the java treats the multiple catch statements like cases in
switch statement.
The first statement whose parameter matches with the exception object will be executed, and the
remaining statements will be skipped.
When you are using multiple catch blocks, it is important to remember that exception subclasses
must come before any of their superclasses.
This is because a catch statement that uses a superclass will catch exceptions of that type plus any
of its subclasses.
Thus, a subclass will never be reached if it comes after its superclass. And it will result into syntax
error.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
15
// Catching super exception before sub
EX :
class etion3
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
}
catch (Exception e)
{
System.out.println("This is mistake. ");
}
catch(ArithmeticException g)
{
System.out.println("Division by zero");
}
}
}
Output :
If you try to compile this program, you will receive an error message because the exception has
already been caught in first catch block.
Since ArithmeticException is a subclass of Exception, the first catch block will handle all exception
based errors, including ArithmeticException. This means that the second catch statement will never
execute.
To fix the problem, revere the order of the catch statement.
Nested try statements :
The try statement can be nested.
That is, a try statement can be inside a block of another try.
Each time a try statement is entered, its corresponding catch block has to entered.
The catch statements are operated from corresponding statement blocks defined by try.
EX :
public class NestedTry
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;
try
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
16
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
}
catch(ArithmeticException e)
{
System.out.println("This is inner catch");
}
}
catch(ArithmeticException g)
{
System.out.println("This is outer catch");
}
}
}
Output :
This is outer catch
Finally
Java supports another statement known as finally statement that can be used to handle an exception
that is not caught by any of the previous catch statements.
We can put finally block after the try block or after the last catch block.
The finally block is executed in all circumstances. Even if a try block completes without problems,
the finally block executes.
EX :
public class Finally_Demo
{
public static void main(String args[])
{
int num1 = 100;
int num2 = 50;
int num3 = 50;
int result1;
try
{
result1 = num1/(num2-num3);
System.out.println("Result1 = " + result1);
}
catch(ArithmeticException g)
{
System.out.println("Division by zero");
}
finally
{
System.out.println("This is final");
}
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
17
Output :
Division by zero
This is final
4.9 Throws
We saw that an exception was generated by the JVM when certain run-time problems occurred.
It is also possible for our program to explicitly generate an exception.
This can be done with a throw statement. Its form is as follows:
Throw object;
Inside a catch block, you can throw the same exception object that was provided as an argument.
This can be done with the following syntax:
catch(ExceptionType object)
{
throw object;
}
Alternatively, you may create and throw a new exception object as follows:
Throw new ExceptionType(args);
Here, exceptionType is the type of the exception object and args is the optional argument list for its
constructor.
When a throw statement is encountered, a search for a matching catch block begins and if found it
is executed.
class Throw_Demo
{
public static void a()
{
try
{
System.out.println("Before b");
b();
}
catch(ArrayIndexOutOfBoundsException j) //manually thrown object catched here
{
System.out.println("J : " + j) ;
}
}
public static void b()
{
int a=5,b=0;
try
{
System.out.println("We r in b");
System.out.println("********");
int x = a/b;
}
catch(ArithmeticException e)
{
System.out.println("c : " + e);
throw new ArrayIndexOutOfBoundsException("demo"); //throw from here
}
}
public static void main(String args[])
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
18
{
try
{
System.out.println("Before a");
a();
System.out.println("********");
System.out.println("After a");
}
catch(ArithmeticException e)
{
System.out.println("Main Program : " + e);
}
}
}
Output :
Before a
Before b
We r in b
********
c : java.lang.ArithmeticException: / by zero
J : java.lang.ArrayIndexOutOfBoundsException: demo
********
After a
Throwing our own object :
If we want to throw our own exception, we can do this by using the keyword throw as follow.
throw new Throwable_subclass;
Example : throw new ArithmaticException( );
throw new NumberFormatException( );
EX :
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String[] args)
{
int x = 5, y = 1000;
try
{
float z = (float)x / (float)y;
if(z < 0.01)
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
19
{
throw new MyException("Number is too small");
}
}
catch(MyException e)
{
System.out.println("Caught MyException");
System.out.println(e.getMessage());
}
finally
{
System.out.println("java2all.com");
}
}
}
Output :
Caught MyException
Number is too small
java2all.com
Here The object e which contains the error message "Number is too small" is caught by the catch
block which then displays the message using getMessage( ) method.
NOTE:
Exception is a subclass of Throwable and therefore MyException is a subclass of Throwable class.
An object of a class that extends Throwable can be thrown and caught.
Throws
If a method is capable of causing an exception that it does not handle, it must specify this behavior
so that callers of the method can guard themselves against that exception.
You do this by including a throws clause in the method’s declaration. Basically it is used for
IOException.
A throws clause lists the types of exceptions that a method might throw. This is necessary for all
exceptions, except those of type Error or RuntimeException,or any of their subclasses. All other
exceptions that a method can throw must be declared in the throws clause.
If they are not, a compile-time error will result.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Throw is used to actually throw the exception, whereas throws is declarative statement for the
method. They are not interchangeable.
EX :
class NewException extends Exception
{
public String toS()
{
return "You are in NewException ";
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
20
class customexception
{
public static void main(String args[])
{
try
{
doWork(3);
doWork(2);
doWork(1);
doWork(0);
}
catch (NewException e)
{
System.out.println("Exception : " + e.toS());
}
}
static void doWork(int value) throws NewException
{
if (value == 0)
{
throw new NewException();
}
else
{
System.out.println("****No Problem.****");
}
}
}
Output:
****No Problem.****
****No Problem.****
****No Problem.****
Exception : You are in NewException
4.10 StackTraceElement
The java.lang.StackTraceElement class element represents a single stack frame. All stack frames
except for the one at the top of the stack represent a method invocation. The frame at the top of the
stack represents the execution point at which the stack trace was generated.
Class declaration
Following is the declaration for java.lang.StackTraceElement class:
public final class StackTraceElement
extends Object
implements Serializable
Class constructors
StackTraceElement(String declaringClass, String methodName, String fileName, int
lineNumber)
This creates a stack trace element representing the specified execution point.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
21
Class methods
StackTraceElement.getMethodName() Method
The java.lang.StackTraceElement.getMethodName() method returns the name of the method containing
the execution point represented by this stack trace element.
Declaration
Following is the declaration for java.lang.StackTraceElement.getMethodName() method
public String getMethodName()
import java.lang.*;
public class StackTraceElementDemo {
public static void main(String[] args) {
function1();
}
public static void function1()
{
new StackTraceElementDemo().function2();
}
public void function2()
{
int i;
System.out.println("method name : ");
// print stack trace
for( i = 1; i <= 3; i++ ) {
System.out.println(Thread.currentThread().getStackTrace()[i]. getMethodName());
} }}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
22
Output:
method name :
function2
function1
main
4.11 Java Assertion
 Assertions are simple check assumption made at the beginning of the program to ensure the program
is true throughout provided by the Java language.
o For example, the range of age should be in between 18 and above; or cannot be more than
50.
 These are the set of expression used in java that enables you to check the assumption made in a
program during throughout the execution of program.
 An Assertion contains a Boolean expression which is set to be true in the beginning of the program.
o For Example ,a program has a method that allow the value being passed to it should not be
zero and negative, you test this assert by sending a only positive number that is greater than
zero by using assert statement in java.
Simple Assertion Form
 The assertion statement has two forms
 The first is:
assert Expression1 ;
- Where Expression1 is a boolean expression
 When the system runs the assertion, it evaluates Expression1 and if it is false throws an
AssertionError with no details
 The second form of the assertion statement is:
assert Expression1 : Expression2 ;
- where:
 Expression1 is a boolean expression
 Expression2 is an expression that has a value
 It cannot invoke of a method that is declared void
 Use the second version of the assert statement to provide a detailed message for the AssertionError
 The system passes the value of Expression2 to the appropriate AssertionError constructor, which
uses the string error message
 The purpose of the message is to communicate the reason for the assertion failure
When an Assertion Fails
 Assertion failures are labeled in stack trace with the file and line number from which they were
thrown
 Second form of the assertion statement should be used in preference to the first when the program
has some additional information that might help diagnose the failure
How to Compile Assertion Files
The Assertion file is compiled with an option ,-source 1.4.The Syntax used in compilation of program is
Javac-source 1.4 AssertDemonstration.java
Where Assert Demonstration is the name of java program using assertion.
-source 1.4 is a command line option to make the compile to accept the code containing assertions.
How to Enable and Disable Assertion
Assertion are disabled at run-time during execution of java program .
The command line prompt -ea or enable assertions is used to enable assertion during run-time execution of
the program.
java -ea:AssertDemonstration
The command prompt -da or disable is used to disable assertion during run-time execution of the program
java -da :AssertDemonstration
Example:
In this Example We, defined a public class 'Mark Assert Demo' Inside the class we define the static variable
i.e. maximum marks to be 100, changes is another static variable, The main static ( ) method has assumption
of maximum marks i.e. 40,if the marks come below to 40,the code will show you java.lang.AssertionError
and display the Marks is below than 40 on the command prompt.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
23
public class MarkAssertDemo
{
static float maximummarks=100;
static float changes(float mark)
{
maximummarks=maximummarks-mark;
System.out.println("The maximummark is:" + maximummarks);
return maximummarks;
}
public static void main(String args[])
{
float g;
for(int i=0;i<5;i++)
{
g=changes(15);
assert maximummarks>=40.00:"marks is below 40.";
}
}
}
Output:
C:>javac -source 1.4 MarkAssertDemo.java
C:>java -ea MarkAssertDemo
The maximummark is:85.0
The maximummark is:70.0
The maximummark is:55.0
The maximummark is:40.0
The maximummark is:25.0
Exception in thread "main" java.lang.AssertionError: marks is below 40.
at MarkAssertDemo.main(MarkAssertDemo.java:16)
4.12 Logging
 ―Logging‖ is producing messages that tell you what your program is doing
 It’s not much different than using System.out.println(...)
 Log messages can go to the console, to a file, or one of several other places (e.g. sent over the
Internet)
 You can use logging to help you debug a program
 You can use logging to produce a file when the user runs your program
Java Logger
 Logger is the class of java.util.logging package that extends the Object class.
 Java provides logging APIs like: Logger, Level, Handler etc. for implementing logging features in
your java application.
 It is a part of J2SE (Java 2 Standard Edition).
 When you go to create java logging program then first of all need a Logger object.
 The Logger object contains log messages. Logger has one or more handler that performs log records.
 A logger object used for logging messages for individual system or an application component that
can be derived by getLogger methods.
 Java logging provides a way to contain multiple types of message like: warning, info, severe etc. for
an application.
 These information or messages can be used for many purposes but it is specially used for debugging,
troubleshooting and auditing.
Logging levels and methods
 Level.SEVERE
 Level.WARNING
 Level.INFO
 Level.CONFIG
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
24
 Level.FINE
 Level.FINER
 Level.FINEST
 myLogger.severe(String msg);
 myLogger.warning(String msg);
 myLogger.info(String msg);
 myLogger.config(String msg);
 myLogger.fine(String msg);
 myLogger.finer(String msg);
 myLogger.finest(String msg);
 These levels are ordered, so that you can set the level of severity that results in log messages
 However, the levels have no inherent meaning--they are what you make of them
Controlling logging levels
 public void Logger.setLevel(Level newLevel)
 Sets the logger to log all messages at newLevel or above
 Logger calls at lower levels don’t do anything
 Example: logger.setLevel(Level.WARNING);
 Additional settings:
 logger.setLevel(Level.ALL);
 logger.setLevel(Level.OFF);
 public Level getLevel()
 Note that this returns a Level, not an int
 Level has intValue() and toString() methods
Additional Logger methods
 void entering(String sourceClass, String sourceMethod)
 void entering(String sourceClass, String sourceMethod, Object param1)
 void entering(String sourceClass, String sourceMethod, Object[] params)
 void exiting(String sourceClass, String sourceMethod)
 void exiting(String sourceClass, String sourceMethod, Object result)
 These log messages at level FINER
Logging flow of control
 You send your message to a Logger
 The Logger checks a Filter to see whether to ignore the message
 The Logger sends the message to a Handler to put the message somewhere
 The Handler checks another Filter to see whether to ignore this kind of message sent to this
destination
 The Handler calls a Formatter to decide what kind of a text string to produce
 The Handler sends the formatted message somewhere
Filters
 Filter is an interface; it defines the single method
boolean isLoggable(LogRecord record)
 A LogRecord is another class in java.util.logging; it provides numerous methods for examining the
proposed logging message
Logging formatting and destinations
 The JDK defines five Handlers:
 StreamHandler: sends messages to an OutputStream
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
25
 ConsoleHandler: sends messages to System.err (default)
 FileHandler: sends messages to a file
 SocketHandler: sends messages to a TCP port
 MemoryHandler: buffers messages in memory
 It also defines two ways to format messages:
 SimpleFormatter (default)
 XMLFormatter
 And, of course, you can define your own Handlers and Formatters
 As you can tell from the ―Basic Use‖ slide earlier, you can ignore all of this and just use the defaults
Program Descriptions:
This program simply create a log file and shows log message for the warning, info and servere and another
checked the logging message. This program creates a log file that contains multiple information.
import java.io.*;
import java.util.logging.*;
public class QuintLog{
public static void main(String[] args) {
try{
FileHandler hand = new FileHandler("vk.log");
Logger log = Logger.getLogger("log_file");
log.addHandler(hand);
log.warning("Doing carefully!");
log.info("Doing something ...");
log.severe("Doing strictily ");
System.out.println(log.getName());
}
catch(IOException e){}
}
}
Output:
Aug 27, 2013 9:17:46 AM QuintLog main
WARNING: Doing carefully!
Aug 27, 2013 9:17:46 AM QuintLog main
INFO: Doing something ...
Aug 27, 2013 9:17:46 AM QuintLog main
SEVERE: Doing strictily
log_file
Program Descriptions:
This program check logger object. If given instruction is certify then shows finest message like: 'Display a
finest message' otherwise no any message appear to here.
import java.io.*;
import java.util.logging.*;
public class CheckLogMessage{
public static void main(String[] args) {
Logger log = Logger.getLogger("log_file");
if(log.isLoggable(Level.OFF)){
log.finest("Display a finest message");
}
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
1
UNIT V
CONCURRENT PROGRAMMING
5.1 Multi-threaded programming
5.2 interrupting threads
5.3 thread states
5.4 thread properties
5.5 thread synchronization
5.6 thread-safe Collections
5.7 Executors
5.8 synchronizers
5.9 threads and event-driven programming
Introduction
• Performing operations concurrently (in parallel)
– We can walk, talk, breathe, see, hear, smell... all at the same time
– Computers can do this as well - download a file, print a file, receive email, run the clock,
more or less in parallel….
• How are these tasks typically accomplished?
• Operating systems support processes
• What’s the difference between a process and a thread?
• Processes have their own memory space, threads share memory
• Hence processes are “heavyweight” while threads are “lightweight”
– Most programming languages do not allow concurrency
– Usually limited to operating system "primitives" available to systems programmers
– Java supports concurrency as part of language and libraries
– What other languages support concurrency in the language?
– Each thread is a portion of a program that can execute concurrently with other threads
(multithreading)
• C and C++ are single-threaded
• Gives Java powerful capabilities not found in C and C++
– Example: downloading a video clip
• Instead of having to download the entire clip then play it:
• Download a portion, play that portion, download the next portion, play that
portion... (streaming)
• Ensure that it is done smoothly
5.1 Multithreading Programming
Multithreading is a conceptual programming paradigm where a program (process) is divided in to
two or more sub programs (processes) which can be implemented at the same time in interval. A thread is
similar to a program that has a single flow of control. It has a beginning a body, and an end, and executes
commands sequentially.
A unique property of java is its support for multithreading. (i.e) Java enables us to use multiple of
control may be thought of as a separate tiny program (or module) known as a thread that runs in parallel to
others. A program that contains multiple flows of control is known as Multithreaded Program.
Thread Priorities:
• All Java applets / applications are multithreaded
– Threads have priority from 1 to 10
• Thread.MIN_PRIORITY - 1
• Thread.NORM_PRIORITY - 5 (default)
• Thread.MAX_PRIORITY - 10
• New threads inherit priority of thread that created it
• Priority methods
– setPriority( int priorityNumber )
– getPriority
– yield - thread yields processor to threads of equal priority
• Useful for non-timesliced systems, where threads run to completion
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
2
Creating Threads in Java
Java defines two ways in which this can be accomplished:
1. implementing the Runnable interface (java.lang.Runnable)
– The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. The class must define a method, called run, with no arguments.
– invoke Thread constructor with an instance of this Runnable class
2. extending Thread
– Define a subclass of java.lang.Thread
• Define a run method
– In another thread (e.g., the main), create an instance of the Thread subclass
• Then, call start method of that instance
 Threads are implemented in the form of objects that contain a method called run(). The run()
method is the heart and soul of any thread. It makes up the entire body of a thread and is the only
method in which the thread’s behavior can be implemented.
 The run() method should be invoked by an object of the concerned thread. This can be achieved by
creating the thread and initiating it with the help of another thread method called start().
implementing the Runnable interface (java.lang.Runnable)
– Create new threads using Thread constructors
• Thread( runnableObject )
• Thread( runnableObject, threadName )
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}
class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to instantiate a
thread implementing runnable interface
t.start(); // starts the thread by running the run method
}
}
• Calling t.run() does not start a thread, it is just a simple method call.
• Creating an object does not create a thread, calling start() method creates the thread.
extending Thread
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output:
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
3
thread is running…..
Multithreading example
//<b><i>Program of performing two tasks by two threads</i></b>
class Simple1 extends Thread{
public void run(){
System.out.println("task one");
}
}
class Simple2 extends Thread{
public void run(){
System.out.println("task two");
}
}
class Test{
public static void main(String args[]){
Simple1 t1=new Simple1();
Simple2 t2=new Simple2();
t1.start();
t2.start();
}
}
Output
task one
task two
Thread Methods:
5.2 Interrupting Threads
 Interrupting a thread means stopping what it is doing before it has completed its task, effectively
aborting its current operation.
 The interrupt method can be used to request termination of a thread. When the interrupt method is
called on a thread, the interrupted status of the thread is set.
 This is a boolean flag that is present in every thread. Each thread should occasionally check whether
it has been interrupted.
 To find out whether the interrupted status was set, first call the static Thread.currentThread method
to get the current thread and then call the isInterrupted method.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
4
while (!Thread.currentThread().isInterrupted() && more work to do)
{
do more work
}
However, if a thread is blocked, it cannot check the interrupted status.
This is where the InterruptedException comes in. When the interrupt method is called on a thread that blocks
on a call such as sleep or wait, the blocking call is terminated by an InterruptedException.
Eg:threadinterrupttest.java
class athread extends Thread
{
public void run()
{
while(true)
{
System.out.println("Thread Running...");
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println("Thread Interrupted...");
}
}
}
}
class threadinterrupttest
{
public static void main(String arg[])throws Exception
{
athread p = new athread();
System.out.println("Thread starting");
p.start();
Thread.sleep(2000);
p.interrupt();
System.out.println("Stopping Application");
System.exit(0);
}
}
5.3 Thread States
• Born state
– Thread just created
– When start called, enters ready state
• Ready state (runnable state)
– Highest-priority ready thread enters running state
• Running state
– System assigns processor to thread (thread begins executing)
– When run completes or terminates, enters dead state
• Dead state
– Thread marked to be removed by system
– Entered when run terminates or throws uncaught exception
• Blocked state
– Entered from running state
– Blocked thread cannot use processor, even if available
– Common reason for blocked state - waiting on I/O request
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
5
• Sleeping state
– Entered when sleep method called
– Cannot use processor
– Enters ready state after sleep time expires
• Waiting state
– Entered when wait called in an object thread is accessing
– One waiting thread becomes ready when object calls notify
– notifyAll - all waiting threads become ready
invoking methods like new(), start(), yield(), sleep(), wait(), notify()…
5.4 Thread Property
• static void sleep( long milliseconds )
– Thread sleeps (does not contend for processor) for number of milliseconds
– Why might we want a program to invoke sleep?
– Can give lower priority threads a chance to run
• void interrupt() - interrupts a thread
• boolean isInterrupted()
– Determines if a thread is interrupted
• boolean isAlive()
– Returns true if start called and thread not dead (run has not completed)
• getPriority() - returns this thread's priority
• setPriority() – sets this threads priority
• Etc.
class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
class TwoThreadsTest {
public static void main (String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
You should see output similar to the following:
0 Jamaica
0 Fiji
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
6
1 Fiji
1 Jamaica
2 Jamaica
2 Fiji
3 Fiji
3 Jamaica
4 Jamaica
4 Fiji
5 Jamaica
5 Fiji
6 Fiji
6 Jamaica
7 Jamaica
7 Fiji
8 Fiji
9 Fiji
8 Jamaica
DONE! Fiji
9 Jamaica
DONE! Jamaica
(Looks like I'm going to Fiji!!) Notice how the output from each thread is intermingled with the output from
the other. This is because both SimpleThread threads are running concurrently. Thus, both run methods are
running at the same time and each thread is displaying its output at the same time as the other.
5.5 Thread Synchronization
• Synchronization is prevent data corruption
• Synchronization allows only one thread to perform an operation on a object at a time.
• If multiple threads require an access to an object, synchronization helps in maintaining consistency.
Types of Thread synchronization
1. Mutual Exclusive
a. Synchronized method
b. Static synchronization
c. Synchronized block
2. Inter-thread Communication
Problems in syncronization
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
public setCount(int count){
this.count = count;
}
}
• In this example, the counter tells how many an access has been made.
• If a thread is accessing setCount and updating count and another thread is accessing getCount at the
same time, there will be inconsistency in the value of count.
Solution by synchronized method
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
7
• By adding the synchronized keyword we make sure that when one thread is in the setCount method
the other threads are all in waiting state.
• The synchronized keyword places a lock on the object, and hence locks all the other methods which
have the keyword synchronized. The lock does not lock the methods without the keyword
synchronized and hence they are open to access by other threads.
Solution by static synchronized
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public static synchronized setCount(int count){
this.count = count;
}
}
• In this example the methods are static and hence are associated with the class object and not the
instance.
• Hence the lock is placed on the class object that is, Counter.class object and not on the object itself.
Any other non static synchronized methods are still available for access by other threads.
Common Synchronization mistake
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public synchronized setCount(int count){
this.count = count;
}
}
• The common mistake here is one method is static synchronized and another method is non static
synchronized.
• This makes a difference as locks are placed on two different objects. The class object and the
instance and hence two different threads can access the methods simultaneously.
Solution by synchronized method
• The object can be explicitly locked in this way
synchronized(myInstance){
try{
wait();
}catch(InterruptedException ex){
}
System.out.println(“Iam in this “);
notifyAll();
}
• The synchronized keyword locks the object. The wait keyword waits for the lock to be
acquired, if the object was already locked by another thread. Notifyall() notifies other
threads that the lock is about to be released by the current thread.
• Another method notify() is available for use, which wakes up only the next thread which is
in queue for the object, notifyall() wakes up all the threads and transfers the lock to another
thread having the highest priority.
5.6 Thread safe Collection
 The methods of legacy classes (the data structure that comes with JDK 1.0) like Vector and
Hashtable are implicitly synchronized. They are best suitable for thread-safe operations.
 An operation is said to be thread-safe when multiple threads access the data, the data should not get
corrupted or result in inconsistency. It is the precaution to be taken in a multithreaded environment.
 But collection classes are not implicitly thread-safe as their methods are not synchronized. It's
synchronizedCollection() method returns an object of Collection with synchronized methods. That is
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
8
with collection classes, you got a choice to have synchronized or non-synchronized version. But
incase of legacy classes it is not possible; you must have synchronized vector or hash table only.
 Following is the method signature
o static Collection synchronizedCollection(Collection col1): Returns a synchronized version
of Collection col1. It is used for thread-safe operations.
o The synchronized version can be used safely in a multithreaded environment.
 Methods like
 synchronizedSet(),
 synchronizedSortedSet(),
 synchronizedList(),
 synchronizedMap() and
 synchronizedSortedMap() also exist to use with set, list and map.
import java.util.*;
public class CollectionsSynchronized {
public static void main(String args[]) {
ArrayList firstList = new ArrayList();
firstList.add(10);
firstList.add(20);
firstList.add(30);
firstList.add(40);
List secondList = Collections.synchronizedList(firstList);
System.out.println("secondList elements: " + secondList);
HashSet firstSet = new HashSet();
firstSet.add("hello");
firstSet.add("world");
Set secondSet = Collections.synchronizedSet(firstSet);
System.out.println("nsecondSet elements: " + secondSet); } }
ArrayList firstList = new ArrayList();
firstList.add(10);
An ArrayList object firstList is created and added with few elements with add() method inherited from List
interface. This object works nice in general conditions but not in multithreaded programming.
List secondList = Collections.synchronizedList(firstList);
The synchronizedList(firstList) method of Collections class returns an object of List, secondList. Now
secondList methods are synchronized and suitable with multiple threads access. But still the original firstList
methods not synchronized. Now programmer has the choice between the two, firstList and secondList, to use
in his code.
HashSet firstSet = new HashSet();
firstSet.add(“hello”); firstSet.add(“world”);
Set secondSet = Collections.synchronizedSet(firstSet);
Similarly, from the HashSet object firstSet, it is possible to obtain a synchronized version with
synchronizedSet(firstSet) method. The returned Set object, secondSet, is synchronized.
5.7 Executors
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
9
 Constructing a new thread is somewhat expensive because it involves interaction with the operating
system.
 If your program creates a large number of short-lived threads, then it should instead use a thread
pool.
 A thread pool contains a number of idle threads that are ready to run. You give a Runnable to the
pool, and one of the threads calls the run method. When the run method exits, the thread doesn’t die
but stays around to serve the next request.
 Creating a huge number of threads can greatly degrade performance and even crash the virtual
machine. If you have an algorithm that creates lots of threads, then you should use a “fixed” thread
pool that bounds the total number of concurrent threads.
 How the Connection pool is executed?
1. Call the static newCachedThreadPool or newFixedThreadPool method of the Executors
class.
2. Call submit to submit Runnable or Callable objects.
3. If you want to be able to cancel a task or if you submit Callable objects, hang on to the
returned Future objects.
4. Call shutdown when you no longer want to submit any tasks.
 The Executors class helps you manage the creation of threads in a pool, their scheduling (if
applicable), as well as their termination. In general, it helps you avoid having to create and manage
threads yourself.
 The Executors class has a number of static factory methods for constructing thread pools;
 For example, rather than creating a new thread and starting it, the following can be done.
ExecutorService executor = some Executor factory method;
executor.execute(aRunnable);
 If you have several Runnable tasks to carry out, then a simple thread pool arrangement is provided as
follows:
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());
…………….
 here the tasks run and complete under the control of the Executor, which reuses threads from the
thread pool as needed without incurring the overhead of always creating new threads.
 The threads can be stopped with executor.shutdown();
5.8 Java Synchronizers
 Java 5 introduces general purpose synchronization classes, including semaphores, mutexes,
barriers, latches, and exchangers, which facilitate coordination between threads.
 These classes are a part of the java.util.concurrent package.
 A brief description of each of these follows:
Semaphores
 A counting semaphore maintains a set of permits.
 Each acquire() blocks if necessary until a permit is available, and then takes it.
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
10
 Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit
objects are used; the Semaphore just keeps a count of the number available and acts accordingly.
 Semaphores are often used to restrict the number of threads than can access some (physical or
logical) resource.
Barrier
 A synchronization aid that allows a set of threads to all wait for each other to reach a common
barrier point.
 CyclicBarriers are useful in programs involving a fixed sized group of threads that must
occasionally wait for each other.
 The barrier is called cyclic because it can be re-used after the waiting threads are released.
Exchangers
 A synchronization point at which two threads can exchange objects.
 Each thread presents some object on entry to the exchange method, and receives the object presented
by the other thread on return.
Latches
 A synchronization aid that allows one or more threads to wait until a set of operations being
performed in other threads completes.
 A CountDownLatch is initialized with a given count. T
 he await methods block until the current count reaches zero due to invocations of the countDown()
method, after which all waiting threads are released and any subsequent invocations of await return
immediately.
5.9 Threads and Event Driven Programming
 Once a Swing component has been realized, all code that might affect or depend on the state of that
component should be executed in the event-dispatching thread.
 This rule might sound scary, but for many simple programs, you don't have to worry about threads.
Before we go into detail about how to write Swing code, let's define two terms: realized and event-
dispatching thread.
 Realized means that the component's paint() method has been or might be called.
 A Swing component that's a top-level window is realized by having one of these methods invoked on
it: setVisible(true), show(), or (this might surprise you) pack().
 Once a window is realized, all components that it contains are realized. Another way to realize a
component is to add it to a container that's already realized.
 The event-dispatching thread is the thread that executes drawing and event-handling code.
 For example, the paint() and actionPerformed() methods are automatically executed in the event-
dispatching thread. Another way to execute code in the event-dispatching thread is to use the
SwingUtilities invokeLater() method.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ViewPage
{
public static void main(String[] args)
{
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
11
Runnable r;
r = new Runnable()
{
@Override
public void run()
{
final JFrame frame = new JFrame("View Page");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(new JLabel("Enter URL"));
final JTextField txtURL = new JTextField(40);
panel.add(txtURL);
frame.getContentPane().add(panel, BorderLayout.NORTH);
final JTextArea txtHTML = new JTextArea(10, 40);
frame.getContentPane().add(new JScrollPane(txtHTML),
BorderLayout.CENTER);
ActionListener al;
al = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
txtURL.setEnabled(false);
Runnable worker = new Runnable()
{
public void run()
{
InputStream is = null;
try
{
URL url = new URL(txtURL.getText());
is = url.openStream();
final StringBuilder sb;
sb = new StringBuilder();
int b;
while ((b = is.read()) != -1)
{
sb.append((char) b);
}
Runnable r = new Runnable()
{
public void run()
{
try
{
Thread.sleep(6000);
}
catch (InterruptedException ex)
{
Logger.getLogger(ViewPage.class.getName()).log(Level.SEVERE, null, ex);
}
txtHTML.setText(sb.toString());
txtURL.setEnabled(true);
}
};
try
{
EventQueue.invokeAndWait(r);
}
catch (InterruptedException ie)
{
}
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
12
catch (InvocationTargetException ite)
{
}
}
catch (final IOException ioe)
{
Runnable r = new Runnable()
{
public void run()
{
txtHTML.setText(ioe.getMessage());
txtURL.setEnabled(true);
}
};
try
{
EventQueue.invokeAndWait(r);
}
catch (InterruptedException ie)
{
}
catch (InvocationTargetException ite)
{
}
}
finally
{
Runnable r = new Runnable()
{
public void run()
{
txtHTML.setCaretPosition(0);
txtURL.setEnabled(true);
}
};
try
{
EventQueue.invokeAndWait(r);
}
catch (InterruptedException ie)
{
}
catch (InvocationTargetException ite)
{
}
if (is != null)
{
try
{
is.close();
}
catch (IOException ioe)
{
}
}
}
}
};
new Thread(worker).start();
}
};
CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
13
txtURL.addActionListener(al);
frame.pack();
frame.setVisible(true);
}
};
EventQueue.invokeLater(r);
}
}

More Related Content

What's hot (20)

PPTX
Merge sort
Sindhoo Oad
 
PPTX
Lexical analyzer generator lex
Anusuya123
 
PPTX
0 1 knapsack using branch and bound
Abhishek Singh
 
PPTX
daa-unit-3-greedy method
hodcsencet
 
PPTX
Type checking in compiler design
Sudip Singh
 
PPTX
Activity selection problem
QAU ISLAMABAD,PAKISTAN
 
PPT
chapter 1
yatheesha
 
DOCX
The Burrows-Wheeler Algorithm
Mustafa Salam
 
PPTX
Lexical analysis - Compiler Design
Muhammed Afsal Villan
 
PPTX
Compiler Design LR parsing SLR ,LALR CLR
Riazul Islam
 
PDF
Divide and Conquer
Mohammed Hussein
 
PPTX
Introduction to Dynamic Programming, Principle of Optimality
Bhavin Darji
 
PDF
Lexical Analysis - Compiler design
Aman Sharma
 
PPTX
Quick sort
Dhruv Sabalpara
 
PPTX
AES KEY EXPANSION .pptx
AhmudulHassan
 
PDF
Dynamic programming
Amit Kumar Rathi
 
PPTX
search strategies in artificial intelligence
Hanif Ullah (Gold Medalist)
 
PPTX
Loop optimization
Vivek Gandhi
 
PPTX
Divide and conquer - Quick sort
Madhu Bala
 
PPT
Searching algorithms
Trupti Agrawal
 
Merge sort
Sindhoo Oad
 
Lexical analyzer generator lex
Anusuya123
 
0 1 knapsack using branch and bound
Abhishek Singh
 
daa-unit-3-greedy method
hodcsencet
 
Type checking in compiler design
Sudip Singh
 
Activity selection problem
QAU ISLAMABAD,PAKISTAN
 
chapter 1
yatheesha
 
The Burrows-Wheeler Algorithm
Mustafa Salam
 
Lexical analysis - Compiler Design
Muhammed Afsal Villan
 
Compiler Design LR parsing SLR ,LALR CLR
Riazul Islam
 
Divide and Conquer
Mohammed Hussein
 
Introduction to Dynamic Programming, Principle of Optimality
Bhavin Darji
 
Lexical Analysis - Compiler design
Aman Sharma
 
Quick sort
Dhruv Sabalpara
 
AES KEY EXPANSION .pptx
AhmudulHassan
 
Dynamic programming
Amit Kumar Rathi
 
search strategies in artificial intelligence
Hanif Ullah (Gold Medalist)
 
Loop optimization
Vivek Gandhi
 
Divide and conquer - Quick sort
Madhu Bala
 
Searching algorithms
Trupti Agrawal
 

Similar to Cs2305 programming paradigms lecturer notes (20)

PPT
Md02 - Getting Started part-2
Rakesh Madugula
 
PDF
JAVA-PPT'S.pdf
AnmolVerma363503
 
PDF
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
ApurvaLaddha
 
PPT
Share Unit 1- Basic concept of object-oriented-programming.ppt
hannahrroselin95
 
PPT
Unit 1- Basic concept of object-oriented-programming.ppt
hannahroseline2
 
PPTX
Introduction to OOP concepts
Ahmed Farag
 
DOCX
Ooad notes
NancyJP
 
PDF
MCA NOTES.pdf
RAJASEKHARV10
 
PPTX
JAVA-PPT'S.pptx
RaazIndia
 
PPTX
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
PDF
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
PDF
Bt8901 objective oriented systems1
Techglyphs
 
PPTX
Selenium Training .pptx
SajidTk2
 
PPTX
Introduction to OOPs second year cse.pptx
solemanhldr
 
PPTX
Object oriented programming
baabtra.com - No. 1 supplier of quality freshers
 
PDF
Oops concepts
ACCESS Health Digital
 
PDF
Lecture 2 cst 205-281 oop
ktuonlinenotes
 
PPTX
OOPS in Java
Zeeshan Khan
 
PPTX
object oriented programing lecture 1
Geophery sanga
 
Md02 - Getting Started part-2
Rakesh Madugula
 
JAVA-PPT'S.pdf
AnmolVerma363503
 
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
ApurvaLaddha
 
Share Unit 1- Basic concept of object-oriented-programming.ppt
hannahrroselin95
 
Unit 1- Basic concept of object-oriented-programming.ppt
hannahroseline2
 
Introduction to OOP concepts
Ahmed Farag
 
Ooad notes
NancyJP
 
MCA NOTES.pdf
RAJASEKHARV10
 
JAVA-PPT'S.pptx
RaazIndia
 
JAVA-PPT'S-complete-chrome.pptx
KunalYadav65140
 
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Bt8901 objective oriented systems1
Techglyphs
 
Selenium Training .pptx
SajidTk2
 
Introduction to OOPs second year cse.pptx
solemanhldr
 
Oops concepts
ACCESS Health Digital
 
Lecture 2 cst 205-281 oop
ktuonlinenotes
 
OOPS in Java
Zeeshan Khan
 
object oriented programing lecture 1
Geophery sanga
 
Ad

More from Saravanakumar viswanathan (16)

PPTX
18 cse412 elt-course orientation-saravanakumar
Saravanakumar viswanathan
 
PDF
Bdt unit iv data analyics using r
Saravanakumar viswanathan
 
PDF
Bdt 3 exercise problems
Saravanakumar viswanathan
 
PPTX
How to give a good seminar project presentation
Saravanakumar viswanathan
 
PPTX
18 mdcse117 m&amp;wt -course orientation
Saravanakumar viswanathan
 
PPTX
Python operator precedence and comments
Saravanakumar viswanathan
 
PPTX
Python data types
Saravanakumar viswanathan
 
PPTX
Top 5 python libraries for data science cheat sheat
Saravanakumar viswanathan
 
PPTX
Google colab installing ml libraries
Saravanakumar viswanathan
 
PPTX
Google colab documenting and saving your code
Saravanakumar viswanathan
 
PPTX
Google colab get started
Saravanakumar viswanathan
 
PPTX
Google colab introduction
Saravanakumar viswanathan
 
PPTX
Top 10 python ide
Saravanakumar viswanathan
 
PPTX
Python introduction why to study
Saravanakumar viswanathan
 
PPT
Parts of the computer ppt
Saravanakumar viswanathan
 
18 cse412 elt-course orientation-saravanakumar
Saravanakumar viswanathan
 
Bdt unit iv data analyics using r
Saravanakumar viswanathan
 
Bdt 3 exercise problems
Saravanakumar viswanathan
 
How to give a good seminar project presentation
Saravanakumar viswanathan
 
18 mdcse117 m&amp;wt -course orientation
Saravanakumar viswanathan
 
Python operator precedence and comments
Saravanakumar viswanathan
 
Python data types
Saravanakumar viswanathan
 
Top 5 python libraries for data science cheat sheat
Saravanakumar viswanathan
 
Google colab installing ml libraries
Saravanakumar viswanathan
 
Google colab documenting and saving your code
Saravanakumar viswanathan
 
Google colab get started
Saravanakumar viswanathan
 
Google colab introduction
Saravanakumar viswanathan
 
Top 10 python ide
Saravanakumar viswanathan
 
Python introduction why to study
Saravanakumar viswanathan
 
Parts of the computer ppt
Saravanakumar viswanathan
 
Ad

Recently uploaded (20)

PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PPTX
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
PDF
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PDF
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PDF
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
PDF
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PPTX
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
PPTX
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
PPT
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
How Industrial Project Management Differs From Construction.pptx
jamespit799
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
GitOps_Without_K8s_Training_detailed git repository
DanialHabibi2
 
SERVERLESS PERSONAL TO-DO LIST APPLICATION
anushaashraf20
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
Introduction to Productivity and Quality
মোঃ ফুরকান উদ্দিন জুয়েল
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Halide Perovskites’ Multifunctional Properties: Coordination Engineering, Coo...
TaameBerhe2
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
2025 CGI Congres - Surviving agile v05.pptx
Derk-Jan de Grood
 
MAD Unit - 1 Introduction of Android IT Department
JappanMavani
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
fatigue in aircraft structures-221113192308-0ad6dc8c.pptx
aviatecofficial
 
VITEEE 2026 Exam Details , Important Dates
SonaliSingh127098
 
New_school_Engineering_presentation_011707.ppt
VinayKumar304579
 
Design Thinking basics for Engineers.pdf
CMR University
 

Cs2305 programming paradigms lecturer notes

  • 1. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 1 Unit I – Object Oriented Programming – Fundamentals 1.1 Review of OOP 1.2 Objects and Classes in Java 1.3 Defining Classes 1.4 Methods 1.5 Access Specifiers 1.6 Static Members 1.7 Constructors 1.8 Finalize method 1.9 Arrays 1.10 Strings 1.11 Package 1.12 JavaDoc Comments Programming Paradigms: A programming paradigm is a general approach, orientation, or philosophy of programming that can be used when implementing a program. One paradigm may be generally better for certain kinds of problems than other paradigms are for those problems, and a paradigm may be better for certain kinds of problems than for other kinds of problems. Four most common paradigms: 1. imperative (or procedural) - C 2. applicative (or functional) - ML 3. rule-based (or logic) - prolog 4. object oriented – small talk, C++, Java 1.1 Review of OOP  Process oriented model:  In Process oriented model code is written around what is happening.  This approach characterizes a program as a series of linear steps i.e. the code.  It is the code acting on data.  In a conventional application we typically: o decompose it into a series of functions, o define data structures that those functions act upon o there is no relationship between the two other than the functions act on the data Steps in process oriented approach: 1. Procedure is determined i.e. Algorithm 2. Appropriate ways to store data i.e. Data Structure. Algorithm + Data Structure = Programs Disadvantage of process oriented model:  As program grows larger the complexity increases.
  • 2. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 2  Object Oriented Programming: It organizes program around its data i.e. Objects and set of well defined interface to that data. Object oriented programming is characterized as data controlling access to code. • How is OOP different to conventional programming? – Decompose the application into abstract data types by identifying some useful entities/abstractions – An abstract type is made up of a series of behaviours and the data that those behaviours use. Steps in Object Oriented Programming: 1. Puts the data first. 2. Looks for algorithm to operate on the data. Benefits of OO programming a. Easier to understand (closer to how we view the world) b. Easier to maintain (localised changes) c. Modular (classes and objects) d. Good level of code reuse (aggregation and inheritance) • Understanding OOP is fundamental to writing good Java applications – Improves design of your code – Improves understanding of the Java APIs • There are several concepts underlying OOP:  Object  Abstract Types (Classes)  Encapsulation (or Information Hiding)  Aggregation  Inheritance  Polymorphism  Dynamic binding  Message passing Object  Objects are basic runtime entity in an object oriented system. It is a real world entity & an bundle of related state and behaviour. Object is an instance of Class, We can access Class Member using its Object. e.g-Person, Place ,Book etc Object in java are created using the new operator. Eg: Rectangle rec1; // Declare the object Rec1 = new Rectangle //instantiate the object The above statements can also be combined as follows
  • 3. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 3  Rectangle rec1 = new Rectangle; Abstract Data Types • Identifying abstract types is part of the modelling/design process – The types that are useful to model may vary according to the individual application – For example a payroll system might need to know about Departments, Employees, Managers, Salaries, etc – An E-Commerce application may need to know about Users, Shopping Carts, Products, etc • Object-oriented languages provide a way to define abstract data types, and then create objects from them – It‘s a template (or ‗cookie cutter‘) from which we can create new objects – For example, a Car class might have attributes of speed, colour, and behaviours of accelerate, brake, etc – An individual Car object will have the same behaviours but its own values assigned to the attributes (e.g. 30mph, Red, etc) Classes  A class is a prototype from which objects are created. The entire set of data and code of an object can be made a user defined data-type with the help of a Class. In fact objects are variables of the type class. e.g-object ORANGE belongs to Class FRUIT  Defining the Class: A class is defined by the user is data type with the template that helps in defining the properties. Once the class type has been defined we can create the variables of that type using declarations that are similar to the basic type declarations. In java instances of the classes which are actual objects Eg: classclassname [extends superclassname] { [fields declarations;] [methods declaration;] }  Field Declaration Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables are called as instance variables.
  • 4. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 4 Class Rectangle { int length; int width; }  Method Declaration A Class with only data fields has no life, we must add methods for manipulating the data contained in the class. Methods are declared inside the class immediate after the instance variables declaration. Eg: class Rectangle { int length; //instance variables int width; Void getData(int x, int y) // Method Declartion { Length =x; Width = y; } } Encapsulation • The data (state) of an object is private – it cannot be accessed directly. • The state can only be changed through its behaviour, otherwise known as its public interface or contract • This is called encapsulation  Main benefit of encapsulation o Internal state and processes can be changed independently of the public interface o Limits the amount of large-scale changes required to a system  Example: Automatic transmission on a car.  It encapsulates hundreds of bit of information about engine such as how much acceleration is given, pitch of surface, position of shift lever.  All the information about engine is encapsulated.  The method of affecting this complex encapsulation is by moving the gear shift lever.  We can affect transmission only by using gear shift lever and can‘t affect transmission by using the turn signal or windshield wiper.  Thus gear shift lever is a well defined interface to the transmission.  What occurs inside the transmission does not affect the objects outside the transmission. o For example, shifting gear does not turn on the head lights. Private Data Public Interface "The Doughnut Diagram" Showing that an object has private state and public behaviour. State can only be changed by invoking some behaviour
  • 5. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 5 Aggregation • Aggregation is the ability to create new classes out of existing classes – Treating them as building blocks or components • Aggregation allows reuse of existing code – ―Holy Grail‖ of software engineering • Two forms of aggregation • Whole-Part relationships – Car is made of Engine, Chassis, Wheels • Containment relationships – A Shopping Cart contains several Products – A List contains several Items Inheritance • Inheritance is the ability to define a new class in terms of an existing class – The existing class is the parent, base or superclass – The new class is the child, derived or subclass • The child class inherits all of the attributes and behaviour of its parent class – It can then add new attributes or behaviour – Or even alter the implementation of existing behaviour • Inheritance is therefore another form of code reuse The bird 'robin ' is a part of the class 'flying bird' which is again a part of the class 'bird'. Polymorphism  Polymorphism means the ability to take more than one form.  Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
  • 6. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 6 Dynamic Binding  Binding refers to the linking of a procedure call to the code to be executed.  Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time. Message Communication  Objects communicate with one another by sending and receiving information. A message for an object is a request for execution of a procedure. Message passing involves specifying the name of the object, the name of the function (message) and the information to be sent. Basics of Java Java is a programming language and a platform. Application of Java According to sun Microsystems, 3 billion devices run java. 1. Desktop application such as acrobat reader, media player, antivirus,etc 2. Web application such as irctc.co.in,etc 3. Enterprise application such as banking applications 4. Mobile 5. Embedded systems 6. Smart card 7. Games and so on Types of Java Basically Java Applications can be 4 types 1. Standalone application(like Microsoft office) Technology: core java 2. Client Server application(like yahoo chat) Technology: core java and web technology 3. Web Application(like orkut, facebook etc) Technology: Servlet, JSP, Struts, Hibernate etc. Any web server is required to run this application like TOMCAT 4. Distributed Application (like banking application) Technology: EJB application History of java  James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language in June 1991.  Originally designed for small, embedded systems in electronic appliances like setup box.  Initially called Oak, and was developed as a part of Green project.  In 1995, Oak was renamed as Java. Characteristics of Java  Java is simple  Java is object-oriented  Java is distributed  Java is interpreted  Java is robust  Java is secure  Java is architecture-neutral  Java is portable  Java‘s performance  Java is multithreaded  Java is dynamic
  • 7. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 7 JDK Versions  JDK 1.02 (1995)  JDK 1.1 (1996)  Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)  Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)  Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)  Java 2 SDK v 1.5 (a.k.a JDK 1.4, 2004)  Java 2 SDK v 1.6 (a.k.a JDK 1.4, 2006)  Java 2 SDK v 1.7 (a.k.a JDK 1.4, 2011) JDK Editions  Java Standard Edition (J2SE) o J2SE can be used to develop client-side standalone applications or applets.  Java Enterprise Edition (J2EE) o J2EE can be used to develop server-side applications such as Java servlets and Java ServerPages.  Java Micro Edition (J2ME). o J2ME can be used to develop applications for mobile devices such as cell phones. Java IDE Tools  Forte by Sun MicroSystems  Borland JBuilder  Microsoft Visual J++  WebGain Cafe  IBM Visual Age for Java Basic Structure Simple Example 1. Create a Java program using notepad and save with extension .java. 2. Install the JDK1.6 or higher, if not , download and install it 3. Set path of the bin directory under jdk. 4. Compile: javac filename.java 5. Run: java filename First Java Program: Let us look at a simple code that would print the words Hello World. public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output
  • 8. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 8 */ public static void main(String []args) { System.out.println("Hello World"); // prints Hello World } } Lets look at how to save the file, compile and run the program. Please follow the steps given below:  Open notepad and add the code as above.  Save the file as : MyFirstJavaProgram.java.  Open a command prompt window and go o the directory where you saved the class. Assume its C:.  Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no errors in your code the command prompt will take you to the next line.( Assumption : The path variable is set).  Now type ' java MyFirstJavaProgram ' to run your program.  You will be able to see ' Hello World ' printed on the window. C : > javac MyFirstJavaProgram.java C : > java MyFirstJavaProgram Hello World Basic Syntax: About Java programs, it is very important to keep in mind the following points.  Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have different meaning in Java.  Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class each inner words first letter should be in Upper Case. Example class MyFirstJavaClass  Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. Example public void myMethodName()  Program File Name - Name of the program file should exactly match the class name. When saving the file you should save it using the class name (Remember java is case sensitive) and append '.java' to the end of the name. (if the file name and the class name do not match your program will not compile). Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'  public static void main(String args[]) - java program processing starts from the main() method which is a mandatory part of every java program.. Java Basics Java Identifiers: All java components require names. Names used for classes, variables and methods are called identifiers.
  • 9. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 9 In java there are several points to remember about identifiers. They are as follows:  All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an underscore (_).  After the first character identifiers can have any combination of characters.  A key word cannot be used as an identifier.  Most importantly identifiers are case sensitive.  Examples of legal identifiers:age, $salary, _value, __1_value  Examples of illegal identifiers : 123abc, -salary Java Modifiers: Like other languages it is possible to modify classes, methods etc by using modifiers. There are two categories of modifiers.  Access Modifiers : default(friend), public , protected, private  Non-access Modifiers : final, abstract, strictfp Java Variables: We would see following type of variables in Java:  Local Variables  Class Variables (Static Variables)  Instance Variables (Non static variables) Java Keywords: The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. 1.2 Object and Classes in Java The class is at the core of Java. It is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object. As such, the class forms the basis for object-oriented programming in Java. The entire set of data and code of an object can be made of a user defined data type with the help of a class. Thus, a class is a template for an object, and an object is an instance of a class.
  • 10. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 10 1.3 The General Form of a Class The class contains data and the code that operates on that data. A class is declared by use of the class keyword. The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class. The general form of a class definition is shown here: class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list){ // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } } Here is a class called Box that defines three instance variables: width, height, and depth. Currently, Box does not contain any methods (but some will be added soon). class Box { double width; double height; double depth; } Instantiating a class Class declaration only creates a template; it does not create an actual object. To create a Box object, you will use a statement like the following: Box mybox = new Box(); // create a Box object called mybox  The new operator allocates space for the new object, calls a class constructor and returns a reference to the object.  It should be noted that the class and its constructor have the same name. After this statement executes, mybox will be an instance of Box. Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. Thus, every Box object will contain its own copies of the instance variables width, height, and depth. To access these variables, you will use the dot (.) operator. The dot operator links the name of the object with the name of an instance variable. For example, to assign the width variable of mybox the value 100, you would use the following statement: mybox.width = 100; This statement tells the compiler to assign the copy of width that is contained within the mybox object the value of 100. 1.4 Methods  A class with only data fields has no life. Objects created by such a class cannot respond to any messages.  Methods are declared inside the body of the class but immediately after the declaration of data fields.
  • 11. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 11  The general form of a method declaration is: modifier returnValueType methodName(list of parameters) { // Method body; }  A method definition consists of a method header and a method body. Here are all the parts of a method:  Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.  Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.  Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.  Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.  Method Body: The method body contains a collection of statements that define what the method does. Creating a object:  Declare the Circle class, have created a new data type – Data Abstraction  Can define variables (objects) of that type: Circle aCircle; Circle bCircle;  Objects are created dynamically using the new keyword.  aCircle and bCircle refer to Circle objects aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; Accessing Object/Circle Data ObjectName.VariableName ObjectName.MethodName(parameter-list)
  • 12. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 12 Example Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 program // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); } } 1.5 Access Modifiers :  An access modifier is a Java keyword that indicates how a field or method can be accessed. Variables and methods in Java have access restrictions, described by the following access modifiers:  private: • Used for most instance variables • private variables and methods are accessible only to methods of the class in which they are declared • Declaring instance variables private is known as data hiding • Example: private int x;  default (friend/ this means no modifier is used): • Access is limited to the package in which the member is declared • Example: int x;  protected: • Access is limited to the package in which the member is declared, as well as all subclasses of its class • Example: protected void setName() { . . . }  public: • The member is accessible to all classes in all packages. • Declaring public methods is knows as defining the class‘ public interface. • Example: public String getName() { . . . } Java Access Specifiers :
  • 13. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 13 • Access specifiers indicates which members of a class can be used by other classes • We use of public, protected and private for access specifications • Package access is used when there is no access specifier • Package access means that all classes in the same package can access the member • But for all other classes the member is private 1.6 Static Variables-class variable(static),instance variable(class member variable) and local variable( variable in method definition) The static keyword can be used in 3 scenarios  static variables  static methods  static blocks of code. static (Class) variable  It is a variable which belongs to the class and not to object(instance)  Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables  A single copy to be shared by all instances of the class  A static variable can be accessed directly by the class name and doesn‘t need any object Syntax : <class-name>.<variable-name>  Syntax: accessSpecifier static dataType variableName;  Example: public static int countAutos = 0; static method (Class Method)  It is a method which belongs to the class and not to the object(instance)  A static method can access only static data. It cannot access non-static data (instance variables)  A static method can call only other static methods and can not call a non-static method from it.  A static method can be accessed directly by the class name and doesn‘t need any object Syntax : <class-name>.<method-name>  A static method cannot refer to ―this‖ or ―super‖ keywords in anyway Example class Student { int a; //initialized to zero static int b; //initialized to zero only when class is loaded not for each object created. Student(){ //Constructor incrementing static variable b b++;
  • 14. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 14 } public void showData(){ System.out.println("Value of a = "+a); System.out.println("Value of b = "+b); } //public static void increment(){ //a++; //} } class Demo{ public static void main(String args[]){ Student s1 = new Student(); s1.showData(); Student s2 = new Student(); s2.showData(); //Student.b++; //s1.showData(); } } static block  The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM class Test{ static { //Code goes here } } A static block helps to initialize the static data members, just like constructors help to initialize instance members
  • 15. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 15 1.7 Constructor  A constructor is a special method that is used to initialize a newly created object and is called just after the memory is allocated for the object .It can be used to initialize the objects ,to required ,or default values at the time of object creation. It is not mandatory for the coder to write a constructor for the class. If no user defined constructor is provided for a class, compiler initializes member variables to its default values.  numeric data types are set to 0  char data types are set to null character(‗‘)  reference variables are set to null  The constructor is automatically called immediately after the object is created, before the new operator completes. Box mybox1 = new Box(); Features of constructor  A constructor has the same name as the class.  A class can have more than one constructor.  A constructor may take zero, one, or more parameters.  A constructor has no return value.  A constructor is always called with the new operator. Types: 1. Default Constructor 2. Parameterized Constructor 3. Copy Constructor  Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor). public class Cube1 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube1() { length = 10; breadth = 10; height = 10; } Cube1(int l, int b, int h) { length = l; breadth = b; height = h; } public static void main(String[] args) { Cube1 cubeObj1, cubeObj2; cubeObj1 = new Cube1();
  • 16. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 16 cubeObj2 = new Cube1(10, 20, 30); System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume()); System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume()); } } Copy Constructor in Java  Like C++, Java also supports copy constructor. But, unlike C++, Java doesn‘t create a default copy constructor if you don‘t write your own. // filename: Main.java class Complex { private double re, im; // A normal parametrized constructor public Complex(double re, double im) { this.re = re; this.im = im; } // copy constructor Complex(Complex c) { System.out.println("Copy constructor called"); re = c.re; im = c.im; } // Overriding the toString of Object class @Override public String toString() { return "(" + re + " + " + im + "i)"; } } public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy constructor call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy constructor call as // non-primitive variables are just references. Complex c3 = c2; System.out.println(c2); // toString() of c2 is called here }} Output: Copy constructor called (10.0 + 15.0i)
  • 17. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 17 a) “this” Keyword this can be used inside any method to refer to the current object. this keyword has two meanings:  to denote a reference to the implicit parameter  to call another constructor of the same class. // A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } b) Garbage Collection  The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused.  A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. 1.8 Finalize method  Finalizer methods are like the opposite of constructor methods; whereas a constructor method is used to initialize an object, finalizer methods are called just before the object is garbage collected and its memory reclaimed.  To create a finalizer method, include a method with the following signature in your class definition: void finalize() { ... }  Inside the body of that finalize() method, include any cleaning up you want to do for that object. protected void finalize() throws Throwable { try{ System.out.println("Finalize of Sub Class"); //release resources, perform cleanup ; }catch(Throwable t){ throw t; }finally{ System.out.println("Calling finalize of Super Class"); super.finalize(); } }
  • 18. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 18 1.9 Arrays  Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.  Declaring Array Variables: dataType[] arrayRefVar; // preferred way. Or dataType arrayRefVar[]; // works but not preferred way. Creating Arrays: dataType[] arrayRefVar = new dataType[arraySize]; The above statement does two things: 1. It creates an array using new dataType[arraySize]; 2. It assigns the reference of the newly created array to the variable arrayRefVar.  Alternatively you can create arrays as follows: dataType[] arrayRefVar = {value0, value1, ..., valuek}; Multidimensional Arrays  In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act like regular multidimensional arrays. int twoD[][] = new int[4][5]; The Arrays Class  The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.
  • 19. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 19 1.10 String objects The Java String class (java.lang.String) is a class of object that represents a character array of arbitrary length. While this external class can be used to handle string objects, Java integrates internal, built-in strings into the language. An important attribute of the String class is that once a string object is constructed, its value cannot change (note that it is the value of an object that cannot change, not that of a string variable, which is just a reference to a string object). All String data members are private, and no string method modifies the string‘s value. String Methods Although a string represents an array, standard array syntax cannot be used to inquire into it. These are detailed in the below Table.
  • 20. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 20 String Comparison String comparison methods listed in below Table. String Searching The String class also provides methods that search a string for the occurrence of a single character or substring. These return the index of the matching substring or character if found, or - 1 if not found.  int indexOf (char ch)  int indexOf (char ch, int begin)  int lastIndexOf (char ch)  int lastIndexOf (char ch, int fromIndex)  int indexOf (String str)  int indexOf (String str, int begin)  int lastIndexOf (String str)  int lastIndexOf (String str, int fromIndex) The following example shows the usage of these functions: if (s1.indexOf (‘:‘) >= 0) { … } String suffix = s1.substring (s1.lastIndexOf (‘.‘)); int spaceCount = 0; int index = s1.indexOf (‘ ‘); while (index >= 0) { ++spaceCount; index = s1.indexOf (‘ ‘, index + 1); } int index = s1.indexOf (―that‖);
  • 21. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 21 String Concatenation The String class provides a method for concatenating two strings: String concat (String otherString) The + and += String operators are more commonly used: The Java compiler recognizes the + and += operators as String operators. For each + expression, the compiler generates calls to methods that carry out the concatentation. For each += expression, the compiler generates calls to methods that carry out the concatenation and assignment. Converting Objects To Strings The String + operator accepts a non-string operand, provided the other operand is a string. The action of the + operator on non-string operands is to convert the non-string to a string, then to do the concatenation. Operands of native types are converted to string by formatting their values. Operands of class types are converted to a string by the method toString() that is defined for all classes. Any object or value can be converted to a string by explicitly using one of the static valueOf() methods defined in class String: String str = String.valueOf (obj); If the argument to valueOf() is of class type, then valueOf() calls that object‘s toString() method. Any class can define its own toString() method, or just rely on the default. The output produced by toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text representation of the object, nor is it meant to be parsed. These conversion rules also apply to the right-hand side of the String += operator. Converting Strings To Numbers Methods from the various wrapper classes, such as Integer and Double, can be used to convert numerical strings to numbers. The wrapper classes contain static methods such as parseInt() which convert a string to its own internal data type. 1.11 Packages  Provides a mechanism for grouping a variety of classes and / or interfaces together.  Grouping is based on functionality. Benefits:  The classes contained in the packages of other programs can be reused.  In packages, classes can be unique compared with classes in other packages.  Packages provides a way to hide classes.  Two types of packages: 1. Java API packages 2. User defined packages Java API Packages:  A large number of classes grouped into different packages based on functionality. Examples: Package Categories of Classes java.lang Basic functionality common to many programs, such as the String class and Math class java.awt Graphics classes for drawing and using colors javax.swing User-interface components java.text Classes for formatting numeric output java.util The Scanner class and other miscellaneous classes
  • 22. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 22 Included in the Java SDK are more than 2,000 classes that can be used to add functionality to our programs  APIs for Java classes are published on Sun Microsystems Web site: www.java.sun.com Accessing Classes in a Package 1. Fully Qualified class name: Example:java.awt.Color 2. import packagename.classname; Example: import java.awt.Color; or import packagename.*; Example: import java.awt.*;  Import statement must appear at the top of the file, before any class declaration. Creating Your Own Package 1. Declare the package at the beginning of a file using the form package packagename; 2. Define the class that is to be put in the package and declare it public. 3. Create a subdirectory under the directory where the main source files are stored. 4. Store the listing as classname.java in the subdirectory created. 5. Compile the file. This creates .class file in the subdirectory. Example: package firstPackage; Public class FirstClass { //Body of the class } Example1-Package package p1; public class ClassA { public void displayA( ) { System.out.println(―Class A‖); }}
  • 23. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 23 Source file – ClassA.java Subdirectory-p1 ClassA.Java and ClassA.class->p1 import p1.*; Class testclass { public static void main(String str[]) { ClassA obA=new ClassA(); obA.displayA(); } } Source file-testclass.java testclass.java and testclass.class->in a directory of which p1 is subdirectory. Creating Packages  Consider the following declaration: package firstPackage.secondPackage; This package is stored in subdirectory named firstPackage.secondPackage.  A java package can contain more than one class definitions that can be declared as public.  Only one of the classes may be declared public and that class name with .java extension is the source file name. Example2-Package package p2; public class ClassB { protected int m =10; public void displayB() { System.out.println(―Class B‖); System.out.println(―m= ―+m); } } import p1.*; import p2.*; class PackageTest2 { public static void main(String str[]) { ClassA obA=new ClassA(); Classb obB=new ClassB(); obA.displayA(); obB.displayB(); } }
  • 24. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 24 Example 3- Package import p2.ClassB; class ClassC extends ClassB { int n=20; void displayC() { System.out.println(―Class C‖); System.out.println(―m= ―+m); System.out.println(―n= ―+n); } } class PackageTest3 { public static void main(String args[]) { ClassC obC = new ClassC(); obC.displayB(); obC.displayC(); } } Default Package  If a source file does not begin with the package statement, the classes contained in the source file reside in the default package  The java compiler automatically looks in the default package to find classes. Finding Packages  Two ways: 1.By default, java runtime system uses current directory as starting point and search all the subdirectories for the package. 2.Specify a directory path using CLASSPATH environmental variable. CLASSPATH Environment Variable  The compiler and runtime interpreter know how to find standard packages such as java.lang and java.util  The CLASSPATH environment variable is used to direct the compiler and interpreter to where programmer defined imported packages can be found  The CLASSPATH environment variable is an ordered list of directories and files 1.12 Documentation Comments The Java SDK contains a very useful tool, called javadoc, that generates HTML documentation from your source files. If you add comments that start with the special delimiter /** to your source code, you too can produce professional-looking documentation easily. This is a very nice scheme because it lets you keep your code and documentation in one place. If you put your
  • 25. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 25 documentation into a separate file, then you probably know that the code and comments tend to diverge over time. But since the documentation comments are in the same file as the source code, it is an easy matter to update both and run javadoc again. How to Insert Comments The javadoc utility extracts information for the following items: • Packages • Public classes and interfaces • Public and protected methods • Public and protected fields You can (and should) supply a comment for each of these features. Each comment is placed immediately above the feature it describes. A comment starts with a /** and ends with a */. Each /** . . . */ documentation comment contains free-form text followed by tags. A tag starts with an @, such as @author or @param. The first sentence of the free-form text should be a summary statement. The javadoc utility automatically generates summary pages that extract these sentences. In the free-form text, you can use HTML modifiers such as <em>...</em> for emphasis, <code>...</code> for a monospaced ―typewriter‖ font, <strong>...</strong> for strong emphasis, and even <img ...> to include an image. You should, however, stay away from heading <h1> or rules <hr> since they can interfere with the formatting of the document. Class Comments The class comment must be placed after any import statements, directly before the class definition. Here is an example of a class comment: /** A <code>Card</code> object represents a playing card, such as "Queen of Hearts". A card has a suit (Diamond, Heart, Spade or Club) and a value (1 = Ace, 2 . . . 10, 11 = Jack, 12 = Queen, 13 = King). */ public class Card { . . . } Method Comments Each method comment must immediately precede the method that it describes. In addition to the general-purpose tags, you can use the following tags: @param variable description This tag adds an entry to the ―parameters‖ section of the current method. The description can span multiple lines and can use HTML tags. All @param tags for one method must be kept together. @return description This tag adds a ―returns‖ section to the current method. The description can span multiple lines and can use HTML tags. @throws class description Field Comments You only need to document public fields—generally that means static constants. For example, /** The "Hearts" card suit */ public static final int HEARTS = 1; General Comments The following tags can be used in class documentation comments. @author name This tag makes an ―author‖ entry. You can have multiple @author tags, one for each author. @version text
  • 26. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 26 How to Extract Comments Here, docDirectory is the name of the directory where you want the HTML files to go. Follow these steps: 1. Change to the directory that contains the source files you want to document. If you have nested packages to document, such as com.horstmann.corejava, you must be in the directory that contains the subdirectory com. (This is the directory that contains the overview.html file, if you supplied one.) 2. Run the command javadoc -d docDirectory nameOfPackage for a single package. Or run javadoc -d docDirectory nameOfPackage1 nameOfPackage2... to document multiple packages. If your files are in the default package, then run javadoc -d docDirectory *.java instead. If you omit the -d docDirectory option, then the HTML files are extracted to the current directory. That can get messy, and we don't recommend it. The javadoc program can be fine-tuned by numerous command-line options. For example, you can use the - author and -version options to include the @author and @version tags in the documentation. (By default, they are omitted.)
  • 27. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 1 Unit II – Object Oriented Programming – Inheritance 2.1 Inheritance 2.2 class hierarchy 2.3 polymorphism 2.4 dynamic binding 2.5 final keyword 2.6 abstract classes 2.7 interfaces 2.8 inner classes 2.9 the Object class 2.10 object cloning 2.11 proxies 2.12 Reflection 2.1Inheritance  Inheritance is a process of making a new class that derives from an existing class. The existing class is called the superclass, base class, or parent class. The new class is called the subclass, derived class, or child class.  Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and add its own, unique elements.  Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. The following kinds of inheritance are there in java.  Simple Inheritance  Multilevel Inheritance Simple Inheritance When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance. class A { int x; int y; int get(int p, int q) { x=p; y=q; return(0); } void Show() { System.out.println(x); } } class B extends A { public static void main(String args[]){
  • 28. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 2 A a = new A(); a.get(5,6); a.Show(); } void display(){ System.out.println("B"); } } Multilevel Inheritance It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above ( parent ) class. Multilevel inheritance can go up to any number of level. class A { int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); } } class B extends A{ void Showb(){ System.out.println("B"); }} class C extends B{ void display(){ System.out.println("C"); } public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); }} Multiple Inheritance  The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance.  Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.  In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class. Member Access and Inheritance A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses. Super keyword Super is a special keyword that directs the compiler to invoke the super class method. super has two general forms.  to invoke a superclass constructor.  to invoke a superclass members(variables &methods).
  • 29. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 3 Invoke superclass constructor: A subclass can call a constructor method defined by its superclass by use of the following form of super: super(parameter-list);  Here, parameter-list specifies any parameters needed by the constructor in the superclass.  super( ) must always be the first statement executed inside a subclass constructor.  The compiler implicitly calls the base class’s no-parameter constructor or default constructor.  If the superclass has parameterized constructor and the subclass constructor does not call superclass constructor explicitly, then the Java compiler reports an error. Invoke superclass members: Super always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member;  Here, member can be either a method or an instance variable. This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass.  If a parent class contains a finalize() method, it must be called explicitly by the derived class’s finalize() method. super.finalize(); When Constructors are Called Constructors are called in order of derivation, from superclass to subclass. Because a superclass has no knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass. Therefore, it must be executed first. Advantages  Reusability -- facility to use public methods of base class without rewriting the same  Extensibility -- extending the base class logic as per business logic of the derived class  Data hiding -- base class can decide to keep some data private so that it cannot be altered by the derived class  Overriding--With inheritance, we will be able to override the methods of the base class so that meaningful implementation of the base class method can be designed in the derived class. Disadvantages:-  Both classes (super and subclasses) are tightly-coupled.  As they are tightly coupled (binded each other strongly with extends keyword), they cannot work independently of each other.  Changing the code in super class method also affects the subclass functionality.  If super class method is deleted, the code may not work as subclass may call the super class method with super keyword. Now subclass method behaves independently. 2.2 Class Hierarchy  The collection of all classes extending from a common superclass is called an inheritance hierarchy; the path from a particular class to its ancestors in the inheritance hierarchy is its inheritance chain.  Simple class hierarchies consist of only a superclass and a subclass. But you can build hierarchies that contain as many layers of inheritance as you like.  For example, create three classes called A, B, and C, C can be a subclass of B, which is a subclass of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its superclasses. In this case, C inherits all aspects of B and A.
  • 30. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 4 2.3 Polymorphism  Polymorphism means the ability of methods to behave differently based on the kinds of input. Types of polymorphism  Method Overloading  Method overriding Overloaded methods  Overloaded methods are methods with the same name but different method signature (either a different number of parameters or different types in the parameter list). class A{ void display(){ System.out.println("Hai"); } } class B extends A{ void display(String s){ System.out.println(s); } } public class Test{ public static void main(String arg[]){ A a=new A(); a.display(); B b=new B(); b.display("Hello"); }} Output Hai Hello Method Overriding  The process of a subclass redefining a method contained in the superclass (with the same parameter types) is called overriding the method.  Overridden methods allow Java to support run time polymorphism. Whenever a method is called for a subclass object, the compiler calls the overriding version instead of the superclass version. The version of the method defined by the superclass will be hidden.  Call to an overridden method is resolved at run time, rather than compile time. Rules: 1. Method have same name as in a parent class 2. Method have same parameter as in a parent class //Example of method overriding class Vehicle{ void run() { System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run() {System.out.println("Bike is running safely");} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); }} Output:Bike is running safely
  • 31. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 5 2.4 Dynamic Binding Binding - Connecting a method call to a method body 1. Static binding (Early binding) 2. Dynamic binding (Late binding) STATIC BINDING OR EARLY BINDING  If the compiler can resolve the binding at the compile time only then such a binding is called Static Binding or Early Binding. Resolve the call and binding at compile time.  If the method is private, static, final, or a constructor, then the compiler knows exactly which method to call. This is called static binding.  All the member variables in Java follow static binding.  All the static method calls are resolved at compile time itself.  All private methods are resolved at compile time itself. class Dog{ private void eat() { System.out.println("dog is eating..."); } public static void main(String args[]) { Dog d1=new Dog(); d1.eat(); }} In this example, during compilation, the compiler knows eat() method to be invoked from the class Dog. Dynamic Binding or Late Binding  Selecting the appropriate method at runtime is called dynamic binding. Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding is done at runtime only.  All the instance methods in Java follow dynamic binding.  It is important to understand what happens when a method call is applied to an object. Here are the details:  The compiler looks at the declared type of the object and the method name. The compiler knows all possible candidates for the method to be called.  Next, the compiler determines the types of the parameters that are supplied in the method call. If among all the methods called fun there is a unique method whose parameter types are a best match for the supplied parameters, then that method is chosen to be called. This process is called overloading resolution.
  • 32. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 6  If the method is private, static, final, or a constructor, then the compiler knows exactly which method to call.  When the program runs and uses dynamic binding to call a method, then the virtual machine must call the version of the method that is appropriate for the actual type of the object. The virtual machine precomputes a method table for each class that lists all method signatures and the actual methods to be called. When a method is actually called, the virtual machine simply makes a table lookup. This is used to reduce the time consumed by searching process. class Animal{ void eat(){ System.out.println("animal is eating..."); }} class Dog extends Animal{ void eat(){ System.out.println("dog is eating..."); } public static void main(String args[]){ Animal a=new Dog(); a.eat(); }} Output: Dog is eating… 2.5 FINAL KEYWORD The final keyword in java used to restrict the user. The keyword final has three uses. 1. Final Variables - Used to create the equivalent of a named constant. 2. Final Methods - Used to Prevent Overriding 3. Final Class - Used to Prevent Inheritance Final variables  A variable can be declared as final.  If you make any variable as final, you cannot change the value of variable at runtime. (It is similar to constant) final int a = 1;  Variables declared as final do not occupy memory on a per-instance basis.  Attempts to change it will generate either a compile-time error or an exception. class Bike{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike obj=new Bike(); obj.run(); }} Output: Compile – time error occurs.  Since the variables speedlimit is restricted by the user, so it cannot be reinitialized in run() method.
  • 33. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 7 Final Method  Methods declared as final cannot be overridden  since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding. class Bike{ final void run(){ System.out.println("running");}} class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); }} Output: Compile – time error occurs. Final class  Declaring a class as final implicitly declares all of its methods as final.  So it prevents a class from being inherited. final class Bike{} class Honda extends Bike{ void run(){ System.out.println("running safely with 100kmph"); } public static void main(String args[]){ Honda honda= new Honda(); honda.run(); }} Output: Compile – time error occurs. 2.6 Abstract Classes  When we define a class to be “final”, it cannot be extended. In certain situation, we want to properties of classes to be always extended and used. Such classes are called Abstract Classes.  Abstraction can achieved by 1. Abstract class (0-100%) 2. Interface (100%)  An Abstract class is a conceptual class.  An Abstract class cannot be instantiated – objects cannot be created. Abstract Class Syntax abstract class ClassName { ... … abstract Type MethodName1(); … … Type Method2() { // method body }}  When a class contains one or more abstract methods, it should be declared as abstract class.  The abstract methods of an abstract class must be defined in its subclass.  We cannot declare abstract constructors or abstract static methods.
  • 34. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 8 Abstract Class –Example  Shape is a abstract class. The Shape Abstract Class public abstract class Shape { public abstract double area(); public void move() { // non-abstract method // implementation } }  Is the following statement valid?  Shape s = new Shape();  No. It is illegal because the Shape class is an abstract class, which cannot be instantiated to create its objects. abstract class Shape{ abstract void draw(); } class Rectangle extends Shape{ void draw(){ System.out.println("drawing rectangle"); }} class Circle extends Shape{ void draw(){ System.out.println("drawing circle"); }} class Test{ public static void main(String args[]){ Shape s=new Circle();//In real scenario, Object is provided through factory method s.draw();}} Output: drawing circle In the above example, Shape is an abstract class, its implementation is provided by Rectangle and Circle classes. Mostly, we don’t know about the implementation class (ie hidden to the user) and object implementation class is provided by Factory method. A Factory method is the method returns the instance of the class. Abstract Classes Properties  A class with one or more abstract methods is automatically abstract and it cannot be instantiated.  A class declared abstract, even with no abstract methods cannot be instantiated.  A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them.  A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated.  A private method can’t be abstract. All abstract methods must be public.  A class can’t be both abstract and final.
  • 35. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 9 2.7 Interface  In Java, only single inheritance is permitted. However, Java provides a construct called an interface which can be implemented by a class.  Interfaces are similar to abstract classes.  A class can implement any number of interfaces. In effect using interfaces gives us the benefit of multiple inheritances without many of its problems.  Interfaces are compiled into bytecode just like classes.  Interfaces cannot be instantiated.  Can use interface as a data type for variables.  Can also use an interface as the result of a cast operation.  Interfaces can contain only abstract methods and constants. Defining an Interface An interface must be declared with the keyword interface. access interface interface-name { return-type method-name(parameter-list); type final-varname = value; }  It is also possible to declare that an interface is protected so that it can only be implemented by classes in a particular package. However this is very unusual.  Rules for interface constants. They must always be  public  static  final  Once the value has been assigned, the value can never be modified. The assignment happens in the interface itself (where the constant is declared), so the implementing class can access it and use it, but as a read-only value.  To make a class implement an interface, have to carry out two steps: 1. Declare that your class intends to implement the given interface. 2. Supply definitions for all methods in the interface.  To declare that a class implements an interface, use the implements keyword: access class classname implements interfacename { //definitions for all methods in the interface } interface printable { void print(); } class A implements printable { public void print(){ System.out.println("Hello"); } public static void main(String args[]){ A obj = new A(); obj.print(); }} Multiple inheritance by interface  A class cannot extend two classes but it can implement two interfaces. interface printable{ void print();} interface Showable{ void show();}
  • 36. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 10 class A implements printable,Showable { public void print(){ System.out.println("Hello"); } public void show() { System.out.println("Welcome"); } public static void main(String args[]){ A obj = new A(); obj.print(); obj.show(); }} Output: Hello Welcome Interface vs. abstract class 2.8 Inner Classes  Inner classes are classes defined within other classes  The class that includes the inner class is called the outer(NESTED) class  There is no particular location where the definition of the inner class (or classes) must be place within the outer class  Placing it first or last, however, will guarantee that it is easy to find  An inner class definition is a member of the outer class in the same way that the instance variables and methods of the outer class are members  An inner class is local to the outer class definition  The name of an inner class may be reused for something else outside the outer class definition  If the inner class is private, then the inner class cannot be accessed by name outside the definition of the outer class public class Outer { private class Inner { // inner class instance variables // inner class methods } // end of inner class definition // outer class instance variables // outer class methods }
  • 37. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 11  There are two main advantages to inner classes  They can make the outer class more self-contained since they are defined inside a class  Both of their methods have access to each other's private methods and instance variables  Using an inner class as a helping class is one of the most useful applications of inner classes  If used as a helping class, an inner class should be marked private Types of nested (outer) classes Regular Inner Class  You define an inner class within the curly braces of the outer class, as follows: class MyOuter { class MyInner { } } And if you compile it, %javac MyOuter.java , you’ll end up with two class files:  MyOuter.class  MyOuter$MyInner.class  The inner class is still, in the end, a separate class, so a class file is generated. But the inner class file isn’t accessible to you in the usual way. The only way you can access the inner class is through a live instance of the outer class. Instantiating an Inner Class To instantiate an instance of an inner class, you must have an instance of the outer class. An inner class instance can never stand alone without a direct relationship with a specific instance of the outer class. Instantiating an Inner Class from Within Code in the Outer Class From inside the outer class instance code, use the inner class name in the normal way: class MyOuter { private int x = 7; MyInner mi = new MyInner(); class MyInner { public void seeOuter() { System.out.println("Outer x is " + x); } } public static void main(String arg[]){ MyOuter mo=new MyOuter(); mo.mi.seeOuter(); } } Output: Outer x is 7
  • 38. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 12 Method-Local Inner Classes A method-local inner class is defined within a method of the enclosing class. class MyOuter { void inner() { final int c=9; class MyInner { int x=5; public void display() { System.out.println("Inner x is " + x); System.out.println("Inner c is " + c); } } MyInner mi = new MyInner(); mi.display(); } public static void main(String arg[]){ MyOuter mo = new MyOuter(); mo.inner(); }} Anonymous Inner Classes  Anonymous inner classes have no name, and their type must be either a subclass of the named type or an implementer of the named interface.  An anonymous inner class is always created as part of a statement, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });  An anonymous inner class can extend one subclass, or implement one interface. It cannot both extend a class and implement an interface, nor can it implement more than one interface. class A{ void display(){ System.out.println("Hai"); }} class B { A ob=new A(){ void display(){ System.out.println("Hello"); } }} public class Test{ public static void main(String arg[]){ B b=new B(); b.ob.display(); } } Output: Hello And if you compile it, %javac Test.java , you’ll end up with two class files: A.class B.class B$1.class Test.class Static Nested Classes  Static nested classes are inner classes marked with the static modifier.  Technically, a static nested class is not an inner class, but instead is considered a top-level nested class  Because the nested class is static, it does not share any special relationship with an instance of the outer class. In fact, you don’t need an instance of the outer class to instantiate a static nested class.
  • 39. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 13  Instantiating a static nested class requires using both the outer and nested class names as follows: A.B b=new A.B();  A static nested class cannot access nonstatic members of the outer class, since it does not have an implicit reference to any outer instance (in other words, the nested class instance does not get an outer this reference). class A { static class B { int m=5; void display(){ System.out.println("m="+m); } } } public class Test{ public static void main(String arg[]){ A.B b=new A.B(); b.display(); }} Output: m=5 2.9 Object class  In Java, every class is a descendent of the class Object  Every class has Object as its ancestor  Every object of every class is of type Object, as well as being of the type of its own class  If a class is defined that is not explicitly a derived class of another class, it is still automatically a derived class of the class Object  The class Object is in the package java.lang which is always imported automatically  Having an Object class enables methods to be written with a parameter of type Object  A parameter of type Object can be replaced by an object of any class whatsoever  For example, some library methods accept an argument of type Object so they can be used with an argument that is an object of any class  The class Object has some methods that every Java class inherits  For example, the equals and toString methods  Every object inherits these methods from some ancestor class  Either the class Object itself, or a class that itself inherited these methods (ultimately) from the class Object
  • 40. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 14 2.9 Object Cloning  Object cloning is a way to create exact copy of an object.  For this purpose, clone() method of Object class is used to clone an object.  The method Object.clone() does a bit-by-bit copy of the object's data in storage  The Cloneable interface is another unusual example of a Java interface  It does not contain method headings or defined constants  It is used to indicate how the method clone (inherited from the Object class) should be used and redefined Syntax: protected Object clone() throws CloneNotSupportedException class Student implements Cloneable{ int rollno; String name; Student(int rollno,String name){ this.rollno=rollno; this.name=name; } public Object clone()throws CloneNotSupportedException { return super.clone(); } public static void main(String args[]){ try{ Student s1=new Student(101,"amit"); Student s2=(Student)s1.clone(); System.out.println(s1.rollno+" "+s1.name); System.out.println(s2.rollno+" "+s2.name); } catch(CloneNotSupportedException c) {} }}
  • 41. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 15 2.11Proxy  Proxy used to create new classes at runtime that implement a given set of interfaces. The proxy class can create brand-new classes at runtime.  The proxy class can create brand-new classes at runtime. Such a proxy class implements the interfaces that you specify. In particular, the proxy class has the following methods:  All methods required by the specified interfaces;  All methods defined in the Object class (toString, equals, and so on).  To create a proxy object, you use the newProxyInstance method of the Proxy class. The method has three parameters:  A class loader. As part of the Java security model, it is possible to use different class loaders for system classes, classes that are downloaded from the Internet, and so on.  An array of Class objects, one for each interface to be implemented.  An invocation handler.  Proxies can be used for many purposes, such as:  Routing method calls to remote servers;  Associating user interface events with actions in a running program;  Tracing method calls for debugging purposes 2.12 Reflection  Reflection is the ability of the software to analyze itself at runtime.  Reflection is provided by the java.lang.reflect package and elements in class.  The Reflection API is mainly used in:  IDE (Integrated Development Environment) eg. Eclipse, NetBeans  Debugger  Test Tools  This mechanism is helpful to tool builders, not application programmers. The reflection mechanism is extremely used to a. Analyze the capabilities of classes at run time b. Inspect objects at run time c. Implement generic array manipulation code Analyze the capabilities of classes at run time - Examine the structure of class. The java.lang.Class class performs mainly two tasks: 1. Provides methods to get the metadata of a class at runtime. 2. Provides methods to examine and change the runtime behavior of a class.
  • 42. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 16 Field  Provide information about fields.  The getFields() method returns an array containing Field objects for the public fields.  The getDeclaredField() method returns an array of Field objects for all fields. The methods return an array of length 0 if there are no such fields. import java.lang.reflect.*; class Test{ public int var1; private int var2; protected int var3; int var4;} public class FieldDemo{ public static void main(String args[])throws Exception{ Class c=Class.forName("Test"); Field f[]=c.getFields(); Field fdec[]=c.getDeclaredFields(); System.out.println("public Fields:"); for(int i=0;i<f.length;i++) System.out.println(f[i]); System.out.println("All Fields:"); for(int i=0;i<fdec.length;i++) System.out.println(fdec[i]); }} Output: public Fields: public int Test.var1 All Fields: public int Test.var1 private int Test.var2 protected int Test.var3 int Test.var4 Method  Provides information about method  The getMethods() method return an array containing Method objects that give you all the public methods.  The getDeclaredMethods () return all methods of the class or interface. This includes those inherited from classes or interfaces above it in the inheritance chain. import java.lang.reflect.*; class Test{ public void method1() {} protected void method2() {} private void method3() {} void method4() {} } public class MethodDemo{ public static void main(String args[])throws Exception{ Class c=Class.forName("Test"); Method m[]=c.getMethods(); Method mdec[]=c.getDeclaredMethods(); System.out.println("public Methods of class Test & its Super class:"); for(int i=0;i<m.length;i++) System.out.println(m[i].getName()); System.out.println("All Methods:"); for(int i=0;i<mdec.length;i++) System.out.println(mdec[i].getName()); } }
  • 43. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 17 Output: public Methods of class Test & its Super class: method1 All Methods: hashCode method1 getClass method2 wait method3 equals method4 notify notifyAll toString Constructor  Provide information about constructors  getConstructors () method return an array containing Constructor objects that give you all the public constructors  getDeclaredConstructors () method return all constructors of the class represented by the Class object. Using Reflection to Analyze Objects at Run Time  Look at the contents of the data fields. It is easy to look at the contents of a specific field of an object whose name and type are known when you write a program. But reflection lets you look at fields of objects that were not known at compile time.  f.set(obj, value) sets the field represented by f of the object obj to the new value.  f.get(obj) returns an object whose value is the current value of the field of obj. import java.lang.reflect.*; class A{ public int var1,var2; A(int i, int j){ var1=i; var2=j; } } public class ConstructorDemo { public static void main(String args[]) throws Exception{ A obj=new A(10,20); System.out.println("Before n var1= "+obj.var1); Field f1 = obj.getClass().getField("var1"); int v1 = f1.getInt(obj) + 1; f1.setInt(obj, v1); System.out.println("After n var1= "+v1); System.out.println("Before n var2= "+obj.var2); Field f2 = obj.getClass().getField("var2"); f2.set(obj,21); System.out.println("After n var2= "+f2.get(obj)); } } Output: Before var1= 10 After var1= 11 Before var2= 20 After var2= 21
  • 44. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 18 Using Reflection to implement generic array manipulation code  The Array class in the java.lang.reflect package allows you to create arrays dynamically. First the given array can be converted to an Object[] array. newInstance() method of Array class, constructs a new array.  Object newarray= Array.newInstance(ComponentType, newlength)  newInstance() method needs two parameters  Component Type of new array  To get component type  Get the class object using getClass() method.  Confirm that it is really an array using isArray().  Use getComponentType method of class Class, to find the right type for the array.  Length of new array  Length is obtained by getLength() method. It returns the length of any array(method is static method, Array.getLengh(array name)). import java.lang.reflect.*; public class TestArrayRef { static Object arrayGrow(Object a){ Class cl = a.getClass(); if (!cl.isArray()) return null; Class componentType = cl.getComponentType(); int length = Array.getLength(a); int newLength = length + 10; Object newArray = Array.newInstance(componentType,newLength); System.arraycopy(a, 0, newArray, 0, length); return newArray; } public static void main(String args[]) throws Exception{ int arr[]=new int[10]; System.out.println(arr.length); arr = (int[])arrayGrow(arr); System.out.println(arr.length); } } Output: 10 20
  • 45. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 1 Unit III – Event Driven Programming 3.1 Graphics programming 3.2 Frame 3.3 Components 3.4 working with 2D shapes 3.5 Using color, fonts, and images 3.6 Basics of event handling 3.7 event handlers 3.8 adapter classes 3.9 actions 3.10 mouse events 3.11 AWT event hierarchy 3.12 introduction to Swing 3.13 Model-View-Controller design pattern 3.14 buttons 3.15 layout management 3.16 Swing Components 3.1 Graphics Programming  Java contains support for graphics that enable programmers to visually enhance applications JFC  JFC is a collection of APIs for developing graphical components in Java. It includes the following: 1. AWT (version 1.1 and beyond) 2. 2D API 3. Swing Components 4. Accessibility API AWT  AWT was original toolkit for developing graphical components. The JFC is based on the AWT components.  The Abstract Window Toolkit was a part of Java from the beginning import java.awt.*;  All AWT components must be mapped to platform specific components using peers  The look and feel of these components is tied to the native components of the window manager  AWT components are considered to be very error prone and should not be used in modern Java applications Swing  With the introduction to Swing, lightweight version of many of the AWT components (heavyweight) are created with the prefix J. For example, JFrame for Frame, JButton for Button, etc.  Since Swing was an extension to AWT, all Swing components are organized in javax.swing package compared to java.awt for all AWT components.  Swing also provides many components that AWT lacked.  Some of the original method names have been changed to allow uniform naming for all components.  When a method name will no longer be supported in future newer versions, it is said to be deprecated.
  • 46. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 2
  • 47. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 3 AWT vs Swing  Java 1.0 was introduced with a class library called Abstract Window Toolkit (AWT)  used for basic user interface  delegated creation and behavior of interface elements to the native GUI tookit on the target platform  Windows vs. Solaris vs. Macintosh, etc  Downside to AWT:  Worked well for simple applications but difficult to write high-quality portable graphics  Limited graphics programming to the lowest common denominator.  Different platforms had different bugs  In 1996 Sun worked with Netscape to create Swing  In Swing user interface elements are painted onto blank windows  Swing is not a complete replacement of AWT. Instead it works with AWT.  Swing simply gives you more capable user interface components.  However, even though AWT components are still available, you will rarely use them.  Reasons to choose Swing:  much richer and more convenient set of user interface elements  depends far less on the underlying platform so it is less vulnerable to platform-specific bugs  gives a consistent user experience across platforms  fullfill’s Java’s promise of ―Write Once, Run Anywhere‖  Easier to use than AWT How to Create Graphics in Java  Here are the basic steps you need to take to include graphics in your program:  Create a frame  Create a panel  Override the paintComponent() method in your panel 3.2 Frame  Frame is a top-level window that has a title bar, menu bar, borders, and resizing corners. By default, a frame has a size of 0 × 0 pixels and it is not visible.  Frames are examples of containers. It can contain other user interface components such as buttons and text fields. Class hierarchy for Frame
  • 48. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 4 Component & Window class Methods java.awt.Component  void setVisible(boolean b) - shows or hides the component depending on whether b is true or false.    void setSize(int width, int height) - resizes the component to the specified width and height.    void setBounds(int x, int y, int width, int height) - moves and resizes this component. The location of the top-left corner is given by x and y, and the new size is given by the width and height parameters.    void setBackground(java.awt.Color) – set Background color to the window.    void setForeground(java.awt.Color)- set Foreground color to the window.    void repaint() - causes a repaint of the component ―as soon as possible  void setTitle(String s) - sets the text in the title bar for the frame to the string s.  Frame class constructors  Frame() - Creates a new instance of Frame that is initially invisible.  Frame(String title) - Creates a new instance of Frame that is initially invisible with the specified title. Frame class methods  void setResizable(boolean resizable) - Sets whether or not a frame is resizable  void setTitle(String title) - Sets the title of a frame  void setVisible(boolean visible) - Sets whether or not a frame is visible  void setSize(int width, int height) - Sets the width & height of a frame  String getTitle() - Returns the title of a frame There are two ways to create a frame 1.Create a frame by extending the Frame class 2.Create a frame by creating an instance of the Frame class Create a frame by extending the Frame class import java.awt.*; class AFrame extends Frame{ public static void main(String[] args){ AFrame frame = new AFrame(); frame.setSize(200, 200); frame.setVisible(true); } } Create a frame by creating an instance of the Frame class import java.awt.*; class AFrame{ public static void main(String[] args){ Frame aFrame = new Frame(); aFrame.setSize(200, 200); aFrame.setVisible(true); } } Frame Positioning  Most methods for working the size and position of a frame come from the various superclasses of JFrame. Some important methods include:  the dispose() method: closes the window and reclaims system resources.  the setIconImage() method: takes an Image object to use as the icon when the window is minimized
  • 49. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 5  the setTitle() method: changes the text in the title bar.  the setResizable() method: takes a boolean to determine if a frame will be resizeable by the user.  the setLocation() method: repositions a frame  the setBounds() method: both repositions and resizes a frame.  the setExtendedState(Frame.MAXIMIZED_BOTH): maximizes the size of a frame Note: If you don’t explicitly size the frame, it will default to being 0 by 0 pixels, which is invisible.  In a professional application, you should check the resolution of the user’s screen to determine the appropriate frame size. Java screen coordinate system  Upper-left corner of a GUI component has the coordinates (0, 0)  Contains x-coordinate (horizontal coordinate) - horizontal distance moving right from the left of the screen  Contains y-coordinate (vertical coordinate) - vertical distance moving down from the top of the screen  Coordinate units are measured in pixels. A pixel is a display monitor’s smallest unit of resolution. import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JFrame; public class SizedFrameTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { SizedFrame frame = new SizedFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } class SizedFrame extends JFrame { public SizedFrame() { // get screen dimensions Toolkit kit = Toolkit.getDefaultToolkit(); Dimension screenSize = kit.getScreenSize(); int screenHeight = screenSize.height; int screenWidth = screenSize.width; // set frame width, height and let platform pick screen location setSize(screenWidth / 2, screenHeight / 2); setLocationByPlatform(true); // set frame icon and title Image img = kit.getImage("icon.gif"); setIconImage(img); setTitle("SizedFrame"); } }
  • 50. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 6 Display information inside frame  Frames in Java are designed to be containers for other components like button, menu bar, etc.  You can directly draw onto a frame, but it’s not a good programming practice  Normally draw on another component, called panel, using Jpanel Before JDK5, get the content pane of frame first, then add component on it Container contentPane = getContentPane(); Component c = …; contentPane.add(c); After JDK5, you can directly use frame.add(c); import javax.swing.*; import java.awt.*; class NotHelloWorld { public static void main(String[] args) { NotHelloWorldFrame frame = new NotHelloWorldFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } /** A frame that contains a message panel */ class NotHelloWorldFrame extends JFrame { public NotHelloWorldFrame() { setTitle("NotHelloWorld"); setSize(300,300); // add panel to frame NotHelloWorldPanel panel = new NotHelloWorldPanel(); add(panel); } } /** A panel that displays a message. */ class NotHelloWorldPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("Not a Hello, World program", 75,100); } }  paintComponent() is a method of JComponent class, which is superclass for all nonwindow Swing components  Never call paintComponent() yourself. It’s called automatically whenever a part of your application needs to be drawn  User increase the size of the window  User drag and move the window  Minimize then restore  It takes a Graphics object, which collects the information about the display setting 3.3 Components  The java.awt.Component is one of the cornerstones of AWT programming. It contains approximately half of the classes in AWT. AWT is built on the Component class.
  • 51. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 7  Component class – an abstract class for GUI components such as buttons, menus, labels, lists, etc.  Container – An abstract class that extends Component. Classes derived from the Container class can contain multiple components. Examples are Panel, Applet, Window, Frame, etc.  LayoutManager – An interface for positing and sizing Container objects. Java defines several default implementations. You can also create your custom layout.  Graphics class– An abstract class that defines methods for performing graphical operations. Every component has an associated Graphics object.  java.awt.Component subclasses (in java.awt package):  java.awt.Container subclasses (in java.awt package):  java.awt.LayoutManager interface implementations: Label Displays text in a box Button A clickable button, can generate event Canvas Area for painting graphics Checkbox A button that provides on/off toggle values. Can be used for both Check box and radio buttons (when contained in a CheckBoxGroup) Choice Combo box where a list of items can be displayed by clicking the button List A component that displays a list of selectable items Scrollbar A scrollable bar TextComponent Superclass for TextField and TextArea TextArea Multiple line text input box TextField One line user input text box Applet Superclass of all applets, an extension of Panel Dialog Can be modal or non-modal. Extends Window FileDialog Opens a regular file dialog Frame All applications are contained in a Frame. Extends Window. It can have a menubar unlike an applet Panel A simple container of other components including Panels Window It is rarely used directly, but useful for spash screen when an app starts. No menu or border. Parent of Frame and Dialog BorderLayout Compoents are layed out in North/South, East/West and Center CardLayout Deck of panels where panels are displayed one at a time FlowLayout Component flow from left to right, top to bottom. When there is no real estate to maneuvar on the right, goes down. Widely used. GridBagLayout Each componet location is defined using grid. Most difficult to implement. GridLayout Components are layed out in a grid. Component is streched to fill the grid.
  • 52. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 8 3.4Working with 2D shapes  To draw shapes in the Java 2D library, you need to obtain an object of the Graphics2D class. This class is a subclass of the Graphics class. Ever since Java SE 2, methods such as paintComponent automatically receive an object of the Graphics2D class. Simply use a cast, as follows: public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; . . . }  The Java 2D library organizes geometric shapes in an object-oriented fashion. In particular, there are classes to represent lines, rectangles, and ellipses:  Line2D  Rectangle2D  Ellipse2D These classes all implement the Shape interface.  To draw a shape, you first create an object of a class that implements the Shape interface and then call the draw method of the Graphics2D class. Drawing Rectangle Rectangle 2D rect = . . .; g2.draw(rect);  There are two versions of each Shape class  one with float coordinates (conserves memory)  one with double coordinates (easier to use) Rectangle2D.Float floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F); Rectangle2D.Double doubleRect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);  Rectangles are simple to construct  Requires four arguments  x- and y-coordinates of the upper-left corner  the width and the height  The Rectangle2D class has over 20 useful methods including:  get Width  getHeight  getCenterX  getCenterY  Sometimes you don’t have the top-left corner readily available.
  • 53. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 9  It is possible to have two diagonal corners of a rectangle that are not the top-left corner and the bottom-right corner.  To create a rectangle in this case use the setFrameFromDiagonal method. Rectangle2D rect = new Rectangle2D.Double(); rect.setFrameFromDiagonal(px, py, qx, qy);  If you have a Point2D object, you can also create a rectangle by calling Rectangle2D rect = new Rectangle2D.Double(p1, p2); Drawing Ellipse  The class Ellipse2D is inherited from the same Rectangle class that Rectangle2D is.  because of the bounding box surrounding the ellipse  So, creating an Ellipse2D object is very similar to creating a Rectangle2D object. Ellipse2D e = new Ellipse2D.Double(px, py, qx, qy) where px, py are the x- and y-coordinates of the top-left corner and qx, qy are the x- and y-coordinates of the bottom-right corner of the bounding box of the ellipse Drawing Line  To construct a line, simple use the Line2D class.  It too, requires 4 arguments (the x and y coordinates of the start and end positions)  These coordinates can be 2 Point2D objects or 2 pairs of numbers. Line2D line = new Line2D.Double(start, end) or Line2D line = new Line2D.Double(px, py, qx, qy) Filling Shapes  You can fill the interior of closed shape objects with a color.  Simply call the fill instead of draw method on the Graphics object. Rectangle2D rect = new Rectangle2D.Double(x, y, x2, y2); g2.setPaint(Color.red); g2.fill(rect); /** * A frame that contains a panel with drawings */ class DrawFrame extends JFrame { public DrawFrame() { setTitle("DrawTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add panel to frame DrawComponent component = new DrawComponent(); add(component); } public static final int DEFAULT_WIDTH = 400; public static final int DEFAULT_HEIGHT = 400; } /** * A component that displays rectangles and ellipses. */ class DrawComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // draw a rectangle double leftX = 100; double topY = 100; double width = 200; double height = 150; Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height); g2.draw(rect);
  • 54. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 10 // draw the enclosed ellipse Ellipse2D ellipse = new Ellipse2D.Double(); ellipse.setFrame(rect); g2.draw(ellipse); // draw a diagonal line g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height)); // draw a circle with the same center double centerX = rect.getCenterX(); double centerY = rect.getCenterY(); double radius = 150; Ellipse2D circle = new Ellipse2D.Double(); circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius); g2.draw(circle); } } 3.5 using colors  Class Color declares methods and constants for manipulating colors in a Java program(java.awt.Color)  Every color is created from a red, a green and a blue component – RGB values Common Constructors:  Color (int Red, int Green, int Blue) Creates a color with the designated combination of red, green, and blue (each 0-255).  Color (float Red, float Green, float Blue) Creates a color with the designated combination of red, green, and blue (each 0-1).  Color (int rgb) Creates a color with the designated combination of red, green, and blue (each 0-255). Common Methods:  getBlue () Returns the blue component of the color.  getGreen () Returns the green component of the color.  getRed () Returns the red component of the color. import java.awt.*; import java.awt.geom.*; import javax.swing.*; class FillTest { public static void main(String[] args) { FillFrame frame = new FillFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }} /** A frame that contains a panel with drawings Color constant Color RGB value public final static Color RED red 255, 0, 0 public final static Color GREEN green 0, 255, 0 public final static Color BLUE blue 0, 0, 255 public final static Color ORANGE orange 255, 200, 0 public final static Color PINK pink 255, 175, 175 public final static Color CYAN cyan 0, 255, 255 public final static Color MAGENTA magenta 255, 0, 255 public final static Color YELLOW yellow 255, 255, 0 public final static Color BLACK black 0, 0, 0 public final static Color WHITE white 255, 255, 255 public final static Color GRAY gray 128, 128, 128 public final static Color LIGHT_GRAY lightgray 192, 192, 192 public final static Color DARK_GRAY darkgray 64, 64, 64
  • 55. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 11 */ class FillFrame extends JFrame { public FillFrame() { setTitle("FillTest"); setSize(400,400); // add panel to frame FillPanel panel = new FillPanel(); Container contentPane = getContentPane(); contentPane.add(panel); } } /** A panel that displays filled rectangles and ellipses */ class FillPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; // draw a rectangle Rectangle2D rect = new Rectangle2D.Double(100,100,200,150); g2.setPaint(Color.RED); g2.fill(rect); // draw the enclosed ellipse Ellipse2D ellipse = new Ellipse2D.Double(); ellipse.setFrame(rect); g2.setPaint(new Color(0, 128, 128)); // a dull blue-green g2.fill(ellipse); }} 3.5 using font  Class Font  Constructor takes three arguments—the font name, font style and font size  Font name – any font currently supported by the system on which the program is running  Font style –Font.PLAIN, Font.ITALIC or Font.BOLD. Font styles can be used in combination  Font sizes – measured in points. A point is 1/72 of an inch.  Methods getName, getStyle and getSize retrieve information about Font object  Graphics methods getFont and setFont retrieve and set the current font, respectively Method or constant Description Font constants, constructors and methods public final static int PLAIN A constant representing a plain font style. public final static int BOLD A constant representing a bold font style. public final static int ITALIC A constant representing an italic font style. public Font( String name, int style, int size ) Creates a Font object with the specified font name, style and size. public int getStyle() Returns an integer value indicating the current font style. public int getSize() Returns an integer value indicating the current font size.
  • 56. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 12 import java.awt.*; import java.awt.font.*; import java.awt.geom.*; import javax.swing.*; class FontTest { public static void main(String[] args) { FontFrame frame = new FontFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } } /** A frame with a text message panel */ class FontFrame extends JFrame { public FontFrame() { setTitle("FontTest"); setSize(300,200); // add panel to frame FontPanel panel = new FontPanel(); Container contentPane = getContentPane(); contentPane.add(panel); } } /** A panel that shows a centered message in a box. */ class FontPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); String message = "Hello, World!"; Font f = new Font("Serif", Font.BOLD, 36); g.setFont(f); g.drawString(message, 50,100); Font f1 = new Font("Arial", Font.ITALIC, 30); g.setFont(f1); g.drawString(message, 50,150); } } Method or constant Description public String getName() Returns the current font name as a string. public String getFamily() Returns the font’s family name as a string. public boolean isPlain() Returns true if the font is plain, else false. public boolean isBold() Returns true if the font is bold, else false. public boolean isItalic() Returns true if the font is italic, else false. Graphics methods for manipulating Fonts public Font getFont() Returns a Font object reference representing the current font. public void setFont( Font f ) Sets the current font to the font, style and size specified by the Font object reference f.
  • 57. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 13 3.5 using images  You can display images on the Graphics object.  You can use images stored locally or someplace on the Internet. Step1: Loading an image java.awt.Toolkit Toolkit getDefaultToolkit()- returns the default toolkit. Image getImage(String filename) - returns an image that will read its pixel data from a file. Toolkit object can only read GIF and JPEG files. Step2: displaying an image java.awt.Graphics boolean drawImage(Image img, int x, int y, ImageObserver observer)- draws a scaled image. boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) - draws a scaled image. The system scales the image to fit into a region with the given width and height. Note: This call may return before the image is drawn.  If an image is stored locally call: String filename = ―…‖; Image image = ImageIO.read(new File(filename));  If an image is on the Internet, use the url: String filename = ―…‖; Image image = ImageIO.read(new URL(url); import java.awt.*; class Demo extends Frame{ Demo(String s){ super(s);setSize(300,300); setVisible(true); } public void paint(Graphics g) { Toolkit tk = Toolkit.getDefaultToolkit(); Image img= tk.getImage("Sunset.jpg"); for (int i = 20; i <300-20; i=i+20) for (int j = 40; j <300-20; j=j+20) g.drawImage(img,i,j,20,20,null); } public static void main(String arg[]){ Demo ob=new Demo("Image Demo"); } } AWT Components  All components are subclass of Component class    Components allow the user to interact with application. A layout manager arranges components within a container (Frame/Applet/Panel).  Adding and Removing Controls
  • 58. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 14  add(Component compObj)- add components to the conatainer. Once it is added, it will automatically be visible whenever its parent window is displayed. Here, compObj is an instance of the control that you want to add.    void remove(Component obj)- remove a control from a window    removeAll( )- remove all controls from a window  Component Constructor Methods Label Label( ) void setText(String str) Label(String str) String getText( ) Label(String str, int how) Button Button( ) void setLabel(String str) Button(String str) String getLabel( ) List List( ) void add(String name) List(int numRows) void add(String name, int List(int numRows, boolean multipleSelect) index) String getSelectedItem( ) int getSelectedIndex( ) String[ ] getSelectedItems( ) Choice Choice( ) void add(String name) String getSelectedItem( ) int getSelectedIndex( ) Checkbox Checkbox( ) boolean getState( ) Checkbox(String str) void setState(boolean on) Checkbox(String str, boolean on) String getLabel( ) Checkbox(String str, boolean on, CheckboxGroup cbGroup) void setLabel(String str) Checkbox(String str, CheckboxGroup cbGroup, boolean on) TextField TextField( ) String getText( ) TextField(int numChars) void setText(String str) TextField(String str) void setEditable(boolean TextField(String str, int numChars) canEdit) TextArea TextArea( ) void append(String str) TextArea(int numLines, int numChars) void insert(String str, int TextArea(String str) index) TextArea(String str, int numLines, int numChars) Label  Labels are components that hold text.    Labels don’t react to user input. It is used to identify components.  Constructors  Label(String str) - constructs a label with left-aligned text.    Label(String str, int how) - constructs a label with the alignment specified by how.  Methods  void setText(String str)- set the text in the label    String getText( )- return the text of label 
  • 59. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 15 Example: The following example creates three labels and adds them to a frame..The labels are organized in the frame by the flow layout manager. import java.awt.*; Demo ob=new Demo("Label Demo"); public class Demo extends Frame{ } Label lb1 = new Label("One"); } Label lb2 = new Label("Two"); Output: Label lb3 = new Label("Three"); FlowLayout flow= new FlowLayout(); Demo(String s){ super(s); setSize(200,200); setLayout(flow); add(lb1);add(lb2);add(lb3); setVisible(true); } public static void main(String arg[]){ Button A push button is a component that contains a label and that generates an event when it is pressed. Push buttons are objects of type Button. Constructors  Button( )- creates an empty button    Button(String str)- creates a button that contains str as a label.  Methods  void setLabel(String str) -set the label in the button    String getLabel( ) -return the label of button  Example: The following example creates three buttons and adds them to a frame. The buttons are organized in the frame by the flow layout manager. public static void main(String arg[]){ import java.awt.*; Demo ob=new Demo("Button Demo"); public class Demo extends Frame{ } } FlowLayout flow= new FlowLayout(); Output: Button b=new Button(); Button b1=new Button(); Button b2=new Button("Button 2"); Demo(String s){ super(s);setSize(200,200); setLayout(flow); b1.setLabel("Button 1"); add(b);add(b1);add(b2); setVisible(true); }
  • 60. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 16 List The List class provides a compact, multiple-choice, scrolling selection list. List object can be constructed to display any number of choices in the visible window. It allows the user to select multiple items. Constructors  List( )- allows to select one item at any one time    List(int numRows)- the value of numRows specifies the number of entries in the list that  will be visible always  List(int numRows, boolean multipleSelect)- if multipleSelect is true, then the user may  select two or more items at a time Method  void add(String name)- Here, name is the name of the item added to the list. The first form adds items to the end of the list.    void add(String name, int index) -adds the item at the index specified by index    String getSelectedItem( )- return the selected item    String[ ] getSelectedItems( )- return the selected items.  Example: The following example creates a list and adds it to a frame. import java.awt.*; Demo ob=new public class Demo extends Frame{ Demo("List Demo"); FlowLayout flow= new FlowLayout(); } List l1=new List(2); } List l2=new List(3); List l3=new List(4,true); Label lb1 = new Label("Dept"); Label lb2 = new Label("Dept"); Label lb3 = new Label("Dept"); Demo(String s){ super(s); setSize(200,300); setLayout(flow); l1.add("CSE");l1.add("ECE");l1.add("EEE");l1.add("MECH"); l2.add("CSE");l2.add("ECE");l2.add("EEE");l2.add("MECH"); l3.add("CSE");l3.add("ECE");l3.add("EEE");l3.add("MECH"); add(lb1);add(l1);add(lb2);add(l2);add(lb3);add(l3); setVisible(true); } public static void main(String arg[]){ CheckBox A check box is a control that is used to turn an option on or off. It consists of a small box that can
  • 61. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 17 either contain a check mark or not. There is a label associated with each check box that describes what option the box represents. Constructors  Checkbox( )- check box whose label is initially blank    Checkbox(String str)- check box whose label is specified by str.    Checkbox(String str, boolean on) - allows you to set the initial state of the check box. If on is true, the check box is initially checked    Checkbox(String str, boolean on, CheckboxGroup cbGroup)- group is specified by cbGroup    Checkbox(String str, CheckboxGroup cbGroup, boolean on)  Methods  boolean getState( )    void setState(boolean on)    String getLabel( )    void setLabel(String str)  CheckboxGroup Create a set of mutually exclusive check boxes in which one and only one check box in the group can be checked at any one time. These check boxes are often called radio buttons. The default constructor is defined, which creates an empty group. Example: The following example creates a checkbox group (Gender) and checkboxes (Languages Known). import java.awt.*; Label l2=new Label("Languages Known"); public class Demo extends Frame{ CheckboxGroup cg=new CheckboxGroup(); FlowLayout flow= new FlowLayout(); Checkbox c1=new Checkbox("Male",cg,true); Label l1=new Label("Gender"); Checkbox c2=new Checkbox("Female",cg,false); Checkbox c3=new Checkbox("VisualBasic"); } Checkbox c4=new Checkbox("C++"); } Checkbox c5=new Checkbox("Java"); Checkbox c6=new Checkbox("C"); Output: Demo(String s){ super(s); setSize(200,200); setLayout(flow); add(l1);add(c1);add(c2); add(l2);add(c3);add(c4);add(c5);add(c6); setVisible(true); } public static void main(String arg[]){ Demo ob=new Demo("Checkbox Demo");
  • 62. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 18 Choice The Choice class is used to create a pop-up list of items from which the user may choose. It allows the user to select single item at any time. Choice only defines the default constructor, which creates an empty list. To add a item to the list, call add( ). It has this general form:  void add(String name)    To determine which item is currently selected, you may call either getSelectedItem( ) or getSelectedIndex( ).  import java.awt.*; public class Demo extends Frame{ FlowLayout flow= new FlowLayout(); Label lb=new Label("City"); Choice c=new Choice(); Demo(String s){ super(s); setSize(200,200);setLayout(flow); c.add("Chennai");c.add("Coimbatore"); c.add("KanyaKumari");c.add("Madurai"); c.add("Tirunelveli"); add(lb);add(c); setVisible(true); } public static void main(String arg[]){ Demo ob=new Demo("Checkbox Demo"); } } TextField Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections.  TextField( )- creates a default text field    TextField(int numChars)- creates a text field that is numChars characters wide    TextField(String str)- initializes the text field with the string contained in str    TextField(String str, int numChars)  Methods  String getText( )    void setText(String str)  TextArea Simple multiline editor allow the user to enter strings. TextArea and TextField are subclass of TextComponent. Therefore, it supports the getText( ), setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods described in TextField class.
  • 63. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 19 import java.awt.*; TextArea ta=new TextArea(2,10); public class Demo extends Frame{ Demo(String s){ FlowLayout flow= new FlowLayout(); super(s); Label lb1=new Label("Name"); setSize(250,200); Label lb2=new Label("No"); setLayout(flow); Label lb3=new Label("Message"); add(lb1);add(t1); TextField t1=new TextField(20); add(lb2);add(t2); TextField t2=new TextField(15); add(lb3);add(ta); setVisible(true); } public static void main(String arg[]){ Demo ob=new Demo("TextComponents Demo"); } } output: 3.7 Basics of Event Handling  Event handling is a basic concept of graphical user interfaces.  What is event handling? -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. Examples. Pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse, timer expires, counter, h/w or s/w failure. The way event handling works is this:  Any operating system that supports GUIs constantly monitors events such as keystrokes and mouse clicks.  The operating system reports these events to programs that are running.  The programs decide what, if anything, they want to do with these events.
  • 64. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 20  In Java, you control how to handle these events by setting up event source objects and event listener objects. Event Source  A source is an object that generates an event.  This occurs when the internal state of that object changes.  A source must register listeners. Event Source Description Button Generates action events when the button is pressed. Checkbox Generates item events when the check box is selected or deselected. Choice Generates item events when the choice is changed. List Generates action events when an item is double-clicked; generates item events when an item is selected or deselected. Mouse Generates Mouse events when Mouse input occurs. Keyboard Generates Key events when keyboard input occurs. Event Listeners  Listener is an object that is notified when an event occurs. It has two major requirements.  It must have been registered with one or more sources to receive notifications about specific types of events.  It must implement methods to receive and process these notifications.  The package java.awt.event defines several types of events that are generated by various user interface elements.
  • 65. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 21 How event handling in the AWT works  A listener object is an instance of a class that implements a special interface called (naturally enough) a listener interface.  An event source is an object that can register listener objects and send them event objects.  The event source sends out event objects to all registered listeners when that event occurs.  The listener objects will then use the information in the event object to determine their reaction to the event.  You register the listener object with the source object by using lines of code that follow the model: eventSourceObject.addEventListener(eventListenerObject); 3.8 AWT Event Hierarchy Source Event Class Class Methods Listener Interface Interface Methods Button ActionEvent String ActionListener actionPerformed(ActionEvent ae) getActionCommand( ) List, ItemEvent Object getItem( ) ItemListener itemStateChanged(ItemEvent ie) Choice, ItemSelectable Checkbox getItemSelectable( ) Keyboard KeyEvent char getKeyChar( ) KeyListener keyPressed(KeyEvent ke) int getKeyCode( ) keyReleased(KeyEvent ke) keyTyped(KeyEvent ke)
  • 66. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 22 Mouse MouseEvent int getX( ) MouseListener mouseClicked(MouseEvent me) int getY( ) mouseEntered(MouseEvent me) mouseExited(MouseEvent me) mousePressed(MouseEvent me) mouseReleased(MouseEvent me) MouseMotionListener mouseDragged(MouseEvent me) mouseMoved(MouseEvent me) Handling Keyboard Events A KeyEvent is fired (to all its registered KeyListeners) when you pressed, released, and typed (pressed followed by released) a key on the source object. A KeyEvent listener must implement KeyListener interface, which declares three abstract methods: public void keyTyped(KeyEvent e) // Called-back when a key has been typed (pressed and released). public void keyPressed(KeyEvent e) public void keyReleased(KeyEvent e) // Called-back when a key has been pressed/released. Source: KeyBoard Event Class: java.awt.event.KeyEvent Listener Interface: java.awt.event.KeyListener Example: The following program demonstrates keyboard input. When program receives keystrokes, identifies the key and perform the corresponding actions specified by the program. import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; // An AWT GUI program inherits the top-level container java.awt.Frame class KeyEventDemo extends Frame implements KeyListener { // This class acts as KeyEvent Listener private TextField tfInput; // single-line TextField to receive tfInput key private TextArea taDisplay; // multi-line TextArea to taDisplay result
  • 67. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 23 /** Constructor to setup the GUI */ public KeyEventDemo() { setLayout(new FlowLayout()); // "this" frame sets to FlowLayout add(new Label("Enter Text: ")); tfInput = new TextField(10); add(tfInput); taDisplay = new TextArea(5, 40); // 5 rows, 40 columns add(taDisplay); tfInput.addKeyListener(this); // tfInput TextField fires KeyEvent to its registered KeyListener // It adds "this" object as a KeyEvent listener setTitle("KeyEvent Demo"); // "this" Frame sets title setSize(400, 200); // "this" Frame sets initial size setVisible(true); // "this" Frame shows } /** The entry main() method */ public static void main(String[] args) { new KeyEventDemo(); // Let the constructor do the job } /** KeyEvent handlers */ // Called back when a key has been typed (pressed and released) @Override public void keyTyped(KeyEvent e) { taDisplay.append("You have typed " + e.getKeyChar() + "n"); } // Not Used, but need to provide an empty body for compilation @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } } In this example: 1. We identify the TextField (input) as the source object, which fires a KeyEvent when you press/release/type a key onto it. 2. We select this object as the KeyEvent listener. 3. We register this object as the KeyEvent listener to the source TextField via method input.addKeyListener(this).
  • 68. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 24 4. The KeyEvent listener (this object) needs to implement the KeyListener interface, which declares 3 abstract methods: keyTyped(), keyPressed(), keyReleased(). 5. We override the keyTyped() to display key typed on the display TextArea. We ignore the keyPressed() and keyReleased(). 3.9 Handling Mouse Events A MouseEvent is fired to all its registered listeners, when you press, release, or click (press followed by release) a mouse-button (left or right button) at the source object; or position the mouse-pointer at (enter) and away (exit) from the source object. A MouseEvent listener must implement the MouseListener interface, which declares the following five abstract methods: public void mouseClicked(MouseEvent e) // Called-back when the mouse-button has been clicked (pressed followed by released) on the source. public void mousePressed(MouseEvent e) public void mouseReleased(MouseEvent e) // Called-back when a mouse-button has been pressed/released on the source. // A mouse-click invokes mousePressed(), mouseReleased() and mouseClicked(). public void mouseEntered(MouseEvent e) public void mouseExited(MouseEvent e) // Called-back when the mouse-pointer has entered/exited the source. public void mouseDragged(MouseEvent e) // Called-back when a mouse-button is pressed on the source component and then dragged. public void mouseMoved(MouseEvent e) // Called-back when the mouse-pointer has been moved onto the source component but no buttons have been pushed. Source: Mouse Event Class: java.awt.event.MouseEvent Listener Interface: java.awt.event.MouseListener java.awt.event.MouseMotionListener import java.awt.*; import javax.swing.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; // An AWT GUI program inherits the top-level container java.awt.Frame class MouseMotionDemo extends JFrame implements MouseListener, MouseMotionListener { // This class acts as MouseListener and MouseMotionListener
  • 69. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 25 // To display the (x, y) coordinates of the mouse-clicked private JTextField tfMouseClickX; private JTextField tfMouseClickY; // To display the (x, y) coordinates of the current mouse-pointer position private JTextField tfMousePositionX; private JTextField tfMousePositionY; /** Constructor to setup the GUI */ public MouseMotionDemo() { setLayout(new FlowLayout()); // "this" frame sets to FlowLayout add(new Label("X-Click: ")); tfMouseClickX = new JTextField(10); tfMouseClickX.setEditable(false); add(tfMouseClickX); add(new JLabel("Y-Click: ")); tfMouseClickY = new JTextField(10); tfMouseClickY.setEditable(false); add(tfMouseClickY); add(new JLabel("X-Position: ")); tfMousePositionX = new JTextField(10); tfMousePositionX.setEditable(false); add(tfMousePositionX); add(new Label("Y-Position: ")); tfMousePositionY = new JTextField(10); tfMousePositionY.setEditable(false); add(tfMousePositionY); addMouseListener(this); addMouseMotionListener(this); // "this" frame fires MouseEvent to all its registered MouseListener and MouseMotionListener // "this" frame adds "this" object as MouseListener and MouseMotionListener setTitle("MouseMotion Demo"); // "this" Frame sets title setSize(200, 200); // "this" Frame sets initial size setVisible(true); // "this" Frame shows } /** The entry main() method */ public static void main(String[] args) { new MouseMotionDemo(); // Let the constructor do the job }
  • 70. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 26 /** MouseListener handlers */ // Called back when a mouse-button has been clicked @Override public void mouseClicked(MouseEvent e) { tfMouseClickX.setText(e.getX() + ""); tfMouseClickY.setText(e.getY() + ""); } // Not Used, but need to provide an empty body for compilation @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } /** MouseMotionEvent handlers */ // Called back when the mouse-pointer has been moved @Override public void mouseMoved(MouseEvent e) { tfMousePositionX.setText(e.getX() + ""); tfMousePositionY.setText(e.getY() + ""); } // Not Used, but need to provide an empty body for compilation @Override public void mouseDragged(MouseEvent e) { } } In this example, we shall illustrate both the MouseListener and MouseMotionListener. 1. We identify this Frame as the source, which fires the MouseEvent to its registered MouseListener and MouseMotionListener. 2. We select this object as the MouseListener and MouseMotionListner (for simplicity). 3. We register this object as the listener to this Frame via method this.addMouseListener(this) and this.addMouseMotionListener(this). 4. The MouseMotionListener (this object) needs to implement 2 abstract methods: mouseMoved() and mouseDragged() declared in the MouseMotionListener interface. 5. We override the mouseMoved() to display the (x, y) position of the mouse pointer. We ignore the MouseDragged() handler by providing an empty body for compilation.
  • 71. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 27 Action Event To handle Action events, class must implement the ActionListener interface. Source objects needs to register action listener to receive events. SourceObject.addActionListener(this); Source: Button Event Class: java.awt.event.ActionEvent Listener Interface: java.awt.event.ActionListener Example: The following program demonstrates Action event handling. Application window has 3 Text Fields and two buttons. Text fields are used to get user input and show the result to the user. When the user presses Button, it will generate an action event. Listener receives the event and performs the operation specified in the actionPerformed Method. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Demo extends JFrame implements ActionListener{ FlowLayout flow=new FlowLayout(); JLabel lb1 = new JLabel("Number1"); JLabel lb2 = new JLabel("Number2"); JLabel lb3 = new JLabel("Result"); JTextField t1=new JTextField(20); JTextField t2=new JTextField(20); JTextField t3=new JTextField(20); JButton b1=new JButton("Add"); JButton b2=new JButton("Multiply"); Demo(String s){ super(s); setLayout(flow); add(lb1);add(t1); add(lb2);add(t2); add(b1);add(b2); add(lb3);add(t3); b1.addActionListener(this); b2.addActionListener(this); setSize(350,280); setVisible(true); } public void actionPerformed(ActionEvent ae){ String s=ae.getActionCommand(); int n1,n2; n1=Integer.parseInt(t1.getText());
  • 72. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 28 n2=Integer.parseInt(t2.getText()); if(s.equals("Add")){ t3.setText(String.valueOf(n1+n2)); } if(s.equals("Multiply")){ t3.setText(String.valueOf(n1*n2)); }} public static void main(String arg[]){ Demo my=new Demo("Action event demo"); }} Item Event To handle Item events, class must implement the ItemListener interface. Source objects needs to register action listener to receive events. SourceObject.addActionListener(this); Source: List, Choice, Checkbox Event Class: java.awt.event.ItemEvent Listener Interface: java.awt.event.ItemListener Example: The following program demonstrates Item event handling. Application window has Text Field, Checkbox, and Choice. Text fields are used to show the result to the user. When the user select item from any component, then the selected item will be displayed in text field. A listener receives the event and performs the operation specified in the itemStateChanged() Method. import java.awt.*; TextField t=new TextField(20); import java.awt.event.*; Demo(String s){ public class Demo extends Frame implements super(s); ItemListener{ setLayout(flow); String msg=""; c.add("Chennai");c.add("Coimbatore"); FlowLayout flow=new FlowLayout(); c.add("KanyaKumari");c.add("Madurai"); Label lb1 = new Label("City"); c.add("Tirunelveli"); Label lb2 = new Label("Qualification"); add(lb1);add(c); Label lb3 = new Label("Languages Known"); add(lb2);add(c1);add(c2); Choice c=new Choice(); add(lb3);add(c3);add(c4);add(c5);add(c6); CheckboxGroup cg=new CheckboxGroup(); add(t); Checkbox c1=new Checkbox("UG",cg,true); setSize(200,300); Checkbox c2=new Checkbox("PG",cg,false); setVisible(true); Checkbox c3=new Checkbox("Visual Basic"); c.addItemListener(this); Checkbox c4=new Checkbox("C++"); c1.addItemListener(this); Checkbox c5=new Checkbox("Java"); c2.addItemListener(this); Checkbox c6=new Checkbox("dotnet"); c3.addItemListener(this); c4.addItemListener(this); c5.addItemListener(this); c6.addItemListener(this); } public void itemStateChanged(ItemEvent ie){ String msg=(String)ie.getItem(); t.setText(msg); } public static void main(String arg[]){ Demo ob=new Demo("List event Demo"); }}
  • 73. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 29 Event Listener's Adapter Class WindowListener/WindowAdapter A WindowEvent listener is required to implement the WindowListener interface, which declares 7 abstract methods. Although we are only interested in windowClosing(), we need to provide an empty body to the other 6 methods in order to compile the program. This is tedious. For example, we can rewrite the WindowEventDemo using an inner class implementing ActionListener as follows: import java.awt.*; import javax.swing.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame class WindowEventDemoWithInnerClass extends JFrame { private JTextField tfCount; private int count = 0; /** Constructor to setup the GUI */ public WindowEventDemoWithInnerClass () { setLayout(new FlowLayout()); add(new JLabel("Counter")); tfCount = new JTextField("0", 10); tfCount.setEditable(false); add(tfCount); JButton btnCount = new JButton("Count"); add(btnCount); btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + ""); } }); // Allocate an anonymous instance of an anonymous inner class // that implements WindowListener. // "this" Frame adds the instance as WindowEvent listener. addWindowListener(new WindowListener() { @Override public void windowClosing(WindowEvent e) { System.exit(0); // terminate the program } // Need to provide an empty body for compilation
  • 74. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 30 @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } }); setTitle("WindowEvent Demo"); setSize(250, 100); setVisible(true); } /** The entry main method */ public static void main(String[] args) { new WindowEventDemoWithInnerClass(); // Let the constructor do the job } } 3.10 Adapter class An adapter class called WindowAdapter is therefore provided, which implements the WindowListener interface and provides default implementations to all the 7 abstract methods. You can then derive a subclass from WindowAdapter and override only methods of interest and leave the rest to their default implementation. For example, import java.awt.*; import javax.swing.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame class WindowEventDemoAdapter extends JFrame { private JTextField tfCount; private int count = 0; /** Constructor to setup the GUI */ public WindowEventDemoAdapter () { setLayout(new FlowLayout()); add(new Label("Counter")); tfCount = new JTextField("0", 10); tfCount.setEditable(false); add(tfCount); JButton btnCount = new JButton("Count"); add(btnCount);
  • 75. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 31 btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + ""); } }); // Allocate an anonymous instance of an anonymous inner class // that extends WindowAdapter. // "this" Frame adds the instance as WindowEvent listener. addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); // Terminate the program } }); setTitle("WindowEvent Demo"); setSize(250, 100); setVisible(true); } /** The entry main method */ public static void main(String[] args) { new WindowEventDemoAdapter(); // Let the constructor do the job } } Other Event-Listener Adapter Classes  Similarly, adapter classes such as MouseAdapter, MouseMotionAdapter, KeyAdapter, FocusAdapter are available for Mou seListener, MouseMotionListener, KeyListener, and FocusListener, respectively.  There is no ActionAdapter for ActionListener, because there is only one abstract method (i.e. actionPerformed()) declared in the ActionListener interface. This method has to be overridden and there is no need for an adapter 3.11 Layout Managers A container has a so-called layout manager to arrange its components. The layout managers provide a level of abstraction to map your user interface on all windowing systems, so that the layout can be platform-independent. AWT provides the following layout managers (in package java.awt): FlowLayout, GridLayout, BorderLayout, GridBagLayout, BoxLayout, CardLayout, and others.
  • 76. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 32 Container's setLayout() A container has a setLayout() method to set its layout manager: // java.awt.Container public void setLayout(LayoutManager mgr) To set up the layout of a Container (such as Frame, JFrame, Panel, or JPanel), you have to: 1. Construct an instance of the chosen layout object, via new and constructor, e.g., new FlowLayout()) 2. Invoke the setLayout() method of the Container, with the layout object created as the argument; 3. Place the GUI components into the Container using the add() method in the correct order; or into the correct zones. For example, // Allocate a Panel (containter) Panel p = new Panel(); // Allocate a new Layout object. The Panel container sets to this layout. p.setLayout(new FlowLayout()); // The Panel container adds components in the proper order. p.add(new JLabel("One")); p.add(new JLabel("Two")); p.add(new JLabel("Three")); ...... Container's getLayout() You can get the current layout via Container's getLayout(). Panel awtPanel = new Panel(); System.out.println(awtPanel.getLayout()); // java.awt.FlowLayout[hgap=5,vgap=5,align=center] Panel's Inital Layout Panel (and Swing's JPanel) provides a constructor to set its initial layout manager. It is because a primary function of Panel is to layout a group of component in a particular layout. public void Panel (LayoutManager layout) // Construct a Panel in the given layout // By default, Panel (and JPanel) has FlowLayout // For example, create a Panel in BorderLayout Panel mainPanel = new Panel(new BorderLayout()); FlowLayout In the java.awt.FlowLayout, components are arranged from left-to-right inside the container in the order that they are added (via method aContainer.add(aComponent)). When one row is filled, a new row will be started. The actual appearance depends on the width of the display window. Constructors public FlowLayout(); public FlowLayout(int align); public FlowLayout(int align, int hgap, int vgap);
  • 77. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 33 // align: FlowLayout.LEFT (or LEADING), FlowLayout.RIGHT (or TRAILING), or FlowLayout.CENTER // hgap, vgap: horizontal/vertical gap between the components // By default: hgap=5, vgap=5, align=CENTER import java.awt.*; import javax.swing.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame class AWTFlowLayoutDemo extends JFrame { private JButton btn1, btn2, btn3, btn4, btn5, btn6; /** Constructor to setup GUI components */ public AWTFlowLayoutDemo () { setLayout(new FlowLayout()); // "this" Frame sets layout to FlowLayout, which arranges the components // from left-to-right, and flow from top-to-bottom. btn1 = new JButton("Button 1"); add(btn1); btn2 = new JButton("This is Button 2"); add(btn2); btn3 = new JButton("3"); add(btn3); btn4 = new JButton("Another Button 4"); add(btn4); btn5 = new JButton("Button 5"); add(btn5); btn6 = new JButton("One More Button 6"); add(btn6); setTitle("FlowLayout Demo"); // "this" Frame sets title setSize(280, 150); // "this" Frame sets initial size setVisible(true); // "this" Frame shows }
  • 78. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 34 /** The entry main() method */ public static void main(String[] args) { new AWTFlowLayoutDemo(); // Let the constructor do the job } } GridLayout In java.awt.GridLayout, components are arranged in a grid (matrix) of rows and columns inside the Container. Components are added in a left-to-right, top-to-bottom manner in the order they are added (via method aContainer.add(aComponent)). Constructors public GridLayout(int rows, int columns); public GridLayout(int rows, int columns, int hgap, int vgap); // By default: rows=1, cols=0, hgap=0, vgap=0 import java.awt.*; import javax.swing.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame class AWTGridLayoutDemo extends JFrame { private JButton btn1, btn2, btn3, btn4, btn5, btn6; /** Constructor to setup GUI components */ public AWTGridLayoutDemo () { setLayout(new GridLayout(3, 2, 3, 3)); // "this" Frame sets layout to 3x2 GridLayout, horizontal and verical gaps of 3 pixels // The components are added from left-to-right, top-to-bottom btn1 = new JButton("Button 1"); add(btn1); btn2 = new JButton("This is Button 2"); add(btn2); btn3 = new JButton("3"); add(btn3); btn4 = new JButton("Another Button 4"); add(btn4);
  • 79. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 35 btn5 = new JButton("Button 5"); add(btn5); btn6 = new JButton("One More Button 6"); add(btn6); setTitle("GridLayout Demo"); // "this" Frame sets title setSize(280, 150); // "this" Frame sets initial size setVisible(true); // "this" Frame shows } /** The entry main() method */ public static void main(String[] args) { new AWTGridLayoutDemo(); // Let the constructor do the job } } If rows or cols is 0, but not both, then any number of components can be placed in that column or row. If both the rows and cols are specified, the cols value is ingored. The actual cols is determined by the actual number of components and rows. BorderLayout In java.awt.BorderLayout, the container is divided into 5 zones: EAST, WEST, SOUTH, NORTH, and CENTER. Components are added using method aContainer.add(acomponent, aZone), where azone is either BorderLayout.NORTH (or PAGE_START), BorderLayout.SOUTH (or PAGE_END), BorderLayout.WEST (or LINE_START), BorderLayout.EAST (or LINE_END), or BorderLayout.CENTER. The method aContainer.add(aComponent) without specifying the zone adds the component to the CENTER. You need not add components to all the 5 zones. The NORTH and SOUTH components may be stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may stretch both horizontally and vertically to fill any space left over. Constructors public BorderLayout(); public BorderLayout(int hgap, int vgap); // By default hgap=0, vgap=0
  • 80. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 36 import java.awt.*; import javax.swing.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame class AWTBorderLayoutDemo extends JFrame { private JButton btnNorth, btnSouth, btnCenter, btnEast, btnWest; /** Constructor to setup GUI components */ public AWTBorderLayoutDemo () { setLayout(new BorderLayout(3, 3)); // "this" Frame sets layout to BorderLayout, // horizontal and vertical gaps of 3 pixels // The components are added to the specified zone btnNorth = new JButton("NORTH"); add(btnNorth, BorderLayout.NORTH); btnSouth = new JButton("SOUTH"); add(btnSouth, BorderLayout.SOUTH); btnCenter = new JButton("CENTER"); add(btnCenter, BorderLayout.CENTER); btnEast = new JButton("EAST"); add(btnEast, BorderLayout.EAST); btnWest = new JButton("WEST"); add(btnWest, BorderLayout.WEST); setTitle("BorderLayout Demo"); // "this" Frame sets title setSize(280, 150); // "this" Frame sets initial size setVisible(true); // "this" Frame shows } /** The entry main() method */ public static void main(String[] args) { new AWTBorderLayoutDemo(); // Let the constructor do the job } }
  • 81. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 37 Using Panels as Sub-Container to Organize Components An AWT Panel is a retangular pane, which can be used as sub-container to organized a group of related components in a specific layout (e.g., FlowLayout, BorderLayout). Panels are secondary containers, which shall be added into a top-level container (such as Frame), or another Panel. For example, the following figure shows a Frame (in BorderLayout) containing two Panels, panelResult in FlowLayout and panelButtons in GridLayout. panelResult is added to the NORTH, and panelButtons is added to the CENTER. import java.awt.*; import javax.swing.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame class AWTPanelDemo extends JFrame { private JButton[] btnNumbers = new JButton[10]; // Array of 10 numeric buttons private JButton btnHash, btnStar; private JTextField tfDisplay; /** Constructor to setup GUI components */ public AWTPanelDemo () { // Set up display panel JPanel panelDisplay = new JPanel(new FlowLayout()); tfDisplay = new JTextField("0", 20); panelDisplay.add(tfDisplay); // Set up button panel JPanel panelButtons = new JPanel(new GridLayout(4, 3)); btnNumbers[1] = new JButton("1"); panelButtons.add(btnNumbers[1]); btnNumbers[2] = new JButton("2"); panelButtons.add(btnNumbers[2]); btnNumbers[3] = new JButton("3"); panelButtons.add(btnNumbers[3]); btnNumbers[4] = new JButton("4"); panelButtons.add(btnNumbers[4]); btnNumbers[5] = new JButton("5"); panelButtons.add(btnNumbers[5]); btnNumbers[6] = new JButton("6");
  • 82. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 38 panelButtons.add(btnNumbers[6]); btnNumbers[7] = new JButton("7"); panelButtons.add(btnNumbers[7]); btnNumbers[8] = new JButton("8"); panelButtons.add(btnNumbers[8]); btnNumbers[9] = new JButton("9"); panelButtons.add(btnNumbers[9]); // Can use a loop for the above statements! btnStar = new JButton("*"); panelButtons.add(btnStar); btnNumbers[0] = new JButton("0"); panelButtons.add(btnNumbers[0]); btnHash = new JButton("#"); panelButtons.add(btnHash); setLayout(new BorderLayout()); // "this" Frame sets to BorderLayout add(panelDisplay, BorderLayout.NORTH); add(panelButtons, BorderLayout.CENTER); setTitle("BorderLayout Demo"); // "this" Frame sets title setSize(200, 200); // "this" Frame sets initial size setVisible(true); // "this" Frame shows } /** The entry main() method */ public static void main(String[] args) { new AWTPanelDemo(); // Let the constructor do the job } } 3.11 Model-View-Controller design pattern Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each of its components. Essentially, MVC breaks GUI components into three elements. Each of these elements plays a crucial role in how the component behaves. Model - (includes state data for each component) The model encompasses the state data for each component. There are different models for different types of components. Model has no user interface. Model data always exists independent of the
  • 83. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 39 component's visual representation. For example, model of a Choice list might contain the information about list of items and currently selected item. This information remains the same no matter how the component is painted on the screen. View - (to display component on screen) The view refers to how you see the component on the screen. It determines exactly where and how to draw the choice list by the information offered by the model. Controller- (handles user Input) The controller decides the behavior of each component with respect to the events. Events come in many forms (a mouse click, a keyboard event).The controller decides how each component will react to the event—if it reacts at all. MVC Interaction In MVC, each of the three elements—the model, the view, and the controller—requires the services of another element to keep itself continually updated. Model-View-Controller Analysis of Swing Buttons For most components, the model class implements an interface whose name ends in Model; thus the interface called ButtonModel. Classes implementing that interface can define the state of the various kinds of buttons. Actually, buttons aren’t all that complicated, and the Swing library contains a single class, called DefaultButtonModel, that implements this interface.
  • 84. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 40 Each JButton object stores a button model object, which you can retrieve. JButton button = new JButton("Blue"); ButtonModel model = button.getModel(); 3.12 Swing Swing is part of the so-called "Java Foundation Classes (JFC)" (have you heard of MFC?), which was introduced in 1997 after the release of JDK 1.1. JFC was subsequently included as an integral part of JDK since JDK 1.2. JFC consists of: Swing API: for advanced graphical programming. Accessibility API: provides assistive technology for the disabled. Java 2D API: for high quality 2D graphics and images. Pluggable look and feel supports. Drag-and-drop support between Java and native applications. The goal of Java GUI programming is to allow the programmer to build GUI that looks good on ALL platforms. JDK 1.0's AWT was awkward and non-object-oriented (using many event.getSource()). JDK 1.1's AWT introduced event-delegation (event-driven) model, much clearer and object-oriented. JDK 1.1 also introduced inner class and JavaBeans – a component programming model for visual programming environment (similar to Visual Basic and Dephi). Swing appeared after JDK 1.1. It was introduced into JDK 1.1 as part of an add-on JFC (Java Foundation Classes). Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI components that can be dragged and dropped as "GUI builders" in visual programming environment. Swing is now an integral part of Java since JDK 1.2. Swing's Features The main features of Swing are (extracted from the Swing website): 1. Swing is written in pure Java (except a few classes) and therefore is 100% portable.
  • 85. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 41 2. Swing components are lightweight. The AWT components are heavyweight (in terms of system resource utilization). Each AWT component has its own opaque native display, and always displays on top of the lightweight components. AWT components rely heavily on the underlying windowing subsystem of the native operating system. For example, an AWT button ties to an actual button in the underlying native windowing subsystem, and relies on the native windowing subsystem for their rendering and processing. Swing components (JComponents) are written in Java. They are generally not "weight-down" by complex GUI considerations imposed by the underlying windowing subsystem. 3. Swing components support pluggable look-and-feel. You can choose between Java look- and-feel and the look-and-feel of the underlying OS (e.g., Windows, UNIX or Mac). If the later is chosen, a Swing button runs on the Windows looks like a Windows' button and feels like a Window's button. Similarly, a Swing button runs on the UNIX looks like a UNIX's button and feels like a UNIX's button. 4. Swing supports mouse-less operation, i.e., it can operate entirely using keyboard. 5. Swing components support "tool-tips". 6. Swing components are JavaBeans – a Component-based Model used in Visual Programming (like Visual Basic). You can drag-and-drop a Swing component into a "design form" using a "GUI builder" and double-click to attach an event handler. 7. Swing application uses AWT event-handling classes (in package java.awt.event). Swing added some new classes in package javax.swing.event, but they are not frequently used. 8. Swing application uses AWT's layout manager (such as FlowLayout and BorderLayout in package java.awt). It added new layout managers, such as Springs, Struts, and BoxLayout (in package javax.swing). 9. Swing implements double-buffering and automatic repaint batching for smoother screen repaint. 10. Swing introduces JLayeredPane and JInternalFrame for creating Multiple Document Interface (MDI) applications. 11. Swing supports floating toolbars (in JToolBar), splitter control, "undo". 12. Others - check the Swing website.
  • 86. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 42 S.No AWT(Abstract Window Toolkit) Swing 1 AWT components are heavy weight, Swing components are light weight, components are platform dependent. components are platform independent. 2 AWT components support Delegate Swing components support MVC (model, Event Model. view, control architecture) 3 AWT components provide static look Swing components provide dynamic look and feel. and feel 4 It does not provide Tooltip text for It provide Tooltip text for components components Writing Swing Applications In summary, to write a Swing application, you have: 1. Use the Swing components with prefix "J" in package javax.swing. 2. A top-level container (such as JFrame or JApplet) is needed. The JComponents cannot be added directly onto the top-level container. They shall be added onto the content-pane of the top-level container. You can retrieve a reference to the content-pane by invoking method getContentPane() from the top-level container, or set the content-pane to the main JPanel created in your program Swing Components javax.swing 3. Component Constructor Methods JLabel JLabel() void setText(String str) JLabel(String text) String getText( ) JLabel(String text, int horizontalAlignment) JButton JButton( ) void setLabel(String str) JButton(String str) String getLabel( ) JList JList() Object getSelectedValue( ) JList(String[] ) int getSelectedIndex( ) String[] getSelectedItems( ) JRadioButton JRadioButton() JRadioButton(String text) JRadioButton(String text, boolean selected) JRadioButton(String text, Icon icon, boolean selected) JComboBox JComboBox() void add(String name) JComboBox(Object items[]) String getSelectedItem( ) int getSelectedIndex( ) JCheckbox JCheckbox( ) boolean getState( ) JCheckbox(String str) void setState(boolean on) JCheckbox(String str, boolean on) String getLabel( )
  • 87. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 43 JCheckBox(String text, Icon icon) void setLabel(String str) JTextField JTextField(int numChars) String getText( ) JTextField(String str, int numChars) void setText(String str) void setEditable(boolean canEdit) JTextArea JTextArea(int numLines, int numChars) void append(String str) JTextArea(String str, int numLines, int numChars) void insert(String str, int index) JPasswordField JPasswordField(String text, int columns) void setEchoChar(char echo) The JLabel Class Swing allows you to create labels that can contain text, images, or both. Unlike java.awt.Label objects, JLabel objects may consist of both text and graphics (icons). Text Input In Java, two components are used to get text input:  JTextField    JTextArea.  The difference between them is that a text field can accept only one line of text and a text area can accept multiple lines of text. The classes are called JTextField for single-line input and JTextArea for multiple lines of text. The JPasswordField Class Password fields are a special kind of text field. To avoid nosy bystanders being able to glance at a password, the characters that the user entered are not actually displayed. Instead, each typed character is represented by an echo character, typically an asterisk (*). The Swing set supplies a JPasswordField class that implements such a text field. The JButton Class They are typically used much like java.awt.Buttons. JButtons fire ActionEvents when they are clicked. The JCheckBox Class It is used to allow the user to turn a given feature on or off, or to make multiple selections from a set of choices. A JCheckBox is usually rendered by showing a small box into which a "check" is placed when selected. The user could check either, both, or none of the two check boxes. The JRadioButton Class JRadioButtons, allowing users to make a single selection from a set of options.
  • 88. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 44 The JList Class A list is a graphical component from which the user can select choices. Lists typically display several items at a time, allowing the user to make either a single selection or multiple selections.AWT limited the contents of its List component to strings. The Swing JList component lifts this restriction. List elements can now be strings, images. The JComboBox Class A combo box component is actually a combination of a Swing list and a text field. Unlike lists, a combo box only allows the user one selection at a time, which is usually copied into an editable component at the top, such as a text field. The user can be permitted, however, to manually enter in a selection as well. JComboBox is the Swing version of a combo box component. It is very similar to the AWT Choice component. The JPanel Class JPanel is an extension of JComponent (which, remember, extends java.awt.Container) used for grouping together other components. It gets most of its implementation from its superclasses. Typically, using JPanel amounts to instantiating it, setting a layout manager (this can be set in the constructor and defaults to a FlowLayout), and adding components to it using the add() methods inherited from Container.
  • 89. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 1 Unit IV – Generic Programming 4.1. Motivation for generic programming 4.2. generic classes 4.3. generic methods 4.4. generic code and virtual machine 4.5. inheritance and generics 4.6. reflection and generics 4.7. exceptions 4.8. exception hierarchy 4.9. throwing and catching exceptions 4.10. Stack Trace Elements 4.11. assertions 4.12. logging 4.1 Background • old version 1.4 Java collections were Object-based and required the use of ugly casts – cannot specify the exact type of elements – must cast to specific classes when accessing Java generics • Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters. • lets you write code that is safer and easier to read • is especially useful for general data structures, such as ArrayList • generic programming = programming with classes and methods parameterized with types • generic types are a powerful tool to write reusable object-oriented components and libraries • however, the generic language features are not easy to master and can be misused • their full understanding requires the knowledge of the type theory of programming languages • especially covariant and contravariant typing As per Java Language Specification:  A type variable is an unqualified identifier. Type variables are introduced by generic class declarations, generic interface declarations, generic method declarations, and by generic constructor declarations.    A class is generic if it declares one or more type variables. These type variables are known as the type parameters of the class. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types, one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime.    An interface is generic if it declares one or more type variables. These type variables are known as the type parameters of the interface. It defines one or more type variables that act as parameters. A generic interface declaration defines a set of types, one for each possible invocation of the type parameter section. All parameterized types share the same interface at runtime.    A method is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the method. The form of the formal type parameter list is identical to a type parameter list of a class or interface.    A constructor can be declared as generic, independently of whether the class the constructor is declared in is itself generic. A constructor is generic if it declares one or more type variables. These type variables are known as the formal type parameters of the constructor. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface.
  • 90. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 2 Motivation for Generics:  Overloaded methods are often used to perform similar operations on different types of data. To motivate generic methods, let’s begin with an example that contains three overloaded printArray methods. These methods print the string representations of the elements of an Integer array, a Double array and a Character array, respectively. Note that we could have used arrays of primitive types int, double and char in this example. We chose to use arrays of type Integer, Double and Character to set up our generic method example, because only reference types can be used with generic methods and classes public class OverloadedMethods { // method printArray to print Integer array public static void printArray( Integer[] inputArray ) { // display array elements for ( Integer element : inputArray ) System.out.printf( "%s ", element ); System.out.println(); } // end method printArray // method printArray to print Double array public static void printArray( Double[] inputArray ) { // display array elements for ( Double element : inputArray ) System.out.printf( "%s ", element ); System.out.println(); } // end method printArray // method printArray to print Character array public static void printArray( Character[] inputArray ) { // display array elements for ( Character element : inputArray ) System.out.printf( "%s ", element ); System.out.println(); } // end method printArray public static void main( String args[] ) { // create arrays of Integer, Double and Character Integer[] integerArray = { 1, 2, 3, 4, 5, 6 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; Character[] characterArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println( "Array integerArray contains:" ); printArray( integerArray ); // pass an Integer array System.out.println( "nArray doubleArray contains:" ); printArray( doubleArray ); // pass a Double array System.out.println( "nArray characterArray contains:" ); printArray( characterArray ); // pass a Character array } // end main } // end class OverloadedMethods OUTPUT: Array integerArray contains: 1 2 3 4 5 6
  • 91. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 3 Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array characterArray contains: H E L L O 4.2 Generic class definitions  Generic methods and generic classes (and interfaces) enable you to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively.  A generic class can have more than one type variable.  Generics also provide compile-time type safety that allows you to catch invalid types at compile time. Here is an example of a generic class: public class Pair<T, S> { public Pair(T f, S s) { first = f; second = s; } public T getFirst() { return first; } public S getSecond() { return second; } public String toString() { return "(" + first.toString() + ", " + second.toString() + ")"; } private T first; private S second; } This generic class can be used in the following way: Pair<String, String> grade440 = new Pair<String, String>("mike", "A"); Pair<String, Integer> marks440 = new Pair<String, Integer>("mike", 100); System.out.println("grade:" + grade440.toString()); System.out.println("marks:" + marks440.toString()); Explanation The Pair class introduces a type variable T, enclosed in angle brackets < >, after the class name. A generic class can have more than one type variable. For example, we could have defined the Pair class with separate types for the first and second field:
  • 92. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 4 public class Pair<T, U> { . . . } The type variables are used throughout the class definition to specify method return types and the types of fields and local variables. For example: private T first; // uses type variable Type erasure Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:  Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.  Insert type casts if necessary to preserve type safety.  Generate bridge methods to preserve polymorphism in extended generic types. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead. 4.3 Generic Methods  All generic method declarations have a type-parameter section delimited by angle brackets (< and >) that precedes the method’s return type (< E > in this example).  Each type-parameter section contains one or more type parameters (also called formal type parameters), separated by commas.  A type parameter, also known as a type variable, is an identifier that specifies a generic type name.  Can be used to declare the return type, parameter types and local variable types in a generic method, and act as placeholders for the types of the arguments passed to the generic method (actual type arguments).  A generic method’s body is declared like that of any other method.  Type parameters can represent only reference types—not primitive types. Example: public class GenericMethodTest { // generic method printArray public static < E > void printArray( E[] inputArray ) { // display array elements for ( E element : inputArray ) System.out.printf( "%s ", element ); System.out.println(); } // end method printArray public static void main( String args[] ) { // create arrays of Integer, Double and Character Integer[] integerArray = { 1, 2, 3, 4, 5 }; Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 }; Character[] charArray = { 'H', 'E', 'L', 'L', 'O' }; System.out.println( "Array integerArray contains:" ); printArray( integerArray ); // pass an Integer array System.out.println( "nArray doubleArray contains:" ); printArray( doubleArray ); // pass a Double array System.out.println( "nArray characterArray contains:" ); printArray( characterArray ); // pass a Character array } // end main } // end class GenericMethodTest
  • 93. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 5 Output: Array integerArray contains: 1 2 3 4 5 6 Array doubleArray contains: 1.1 2.2 3.3 4.4 5.5 6.6 7.7 Array characterArray contains: H E L L O 4.4 Generic Code and the Virtual Machine The virtual machine does not have objects of generic types—all objects belong to ordinary classes Whenever you define a generic type, a corresponding raw type is automatically provided. The name of the raw type is simply the name of the generic type, with the type parameters removed. The type variables are erased and replaced by their bounding types (or Object for variables without bounds.) For example, the raw type for Pair<T> looks like this: public class Pair { public Pair(Object first, Object second) { this.first = first; this.second = second; } public Object getFirst() { return first; } public Object getSecond() { return second; } public void setFirst(Object newValue) { first = newValue; } public void setSecond(Object newValue) { second = newValue; } private Object first; private Object second; } Because T is an unbounded type variable, it is simply replaced by Object. The result is an ordinary class, just as you might have implemented it before generics were added to the Java programming language. Your programs may contain different kinds of Pair, such as Pair<String> or Pair<Gregorian- Calendar>, but erasure turns them all into raw Pair types Translating Generic Expressions When you program a call to a generic method, the compiler inserts casts when the return type has been erased. For example, consider the sequence of statements Pair<Employee> buddies = . . .; Employee buddy = buddies.getFirst(); The erasure of getFirst has return type Object. The compiler automatically inserts the cast to Employee. That is, the compiler translates the method call into two virtual machine instructions: Translating Generic Methods Type erasure also happens for generic methods. Programmers usually think of a generic method such as public static <T extends Comparable> T min(T[] a)
  • 94. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 6 as a whole family of methods, but after erasure, only a single method is left: public static Comparable min(Comparable[] a) Note that the type parameter T has been erased, leaving only its bounding type Comparable. In summary, you need to remember these facts about translation of Java generics: 1. There are no generics in the virtual machines, only ordinary classes and methods. 2. All type parameters are replaced by their bounds. 3. Bridge methods are synthesized to preserve polymorphism. 4. Casts are inserted as necessary to preserve type safety. 4.5 Generics and Inheritance As you already know, it is possible to assign an object of one type to an object of another type provided that the types are compatible. For example, you can assign an Integer to an Object, since Object is one of Integer's supertypes: Object someObject = new Object(); Integer someInteger = new Integer(10); someObject = someInteger; // OK In object-oriented terminology, this is called an "is a" relationship. Since an Integer is a kind of Object, the assignment is allowed. But Integer is also a kind of Number, so the following code is valid as well: public void someMethod(Number n) { /* ... */ } someMethod(new Integer(10)); // OK someMethod(new Double(10.1)); // OK The same is also true with generics. You can perform a generic type invocation, passing Number as its type argument, and any subsequent invocation of add will be allowed if the argument is compatible with Number: Box<Number> box = new Box<Number>(); box.add(new Integer(10)); // OK box.add(new Double(10.1)); // OK Now consider the following method: public void boxTest(Box<Number> n) { /* ... */ } What type of argument does it accept? By looking at its signature, you can see that it accepts a single argument whose type is Box<Number>. But what does that mean? Are you allowed to pass in Box<Integer> or Box<Double>, as you might expect? The answer is "no", because Box<Integer> and Box<Double> are not subtypes of Box<Number>. This is a common misunderstanding when it comes to programming with generics, but it is an important concept to learn.
  • 95. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 7 Box<Integer> is not a subtype of Box<Number> even though Integer is a subtype of Number. Note: Given two concrete types A and B (for example, Number and Integer), MyClass<A> has no relationship to MyClass<B>, regardless of whether or not A and B are related. The common parent of MyClass<A> and MyClass<B> is Object. Wildcards and Subtyping Generic classes or interfaces are not related merely because there is a relationship between their types. However, you can use wildcards to create a relationship between generic classes or interfaces. Given the following two regular (non-generic) classes: class A { /* ... */ } class B extends A { /* ... */ } It would be reasonable to write the following code: B b = new B(); A a = b; This example shows that inheritance of regular classes follows this rule of subtyping: class B is a subtype of class A if B extends A. This rule does not apply to generic types: List<B> lb = new ArrayList<>(); List<A> la = lb; // compile-time error Given that Integer is a subtype of Number, what is the relationship between List<Integer> and List<Number>? The common parent is List<?>. Although Integer is a subtype of Number, List<Integer> is not a subtype of List<Number> and, in fact, these two types are not related. The common parent of List<Number> and List<Integer> is List<?>. In order to create a relationship between these classes so that the code can access Number's methods through List<Integer>'s elements, use an upper bounded wildcard: List<? extends Integer> intList = new ArrayList<>();
  • 96. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 8 List<? extends Number> numList = intList; // OK. List<? extends Integer> is a subtype of List<? extends Number> Because Integer is a subtype of Number, and numList is a list of Number objects, a relationship now exists between intList (a list of Integer objects) and numList. The following diagram shows the relationships between several List classes declared with both upper and lower bounded wildcards. A hierarchy of several generic List class declarations. 4.6 Reflection and Generics 1. The Generics Reflection Rule of Thumb 2. Generic Method Return Type 3. Generic Method Parameter Types 4. Generic Field Types The Generics Reflection Rule of Thumb Using Java Generics typically falls into one of two different situations: 1. Declaring a class/interface as being parameterizable. 2. Using a parameterizable class. When you write a class or interface you can specify that it should be paramerizable. This is the case with the java.util.List interface. Rather than create a list of Object you can parameterize java.util.List to create a list of say String. When runtime inspecting a parameterizable type itself, like java.util.List, there is no way of knowing what type is has been parameterized to. This makes sense since the type can be parameterized to all kinds of types in the same application. But, when you inspect the method or field that declares the use of a parameterized type, you can see at runtime what type the paramerizable type was parameterized to. In short: You cannot see on a type itself what type it is parameterized to a runtime, but you can see it in fields and methods where it is used and parameterized. Its concrete parameterizations in other words. The following sections take a closer look at these situations. Generic Method Return Types If you have obtained a java.lang.reflect.Method object it is possible to obtain information about its generic return type. This cannot be any of the Method objects in the parameterized type, but in the class that uses the parameterized type. You can read how to obtain Method objects in the text "Java Generics: Methods". Here is an example class with a method having a parameterized return type: import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.List; public class MethodReturnType {
  • 97. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 9 List mRaw() { return null; } List<String> mTypeString() { return null; } List<?> mWildcard() { return null; } List<? extends Number> mBoundedWildcard() { return null; } <T extends List<String>> List<T> mTypeLiteral() { return null; } public static void main(String[] args) { for (Method method : MethodReturnType.class.getDeclaredMethods()) { Type type = method.getGenericReturnType(); System.out.println(method.getName() + " - " + Generics.typeToString(type)); } } } Output: mRaw - java.util.List mTypeString - java.util.List<java.lang.String> mWildcard - java.util.List<? extends java.lang.Object> mBoundedWildcard - java.util.List<? extends java.lang.Number> mTypeLiteral - java.util.List<T extends java.util.List<java.lang.String>> Generic Method Parameter Types You can also access the generic types of parameter types at runtime via Java Reflection. Here is an example class with a method taking a parameterized List as parameter: import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.List; public class MethodParameterType { <T extends List<T>> void m(String p1, T p2, List<?> p3, List<T> p4) { } public static void main(String[] args) { for (Method method : MethodParameterType.class.getDeclaredMethods()) { for (Type type : method.getGenericParameterTypes()) { System.out.println(method.getName() + " - " + Generics.typeToString(type)); } } } } Output: m - java.lang.String m - T extends java.util.List<T> m - java.util.List<? extends java.lang.Object> m - java.util.List<T extends java.util.List<T>> Generic Field Types It is also possible to access the generic types of public fields. Fields are class member variables - either static or instance variables. You can read about obtaining Field objects in the text "Java Generics: Fields". Here is the example from earlier, with an instance field called stringList.
  • 98. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 10 import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; public class FieldType<K extends Number, V extends List<String> & Collection<String>> { List fRaw; List<Object> fTypeObject; List<String> fTypeString; List<?> fWildcard; List<? super List<String>> fBoundedWildcard; Map<String, List<Set<Long>>> fTypeNested; Map<K, V> fTypeLiteral; K[] fGenericArray; public static void main(String[] args) { for (Field field : FieldType.class.getDeclaredFields()) { Type type = field.getGenericType(); System.out.println(field.getName() + " - " + Generics.typeToString(type)); } } } Output: fRaw - java.util.List fTypeObject - java.util.List<java.lang.Object> fTypeString - java.util.List<java.lang.String> fWildcard - java.util.List<? extends java.lang.Object> fBoundedWildcard - java.util.List<? super java.util.List<java.lang.String>> fTypeNested - java.util.Map<java.lang.String>, <java.util.List<java.util.Set<java.lang.Long>>> fTypeLiteral - java.util.Map<K extends java.lang.Number>, <V extends java.util.List<java.lang.String> & java.util.Collection<java.lang.String>> fGenericArray - K[] 4.7 Java exception handling: Exception is a run-time error which arises during the execution of java program. The term exception in java stands for an “exceptional event”. So Exceptions are nothing but some abnormal and typically an event or conditions that arise during the execution which may interrupt the normal flow of program. An exception can occur for many different reasons, including the following: · A user has entered invalid data. · A file that needs to be opened cannot be found. · A network connection has been lost in the middle of communications, or the JVM has run out of memory.
  • 99. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 11 ―If the exception object is not handled properly, the interpreter will display the error and will terminate the program. Now if we want to continue the program with the remaining code, then we should write the part of the program which generate the error in the try{} block and catch the errors using catch() block.. Exception turns the direction of normal flow of the program control and send to the related catch() block and should display error message for taking proper action. This process is known as Exception handling.‖ The purpose of exception handling is to detect and report an exception so that proper action can be taken and prevent the program which is automatically terminate or stop the execution because of that exception. Java exception handling is managed by using five keywords: try, catch, throw, throws and finally. Try: Piece of code of your program that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Catch: Catch block can catch this exception and handle it in some logical manner. Throw: System-generated exceptions are automatically thrown by the Java run-time system. Now if we want to manually throw an exception, we have to use the throw keyword. Throws: If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. Basically it is used for IOException. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. Finally: Any code that absolutely must be executed before a method returns, is put in a finally block. General form: try { // block of code to monitor for errors } catch (ExceptionType1 e1) { // exception handler for ExceptionType1 } catch (ExceptionType2 e2) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends } 4.8 Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class.
  • 100. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 12 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 : These are not normally trapped form the Java programs. Errors are typically ignored in your code because you can rarely do anything about an error. 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. For Example : (1) JVM is out of Memory. Normally programs cannot recover from errors. (2) If a stack overflow occurs then an error will arise. They are also ignored at the time of compilation. The Exception class has two main subclasses: (1) IOException or Checked Exceptions class and (2) RuntimeException or Unchecked Exception class (1) IOException or Checked Exceptions : Exceptions that must be included in a method’s throws list if that method can generate one of these exceptions and does not handle it itself. These are called checked exceptions. 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. Java’s Checked Exceptions Defined in java.lang (2) RuntimeException or Unchecked Exception : Exceptions need not be included in any method’s throws list. These are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Java’s Unchecked RuntimeException Subclasses BUILT-IN ECEPTIONS 1. ArithmeticException (Divide by zero) 2. ArrayIndexOutOfBoundsException(array index) 3. ArrayStoreException (incompatible type element) 4. ClassCastException(Invalid cast) 5. IllegalArgumentException (Illegal argument to a method) 6. IllegalMonitorStateException (waiting on an unlocked thread) 7. IllegalStateException (incorrect state) 8. IllegalThreadStateException (operation not compatible with current state) 9. IndexOutOfBoundsException (index exceding) 10. Negative ArrayStoreException (negative index) 11. NullPointerException (null pointer) 12. NumberFormatException (Invalid conversion of String to number) 13. SecurityException (Attempts to violate the security)
  • 101. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 13 14. StringIndexOutOfBounds (index exceeds) 15. UnsupportedOperationException (unsupported operation encountered) 16. ClassNotFoundException (Class not Found) 17. CloneNotSupportedException (attempts to clone object where Clonable not implemented) 18. IllegalAccessException (Access to a class is denied) 19. InstantiationException (creating object from abstract class) 20. InterruptedException (when thread has been interrupted) 21. NoSuchFieldException (when Field does not exist) 22. NoSuchMethodException (when Method does not exist) Try and catch with example in java: Now here is the some examples of try and catch block. EX : public class TC_Demo { public static void main(String[] args) { int a=10; int b=5,c=5; int x,y; try { x = a / (b-c); } catch(ArithmeticException e) { System.out.println("Divide by zero"); } y = a / (b+c); System.out.println("y = " + y); } } Output : Divide by zero y = 1 Note that program did not stop at the point of exceptional condition. It catches the error condition, prints the error message, and continues the execution, as if nothing has happened. If we run same program without try catch block we will not gate the y value in output. It displays the following message and stops without executing further statements. Exception in thread "main" java.lang.ArithmeticException: / by zero at Thrw_Excp.TC_Demo.main(TC_Demo.java:10) Here we write ArithmaticException in catch block because it caused by math errors such as divide by zero. Now how to display description of an exception ? You can display the description of thrown object by using it in a println() statement by simply passing the exception as an argument. For example;
  • 102. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 14 catch (ArithmeticException e) { system.out.pritnln(―Exception:‖ +e); } Multiple catch blocks : It is possible to have multiple catch blocks in our program. EX : public class MultiCatch { public static void main(String[] args) { int a [] = {5,10}; int b=5; try { int x = a[2] / b - a[1]; } catch(ArithmeticException e) { System.out.println("Divide by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index error"); } catch(ArrayStoreException e) { System.out.println("Wrong data type"); } int y = a[1]/a[0]; System.out.println("y = " + y); } } Output : Array index error y = 2 Note that array element a[2] does not exist. Therefore the index 2 is outside the array boundry. When exception in try block is generated, the java treats the multiple catch statements like cases in switch statement. The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped. When you are using multiple catch blocks, it is important to remember that exception subclasses must come before any of their superclasses. This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass will never be reached if it comes after its superclass. And it will result into syntax error.
  • 103. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 15 // Catching super exception before sub EX : class etion3 { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); } catch (Exception e) { System.out.println("This is mistake. "); } catch(ArithmeticException g) { System.out.println("Division by zero"); } } } Output : If you try to compile this program, you will receive an error message because the exception has already been caught in first catch block. Since ArithmeticException is a subclass of Exception, the first catch block will handle all exception based errors, including ArithmeticException. This means that the second catch statement will never execute. To fix the problem, revere the order of the catch statement. Nested try statements : The try statement can be nested. That is, a try statement can be inside a block of another try. Each time a try statement is entered, its corresponding catch block has to entered. The catch statements are operated from corresponding statement blocks defined by try. EX : public class NestedTry { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try
  • 104. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 16 { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); } catch(ArithmeticException e) { System.out.println("This is inner catch"); } } catch(ArithmeticException g) { System.out.println("This is outer catch"); } } } Output : This is outer catch Finally Java supports another statement known as finally statement that can be used to handle an exception that is not caught by any of the previous catch statements. We can put finally block after the try block or after the last catch block. The finally block is executed in all circumstances. Even if a try block completes without problems, the finally block executes. EX : public class Finally_Demo { public static void main(String args[]) { int num1 = 100; int num2 = 50; int num3 = 50; int result1; try { result1 = num1/(num2-num3); System.out.println("Result1 = " + result1); } catch(ArithmeticException g) { System.out.println("Division by zero"); } finally { System.out.println("This is final"); } } }
  • 105. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 17 Output : Division by zero This is final 4.9 Throws We saw that an exception was generated by the JVM when certain run-time problems occurred. It is also possible for our program to explicitly generate an exception. This can be done with a throw statement. Its form is as follows: Throw object; Inside a catch block, you can throw the same exception object that was provided as an argument. This can be done with the following syntax: catch(ExceptionType object) { throw object; } Alternatively, you may create and throw a new exception object as follows: Throw new ExceptionType(args); Here, exceptionType is the type of the exception object and args is the optional argument list for its constructor. When a throw statement is encountered, a search for a matching catch block begins and if found it is executed. class Throw_Demo { public static void a() { try { System.out.println("Before b"); b(); } catch(ArrayIndexOutOfBoundsException j) //manually thrown object catched here { System.out.println("J : " + j) ; } } public static void b() { int a=5,b=0; try { System.out.println("We r in b"); System.out.println("********"); int x = a/b; } catch(ArithmeticException e) { System.out.println("c : " + e); throw new ArrayIndexOutOfBoundsException("demo"); //throw from here } } public static void main(String args[])
  • 106. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 18 { try { System.out.println("Before a"); a(); System.out.println("********"); System.out.println("After a"); } catch(ArithmeticException e) { System.out.println("Main Program : " + e); } } } Output : Before a Before b We r in b ******** c : java.lang.ArithmeticException: / by zero J : java.lang.ArrayIndexOutOfBoundsException: demo ******** After a Throwing our own object : If we want to throw our own exception, we can do this by using the keyword throw as follow. throw new Throwable_subclass; Example : throw new ArithmaticException( ); throw new NumberFormatException( ); EX : import java.lang.Exception; class MyException extends Exception { MyException(String message) { super(message); } } class TestMyException { public static void main(String[] args) { int x = 5, y = 1000; try { float z = (float)x / (float)y; if(z < 0.01)
  • 107. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 19 { throw new MyException("Number is too small"); } } catch(MyException e) { System.out.println("Caught MyException"); System.out.println(e.getMessage()); } finally { System.out.println("java2all.com"); } } } Output : Caught MyException Number is too small java2all.com Here The object e which contains the error message "Number is too small" is caught by the catch block which then displays the message using getMessage( ) method. NOTE: Exception is a subclass of Throwable and therefore MyException is a subclass of Throwable class. An object of a class that extends Throwable can be thrown and caught. Throws If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. Basically it is used for IOException. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException,or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw. Throw is used to actually throw the exception, whereas throws is declarative statement for the method. They are not interchangeable. EX : class NewException extends Exception { public String toS() { return "You are in NewException "; } }
  • 108. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 20 class customexception { public static void main(String args[]) { try { doWork(3); doWork(2); doWork(1); doWork(0); } catch (NewException e) { System.out.println("Exception : " + e.toS()); } } static void doWork(int value) throws NewException { if (value == 0) { throw new NewException(); } else { System.out.println("****No Problem.****"); } } } Output: ****No Problem.**** ****No Problem.**** ****No Problem.**** Exception : You are in NewException 4.10 StackTraceElement The java.lang.StackTraceElement class element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the execution point at which the stack trace was generated. Class declaration Following is the declaration for java.lang.StackTraceElement class: public final class StackTraceElement extends Object implements Serializable Class constructors StackTraceElement(String declaringClass, String methodName, String fileName, int lineNumber) This creates a stack trace element representing the specified execution point.
  • 109. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 21 Class methods StackTraceElement.getMethodName() Method The java.lang.StackTraceElement.getMethodName() method returns the name of the method containing the execution point represented by this stack trace element. Declaration Following is the declaration for java.lang.StackTraceElement.getMethodName() method public String getMethodName() import java.lang.*; public class StackTraceElementDemo { public static void main(String[] args) { function1(); } public static void function1() { new StackTraceElementDemo().function2(); } public void function2() { int i; System.out.println("method name : "); // print stack trace for( i = 1; i <= 3; i++ ) { System.out.println(Thread.currentThread().getStackTrace()[i]. getMethodName()); } }}
  • 110. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 22 Output: method name : function2 function1 main 4.11 Java Assertion  Assertions are simple check assumption made at the beginning of the program to ensure the program is true throughout provided by the Java language. o For example, the range of age should be in between 18 and above; or cannot be more than 50.  These are the set of expression used in java that enables you to check the assumption made in a program during throughout the execution of program.  An Assertion contains a Boolean expression which is set to be true in the beginning of the program. o For Example ,a program has a method that allow the value being passed to it should not be zero and negative, you test this assert by sending a only positive number that is greater than zero by using assert statement in java. Simple Assertion Form  The assertion statement has two forms  The first is: assert Expression1 ; - Where Expression1 is a boolean expression  When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no details  The second form of the assertion statement is: assert Expression1 : Expression2 ; - where:  Expression1 is a boolean expression  Expression2 is an expression that has a value  It cannot invoke of a method that is declared void  Use the second version of the assert statement to provide a detailed message for the AssertionError  The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string error message  The purpose of the message is to communicate the reason for the assertion failure When an Assertion Fails  Assertion failures are labeled in stack trace with the file and line number from which they were thrown  Second form of the assertion statement should be used in preference to the first when the program has some additional information that might help diagnose the failure How to Compile Assertion Files The Assertion file is compiled with an option ,-source 1.4.The Syntax used in compilation of program is Javac-source 1.4 AssertDemonstration.java Where Assert Demonstration is the name of java program using assertion. -source 1.4 is a command line option to make the compile to accept the code containing assertions. How to Enable and Disable Assertion Assertion are disabled at run-time during execution of java program . The command line prompt -ea or enable assertions is used to enable assertion during run-time execution of the program. java -ea:AssertDemonstration The command prompt -da or disable is used to disable assertion during run-time execution of the program java -da :AssertDemonstration Example: In this Example We, defined a public class 'Mark Assert Demo' Inside the class we define the static variable i.e. maximum marks to be 100, changes is another static variable, The main static ( ) method has assumption of maximum marks i.e. 40,if the marks come below to 40,the code will show you java.lang.AssertionError and display the Marks is below than 40 on the command prompt.
  • 111. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 23 public class MarkAssertDemo { static float maximummarks=100; static float changes(float mark) { maximummarks=maximummarks-mark; System.out.println("The maximummark is:" + maximummarks); return maximummarks; } public static void main(String args[]) { float g; for(int i=0;i<5;i++) { g=changes(15); assert maximummarks>=40.00:"marks is below 40."; } } } Output: C:>javac -source 1.4 MarkAssertDemo.java C:>java -ea MarkAssertDemo The maximummark is:85.0 The maximummark is:70.0 The maximummark is:55.0 The maximummark is:40.0 The maximummark is:25.0 Exception in thread "main" java.lang.AssertionError: marks is below 40. at MarkAssertDemo.main(MarkAssertDemo.java:16) 4.12 Logging  ―Logging‖ is producing messages that tell you what your program is doing  It’s not much different than using System.out.println(...)  Log messages can go to the console, to a file, or one of several other places (e.g. sent over the Internet)  You can use logging to help you debug a program  You can use logging to produce a file when the user runs your program Java Logger  Logger is the class of java.util.logging package that extends the Object class.  Java provides logging APIs like: Logger, Level, Handler etc. for implementing logging features in your java application.  It is a part of J2SE (Java 2 Standard Edition).  When you go to create java logging program then first of all need a Logger object.  The Logger object contains log messages. Logger has one or more handler that performs log records.  A logger object used for logging messages for individual system or an application component that can be derived by getLogger methods.  Java logging provides a way to contain multiple types of message like: warning, info, severe etc. for an application.  These information or messages can be used for many purposes but it is specially used for debugging, troubleshooting and auditing. Logging levels and methods  Level.SEVERE  Level.WARNING  Level.INFO  Level.CONFIG
  • 112. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 24  Level.FINE  Level.FINER  Level.FINEST  myLogger.severe(String msg);  myLogger.warning(String msg);  myLogger.info(String msg);  myLogger.config(String msg);  myLogger.fine(String msg);  myLogger.finer(String msg);  myLogger.finest(String msg);  These levels are ordered, so that you can set the level of severity that results in log messages  However, the levels have no inherent meaning--they are what you make of them Controlling logging levels  public void Logger.setLevel(Level newLevel)  Sets the logger to log all messages at newLevel or above  Logger calls at lower levels don’t do anything  Example: logger.setLevel(Level.WARNING);  Additional settings:  logger.setLevel(Level.ALL);  logger.setLevel(Level.OFF);  public Level getLevel()  Note that this returns a Level, not an int  Level has intValue() and toString() methods Additional Logger methods  void entering(String sourceClass, String sourceMethod)  void entering(String sourceClass, String sourceMethod, Object param1)  void entering(String sourceClass, String sourceMethod, Object[] params)  void exiting(String sourceClass, String sourceMethod)  void exiting(String sourceClass, String sourceMethod, Object result)  These log messages at level FINER Logging flow of control  You send your message to a Logger  The Logger checks a Filter to see whether to ignore the message  The Logger sends the message to a Handler to put the message somewhere  The Handler checks another Filter to see whether to ignore this kind of message sent to this destination  The Handler calls a Formatter to decide what kind of a text string to produce  The Handler sends the formatted message somewhere Filters  Filter is an interface; it defines the single method boolean isLoggable(LogRecord record)  A LogRecord is another class in java.util.logging; it provides numerous methods for examining the proposed logging message Logging formatting and destinations  The JDK defines five Handlers:  StreamHandler: sends messages to an OutputStream
  • 113. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 25  ConsoleHandler: sends messages to System.err (default)  FileHandler: sends messages to a file  SocketHandler: sends messages to a TCP port  MemoryHandler: buffers messages in memory  It also defines two ways to format messages:  SimpleFormatter (default)  XMLFormatter  And, of course, you can define your own Handlers and Formatters  As you can tell from the ―Basic Use‖ slide earlier, you can ignore all of this and just use the defaults Program Descriptions: This program simply create a log file and shows log message for the warning, info and servere and another checked the logging message. This program creates a log file that contains multiple information. import java.io.*; import java.util.logging.*; public class QuintLog{ public static void main(String[] args) { try{ FileHandler hand = new FileHandler("vk.log"); Logger log = Logger.getLogger("log_file"); log.addHandler(hand); log.warning("Doing carefully!"); log.info("Doing something ..."); log.severe("Doing strictily "); System.out.println(log.getName()); } catch(IOException e){} } } Output: Aug 27, 2013 9:17:46 AM QuintLog main WARNING: Doing carefully! Aug 27, 2013 9:17:46 AM QuintLog main INFO: Doing something ... Aug 27, 2013 9:17:46 AM QuintLog main SEVERE: Doing strictily log_file Program Descriptions: This program check logger object. If given instruction is certify then shows finest message like: 'Display a finest message' otherwise no any message appear to here. import java.io.*; import java.util.logging.*; public class CheckLogMessage{ public static void main(String[] args) { Logger log = Logger.getLogger("log_file"); if(log.isLoggable(Level.OFF)){ log.finest("Display a finest message"); } } }
  • 114. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 1 UNIT V CONCURRENT PROGRAMMING 5.1 Multi-threaded programming 5.2 interrupting threads 5.3 thread states 5.4 thread properties 5.5 thread synchronization 5.6 thread-safe Collections 5.7 Executors 5.8 synchronizers 5.9 threads and event-driven programming Introduction • Performing operations concurrently (in parallel) – We can walk, talk, breathe, see, hear, smell... all at the same time – Computers can do this as well - download a file, print a file, receive email, run the clock, more or less in parallel…. • How are these tasks typically accomplished? • Operating systems support processes • What’s the difference between a process and a thread? • Processes have their own memory space, threads share memory • Hence processes are “heavyweight” while threads are “lightweight” – Most programming languages do not allow concurrency – Usually limited to operating system "primitives" available to systems programmers – Java supports concurrency as part of language and libraries – What other languages support concurrency in the language? – Each thread is a portion of a program that can execute concurrently with other threads (multithreading) • C and C++ are single-threaded • Gives Java powerful capabilities not found in C and C++ – Example: downloading a video clip • Instead of having to download the entire clip then play it: • Download a portion, play that portion, download the next portion, play that portion... (streaming) • Ensure that it is done smoothly 5.1 Multithreading Programming Multithreading is a conceptual programming paradigm where a program (process) is divided in to two or more sub programs (processes) which can be implemented at the same time in interval. A thread is similar to a program that has a single flow of control. It has a beginning a body, and an end, and executes commands sequentially. A unique property of java is its support for multithreading. (i.e) Java enables us to use multiple of control may be thought of as a separate tiny program (or module) known as a thread that runs in parallel to others. A program that contains multiple flows of control is known as Multithreaded Program. Thread Priorities: • All Java applets / applications are multithreaded – Threads have priority from 1 to 10 • Thread.MIN_PRIORITY - 1 • Thread.NORM_PRIORITY - 5 (default) • Thread.MAX_PRIORITY - 10 • New threads inherit priority of thread that created it • Priority methods – setPriority( int priorityNumber ) – getPriority – yield - thread yields processor to threads of equal priority • Useful for non-timesliced systems, where threads run to completion
  • 115. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 2 Creating Threads in Java Java defines two ways in which this can be accomplished: 1. implementing the Runnable interface (java.lang.Runnable) – The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method, called run, with no arguments. – invoke Thread constructor with an instance of this Runnable class 2. extending Thread – Define a subclass of java.lang.Thread • Define a run method – In another thread (e.g., the main), create an instance of the Thread subclass • Then, call start method of that instance  Threads are implemented in the form of objects that contain a method called run(). The run() method is the heart and soul of any thread. It makes up the entire body of a thread and is the only method in which the thread’s behavior can be implemented.  The run() method should be invoked by an object of the concerned thread. This can be achieved by creating the thread and initiating it with the help of another thread method called start(). implementing the Runnable interface (java.lang.Runnable) – Create new threads using Thread constructors • Thread( runnableObject ) • Thread( runnableObject, threadName ) class mythread implements Runnable{ public void run(){ System.out.println(“Thread Started”); } } class mainclass { public static void main(String args[]){ Thread t = new Thread(new mythread()); // This is the way to instantiate a thread implementing runnable interface t.start(); // starts the thread by running the run method } } • Calling t.run() does not start a thread, it is just a simple method call. • Creating an object does not create a thread, calling start() method creates the thread. extending Thread class Multi extends Thread{ public void run(){ System.out.println("thread is running..."); } public static void main(String args[]){ Multi t1=new Multi(); t1.start(); } } Output:
  • 116. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 3 thread is running….. Multithreading example //<b><i>Program of performing two tasks by two threads</i></b> class Simple1 extends Thread{ public void run(){ System.out.println("task one"); } } class Simple2 extends Thread{ public void run(){ System.out.println("task two"); } } class Test{ public static void main(String args[]){ Simple1 t1=new Simple1(); Simple2 t2=new Simple2(); t1.start(); t2.start(); } } Output task one task two Thread Methods: 5.2 Interrupting Threads  Interrupting a thread means stopping what it is doing before it has completed its task, effectively aborting its current operation.  The interrupt method can be used to request termination of a thread. When the interrupt method is called on a thread, the interrupted status of the thread is set.  This is a boolean flag that is present in every thread. Each thread should occasionally check whether it has been interrupted.  To find out whether the interrupted status was set, first call the static Thread.currentThread method to get the current thread and then call the isInterrupted method.
  • 117. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 4 while (!Thread.currentThread().isInterrupted() && more work to do) { do more work } However, if a thread is blocked, it cannot check the interrupted status. This is where the InterruptedException comes in. When the interrupt method is called on a thread that blocks on a call such as sleep or wait, the blocking call is terminated by an InterruptedException. Eg:threadinterrupttest.java class athread extends Thread { public void run() { while(true) { System.out.println("Thread Running..."); try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.println("Thread Interrupted..."); } } } } class threadinterrupttest { public static void main(String arg[])throws Exception { athread p = new athread(); System.out.println("Thread starting"); p.start(); Thread.sleep(2000); p.interrupt(); System.out.println("Stopping Application"); System.exit(0); } } 5.3 Thread States • Born state – Thread just created – When start called, enters ready state • Ready state (runnable state) – Highest-priority ready thread enters running state • Running state – System assigns processor to thread (thread begins executing) – When run completes or terminates, enters dead state • Dead state – Thread marked to be removed by system – Entered when run terminates or throws uncaught exception • Blocked state – Entered from running state – Blocked thread cannot use processor, even if available – Common reason for blocked state - waiting on I/O request
  • 118. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 5 • Sleeping state – Entered when sleep method called – Cannot use processor – Enters ready state after sleep time expires • Waiting state – Entered when wait called in an object thread is accessing – One waiting thread becomes ready when object calls notify – notifyAll - all waiting threads become ready invoking methods like new(), start(), yield(), sleep(), wait(), notify()… 5.4 Thread Property • static void sleep( long milliseconds ) – Thread sleeps (does not contend for processor) for number of milliseconds – Why might we want a program to invoke sleep? – Can give lower priority threads a chance to run • void interrupt() - interrupts a thread • boolean isInterrupted() – Determines if a thread is interrupted • boolean isAlive() – Returns true if start called and thread not dead (run has not completed) • getPriority() - returns this thread's priority • setPriority() – sets this threads priority • Etc. class SimpleThread extends Thread { public SimpleThread(String str) { super(str); } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " + getName()); try { sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) {} } System.out.println("DONE! " + getName()); } } class TwoThreadsTest { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); } } You should see output similar to the following: 0 Jamaica 0 Fiji
  • 119. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 6 1 Fiji 1 Jamaica 2 Jamaica 2 Fiji 3 Fiji 3 Jamaica 4 Jamaica 4 Fiji 5 Jamaica 5 Fiji 6 Fiji 6 Jamaica 7 Jamaica 7 Fiji 8 Fiji 9 Fiji 8 Jamaica DONE! Fiji 9 Jamaica DONE! Jamaica (Looks like I'm going to Fiji!!) Notice how the output from each thread is intermingled with the output from the other. This is because both SimpleThread threads are running concurrently. Thus, both run methods are running at the same time and each thread is displaying its output at the same time as the other. 5.5 Thread Synchronization • Synchronization is prevent data corruption • Synchronization allows only one thread to perform an operation on a object at a time. • If multiple threads require an access to an object, synchronization helps in maintaining consistency. Types of Thread synchronization 1. Mutual Exclusive a. Synchronized method b. Static synchronization c. Synchronized block 2. Inter-thread Communication Problems in syncronization public class Counter{ private int count = 0; public int getCount(){ return count; } public setCount(int count){ this.count = count; } } • In this example, the counter tells how many an access has been made. • If a thread is accessing setCount and updating count and another thread is accessing getCount at the same time, there will be inconsistency in the value of count. Solution by synchronized method public class Counter{ private static int count = 0; public synchronized int getCount(){ return count; } public synchoronized setCount(int count){ this.count = count; } }
  • 120. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 7 • By adding the synchronized keyword we make sure that when one thread is in the setCount method the other threads are all in waiting state. • The synchronized keyword places a lock on the object, and hence locks all the other methods which have the keyword synchronized. The lock does not lock the methods without the keyword synchronized and hence they are open to access by other threads. Solution by static synchronized public class Counter{ private int count = 0; public static synchronized int getCount(){ return count; } public static synchronized setCount(int count){ this.count = count; } } • In this example the methods are static and hence are associated with the class object and not the instance. • Hence the lock is placed on the class object that is, Counter.class object and not on the object itself. Any other non static synchronized methods are still available for access by other threads. Common Synchronization mistake public class Counter{ private int count = 0; public static synchronized int getCount(){ return count; } public synchronized setCount(int count){ this.count = count; } } • The common mistake here is one method is static synchronized and another method is non static synchronized. • This makes a difference as locks are placed on two different objects. The class object and the instance and hence two different threads can access the methods simultaneously. Solution by synchronized method • The object can be explicitly locked in this way synchronized(myInstance){ try{ wait(); }catch(InterruptedException ex){ } System.out.println(“Iam in this “); notifyAll(); } • The synchronized keyword locks the object. The wait keyword waits for the lock to be acquired, if the object was already locked by another thread. Notifyall() notifies other threads that the lock is about to be released by the current thread. • Another method notify() is available for use, which wakes up only the next thread which is in queue for the object, notifyall() wakes up all the threads and transfers the lock to another thread having the highest priority. 5.6 Thread safe Collection  The methods of legacy classes (the data structure that comes with JDK 1.0) like Vector and Hashtable are implicitly synchronized. They are best suitable for thread-safe operations.  An operation is said to be thread-safe when multiple threads access the data, the data should not get corrupted or result in inconsistency. It is the precaution to be taken in a multithreaded environment.  But collection classes are not implicitly thread-safe as their methods are not synchronized. It's synchronizedCollection() method returns an object of Collection with synchronized methods. That is
  • 121. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 8 with collection classes, you got a choice to have synchronized or non-synchronized version. But incase of legacy classes it is not possible; you must have synchronized vector or hash table only.  Following is the method signature o static Collection synchronizedCollection(Collection col1): Returns a synchronized version of Collection col1. It is used for thread-safe operations. o The synchronized version can be used safely in a multithreaded environment.  Methods like  synchronizedSet(),  synchronizedSortedSet(),  synchronizedList(),  synchronizedMap() and  synchronizedSortedMap() also exist to use with set, list and map. import java.util.*; public class CollectionsSynchronized { public static void main(String args[]) { ArrayList firstList = new ArrayList(); firstList.add(10); firstList.add(20); firstList.add(30); firstList.add(40); List secondList = Collections.synchronizedList(firstList); System.out.println("secondList elements: " + secondList); HashSet firstSet = new HashSet(); firstSet.add("hello"); firstSet.add("world"); Set secondSet = Collections.synchronizedSet(firstSet); System.out.println("nsecondSet elements: " + secondSet); } } ArrayList firstList = new ArrayList(); firstList.add(10); An ArrayList object firstList is created and added with few elements with add() method inherited from List interface. This object works nice in general conditions but not in multithreaded programming. List secondList = Collections.synchronizedList(firstList); The synchronizedList(firstList) method of Collections class returns an object of List, secondList. Now secondList methods are synchronized and suitable with multiple threads access. But still the original firstList methods not synchronized. Now programmer has the choice between the two, firstList and secondList, to use in his code. HashSet firstSet = new HashSet(); firstSet.add(“hello”); firstSet.add(“world”); Set secondSet = Collections.synchronizedSet(firstSet); Similarly, from the HashSet object firstSet, it is possible to obtain a synchronized version with synchronizedSet(firstSet) method. The returned Set object, secondSet, is synchronized. 5.7 Executors
  • 122. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 9  Constructing a new thread is somewhat expensive because it involves interaction with the operating system.  If your program creates a large number of short-lived threads, then it should instead use a thread pool.  A thread pool contains a number of idle threads that are ready to run. You give a Runnable to the pool, and one of the threads calls the run method. When the run method exits, the thread doesn’t die but stays around to serve the next request.  Creating a huge number of threads can greatly degrade performance and even crash the virtual machine. If you have an algorithm that creates lots of threads, then you should use a “fixed” thread pool that bounds the total number of concurrent threads.  How the Connection pool is executed? 1. Call the static newCachedThreadPool or newFixedThreadPool method of the Executors class. 2. Call submit to submit Runnable or Callable objects. 3. If you want to be able to cancel a task or if you submit Callable objects, hang on to the returned Future objects. 4. Call shutdown when you no longer want to submit any tasks.  The Executors class helps you manage the creation of threads in a pool, their scheduling (if applicable), as well as their termination. In general, it helps you avoid having to create and manage threads yourself.  The Executors class has a number of static factory methods for constructing thread pools;  For example, rather than creating a new thread and starting it, the following can be done. ExecutorService executor = some Executor factory method; executor.execute(aRunnable);  If you have several Runnable tasks to carry out, then a simple thread pool arrangement is provided as follows: ExecutorService executor = Executors.newFixedThreadPool(5); executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2()); …………….  here the tasks run and complete under the control of the Executor, which reuses threads from the thread pool as needed without incurring the overhead of always creating new threads.  The threads can be stopped with executor.shutdown(); 5.8 Java Synchronizers  Java 5 introduces general purpose synchronization classes, including semaphores, mutexes, barriers, latches, and exchangers, which facilitate coordination between threads.  These classes are a part of the java.util.concurrent package.  A brief description of each of these follows: Semaphores  A counting semaphore maintains a set of permits.  Each acquire() blocks if necessary until a permit is available, and then takes it.
  • 123. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 10  Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.  Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource. Barrier  A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.  CyclicBarriers are useful in programs involving a fixed sized group of threads that must occasionally wait for each other.  The barrier is called cyclic because it can be re-used after the waiting threads are released. Exchangers  A synchronization point at which two threads can exchange objects.  Each thread presents some object on entry to the exchange method, and receives the object presented by the other thread on return. Latches  A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.  A CountDownLatch is initialized with a given count. T  he await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. 5.9 Threads and Event Driven Programming  Once a Swing component has been realized, all code that might affect or depend on the state of that component should be executed in the event-dispatching thread.  This rule might sound scary, but for many simple programs, you don't have to worry about threads. Before we go into detail about how to write Swing code, let's define two terms: realized and event- dispatching thread.  Realized means that the component's paint() method has been or might be called.  A Swing component that's a top-level window is realized by having one of these methods invoked on it: setVisible(true), show(), or (this might surprise you) pack().  Once a window is realized, all components that it contains are realized. Another way to realize a component is to add it to a container that's already realized.  The event-dispatching thread is the thread that executes drawing and event-handling code.  For example, the paint() and actionPerformed() methods are automatically executed in the event- dispatching thread. Another way to execute code in the event-dispatching thread is to use the SwingUtilities invokeLater() method. import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public class ViewPage { public static void main(String[] args) {
  • 124. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 11 Runnable r; r = new Runnable() { @Override public void run() { final JFrame frame = new JFrame("View Page"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); panel.add(new JLabel("Enter URL")); final JTextField txtURL = new JTextField(40); panel.add(txtURL); frame.getContentPane().add(panel, BorderLayout.NORTH); final JTextArea txtHTML = new JTextArea(10, 40); frame.getContentPane().add(new JScrollPane(txtHTML), BorderLayout.CENTER); ActionListener al; al = new ActionListener() { public void actionPerformed(ActionEvent ae) { txtURL.setEnabled(false); Runnable worker = new Runnable() { public void run() { InputStream is = null; try { URL url = new URL(txtURL.getText()); is = url.openStream(); final StringBuilder sb; sb = new StringBuilder(); int b; while ((b = is.read()) != -1) { sb.append((char) b); } Runnable r = new Runnable() { public void run() { try { Thread.sleep(6000); } catch (InterruptedException ex) { Logger.getLogger(ViewPage.class.getName()).log(Level.SEVERE, null, ex); } txtHTML.setText(sb.toString()); txtURL.setEnabled(true); } }; try { EventQueue.invokeAndWait(r); } catch (InterruptedException ie) { }
  • 125. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 12 catch (InvocationTargetException ite) { } } catch (final IOException ioe) { Runnable r = new Runnable() { public void run() { txtHTML.setText(ioe.getMessage()); txtURL.setEnabled(true); } }; try { EventQueue.invokeAndWait(r); } catch (InterruptedException ie) { } catch (InvocationTargetException ite) { } } finally { Runnable r = new Runnable() { public void run() { txtHTML.setCaretPosition(0); txtURL.setEnabled(true); } }; try { EventQueue.invokeAndWait(r); } catch (InterruptedException ie) { } catch (InvocationTargetException ite) { } if (is != null) { try { is.close(); } catch (IOException ioe) { } } } } }; new Thread(worker).start(); } };
  • 126. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE 13 txtURL.addActionListener(al); frame.pack(); frame.setVisible(true); } }; EventQueue.invokeLater(r); } }