EINSTEIN COLLEGE OF ENGINEERING

Sir.C.V.Raman Nagar, Tirunelveli-12

CS55 PROGRAMMING PARADIGMS E - NOTES

Unit No I II III IV V

Title
Object-oriented Programming – Fundamentals Object-oriented Programming – Inheritance Event-Driven Programming Generic Programming Concurrent Programming

CS55 PROGRAMMING PARADIGMS UNIT I OBJECT-ORIENTED PROGRAMMING – FUNDAMENTALS 1) Review of OOP Concepts a) Encapsulation b) Inheritance c) Polymorphism 2) Objects and Classes in Java 3) Language Basics a) Comments b) Data Types c) Variables d) Statements e) Functions 4) Defining Classes 5) Methods 6) Access Specifiers 7) Static Members 8) Constructors a) Parameterized Constructors b) this Keyword c) Garbage Collection 9) Finalize Method 10) Arrays a) One Dimensional Arrays b) Multi Dimensional Arrays 11) Strings 12) Packages 13) JavaDOC Comments 14) References 1. Review OOP concepts The object oriented paradigm is built on the foundation laid by the structured programming concepts.  The fundamental change in OOP is that a program is designed around the data being operated upon rather upon the operations themselves.  Data and its functions are encapsulated into a single entity.  OOP facilitates creating reusable code that can eventually save a lot of work.  Polymorphism permits to create multiple definitions for functions.  Inheritance permits to derive new classes from old ones. Benefits of object oriented programming  Data security is enforced.  Inheritance saves time.  User defined data types can be easily constructed. Page 2 of 158 © Einstein College of Engineering

CS55 PROGRAMMING PARADIGMS   Inheritance emphasizes inventions of new data types. Large complexity in the software development can be easily managed.

Java History Java is a general-purpose object oriented programming language developed by Sun Microsystems of USA in 1991. Originally called ―oak‖ by James Gosling, one of the inventors if the language. This goal had a strong impact on the development team to make the language simple, portable, highly reliable and powerful language. Java also adds some new features. While C++ is a superset of C. Java is neither a superset nor a subset of C or C++.

C++ C Java

Basic concepts of Object oriented programming  All Java programs are object oriented. Computer programs consist of two elements: code and data.  In process oriented model code acting on data. Procedural languages such as C employ this model.  To manage increasing complexity object-oriented Programming approach was conceived. Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code. Abstraction An essential element of object-oriented programming is abstraction. Abstraction refers to the act of representing essential features without including the background details or explanations. For example, people do not think of a car as a set of tens of thousands of individual parts. They think of it as a well-defined object with its own unique behavior. This abstraction allows people to use a car to drive to the grocery store without being overwhelmed by the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. Instead they are free to utilize the object as a whole. The Three OOP Principles All object-oriented programming languages provide mechanisms to implement the object-oriented model. They are  Encapsulation  Inheritance  Polymorphism

Page 3 of 158 © Einstein College of Engineering

this new type can be used to create objects of that type. Page 4 of 158 © Einstein College of Engineering . For this reason. A class defines the structure and behavior (data and code) that will be shared by a set of objects. The concept of inheritance provides the idea of reusability. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. Once defined. a class is a logical construct and an object has physical reality.CS55 PROGRAMMING PARADIGMS a) Encapsulation Encapsulation is the mechanism that binds together code and the data it manipulates. c) Polymorphism Polymorphism means the ability to take more than one form. Class and Object Class defines a new data type. In Java the basis of encapsulation is the class. b) Inheritance Inheritance is the process by which one object acquires the properties of another object. Thus. Thus. Shape Draw() Circle Object Draw() Box Object Draw() Triangle Object Draw() 2. and keeps both safe from outside interference and misuse. For example. 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. shifting gears does not turn on the headlights in car. Class A class is a blueprint or prototype from which objects are created. For example Bird Attributes: Feathers Lay eggs Flying bird Attributes: -------------------- Non flying bird Attributes: --------------------- The bird 'robin ' is a part of the class 'flying bird' which is again a part of the class 'bird'. We can create any number of objects for the same class. objects are sometimes referred to as instances of a class. and an object is an instance of a class. because it encapsulates the information about all process. a class is a template for an object. This is important because it supports the concept of hierarchical classification.

Java programs come in two flavors: 1. Such a compilation unit contains a set of classes and. Java Source Code Java Compiler (Javac) Java Byte Code (. Standalone applications that have no initial context such as a pre-existing main window 2. In the same way we can create any number of objects for the same class. It may represent a person. a place. } Program Execution Create a source code file using a text editor. After finding the class. a package definition to group related classes together. java executes the enclosed main() method with signature: public static void main(String[] args) { ………. Each java program is converted into one or more class files. Object Object is an instance of class. a table of data or any item that the program has to handle. a bank account. Applets for WWW programming Execution begins when you launch the java virtual machine and tell it to find a particular class.CS55 PROGRAMMING PARADIGMS For example the construction of building requires a plan. JVM is an interpreter for bytecode which accepts java bytecode and produces result. optionally.. Without plan we can't construct building. identity and behavior.class) Java Virtual Machine Java program Output Page 5 of 158 © Einstein College of Engineering . Here plan acts as class. Classes contain data and method members that specify the state and behavior of the objects in your program. Building acts as object. Class tells the object’s state and behavior. The content of the class file is a set of instructions called bytecode to be executed by Java Virtual Machine (JVM). Basically class tells what the object should have. Using the same plan we can build any number of buildings. JAVA Program structure A file containing Java source code is considered a compilation unit. Object is real world entity which has state.Java introduces bytecode to create platform independent program.. The source code is then compiled using the java compiler javac.

which represents symbols in a character set.This group includes float and double. and local variables.CS55 PROGRAMMING PARADIGMS 3. 3. which are for whole valued signed numbers.  Floating -point numbers.EXE that ships with the JDK uses these comments to construct HTML documentation files that describe your packages.Everything between initial slash – asterisk .(/*……*/) 2. and a value. or to hold values that you need only inside the method definition itself. int.  Characters . float. char. Java actually has three kinds of variables: instance variables. like letters and numbers.This group includes char. you have to declare it. Scope Page 6 of 158 © Einstein College of Engineering . and long. They have a name. you can then assign values to it.  Class variables are similar to instance variables. a type. and boolean. class variables.Everything between initial slash –asterisk and ending asterisk-slash is ignored by the java compiler. long.  Boolean .asterisk and ending asterisk-slash is ignored by the java compiler and another program called JAVADOC. (/**……*/) b) Data Types Java defines eight simple (or elemental) types of data: byte. These can be put in four groups:  Integers . for example. After it is declared. as temporary variables. which represent numbers with fractional precision.  Instance variables are used to define attributes or the state for a particular object. for index counters in loops. Language Basics a) Comments Java comments make your code easy to understand. classes and methods as well as all the variables used. 1.This group includes boolean. int.  Local variables are declared and used inside method definitions. class and instance variables are accessed and assigned in slightly different ways from local variables. Before you can use a variable. Java supports three different types of comment styles. c) Variables Variables are locations in memory in which values can be stored. short.Double slash (//)mark is ignored by java compiler. Although all three kinds of variables are declared in much the same ways. short.This group includes byte. except their values apply to all that class’s instances (and to the class itself) rather than having different values for each object. modify and use. double. which is a special type for representing true/false values.

For native types. a class is a template for an object. j. 27.CS55 PROGRAMMING PARADIGMS   Java has no global variables. type instance-variable2.  Terminated by semicolon. The semicolon is a required terminator.). The General Form of a Class The class contains data and the code that operates on that data. like C.  A list of variable names. It is the logical construct upon which the entire Java language is built because it defines the shape and nature of an object. All variables must be declared within either a class scope or a function scope. Statements can be made up of zero or more expressions.  This line declares i and j as above and initializes them: int i=3. Java syntax is similar to C and C++ syntax. Page 7 of 158 © Einstein College of Engineering .g. defined within a class are called instance variables. As such. Collectively. A class is declared by use of the class keyword. The general form of a class definition is shown here: class classname { type instance-variable1. The code is contained within methods. Thus. Defining Class The class is at the core of Java. A terminating semicolon (e. d) Statements Java. Expressions must always appear in the context of statements.  An optional initializer following each variable name. 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.) turns it into a legal statement even though it does not do anything useful. the class forms the basis for object-oriented programming in Java. j=4. the syntax may be summarized as follows:  One word type name. 4. the methods and variables defined within a class are called members of the class. The following are examples of variable declarations:  This line of Java code declares a 32-bit integer variable named i: int i. A simple statement consists of an expression and a semicolon. Expressions (except for the return value of void methods) have a value and a type. and an object is an instance of a class.  This line declares two 32-bit integer variables named i and j: int i .. is an expression-based language. A statement consists of an expression followed by a terminating semicolon (. Declaring Variables For variable declarations. The data. or variables. provided that their combination makes syntactic sense. separated by commas.

calls a class constructor and returns a reference to the object. and depth. To create a Box object.. This is the general form of a method: Type name (parameter-list) Page 8 of 158 © Einstein College of Engineering .. and depth. class Box { double width. Thus.CS55 PROGRAMMING PARADIGMS // . you will use a statement like the following: Box mybox = new Box(). it does not create an actual object. This statement tells the compiler to assign the copy of width that is contained within the mybox object the value of 100. you are creating an object that contains its own copy of each instance variable defined by the class. Methods Classes usually consist of two things: instance variables and methods. you would use the following statement: mybox.  It should be noted that the class and its constructor have the same name. The dot operator links the name of the object with the name of an instance variable. Each time you create an instance of a class. type instance-variableN. type methodnameN(parameter-list) { // body of method } } Here is a class called Box that defines three instance variables: width. height. to assign the width variable of mybox the value 100. Box does not contain any methods (but some will be added soon).. For example. After this statement executes. every Box object will contain its own copies of the instance variables width. // create a Box object called mybox  The new operator allocates space for the new object. To access these variables. height. mybox will be an instance of Box. you will use the dot (. 5.width = 100. double height. type methodname1(parameter-list){ // body of method } type methodname2(parameter-list) { // body of method } // . } Instantiating a class Class declaration only creates a template.. Currently. double depth.) operator.

height = 20.out.println(width * height * depth). mybox2. its return type must be void. Methods that have a return type other than void return a value to the calling routine using the following form of the return statement: return value. including class types that you create.depth = 9. Program includes a method inside the box class. The name of the method is specified by name. This can be any legal identifier other than those already used by other items within the current scope. If the method has no parameters. // display volume of second box Page 9 of 158 © Einstein College of Engineering . value is the value returned.print("Volume is "). // display volume of first box mybox1.volume(). Box mybox2 = new Box().CS55 PROGRAMMING PARADIGMS { // body of method } Type specifies the type of data returned by the method. mybox2. double depth. mybox1.depth = 15. Here. The parameter-list is a sequence of type and identifier pairs separated by commas.width = 3.width = 10. This can be any valid type.out. class Box { double width. // display volume of a box void volume() { System. double height.height = 6. } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(). If the method does not return a value. /* assign different values to mybox2's instance variables */ mybox2. then the parameter list will be empty. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. // assign values to mybox1's instance variables mybox1. mybox1. System.

CS55 PROGRAMMING PARADIGMS mybox2. and the call to mybox2. Public When a member of a class is modified by the public specifier.0 The mybox1. a grouping of classes. it displays the volume for the specified box. A class member that has been declared as private will remain private to its class. 6.volume(). you can control what parts of a program can access the members of a class. So main( ) has always been preceded by the public specifier. Certain data elements or methods that are necessary for the class’s internal behavior should be protected from access by outside classes. then that member can be accessed by any other code.volume() invokes the volume( ) method on mybox1. How a member can be accessed is determined by the access specifier that modifies its declaration. Through encapsulation.) Java’s access specifiers are  Public  Private  Protected  default access level. Class members labeled public are accessible to all other classes. you can prevent misuse. Classes can be declared public. } } This program generates the following output. A public class is accessible by any other Java class. Access specifiers Encapsulation provides another important attribute: access control. These should be declared private. It is not accessible by any code outside its class. using the object’s name followed by the dot operator. Class members can be declared public or private to enforce proper encapsulation. it calls volume( ) relative to the mybox1 object. That is. the call to mybox1. (A package is. By controlling access. Private When a member of a class is specified as private. which means that only classes within the same package may access it.volume( ) displays the volume of the box defined by mybox1. THE JAVA LANGUAGE Volume is 3000.volume( ) displays the volume of the box defined by mybox2. Java supplies a rich set of access specifiers. then that member can only be accessed by other members of its class. Each time volume( ) is invoked. Some aspects of access control are related mostly to inheritance or packages. including subclasses. Thus. essentially. Protected Any member that is declared protected is accessible only by a class that is derived from the current class or is in the same package as the containing class. Page 10 of 158 © Einstein College of Engineering . A class that is not declared public has package access.0 Volume is 162.

Let's put it another way. then by default the member of a class is public within its own package. public static final double PI = 3. private int id. But there is a single static field nextId. but there is only one nextId field that is shared among all instances of the class. } Now. then there is only one such field per class. Even if there are no employee objects. but cannot be accessed outside of its package. Constants Static variables are quite rare.. the static field nextId is present.. If there are one thousand objects of the Employee class. In contrast. let's suppose we want to assign a unique identification number to each employee. Page 11 of 158 © Einstein College of Engineering . every employee object has its own id field. each object has its own copy of all instance fields. It belongs to the class. one for each object. However. For example.. not to any individual object. Static Members Static Variables If you define a field as static.. We add an instance field id and a static field nextId to the Employee class: class Employee { . private static int nextId = 1. then there are one thousand instance fields id. the Math class defines a static constant: public class Math { . 7.CS55 PROGRAMMING PARADIGMS default access level When no access specifier is used. For example.14159265358979323846. static constants are more common.

} You can access this constant in your programs as Math. For example.. Here is an example of such a static method: public static int getNextId() { return nextId. . // returns static field } To call this method. public constants (that is.getNextId(). . and every object would have its own copy of PI. it is never a good idea to have public fields because everyone can modify them. it has no implicit parameter.out. When a method only needs to access static fields of the class (example: Employee. the pow method of the Math class is a static method. before the new operator completes. . Box mybox1 = new Box().). final fields) are ok. Constructors always have the same name as the class name. However. Because static methods don't operate on objects...pow(x. } As we mentioned several times. That is. If the keyword static had been omitted. . The expression: Math. y) Computes the power xy. It is declared in the System class as: public class System { . . In other words. You use static methods in two situations: 1. When a method doesn't need to access the object state because all needed parameters are supplied as explicit parameters (example: Math. then PI would have been an instance field of the Math class. Since out has been declared as final. But static methods can access the static fields in their class.getNextId) 8. // ERROR--out is final Static Methods Static methods are methods that do not operate on objects. The constructor is automatically called immediately after the object is created.CS55 PROGRAMMING PARADIGMS . you supply the name of the class: int n = Employee. you can think of static methods as methods that don't have a this parameter. Could you have omitted the keyword static for this method? Yes. public static final PrintStream out = . It does not use any Math object to carry out its task. In other words.. but then you would need to have an object reference of type Employee to invoke the method. you would need an object of the Math class to access PI.. you cannot reassign another print stream to it: out = new PrintStream(.PI. you cannot access instance fields from a static method.. Constructors A constructor is a special method whose purpose is to construct and initialize objects. Page 12 of 158 © Einstein College of Engineering .pow) 2.. Another static constant that you have used many times is System.

double vol.CS55 PROGRAMMING PARADIGMS new Box( ) is calling the Box( ) constructor. double h. height = h. one. // get volume of first box vol = mybox1. You can't apply a constructor to an existing object to reset the instance fields.0 Page 13 of 158 © Einstein College of Engineering . When you do not explicitly define a constructor for a class. and initialize Box objects Box mybox1 = new Box(10. System. Features of constructor  A constructor has the same name as the class. There is an important difference between constructors and other methods: A constructor can only be called in conjunction with the new operator. then Java creates a default constructor for the class.  A constructor has no return value. } // compute and return volume double volume() { return width * height * depth. } } class BoxDemo7 { public static void main(String args[]) { // declare. // This is the constructor for Box. class Box { double width. 20. Box(double w. double depth.println("Volume is " + vol). or more parameters. a) Parameterized Constructors Add parameters to the constructor. double height.  A class can have more than one constructor. allocate.  A constructor is always called with the new operator. depth = d.out.volume(). The default constructor automatically initializes all instance variables to zero.  A constructor may take zero. 15). } } The output from this program is shown here: Volume is 3000. double d) { width = w.

and 15 are passed to the Box( ) constructor when new creates the object. or for other optional behaviors that may make it easier for that object to be removed. however. 20. and even then.. Only removing all references to an object will cause it to be marked for deleting. which may be some time after you’ve removed all references to that object. respectively. Finalizer methods are best used for optimizing the removal of an object —for example. this keyword has two meanings:  to denote a reference to the implicit parameter  to call another constructor of the same class. by removing references to other objects. 20. height. double h. In most cases. Page 14 of 158 © Einstein College of Engineering . mybox1’s copy of width. However. Java may or may not call the finalize() method itself —regardless of whether or not you’ve already called it. and 15.CS55 PROGRAMMING PARADIGMS Object is initialized as specified in the parameters to its constructor. // A redundant use of this. whereas a constructor method is used to initialize an object. To create a finalizer method. and depth will contain the values 10. include a method with the following signature in your class definition: void finalize() { . Thus. } c) 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. 15). } Inside the body of that finalize() method.width = w.height = h. double d) { this. Box(double w. Before you start using finalizer methods extensively in your Java programs. Box mybox1 = new Box(10. Finalizer method Finalizer methods are like the opposite of constructor methods. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. you may not need to use finalize() at all. 9. include any cleaning up you want to do for that object. by cleaning up things that object may have touched. calling finalize() does not trigger an object to be garbage-collected. be aware that finalizer methods have several very important restrictions. this. b) “this” Keyword this can be used inside any method to refer to the current object. the finalizer method is not guaranteed to be called until the object’s memory is actually reclaimed. 20. First of all.depth = d. The values 10.. finalizer methods are called just before the object is garbage collected and its memory reclaimed. this.

Java arrays have their own behavior that is encapsulated into their definition when the compiler creates them. 10. 15. 3. you will want to call it when you are done with the object. such as a file or a handle to another object that uses system resources. the index must be in the range 0 to n-1. for (int i = 0. 0}. Just as importantly. i < ia. or a list of initial element values enclosed in { }.  To instantiate the array. Arrays are ordered collections of identical objects that can be accessed via an index. not 1. provide a dispose method that disposes of the instance fields. i++) { Page 15 of 158 © Einstein College of Engineering . the new operator must be used with the [] operator to enclose the array size. Arrays An array is a group of like-typed variables that are referred to by a common name. In particular. Using Arrays Array elements can be accessed using an index in square brackets [n].length. int ia[] = new int[100]. An array initializer is either a new expression that evaluates to the correct array type. Since Java does automatic garbage collection. The following code declares an array variable and initializes it to null: char data[] = null. If a resource needs to be closed as soon as you have finished using it. where the index must be an integer. All arrays have a data field called length that indicates its size. The most common activity in a destructor is reclaiming the memory set aside for objects. Of course. 4. The array size can be any integer expression. In practice. It is important to distinguish between the array variable and the array instance to which it refers. Arrays offer a convenient means of grouping related information. notably C++. some objects utilize a resource other than memory. Array Constants The declaration of an array must include its type. have explicit destructor methods for any cleanup code that may be needed when an object is no longer used. Any attempt to index an array with an illegal value will cause an exception to be thrown. but not its size. it is important that the resource be reclaimed and recycled when it is no longer needed. Arrays start with index number 0. you need to manage it manually.CS55 PROGRAMMING PARADIGMS Some object-oriented programming languages. If the array is declared size n.  Declaring an array only declares the array variable. A specific element in an array is accessed by its index. In this case. Add a dispose method that you call to clean up what needs cleaning. Arrays of any type can be created and may have one or more dimensions. manual memory reclamation is not needed. The index can be thought of as an offset from the beginning of the array. if your class has an instance field that has a dispose method. array variables behave like class-type variables. do not rely on the finalize method for recycling any resources that are in short supply—you simply cannot know when this method will be called. and Java does not support destructors. The finalize method will be called before the garbage collector sweeps away the object. Since arrays are objects. The following array constant provides initial values for its elements: int[] int_array = {1. The index may not be less than zero or greater than the declared size. if a class you use has a dispose method. You can add a finalize method to any class.

The array will automatically be created large enough to hold the number of elements you specify in the array initializer. An array initializer is a list of commaseparated expressions surrounded by curly braces. 1.CS55 PROGRAMMING PARADIGMS ia[i] = i * i. 31. 31. The elements in the array allocated by new will automatically be initialized to zero. 2. int length = 60. The method can be used on any type of array and is declared as follows: public static void arraycopy (Object src. 31. Method1: The general form of new as it applies to one-dimensional arrays appears as follows: array-var = new type[size]. 30. a) One-Dimensional Arrays A one-dimensional array is a list of like-typed variables. char data[] = null. int length) The method copies elements from the given source array. Create an array variable of the desired type. char[] data = null. class AutoArray { public static void main(String args[]) { int month_days[] = { 31. 30. 30. The commas separate the values of the array elements. For example. Object dst. The process is much the same as that used to initialize the simple types. If range exceeds bounds of either array. 31 }.println("April has " + month_days[3] + " days.out. Allocate memory for array. } } Page 16 of 158 © Einstein College of Engineering .arraycopy() is useful for copying a number of elements from one array to another.30. int dst_position. Method2: Arrays can be initialized when they are declared. Any type of array may be copied. int src_position. a run-time error results. System. 31. the following code creates an initialized array of integers: // An improved version of the previous program. char[] data = new char [length]. Arrays in Java are in between a class and a data type although they are implemented as a class internally by Java."). There is no need to use new. 28. beginning at the specified position to the destination array at the specified position. It copies the number of elements specified by the length argument. The general form of a one dimensional array declaration is type var-name[ ]. } Copying Array Elements The library method System. Array is created by following steps. to store the number of days in each month. 31. The destination array must already be allocated.

Here. the square brackets follow the type specifier. as you might expect. However. int[] a2 = new int[3]. Java integrates internal. For example.String) is a class of object that represents a character array of arbitrary length. the following declares a twodimensional array variable called twoD. built-in strings into the language.lang. String objects The Java String class (java. There is a second form that may be used to declare an array: type[ ] var-name.CS55 PROGRAMMING PARADIGMS b) Multidimensional Arrays In Java. Page 17 of 158 © Einstein College of Engineering . and not the name of the array variable. This allocates a 4 by 5 array and assigns it to twoD. To declare a multidimensional array variable. int twoD[][] = new int[4][5]. The following declarations are also equivalent 11. specify each additional index using another set of square brackets. look and act like regular multidimensional arrays. there are a couple of subtle differences. For example. multidimensional arrays are actually arrays of arrays. Internally this matrix is implemented as an array of arrays of int. the following two declarations are equivalent: int al[] = new int[3]. as you will see. While this external class can be used to handle string objects. These.

CS55 PROGRAMMING PARADIGMS

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.

String Comparison String comparison methods listed in below Table.

Page 18 of 158 © Einstein College of Engineering

CS55 PROGRAMMING PARADIGMS

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); Page 19 of 158 © Einstein College of Engineering

CS55 PROGRAMMING PARADIGMS } int index = s1.indexOf (―that‖); 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. 12. Packages Java allows you to group classes in a collection called a package. A class can use all classes from its own package and all public classes from other packages. You can import a specific class or the whole package. You place import statements at the top of your source files (but below any package statements). For example, you can import all classes in the java.util package with the statement: import java.util.*;

Adding a class into a package To place classes inside a package, you must put the name of the package at the top of your source file, before the code that defines the classes in the package. For example, package com.horstmann.corejava; public class Employee Page 20 of 158 © Einstein College of Engineering

11 = Jack.. A tag starts with an @. method. If you add comments that start with the special delimiter /** to your source code. 2 . A comment starts with a /** and ends with a */.. it is an easy matter to update both and run javadoc again. . that generates HTML documentation from your source files. A card has a suit (Diamond. Spade or Club) and a value (1 = Ace.. This is a very nice scheme because it lets you keep your code and documentation in one place. Here is an example of a class comment: /** A <code>Card</code> object represents a playing card.. or variable) can be accessed by all methods in the same package.  Private features can only be used by the class that defines them.> to include an image.. <code>. . such as "Queen of Hearts".. The javadoc utility automatically generates summary pages that extract these sentences. and even <img . If you put your documentation into a separate file. } Package scope  Public features can be used by any class. the class. such as @author or @param. Each /** . Documentation Comments The Java SDK contains a very useful tool. 10. directly before the class definition. You should. But since the documentation comments are in the same file as the source code. Heart. Each comment is placed immediately above the feature it describes.. <strong>. stay away from heading <h1> or rules <hr> since they can interfere with the formatting of the document. 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. called javadoc. */ public class Card Page 21 of 158 © Einstein College of Engineering . however.CS55 PROGRAMMING PARADIGMS { . you can use HTML modifiers such as <em>. 12 = Queen. you too can produce professional-looking documentation easily.</code> for a monospaced ―typewriter‖ font.. . In the free-form text.</em> for emphasis.. Class Comments The class comment must be placed after any import statements. 13. 13 = King). */ documentation comment contains free-form text followed by tags. The first sentence of the free-form text should be a summary statement. then the feature (that is. ..  If you don't specify either public or private.</strong> for strong emphasis. then you probably know that the code and comments tend to diverge over time.

} Method Comments Each method comment must immediately precede the method that it describes. If your files are in the default package. they are omitted. The javadoc program can be fine-tuned by numerous command-line options. you can use the author and -version options to include the @author and @version tags in the documentation.java instead.. The description can span multiple lines and can use HTML tags. That can get messy..) 2... such as com. to document multiple packages. you must be in the directory that contains the subdirectory com. For example. You can have multiple @author tags. and we don't recommend it.corejava. The description can span multiple lines and can use HTML tags. @return description This tag adds a ―returns‖ section to the current method. For example. Change to the directory that contains the source files you want to document. you can use the following tags: @param variable description This tag adds an entry to the ―parameters‖ section of the curr ent method. If you omit the -d docDirectory option. docDirectory is the name of the directory where you want the HTML files to go. Or run javadoc -d docDirectory nameOfPackage1 nameOfPackage2. one for each author. @author name This tag makes an ―author‖ entry. if you supplied one. All @param tags for one method must be kept together. (This is the directory that contains the overview. @throws class description Field Comments You only need to document public fields—generally that means static constants. Follow these steps: 1.CS55 PROGRAMMING PARADIGMS { . then the HTML files are extracted to the current directory. If you have nested packages to document. (By default. then run javadoc -d docDirectory *. In addition to the general-purpose tags. @version text How to Extract Comments Here.) Page 22 of 158 © Einstein College of Engineering .html file. General Comments The following tags can be used in class documentation comments.horstmann. Run the command javadoc -d docDirectory nameOfPackage for a single package. /** The "Hearts" card suit */ public static final int HEARTS = 1.

2. Horstmann and Gary Cornell.com Page 23 of 158 © Einstein College of Engineering . ―Core Java: Volume I – Fundamentals‖. http://java. Eighth Edition. Sun Microsystems Press. Cay S. McGraw-Hill/Osborne. 3. 2008. Herbert Schildt ―JAVA2:The complete reference‖ Fifth Edition. References 1.CS55 PROGRAMMING PARADIGMS 14.sun.

a subclass is a specialized version of a superclass. Super Keyword 2. derived class.1. you simply incorporate the definition of one class into another by using the extends keyword. Overloaded Methods 4. Static Binding 5.2.2. Final Keyword 6. Proxies Inheritance Inheritance is a process of making a new class that derives from an existing class. Abstract Classes 6. Overridden Methods 3.1. The general form of a class declaration that inherits a superclass is shown here: class subclass-name extends superclass-name { // body of class } You can only specify one superclass for any subclass that you create. Class Hierarchy 3. Member Access And Inheritance 1. Page 24 of 158 © Einstein College of Engineering . The new class is called the subclass. It inherits all of the instance variables and methods defined by the superclass and add its own.2. Abstract Methods 7. Java does not support the inheritance of multiple superclasses into a single subclass.CS55 PROGRAMMING PARADIGMS UNIT II OBJECT-ORIENTED PROGRAMMING – INHERITANCE 1. Reflection 9. Polymorphism 3. Dynamic Binding 4. Protected features in Java are visible to all subclasses as well as all other classes in the same package. or parent class. Inheritance 1. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. The Object Class 8.1. unique elements. The existing class is called the superclass. Therefore. To inherit a class. Dynamic Binding 4. Inner Classes 12. Object Cloning 11. base class. Interfaces 10.1. or child class.

CS55 PROGRAMMING PARADIGMS Member Access and Inheritance A class member that has been declared as private will remain private to its class.  Here.  The compiler implicitly calls the base class’s no-parameter constructor or default constructor. It is not accessible by any code outside its class. Page 25 of 158 © Einstein College of Engineering . including subclasses. Because a superclass has no knowledge of any subclass.  If the superclass has parameterized constructor and the subclass constructor does not call superclass constructor explicitly. then the Java compiler reports an error.finalize(). Super keyword Super is a special keyword that directs the compiler to invoke the superclass method. Therefore. parameter-list specifies any parameters needed by the constructor in the superclass. super has two general forms. member can be either a method or an instance variable. Invoke superclass members:  Super always refers to the superclass of the subclass in which it is used. super.  super( ) must always be the first statement executed inside a subclass constructor. 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. from superclass to subclass. invoke a superclass constructor 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). the path from a particular class to its ancestors in the inheritance hierarchy is its inheritance chain.  to invoke a superclass constructor.member. But you can build hierarchies that contain as many layers of inheritance as you like.  If a parent class contains a finalize() method.  Here. This usage has the following general form: super. CLASS HIERARCHY The collection of all classes extending from a common superclass is called an inheritance hierarchy. it must be called explicitly by the derived class’s finalize() method. When Constructors are Called Constructors are called in order of derivation. it must be executed first. Simple class hierarchies consist of only a superclass and a subclass. any initialization it needs to perform is separate from and possibly prerequisite to any initialization performed by the subclass.  to invoke a superclass members(variables &methods).

display("Hello"). 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. b. create three classes called A. } } Output Hai Hello Overridden methods The process of a subclass redefining a method contained in the superclass (with the same parameter types) is called overriding the method.display(). Page 26 of 158 © Einstein College of Engineering .println("Hai"). B. } } class B extends A{ void display(String s){ System. When this type of situation occurs. C can be a subclass of B. a. public class Test{ public static void main(String arg[]){ A a=new A(). In this case. B b=new B(). The version of the method defined by the superclass will be hidden. which is a subclass of A.out. the compiler calls the overriding version instead of the superclass version. C inherits all aspects of B and A. and C.println(s). each subclass inherits all of the traits found in all of its superclasses. Whenever a method is called for a subclass object.CS55 PROGRAMMING PARADIGMS For example. Overridden methods allow Java to support run time polymorphism.out.

public class Test1{ public static void main(String arg[]){ A a=new A(). This determination is made at run time.callme(). a.out. In particular. } } class A{ protected void display(){ System. if the superclass method is public. } } Page 27 of 158 © Einstein College of Engineering . then the subclass method must also be declared as public. the subclass method must be at least as visible as the superclass method. // object of type A B b = new B().out.display().callme(). b. When an overridden method is called through a superclass reference. // r refers to an A object r. // calls B's version of callme r = c. Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. // calls A's version of callme r = b. // object of type B C c = new C().display(). // r refers to a C object r. Java uses this fact to resolve calls to overridden methods at run time.println("Hello").println("Hai"). // calls C's version of callme } } When you override a method. } } class B extends A{ public void display(){ System. // r refers to a B object r. Then the compiler complains that you try to supply a weaker access privilege. Superclass reference variable can refer to a subclass object. // object of type C A r. It is a common error to accidentally omit the public specifier for the subclass method.callme(). rather than compile time.CS55 PROGRAMMING PARADIGMS Call to an overridden method is resolved at run time. // obtain a reference of type A r = a. B b=new B(). class Dispatch { public static void main(String args[]) { A a = new A().

Dynamic Binding refers to the case where compiler is not able to resolve the call and the binding is done at runtime only. public class Test1{ public static void main(String arg[]){ A a1=new A(). static methods apply to a particular class’s static data and thus make no sense i n a derivation. a2.display().display().  All the instance methods in Java follow dynamic binding. The code contains the method invoking statement of that class need not be recompiled. A a2=new B(). } } class B extends A{ void display(){ System.println("Hello").println("Hai"). private methods are simply not inherited because they would never be callable anyway. and there is the possibility that the variable refers to an object of that class. or static are not subject to dynamic lookup because they may not be overridden. final methods are those designated as not-overridable for reasons of complexity or safety. The method is called automatically if the object happens to refer to the class. Suppose a new class is added.out. a1. private. Dynamic binding has a very important property: It makes programs extensible without recompiling the existing code.out. } } class A{ void display(){ System. } } Output Hai Hello DYNAMIC BINDING Selecting the appropriate method at runtime is called dynamic binding. Page 28 of 158 © Einstein College of Engineering .CS55 PROGRAMMING PARADIGMS Output Hai Hello Methods labeled final.

   All the member variables in Java follow static binding. Resolve the call and binding at compile time. When the program runs and uses dynamic binding to call a method. or a constructor. The compiler knows all possible candidates for the method to be called. If the method is private. This process is called overloading resolution. The keyword final can also be applied to methods. This is called static binding. then that method is chosen to be called. All private methods are resolved at compile time itself. When a method is actually called. or a constructor. static. 3. This is used to reduce the time consumed by searching process. the virtual machine simply makes a table lookup. If among all the methods called fun there is a unique method whose parameter types are a best match for the supplied parameters. but its meaning is substantially different than when it is applied to variables. This means that you must initialize a final variable when it is declared. Next.CS55 PROGRAMMING PARADIGMS Dynamic Binding or Late Binding It is important to understand what happens when a method call is applied to an object. Variables declared as final do not occupy memory on a per-instance basis. the compiler determines the types of the parameters that are supplied in the method call. Here are the details: 1. Page 29 of 158 © Einstein College of Engineering . final. 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. If the method is private. final. Doing so prevents its contents from being modified. a final variable is essentially a constant. then the virtual machine must call the version of the method that is appropriate for the actual type of the object. static. Attempts to change it will generate either a compile-time error or an exception. The compiler looks at the declared type of the object and the method name. All the static method calls are resolved at compile time itself. 2.  Used to Prevent Overriding  Used to Prevent Inheritance Named constant A variable can be declared as final. For example: final int constant = 1. then the compiler knows exactly which method to call. The virtual machine precomputes a method table for each class that lists all method signatures and the actual methods to be called.  Used to create the equivalent of a named constant. Thus. 4. then the compiler knows exactly which method to call. FINAL KEYWORD The keyword final has three uses.

To do this. a call to one can be resolved at compile time.").. System. Here is an example of a final class: final class A { // . Java resolves calls to methods dynamically.. at run time. Even a single abstract method requires that a class be marked abstract.out. } // The following class is illegal.out. precede the class declaration with final. So it prevents a class from being inherited.println("Illegal!").println("This is a final method..CS55 PROGRAMMING PARADIGMS Using final to Prevent Overriding Methods declared as final cannot be overridden. but the abstract class itself is of a type that will not be used directly. Page 30 of 158 © Einstein College of Engineering . Using final to Prevent Inheritance Declaring a class as final implicitly declares all of its methods as final..The syntax is simple. } } Normally. } } class B extends A { void meth() { // ERROR! Can't override. The only reason it exists is to be extended. } ABSTRACT CLASSES An abstract class is a type of class that is not allowed to be instantiated. since final methods cannot be overridden. This is called late binding. class B extends A { // ERROR! Can't subclass A // . It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations. just put the keyword final after the access specifier and before the return type like this: class A { final void meth() { System. However. This is called early binding. Abstract classes contain methods and variables common to all the subclasses.

you cannot declare abstract constructors. Here is a simple example of a class with an abstract method. // no implementation required ……. sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses. because an abstract class is not fully defined.callme(). abstract class A { abstract void callme().callmetoo(). } } class AbstractDemo { public static void main(String args[]) { B b = new B(). You can require that certain methods be overridden by subclasses by specifying the abstract type Page 31 of 158 © Einstein College of Engineering .println("This is a concrete method. or be itself declared abstract. Also. } There can be no objects of an abstract class.CS55 PROGRAMMING PARADIGMS To declare a class abstract. b. leaving it to each subclass to fill in the details. followed by a class which implements that method: // A Simple demonstration of abstract. } } class B extends A { void callme() { System. } } That is.").. Any subclass of an abstract class must either implement all of the abstract methods in the superclass. you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. b. That is. Such a class determines the nature of the methods that the subclasses must implement.out. an abstract class cannot be directly instantiated with the new operator.").println("B's implementation of callme.out. or abstract static methods.// concrete methods are still allowed in abstract classes void callmetoo() { System. abstract class classname { public abstract type methodname(). Such objects would be useless.

The reason for using an abstract method is to ensure that subclasses of this class will include an implementation of this method.CS55 PROGRAMMING PARADIGMS modifier. It can only be used for derivation. Any concrete class (that is. The assignment happens in the interface itself (where the constant is declared). UAGE But while an abstract class can define both abstract and nonabstract methods. Methods declared with the keyword abstract define a skeleton for a method but do not implement it. and therefore capable of being instantiated) must implement all abstract methods it has inherited. Defining an Interface This is the general form of an interface:  An interface must be declared with the keyword interface. so the implementing class can access it and use it. Abstract methods An abstract method is a method declaration that contains no functional code. However this is very unusual. an interface can have only abstract methods. To declare an abstract method. Interface as being similar to an abstract class with no instance fields. A class with one or more abstract methods must itself be declared abstract and cannot be instantiated. Interfaces An interface is a collection of method definitions (without implementations) and constant values. a subclass must override them—it cannot simply use the version defined in the superclass. but as a read-only value. To make a class implement an interface. use this general form: abstract type name(parameter-list). }  It is also possible to declare that an interface is protected so that it can only be implemented by classes in a particular package. This requires a derived class to provide the code for this class. They must always be  public  static  final Once the value has been assigned. the value can never be modified. access interface name { return-type method-name(parameter-list). These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. a class that is not abstract. type final-varname = value. have to carry out two steps: Page 32 of 158 © Einstein College of Engineering . Thus. Rules for interface constants.

class The inner class is still.  Supply definitions for all methods in the interface. Regular Inner Class You define an inner class within the curly braces of the outer class. %javac MyOuter. The only way you can access the inner class is through a live instance of the outer class. In order to be a legal implementation class.)  Type signature of the implementing method must match exactly the type signature specified in the interface definition.java . (The access level can be more accessible than that of the overridden method. use the implements keyword: access class classname implements interfacename { //definitions for all methods in the interface } Implementation classes must adhere to the same rules for method implementation as a class extending an abstract class. a nonabstract implementation class must do the following:  When you implement an interface method. method must be declared as public. so a class file is generated.CS55 PROGRAMMING PARADIGMS  Declare that your class intends to implement the given interface. in the end.class MyOuter$MyInner. a separate class. But the inner class file isn’t accessible to you in the usual way.)  A class can implement one or more interfaces. you’ll end up with two class files: MyOuter. To declare that a class implements an interface. a class can also have member classes. Inner Classes   An inner class is a class that is defined inside another class.  Partial Implementations: If a class includes an interface but does not fully implement the methods defined by that interface. then that class must be declared as abstract. as follows: class MyOuter { class MyInner { } } And if you compile it. Page 33 of 158 © Einstein College of Engineering . Just as classes have member variables and methods. (The argument list and return type must exactly match that of the overridden method. Inner classes let you make one class a member of another class.

println("Outer x is " + x). public void display() { System. mo. use the inner class name in the normal way: class MyOuter { private int x = 7. } public static void main(String arg[]){ MyOuter mo = new MyOuter(). An inner class instance can never stand alone without a direct relationship with a specific instance of the outer class.out. class MyInner { int x=5.inner(). Instantiating an Inner Class from Within Code in the Outer Class From inside the outer class instance code.display().println("Inner c is " + c). } } MyInner mi = new MyInner().out. class MyInner { public void seeOuter() { System. you must have an instance of the outer class.println("Inner x is " + x). class MyOuter { void inner() { final int c=9.mi. } } Page 34 of 158 © Einstein College of Engineering . } } Output: Outer x is 7 Method-Local Inner Classes  A method-local inner class is defined within a method of the enclosing class. MyInner mi = new MyInner(). System. } } public static void main(String arg[]){ MyOuter mo=new MyOuter().seeOuter(). mi. mo.out.CS55 PROGRAMMING PARADIGMS Instantiating an Inner Class To instantiate an instance of an inner class.

and their type must be either a subclass of the named type or an implementer of the named interface.ob. public class Test{ public static void main(String arg[]){ B b=new B(). followed by a closing parenthesis to end the method call.java .class B. a static nested class is not an inner class. so the syntax will end the class definition with a curly brace.display(). b.class Test.  Technically. followed by a semicolon to end the statement: }). but instead is considered a toplevel nested class. It cannot both extend a class and implement an interface. Page 35 of 158 © Einstein College of Engineering . } } class A{ void display(){ System.println("Hai").  An anonymous inner class is always created as part of a statement.println("Hello"). %javac Test. or implement one interface. you’ll end up with two class files: A.out.class Static Nested Classes  Static nested classes are inner classes marked with the static modifier.out.class B$1. } Output: Hello And if you compile it.  An anonymous inner class can extend one subclass. } }. } } class B { A ob=new A(){ void display(){ System. nor can it implement more than one interface.CS55 PROGRAMMING PARADIGMS Output: x is 5 c is 9 Anonymous Inner Classes  Anonymous inner classes have no name.

you don’t need an instance of the outer class to instantiate a static nested class.Nested(). The reflection mechanism is extremely used to Page 36 of 158 © Einstein College of Engineering . public class Test{ public static void main(String arg[]){ A.  This mechanism is helpful to tool builders.B b=new A.reflect package and elements in class.out. Reflection  Reflection is the ability of the software to analyze itself at runtime. it does not share any special relationship with an instance of the outer class. to convert to a string. In fact. void display(){ System. since it does not have an implicit reference to any outer instance (in other words. } } } Output: m=5 The Object Class .lang. the nested class instance does not get an outer this reference).  Instantiating a static nested class requires using both the outer and nested class names as follows: BigOuter. The Object class is the ultimate ancestor Every class in Java extends Object class. such as the ability to compare with another object. not application programmers.Nested n = new BigOuter. b.B().The Cosmic Superclass The Object class sits at the top of the class hierarchy tree in the Java development environment.CS55 PROGRAMMING PARADIGMS  Because the nested class is static. The Object class defines the basic state and behavior that all objects must have.  A static nested class cannot access nonstatic members of the outer class. and to return the object's class. }} class A { static class B { int m=5.println("m="+m). to notify other objects that a condition variable has changed. to wait on a condition variable. which means that they are available in every object. Object defines the following methods.display().  Reflection is provided by the java.

Field    Provide information about fields. methods and constructors that are declared in the class. The getFields method returns an array containing Field objects for the public fields. Return an array of fields.lang.  int getModifiers(). that describes the modifier.reflect Field Method Constructor Methods (Field.lang. Method & Constructor):  String getName() – return the name of the item. The methods return an array of length 0 if there are no such fields. Page 37 of 158 © Einstein College of Engineering . Java.lang.*.Examine the structure of class.Class Field[] getFields() Method[] getMethods() Constructor[] getConstructors() Field[] getDeclaredFields() Method[] getDeclaredMethods() Constructor[] getDeclaredConstructors() Return an array of public fields. The getDeclaredField method returns an array of Field objects for all fields. Java. import java.reflect. This includes private.CS55 PROGRAMMING PARADIGMS  Analyze the capabilities of classes at run time  Inspect objects at run time  Implement generic array manipulation code Analyze the capabilities of classes at run time . This includes all public members of super class.return an integer. protected and public members of class but not members of super class. methods and constructors that the class supports.

var1 All Fields: public int Test.out.out. This includes those inherited from classes or interfaces above it in the inheritance chain.lang.out. private int var2.length. import java.var4 Method  Provides information about method  The getMethods() method return an array containing Method objects that give you all the public methods. for(int i=0.getFields(). Field fdec[]=c. System.i<f.reflect.i++) System.forName("Test").println("All Fields:").println("public Fields:"). System.*.length.  The getDeclaredMethods () return all methods of the class or interface.CS55 PROGRAMMING PARADIGMS class Test{ public int var1. for(int i=0. Field f[]=c. } public class FieldDemo{ public static void main(String args[])throws Exception{ Class c=Class.println(fdec[i]). int var4.println(f[i]). class Test{ public void method1() {} protected void method2() {} private void method3() {} void method4() {} } Page 38 of 158 © Einstein College of Engineering .i++) System. } } Output: public Fields: public int Test.getDeclaredFields().out. protected int var3.var2 protected int Test.var1 private int Test.var3 int Test.i<fdec.

length. System.getName()).println("All Methods:").length.forName("Test").i<m.out.i++) System. Method m[]=c.println(mdec[i].i<mdec. System.getName()).out.i++) System.println("public Methods of class Test & its Super class:").out. for(int i=0. } } Output: public Methods of class Test & its Super class: method1 hashCode getClass wait equals notify notifyAll toString All Methods: method1 method2 method3 method4 Page 39 of 158 © Einstein College of Engineering .CS55 PROGRAMMING PARADIGMS public class MethodDemo{ public static void main(String args[])throws Exception{ Class c=Class. Method mdec[]=c.getDeclaredMethods().println(m[i]. for(int i=0.out.getMethods().

System. A(int i.getField("var2").var2. int v1 = f1.out.reflect.var2).lang. f1.out.CS55 PROGRAMMING PARADIGMS 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. System.get(obj)). v1).*. value) sets the field represented by f of the object obj to the new value. Field f1 = obj. Field f2 = obj. } } Output: Before var1= 10 After var1= 11 Before var2= 20 After Page 40 of 158 © Einstein College of Engineering .set(obj.getClass(). Using Reflection to Analyze Objects at Run Time Look at the contents of the data fields.println("Before \n var1= "+obj. System.println("After \n var2= "+f2.getClass().setInt(obj. import java. class A{ public int var1.println("Before \n var2= "+obj.set(obj.get(obj) returns an object whose value is the current value of the field of obj.21).20).  f. f2.  f.println("After \n var1= "+v1).var1). } } public class ConstructorDemo { public static void main(String args[]) throws Exception{ A obj=new A(10.out.out. 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.getInt(obj) + 1. But reflection lets you look at fields of objects that were not known at compile time. System.getField("var1"). var2=j. int j){ var1=i.

First the given array can be converted to an Object[] array. Array. Confirm that it is really an array using isArray(). constructs a new array.isArray()) return null.getLengh(array name)).reflect. } public static void main(String args[]) throws Exception{ int arr[]=new int[10]. arr = (int[])arrayGrow(arr). It returns the length of any array(method is static method.out.newInstance(ComponentType. public class TestArrayRef { static Object arrayGrow(Object a){ Class cl = a. Get the class object using getClass() method.arraycopy(a.reflect package allows you to create arrays dynamically.newInstance(componentType.lang. Object newArray = Array. to find the right type for the array. newArray.getClass(). 0. Object newarray= Array. System.getComponentType().newLength). 3.println(arr. import java. Class componentType = cl.out. System. newlength) newInstance() method needs two parameters  Component Type of new array To get component type 1. newInstance() method of Array class. int newLength = length + 10.*.length).  Length of new array Length is obtained by getLength() method. Use getComponentType method of class Class.lang. if (!cl.CS55 PROGRAMMING PARADIGMS var2= 21 Using Reflection to implement generic array manipulation code The Array class in the java. int length = Array.length).println(arr. 0. } } Output: 10 20 Object cloning Page 41 of 158 © Einstein College of Engineering . 2. length).getLength(a). System. return newArray.

} } } public class CloneDemo{ public static void main(String arg[]){ Test original=new Test(). } catch(CloneNotSupportedException e){ return null. the original and the copy are references to the same object. Page 42 of 158 © Einstein College of Engineering .out. import java. original. public void display(){ System. class Test implements Cloneable{ int a=10.clone(). When you make a copy of a variable.clone().display(). You can modify the clone without affecting the original. copy. copy. The proxy class can create brand-new classes at runtime. } } Output: a=20 a=80 Proxy Proxy used to create new classes at runtime that implement a given set of interfaces.*. return cloned. original.println("a="+a).CS55 PROGRAMMING PARADIGMS  A clone of an object is a new object that has the same state as the original but a different identity. and  Redefine the clone method with the public access modifier.a=80. } public Object clone(){ try{ Test cloned = (Test)super.display().util. Test copy=(Test)original.a=20. This means a change to either variable also affects the other. If you want to make a clone of any class then the class must  implement the Cloneable interface.

3. As part of the Java security model. classes that are downloaded from the Internet. In particular.CS55 PROGRAMMING PARADIGMS The proxy class can create brand-new classes at runtime. • Tracing method calls for debugging purposes. Such a proxy class implements the interfaces that you specify. A class loader. • All methods defined in the Object class (toString. Proxies can be used for many purposes. The method has three parameters: 1. equals. To create a proxy object. 2. one for each interface to be implemented. you use the newProxyInstance method of the Proxy class. Page 43 of 158 © Einstein College of Engineering . An array of Class objects. An invocation handler. such as: • Routing method calls to remote servers. and so on. it is possible to use different class loaders for system classes. • Associating user interface events with actions in a running program. and so on). the proxy class has the following methods: • All methods required by the specified interfaces.

Color). Frames are examples of containers. int y.awt.awt Component Container Window Frame Component & Window class Methods java. void repaint() .resizes the component to the specified width and height.set Foreground color to the window.shows or hides the component depending on whether b is true or false. The location of the top-left corner is given by x and y. borders. int width. void setForeground(java.CS55 PROGRAMMING PARADIGMS Unit III Event-Driven Programming Graphics programming Frame Frame is a top-level window that has a title bar. void setSize(int width.awt.    void setBackground(java. and resizing corners. It can contain other user interface components such as buttons and text fields.moves and resizes this component.‖ Page 44 of 158 © Einstein College of Engineering . By default. Class hierarchy for Frame Java. int height) . and the new size is given by the width and height parameters. menu bar.Color) – set Background color to the window.Component    void setVisible(boolean b) .causes a repaint of the component ―as soon as possible. a frame has a size of 0 × 0 pixels and it is not visible. int height) . void setBounds(int x.awt.

CS55 PROGRAMMING PARADIGMS

java.awt.Window  void setTitle(String s) - sets the text in the title bar for the frame to the string s.

Frame’s constructors: Frame( ) - creates a standard window that does not contain a title. Frame(String title) - creates a window with the title specified by title Methods of Frame class:    void setSize(int newWidth, int newHeight) - method is used to set the dimensions of the window. The dimensions are specified in terms of pixels. void setVisible(boolean visibleFlag)- The component is visible if the argument to this method is true. Otherwise, it is hidden. void setTitle(String newTitle)- change the title in a frame window.

Creating a Frame Window Method 1: In main() method    Create an instance of a Frame class. Frame f=new Frame(―frame name‖); Set the frame size

f.setSize(500,500); Make the frame visible

f.setVisible(true); Example: The following java program creates a frame with the dimension as 600 x 400 and makes it visible in the screen. Import java.awt package because Frame class is available in that package.
import java.awt.*; public class Demo{ public static void main(String arg[]){ Frame f=new Frame("Demo"); f.setSize(600,400); f.setVisible(true); } } Out Put:

Page 45 of 158 © Einstein College of Engineering

CS55 PROGRAMMING PARADIGMS

Method :2   Create a subclass of Frame. In the Subclass constructor      Example: The following java program creates a frame with the dimension as 600 x 400 and makes it visible in the screen. Import java.awt package because Frame class is available in that package.
import java.awt.*; public class Demo extends Frame{ Demo(String s){ super(s); setSize(600,400); setVisible(true); } public static void main(String arg[]){ Demo ob=new Demo("Demo"); Out Put: }

Change the frame title by calling superclass [Frame] constructor using super(String) method call. Set the size of the window explicitly by calling the setSize( ) method. Make the frame visible by calling setVisible() method.

In main() method Create an instance of subclass.

}

Working with 2D shapes
Graphics: java.awt.Graphics The Graphics class is part of the java.awt package. The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only or filled. Objects are drawn and filled in the currently selected graphics color, which is black by default. When a graphics object is drawn that exceeds the dimensions of the window, output is automatically clipped. Java Coordinate System Java’s coordinate system has the origin (0, 0) in the top left corner. Positive x values are to the Page 46 of 158 © Einstein College of Engineering

CS55 PROGRAMMING PARADIGMS

right, and positive y values are down. Coordinate units are measured in pixels (picture element). All pixel values are integers; there are no partial or fractional pixels.

X coordinate: Horizontal distance moving right from the left of the screen. Y coordinate: Vertical distance moving from top to bottom of the screen. The Graphics class provides a set of simple built-in graphics primitives for drawing, including lines, rectangles, polygons, ovals, and arcs. Lines To draw straight lines, use the drawLine method. drawLine takes four arguments: the x and y coordinates of the starting point and the x and y coordinates of the ending point.  void drawLine(int startX, int startY, int endX, int endY) - displays a line in the current drawing color that begins at startX,startY and ends at endX,endY.

Example: Demo.java import java.awt.*; public class Demo extends Frame{ Demo(String s){ super(s); setSize(100,100); setVisible(true); } public void paint(Graphics g) { g.drawLine(10,10,60,60); } public static void main(String arg[]){ Demo ob=new Demo("Line Demo"); } } Output:

Page 47 of 158 © Einstein College of Engineering

Example: Demo.20. setVisible(true).10). The dimensions of the rectangle are specified by width and height. int y.60. int y.60. int xDiam. int yDiam) A rounded rectangle has rounded corners.fillRoundRect(250. int y. g.100. setSize(500.60.drawRoundRect(100.java import java. Page 48 of 158 © Einstein College of Engineering .drawRect(100. int height.*. int yDiam) void fillRoundRect(int x. int xDiam.     void drawRect(int x.awt.fillRect(250. int width. g. } public static void main(String arg[]){ Output: } } Demo ob=new Demo("Line Demo").60.250. y. } public void paint(Graphics g) { g. int y.10. int height. int height) void drawRoundRect(int x.60.60.20).60). int width.250.500). int height) void fillRect(int x. The diameter of the rounding arc along the Y axis is specified by yDiam. The diameter of the rounding arc along the X axis is specified by xDiam.100. The upper-left corner of the rectangle is at x. public class Demo extends Frame{ Demo(String s){ super(s). int width.60). int width.CS55 PROGRAMMING PARADIGMS Rectangles The Java graphics primitives provide two kinds of rectangles: Plain rectangles and Rounded rectangles(which are rectangles with rounded corners). g.

int y2[] = { 133. int y1[] = { 133. Output: } } Page 49 of 158 © Einstein College of Engineering .170.y2. int x2[] = { 139.java import java.180.58.94.180.awt. draws a line to the second.194.26 }.197. g.drawPolygon(x1.7).153. int numPoints) void fillPolygon(int x[ ].206 }. Set of x and y coordinates are needed to draw a polygon.An integer for the total number of points Example: Demo.97.136.206 }. then a line to the third. public class Demo extends Frame{ public void paint(Graphics g) { int x1[] = { 39. } public static void main(String arg[]){ Demo ob=new Demo("Polygon Demo"). g.136.y1.   void drawPolygon(int x[ ]. and so on.158.208.112.fillPolygon(x2. int y[ ].208.174.126 }.53.174.7).*.170.An array of integers representing y coordinates numPoints.CS55 PROGRAMMING PARADIGMS Polygons Polygons are shapes with an unlimited number of sides.212. int y[ ].An array of integers representing x coordinates y[]. int numPoints) x[]. and the drawing method starts at one.

int width. int left. int left. int height) Page 50 of 158 © Einstein College of Engineering .   void drawOval(int top. int width. int height) void fillOval(int top.CS55 PROGRAMMING PARADIGMS Ovals Use ovals to draw ellipses or circles.

} public void paint(Graphics g) { g. int height. The arc is drawn counterclockwise if sweepAngle is positive.120. int arcAngle) x=0 y=0 width=100 height=100 Startangle=90 arcAngle=180 Page 51 of 158 © Einstein College of Engineering . int y.70).70). int startAngle. and clockwise if arkAngle is negative. int y. g.*. setSize(300.120. public class Demo extends Frame{ Demo(String s){ super(s).fillOval(140. int arcAngle) void fillArc(int x. int width.java import java.drawOval(20.70.   void drawArc(int x.100. Angles are specified in degrees. setVisible(true). int startAngle. } public static void main(String arg[]){ Demo ob=new Demo("Oval Demo").awt. int width.300).CS55 PROGRAMMING PARADIGMS Example:Demo. } } Arc The arc is drawn from startAngle through the angular distance specified by arkAngle. int height.

CS55 PROGRAMMING PARADIGMS Page 52 of 158 © Einstein College of Engineering .

180).CS55 PROGRAMMING PARADIGMS Example:Demo. setSize(200. setVisible(true).  void drawstring(String text.90. } public static void main(String arg[]){ Demo ob=new Demo("Text Demo"). public class Demo extends Frame{ Demo(String s){ super(s).120.200).awt.90.-180). } } Page 53 of 158 © Einstein College of Engineering .*.fillArc(120.90. g.90. int x. int y).180). g.90.drawArc(20. 100).*.90.90. 75. import java.300). public class Demo extends Frame{ Demo(String s){ super(s).java import java. } public void paint(Graphics g) { g.90. } public void paint(Graphics g) { g.120.drawString("welcome".drawArc(170.draws a string in the current font and color.120. setSize(300.awt. setVisible(true). } public static void main(String arg[]){ Demo ob=new Demo("Arc Demo").90. } } Output: Drawing Text Draw text on the screen using the method drawstring().

CS55 PROGRAMMING PARADIGMS Page 54 of 158 © Einstein College of Engineering .

Color) – set Background color to the window.cyan( 0.Color Color class creates a solid RGB color with the specified red.255. green.0.   void setBackground(java.red (255. and blue.awt.0) Color.175.awt.CS55 PROGRAMMING PARADIGMS Using color. and images Color: java.255) Color.0) Color. They are stored in class variables. The values of each color must be in the range (0.192.0) Color.green(0.Color) Page 55 of 158 © Einstein College of Engineering .Graphics setColor() method used to set the current color for the graphics context which is defined in Graphics class. Java.  void setColor(java.255.128) Color.yellow (255. Color.0.Color class used to create new color object for any combination of red.white (255.darkGray (64. blue value in the range (0255).255.awt. green.Component Component class defines setBackground() and setForeground() methods for setting background and foreground colors to the window.0.175) Color.64.128.awt.255. and blue. Java’s abstract color model uses 24-bit color.200.gray (128. int green.magenta (255. void setForeground(java.orange (255.255).255) Color.255) Color.pink (255.black (0.0) Color.lightGray (192.awt. java.awt.64) Color. green.0) java.blue (0.0.192) Color.Color). Since Frame is a subclass of Component class it can use these methods.255) Color.awt. int blue) . and it predefines a few color constants.create new color object for any combination of red. Constructor: Color(int red. fonts.set Foreground color to the window.

gval = (int)Math.random() * 256). each of which has a randomly chosen color in it. of the font is specified by pointSize. The style of the font is specified by fontStyle.floor(Math. It may consist of one or more of thesethree constants: Font. import java.floor(Math. g. bval. buttons etc. first create an object of the class Font.25.setVisible(true). setBackground(Color. fontName specifies the name of the desired font.awt. public class Demo extends Frame{ Demo(String s){ super(s).gval. and the point size. Demo ob=new Demo("Color Demo").CS55 PROGRAMMING PARADIGMS Example: The following program for designing a frame with square boxes.awt. bval = (int)Math. i+= 30){ rval = (int)Math. j < 200-30. point size may or may not be the height of the characters. then specify the font name. the font style. Font. Page 56 of 158 © Einstein College of Engineering .random() * 256).black). gval.PLAIN.j. in points. } } public static void main(String arg[]){ } } Output: Font: java.random() * 256). The size.bval)).setSize(200.*.Font Font class is used to create Font Objects to set the font for drawing text.floor(Math. int pointSize) Here. To draw characters in a font. labels..setColor(new Color(rval. and Font.25).. textField. g. One Font constructor has this general form: Font(String fontName.ITALIC. for (int j = 30.fillRect(i. int fontStyle. i < 200-30. } public void paint(Graphics g) { int rval.BOLD.200). j += 30) for (int i = 30.

*.setFont(fi). Font. Font fbi = new Font("TimesRoman". 18).BOLD + Font. g. g.ITALIC. Font fb = new Font("TimesRoman".200). } } Image: java.drawString("This is a bold font". g. 125). g. 10. 18).awt.setFont(f).awt.setFont(fbi). import java. 18).get the current font by calling getFont( ). 50). 75). 100). g.BOLD. g. Font.setFont(fb). 10.Graphics   void setFont(Font fontObj). Java. g. 10.Component  void setFont(Font fontObj) Example: The following program that draws several lines of text in different fonts.drawString("This is a bold italic font".setVisible(true).drawString("This is a plain font".Image Image class provides support for displaying and manipulation of graphical images. g. } Output: public static void main(String arg[]){ Demo ob=new Demo("Font Demo"). Page 57 of 158 © Einstein College of Engineering . Font.selects a font for the graphics context.awt. Font getFont( ). Font fi = new Font("TimesRoman".awt. 10.PLAIN.setSize(200.drawString("This is an italic font".CS55 PROGRAMMING PARADIGMS Methods Java. 18). Font. public class Demo extends Frame{ Demo(String s){ super(s). Image is simply a rectangular graphical object. That font will be used for subsequent text drawing operations. } public void paint(Graphics g) { Font f = new Font("TimesRoman".ITALIC.

returns the default toolkit.20.j. } } Output: Page 58 of 158 © Einstein College of Engineering . j <300-20.jpg"). public class Demo extends Frame{ Demo(String s){ super(s).Graphics   boolean drawImage(Image img. for (int i = 20. int height.setVisible(true). Image img= tk. ImageObserver observer) draws a scaled image. } public void paint(Graphics g) { Toolkit tk = Toolkit. } public static void main(String arg[]){ Demo ob=new Demo("Image Demo"). boolean drawImage(Image img. int x. int x.*.i.returns an image that will read its pixel data from a file.drawImage(img. The system scales the image to fit into a region with the given width and height. Example: the following program draws a tiled graphics image from the top-left corner to bottom right corner of the window.awt. Step1: Loading an image java. Note: This call may return before the image is drawn.Toolkit   Toolkit getDefaultToolkit(). Image getImage(String filename) . import java. j=j+20) g. int width.getDefaultToolkit(). int y. Toolkit object can only read GIF and JPEG files.CS55 PROGRAMMING PARADIGMS Java provides the functions for reading images that are stored in local files and display them on graphics object.300). i=i+20) for (int j = 40.draws a scaled image. int y.awt.20. i <300-20. Step2: displaying an image java.setSize(300.null). ImageObserver observer).awt.getImage("E:/Sample/ball.

it will automatically be visible whenever its parent window is displayed. int how) Button( ) Button(String str) List( ) List(int numRows) List(int numRows. int numChars) TextArea(String str) TextArea(String str. int numChars) TextField TextArea Page 59 of 158 © Einstein College of Engineering .remove all controls from a window Constructor Label( ) Label(String str) Label(String str. boolean multipleSelect) Methods void setText(String str) String getText( ) void setLabel(String str) String getLabel( ) void add(String name) void add(String name.add components to the conatainer.   void remove(Component obj). Here.remove a control from a window removeAll( ). boolean on) Checkbox(String str. CheckboxGroup cbGroup. compObj is an instance of the control that you want to add. A layout manager arranges components within a container (Frame/Applet/Panel). boolean on) TextField( ) TextField(int numChars) TextField(String str) TextField(String str. CheckboxGroup cbGroup) Checkbox(String str. int index) Component Label Button List Choice Choice( ) Checkbox Checkbox( ) Checkbox(String str) Checkbox(String str. Adding and Removing Controls  add(Component compObj).CS55 PROGRAMMING PARADIGMS AWT Components   All components are subclass of Component class Components allow the user to interact with application. int numChars) TextArea( ) TextArea(int numLines. int index) String getSelectedItem( ) int getSelectedIndex( ) String[ ] getSelectedItems( ) void add(String name) String getSelectedItem( ) int getSelectedIndex( ) boolean getState( ) void setState(boolean on) String getLabel( ) void setLabel(String str) String getText( ) void setText(String str) void setEditable(boolean canEdit) void append(String str) void insert(String str. int numLines. boolean on. Once it is added.

int max) int getMinimum( ) int getMaximum( ) void setValues(int initialValue.constructs a label with left-aligned text. int min.add(lb3). Methods   void setText(String str). setVisible(true). Labels don’t react to user input. Label(String str. int thumbSize. Demo(String s){ super(s). FlowLayout flow= new FlowLayout(). public class Demo extends Frame{ Label lb1 = new Label("One").return the text of label Example: The following example creates three labels and adds them to a frame. setSize(200. Constructors   Label(String str) . Label lb3 = new Label("Three"). int max) Label   Labels are components that hold text. setLayout(flow). } public static void main(String arg[]){ } } Output: Demo ob=new Demo("Label Demo").CS55 PROGRAMMING PARADIGMS Scrollbars Scrollbar( ) Scrollbar(int style) Scrollbar(int style.set the text in the label String getText( ). add(lb1). It is used to ide ntify components. int thumbSize. int min. Label lb2 = new Label("Two")..add(lb2). int how) .*.awt. int initialValue.The labels are organized in the frame by the flow layout manager. Page 60 of 158 © Einstein College of Engineering .constructs a label with the alignment specified by how. import java.200).

CS55 PROGRAMMING PARADIGMS Page 61 of 158 © Einstein College of Engineering .

Button b2=new Button("Button 2"). setLayout(flow). Constructors     Button( ).*.200). Button b1=new Button(). The buttons are organized in the frame by the flow layout manager. add(b).add(b1). Push buttons are objects of type Button.setLabel("Button 1"). It allows the user to select multiple items. setVisible(true). b1.allows to select one item at any one time List(int numRows). public class Demo extends Frame{ FlowLayout flow= new FlowLayout(). 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. scrolling selection list. List The List class provides a compact. Constructors   List( ).CS55 PROGRAMMING PARADIGMS Button A push button is a component that contains a label and that generates an event when it is pressed. public static void main(String arg[]){ import java. multiple-choice. Demo(String s){ super(s).the value of numRows specifies the number of entries in the list that Page 62 of 158 © Einstein College of Engineering . } }} Output: Demo ob=new Demo("Button Demo"). List object can be constructed to display any number of choices in the visible window.creates a button that contains str as a label.awt.creates an empty button Button(String str). Button b=new Button().setSize(200.add(b2).

add("MECH").add(l3). List l3=new List(4. } } ob=new Page 63 of 158 © Einstein College of Engineering . setSize(200.CS55 PROGRAMMING PARADIGMS will be visible always  List(int numRows.add(l2). l2.return the selected items.add("EEE"). l3. setLayout(flow). add(lb1).*. setVisible(true). Label lb3 = new Label("Dept"). public class Demo extends Frame{ FlowLayout flow= new FlowLayout(). import java. name is the name of the item added to the list.l2.add("MECH"). l1. then the user may select two or more items at a time Method     void add(String name).add("EEE"). List l2=new List(3).add(lb3). Label lb1 = new Label("Dept").l2.add("CSE").add(l1). Example: The following example creates a list and adds it to a frame. Label lb2 = new Label("Dept").awt. The first form adds items to the end of the list.l3.add("CSE").if multipleSelect is true.add("ECE").add("ECE"). } public static void main(String arg[]){ Demo Demo("List Demo").l3.add("CSE").true).l1.300). Demo(String s){ super(s). List l1=new List(2).return the selected item String[ ] getSelectedItems( ).l2.add("EEE").l1. void add(String name.l3.add(lb2). int index) -adds the item at the index specified by index String getSelectedItem( ).Here.add("MECH"). boolean multipleSelect).l1.add("ECE").

These check boxes are often called radio buttons.check box whose label is initially blank Checkbox(String str). Checkbox(String str. Page 64 of 158 © Einstein College of Engineering . the check box is initially checked Checkbox(String str. Constructors          Checkbox( ).cg.cg. The default constructor is defined. boolean on. 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. public class Demo extends Frame{ FlowLayout flow= new FlowLayout(). CheckboxGroup cg=new CheckboxGroup(). boolean on) .CS55 PROGRAMMING PARADIGMS CheckBox A check box is a control that is used to turn an option on or off. Checkbox c1=new Checkbox("Male".group is specified by cbGroup Checkbox(String str. Label l2=new Label("Languages Known"). There is a label associated with each check box that describes what option the box represents.allows you to set the initial state of the check box.*. It consists of a small box that can either contain a check mark or not. CheckboxGroup cbGroup). Checkbox c2=new Checkbox("Female". Label l1=new Label("Gender").awt. CheckboxGroup cbGroup. Example: The following example creates a checkbox group (Gender) and checkboxes (Languages Known).false).true). If on is true. which creates an empty group.check box whose label is specified by str. import java.

Choice only defines the default constructor.add(c2).add(c3). It allows the user to select single item at any time.*. public class Demo extends Frame{ FlowLayout flow= new FlowLayout(). c.CS55 PROGRAMMING PARADIGMS Checkbox c3=new Checkbox("VisualBasic").add("Tirunelveli"). add(lb). Checkbox c4=new Checkbox("C++"). Label lb=new Label("City"). c.c. c. setVisible(true). } public static void main(String arg[]){ Demo ob=new Demo("Checkbox Demo").add(c1).add(c). Checkbox c6=new Checkbox("C").awt. which creates an empty list. Checkbox c5=new Checkbox("Java"). you may call either getSelectedItem( ) or getSelectedIndex( ). setSize(200. add(l1). setVisible(true). setLayout(flow). } public static void main(String arg[]){ Demo ob=new Demo("Checkbox Demo").add(c5). Demo(String s){ super(s). Demo(String s){ super(s). setSize(200. add(l2).add("Chennai").setLayout(flow).200).c. call add( ). It has this general form:   void add(String name) To determine which item is currently selected. Choice c=new Choice().add("KanyaKumari"). } } Page 65 of 158 © Einstein College of Engineering .add(c6).add("Coimbatore").200).add(c4). Output: } } Choice The Choice class is used to create a pop-up list of items from which the user may choose. import java.add("Madurai"). To add a item to the list.

awt. setText( ).CS55 PROGRAMMING PARADIGMS TextField Text fields allow the user to enter strings and to edit the text using the arrow keys. TextArea ta=new TextArea(2. public class Demo extends Frame{ FlowLayout flow= new FlowLayout(). Label lb1=new Label("Name"). and setEditable( ) methods described in TextField class. setSize(250. Label lb2=new Label("No"). add(lb3). import java. add(lb2).add(t1). Demo(String s){ super(s). Label lb3=new Label("Message"). and mouse selections. isEditable( ).creates a default text field TextField(int numChars).     TextField( ). it supports the getText( ).*. add(lb1). 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.initializes the text field with the string contained in str TextField(String str. TextField t1=new TextField(20). cut and paste keys.10). getSelectedText( ).creates a text field that is numChars characters wide TextField(String str). Therefore.200). setLayout(flow). TextField t2=new TextField(15). select( ).add(ta).add(t2). Page 66 of 158 © Einstein College of Engineering .

CS55 PROGRAMMING PARADIGMS setVisible(true). } } output: Page 67 of 158 © Einstein College of Engineering . } public static void main(String arg[]){ Demo ob=new Demo("TextComponents Demo").

Page 68 of 158 © Einstein College of Engineering . Mouse Keyboard Generates Mouse events when Mouse input occurs. generates item events when an item is selected or deselected. the listener processes the event and then returns. Generates item events when the choice is changed. Generates item events when the check box is selected or deselected. Generates Key events when keyboard input occurs. Event Listeners Listener is an object that is notified when an event occurs. Events An event is an object that describes a state change in a source. Listener simply waits until it receives an event. Sources may generate more than one type of event.awt. Generates action events when an item is double-clicked. selecting an item in a list. Event Source Button Checkbox Choice List Description Generates action events when the button is pressed. It must implement methods to receive and process these notifications. It has two major requirements. Once received.event defines several types of events that are generated by various user interface elements. entering a character via the keyboard.CS55 PROGRAMMING PARADIGMS Basics of Event Handling Event handling concept is quite simple: a source generates an event and sends it to one or more listeners. Some of the activities that cause events to be generated are pressing a button. and clicking the mouse. The package java. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Event Sources A source is an object that generates an event.   It must have been registered with one or more sources to receive notifications about specific types of events.

The event source sends out event objects to all registered listeners when that event occurs.awt.addEventListener(eventListenerObject). You register the listener object with the source object by using lines of code that follow the model: eventSourceObject. Checkbox Keyboard ItemEvent Object getItem( ) ItemSelectable getItemSelectable( ) ItemListener itemStateChanged(ItemEvent ie) KeyEvent char getKeyChar( ) int getKeyCode( ) KeyListener keyPressed(KeyEvent ke) keyReleased(KeyEvent ke) keyTyped(KeyEvent ke) Mouse MouseEvent int getX( ) int getY( ) MouseListener mouseClicked(MouseEvent me) mouseEntered(MouseEvent me) mouseExited(MouseEvent me) mousePressed(MouseEvent me) mouseReleased(MouseEvent me) MouseMotionListener mouseDragged(MouseEvent me) mouseMoved(MouseEvent me) Page 69 of 158 © Einstein College of Engineering . The listener objects will then use the information in the event object to determine their reaction to the event. AWT Event Hierarchy java.CS55 PROGRAMMING PARADIGMS 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.event Source Button Event Class ActionEvent Class Methods String getActionCommand( ) Listener Interface ActionListener Interface Methods actionPerformed(ActionEvent ae) List. Choice.

if(kc==38 && y>0) y=y-10.30). Demo(String s){ super(s). addKeyListener(this).awt.*. if(kc==40 && y<300) y=y+10. if(kc==37 && x<300) x=x-10. Page 70 of 158 © Einstein College of Engineering .KeyEvent Listener Interface: java.awt. if(kc==39 && x>0) x=x+10. } public void keyPressed(KeyEvent ke){ int kc=ke. public void paint(Graphics g){ g.CS55 PROGRAMMING PARADIGMS Handling Keyboard Events To handle keyboard events.event.300). Source: KeyBoard Event Class: java.KeyListener Example: The following program demonstrates keyboard input. } } Output: } public static void main(String arg[]){ Demo ob=new Demo("Key event Demo"). import java. class must implement the KeyListener interface. identifies the key and perform the corresponding actions specified by the program.event.30.y=20.event.drawRect(x. setVisible(true). } public void keyTyped(KeyEvent ke){ } public void keyReleased(KeyEvent ke){ } repaint(). addKeyListener(this). import java.*. When program receives keystrokes.awt. public class Demo extends Frame implements KeyListener{ int x=20.awt.y. setSize(300.getKeyCode(). Register key listener to receive notifications about KeyEvents.

x2.y1. import java. addMouseListener(this).event. setVisible(true).event.x2. setSize(300.awt.getX().awt.getGraphics().MouseListener java.y2. public class Demo extends Frame implements MouseListener.awt. } public void mouseDragged(MouseEvent me){ x1=x2.event. addMouseMotionListener(this). x1=y2=me.300). import java. When user drag the mouse it draws a line along the motion path.MouseMotionListener{ int x1.awt. addMouseMotionListener(this). } public void mouseReleased(MouseEvent me){} Page 71 of 158 © Einstein College of Engineering . Register mouse listener & mouse motion listener to receive notifications about MouseEvents.drawLine(x1. g. } public void mouseMoved(MouseEvent me){} public void mouseClicked(MouseEvent me){} public void mouseEntered(MouseEvent me){} public void mouseExited(MouseEvent me){ } public void mousePressed(MouseEvent me){ x1=x2=me.y2).*.y1=y2. y2=me.MouseMotionListener Example: The following program demonstrates Mouse event handling.getY(). Source: Mouse Event Class: java.getY().y1.MouseEvent Listener Interface: java. addMouseListener(this). Graphics g=this.event. x2=me.CS55 PROGRAMMING PARADIGMS Handling Mouse Events To handle Mouse events.*.getX().awt. Demo(String s){ super(s). class must implement the MouseListener & MouseMotionLiatener interface.

CS55 PROGRAMMING PARADIGMS public void paint(Graphics g){} public static void main(String arg[]){ Demo ob=new Demo("Mouse event Demo"). } } Page 72 of 158 © Einstein College of Engineering .

n1=Integer. add(lb2). b2. import java.ActionEvent Listener Interface: java. add(lb3).equals("Add")){ t3.getText()).awt.parseInt(t2.parseInt(t1. Button b1=new Button("Add"). TextField t2=new TextField(20). Label lb3 = new Label("Result").*.setText(String.getText()). Label lb2 = new Label("Number2"). add(lb1).addActionListener(this).event.addActionListener(this).addActionListener(this). } } public static void main(String arg[]){ Demo my=new Demo("Action event demo").*. class must implement the ActionListener interface.event.*. Text fields are used to get user input and show the result to the user. When the user presses Button.awt. } if(s.ActionListener Example: The following program demonstrates Action event handling. Listener receives the event and performs the operation specified in the actionPerformed Method.280). Source objects needs to register action listener to receive events. setLayout(flow). setVisible(true). } public void actionPerformed(ActionEvent ae){ String s=ae. n2=Integer. TextField t1=new TextField(20).awt. import java. } } Page 73 of 158 © Einstein College of Engineering .n2.CS55 PROGRAMMING PARADIGMS Action Event To handle Action events.add(t2).setText(String.add(t1). Source: Button Event Class: java.add(b2). Application window has 3 Text Fields and two buttons. Label lb1 = new Label("Number1").awt.add(t3).equals("Multiply")){ t3. add(b1).getActionCommand(). import javax.event. int n1. if(s. public class Demo extends Frame implements ActionListener{ FlowLayout flow=new FlowLayout(). Button b2=new Button("Multiply"). setSize(280. Demo(String s){ super(s). it will generate an action event. SourceObject.valueOf(n1+n2)). b1.swing.valueOf(n1*n2)). TextField t3=new TextField(20).

add(c6).awt. setVisible(true). import java.awt. Choice c=new Choice(). setLayout(flow). import java. public class Demo extends Frame implements ItemListener{ String msg="".add(c5). Application window has Text Field.*.event. Demo(String s){ super(s). Label lb1 = new Label("City"). c.ItemEvent Listener Interface: java. TextField t=new TextField(20).add(c2).event. A listener receives the event and performs the operation specified in the itemStateChanged() Method. Source: List. Text fields are used to show the result to the user. c.add(c1). c. then the selected item will be displayed in text field. Checkbox c1=new Checkbox("UG".add("Chennai"). add(t). Checkbox c4=new Checkbox("C++").add(c). c3.add(c3). and Choice. add(lb1). FlowLayout flow=new FlowLayout(). c. SourceObject.addActionListener(this). class must implement the ItemListener interface.add(c4). Label lb2 = new Label("Qualification"). Checkbox Event Class: java. When the user select item from any component. Page 74 of 158 © Einstein College of Engineering .addItemListener(this).cg. c1.addItemListener(this). Choice.false).awt.CS55 PROGRAMMING PARADIGMS Item Event To handle Item events. Source objects needs to register action listener to receive events.cg.c. add(lb2).awt.ItemListener Example: The following program demonstrates Item event handling. CheckboxGroup cg=new CheckboxGroup().add("KanyaKumari"). Checkbox.300).event. Checkbox c5=new Checkbox("Java"). add(lb3). Checkbox c2=new Checkbox("PG". setSize(200.add("Tirunelveli").addItemListener(this).c.add("Coimbatore").*.add("Madurai"). Label lb3 = new Label("Languages Known"). Checkbox c3=new Checkbox("Visual Basic"). c2.true). Checkbox c6=new Checkbox("dotnet").addItemListener(this).

2. Each container object has a layout manager associated with it. 1. Page 75 of 158 © Einstein College of Engineering .addItemListener(this).Border Layout Whenever a container is resized.Applet . General syntax for setting layout to container Void setLayout(LayouManager obj) Layout Managers are      FlowLayout BorderLayout Grid Layout GridbagLayout BoxLayout Arrange component without using layout Manager: You can position components manually using setBounds() method defined by Component class.CS55 PROGRAMMING PARADIGMS c4. } public void itemStateChanged(ItemEvent ie){ String msg=(String)ie. Givethe location and size of the component which is to be added in the container.getItem(). c6. } public static void main(String arg[]){ Demo ob=new Demo("List event Demo").setText(msg). the layout manager is used to position each of the components within it.   Panel. c5. } } Output: Layout Management Layout manager automatically arranges several components within a window.addItemListener(this).Flow Layout Frame . t. setLayout(null). Disable the default manager of your container.addItemListener(this).

Similarly.setBounds(10. FlowLayout arranges components in rows. public class Demo extends Frame{ FlowLayout flow=new FlowLayout().50. } } Page 76 of 158 © Einstein College of Engineering . } public static void main(String arg[]){ Demo ob=new Demo("FlowLayout Demo").*. The flow layout manager lines the components horizontally until there is no more room and then starts a new row of components. the layout manager automatically reflows the components to fill the available space. Button b1=new Button("one"). FlowLayout FlowLayout arranges the components in rows from left-to-right and top-to-bottom order based on the order in which they were added to the container.create default layout. If you reduce the width of the frame further. b. Button b3=new Button("Three"). Constructor:   FlowLayout() .CS55 PROGRAMMING PARADIGMS setBounds(int x. then portions of the wider components begin to disappear. which centers component and leaves 5 pixels spaces between each component. the components in each row will appear next to the left edge of the container. and if you use a constructor that doesn’t accept these values. int height). setLayout(flow). int y. they both default to 5. Button b2=new Button("Two"). eg: Button b=new Button(―click me‖). and the alignment specifies the alignment of the rows.10. add(b1). FlowLayout(int how)-specify how ech line is aligned. int width.awt.20). Demo(String s){ super(s).200).add(b2). some of the components will become partially or completely inaccessible import java.add(b3). The FlowLayout constructors allow you to specify the horizontal and vertical gaps that should appear between components. if you reduce the frame’s vertical size so that there’s not enough vertical space to display all rows. if you create a FlowLayout that’s left aligned. For example. setVisible(true). setSize(200. When the user resizes the container.

int vspace) . Cells are always same size.construct a grid with specified rows and cols. int cols.to specify the amount of horizontal and vertical space that should appear between adjacent components. GridLayout creates as many rows as it needs to display all the components using the specified number of columns. Page 77 of 158 © Einstein College of Engineering . Constructor   GridLayout(int rows. but not both. Demo(String s){ super(s).awt. and you can add a component to each area. } public static void main(String arg[]){ Demo ob=new Demo("GridLayout Demo").add(b2). import java. Button b3=new Button("Three"). When you create a GridLayout. setVisible(true).add(b3). the cells grow and shrink.*. int cols). When you resize the window. Button b2=new Button("Two"). GridLayout(int rows. setSize(200. public class Demo extends Frame{ GridLayout grid=new GridLayout(2.200). you can specify a value of 0 for either the row count or the column count. add(b1). int hspace. Button b1=new Button("one"). setLayout(grid). evenly allocating the space among all the cells in the grid and placing one component in each cell. but all the cells have identical sizes.CS55 PROGRAMMING PARADIGMS GridLayout The GridLayout layout manager divides the available space into a grid of cells. If you set the number of rows to 0. } } BorderLayout BorderLayout divides the container into five areas.2).

Gridlayout without limitations Page 78 of 158 © Einstein College of Engineering . right. bottom.NORTH). } public static void main(String arg[]){ Demo ob=new Demo("BorderLayout Demo"). along with one in the center.BorderLayout.CENTER). and CENTER for the top. int vspace) – leave space between components. SOUTH.EAST).SOUTH).CENTER|NORTH|SOUTH|EAST|WEST void add(Component obj. } } GridBag Layout . Button b5=new Button("five"). constraint) import java. Constructor   BorderLayout() BorderLayout(int hspace. and center regions.awt.BorderLayout. setSize(200. bottom.BorderLayout. add(b4. public class Demo extends Frame{ BorderLayout grid=new BorderLayout(). Button b2=new Button("Two"). add(b1. add(b2.WEST). setVisible(true). Button b4=new Button("four"). add(b5. add(b3.BorderLayout. left.*.200). Button b3=new Button("Three"). respectively. setLayout(grid).BorderLayout. Border layout grows all components to fill the available space. Each of the five areas is associated with a constant value defined in BorderLayout: NORTH.BorderLayout. and right sides of the container. EAST. Demo(String s){ super(s).CS55 PROGRAMMING PARADIGMS The five regions correspond to the top. WEST.You can add components by specifying a constraint . Button b1=new Button("one"). left.

This object will specify how the components are laid out within the grid bag.specify the row position of the component to be added Gridwidth. Create an object of type GridBagLayout. gc1. 3. 2. GridBagConstraints gc2= new GridBagConstraints(). gc3. gc2. gc1. gc3. gc3.gc1). GridBagConstraints gc3= new GridBagConstraints(). setLayout(gb).*. Set this GridBagLayout object to the container. Create an object of type GridBagConstraints. GridBagConstraints:     Gridx – specify the column position of the component to be added Gridy . GridBagConstraints gc1= new GridBagConstraints(). constraint).gridy=0.CS55 PROGRAMMING PARADIGMS In Grid bag layout. For each components.gridx=0.awt.gc2). public class Demo extends Frame{ GridBagLayout gb=new GridBagLayout().swing Page 79 of 158 © Einstein College of Engineering . you must follow the procedure 1. It is possible to merge two adjacent cells and make a space for placing larger components.gridwidth=1. gc1. } public static void main(String arg[]){ Demo ob=new Demo("GridBagLayout Demo"). No need to specify rows and column. Button b2=new Button("Two").gridwidth=2. gc2. gc2.Finally add the component with the constraint by using the call add(Component. gc2. fill in the GridBagConstraints object. add(b1.gridy=1.gridheight=1.gridx=0. Button b1=new Button("one"). the rows and columns have variable sizes. gc3.add(b2.gridheight=1. Demo(String s){ super(s). 4.gridheight=1. Button b3=new Button("Three"). To describe the layout to grid bag manager. }} BoxLayout – javax.200). setVisible(true). gc1.add(b3.specify how many rows occupied by the component import java.gridwidth=1.specify how many columns occupied by the component Gridheight . setSize(200.gridy=1.gc3).gridx=1.

f.setSize(200. you have to define all of methods in it. It is useful when you want to receive and process only some of the events that are handled by an event listener interface. Some Adapter classes are    KeyAdapter MouseAdapter MouseMotionAdapter Example: If the user only interest in mouse pressed event. If you implement the interface. so you can only redefine the methods that you needed. Components are arranged either vertically from top to bottom or horizontally from left to right BoxLayout(Container Obj.println("Mouse pressed.event. This adapter class defines null methods for all events. The following program listening MouseEvent whenever the user press the mouse it will print ―mouse pressed‖ text on c ommand prompt.awt. f. import java.then simply extends MouseAdapter class and redefine the mousePressed event.out. } public void mousePressed(MouseEvent me){ System.*. Define a new class that extends the adapter class and overrides the desired methods only. Adapter classes An adapter class provides an empty implementation of all methods in an event listener interface.awt.setVisible(true). import java.addMouseListener(ob).. Extends adapter class to create Listener and override the desired methods."). BoxLayout.200).*. public class Demo extends MouseAdapter{ public static void main(String arg[]){ Frame f=new Frame("Mouse Adapter Demo"). } } Page 80 of 158 © Einstein College of Engineering . Demo ob=new Demo(). f.CS55 PROGRAMMING PARADIGMS Arrange components in single row or single column.X_AXIS | Y_AXIS).

CS55 PROGRAMMING PARADIGMS Page 81 of 158 © Einstein College of Engineering .

The controller decides how each component will react to the event —if it reacts at all.(includes state data for each component) The model encompasses the state data for each component. There are different models for different types of components.CS55 PROGRAMMING PARADIGMS Model-View-Controller design pattern Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each of its components. Essentially. Model .(handles user Input) The controller decides the behavior of each component with respect to the events. This information remains the same no matter how the component is painted on the screen. Page 82 of 158 © Einstein college of engineering . View . Events come in many forms (a mouse click. Model has no user interface. MVC breaks GUI components into three elements.(to display component on screen) The view refers to how you see the component on the screen. Model data always exists independent of the component's visual representation. model of a Choice list might contain the information about list of items and currently selected item. Controller. a keyboard event). It determines exactly where and how to draw the choice list by the information offered by the model. For example. Each of these elements plays a crucial role in how the component behaves.

the view. Page 83 of 158 © Einstein college of engineering . and the controller—requires the services of another element to keep itself continually updated. each of the three elements—the model.CS55 PROGRAMMING PARADIGMS MVC Interaction In MVC.

tress tables. Simplified graphics to paint on screen Similar behaviour across all platforms Portable look and feel Only a few top level containers not lightweight. text components. view.     New components -. components are platform independent.CS55 PROGRAMMING PARADIGMS Introduction to Swing Swing Features   Pluggable look-and feels -. components are platform dependent. AWT components support Delegate Swing components support MVC (model. sliders progress bars. Event Model. 2 Swing Swing components are light weight.as above Lightweight components o o o o o Do not depend on native peers to render themselves.No AWT(Abstract Window Toolkit) 1 AWT components are heavy weight. Tooltips -. control architecture) 3 AWT components provide static look Swing components provide dynamic look and feel.textual popup to give additional help arbitrary keyboard event binding Debugging support Difference between AWT and Swing S. frames. and feel It provide Tooltip text for components 4 It does not provide Tooltip text for components Page 84 of 158 © Einstein college of engineering .

int numChars) JTextArea JTextArea(int numLines. int numLines. int horizontalAlignment) Methods void setText(String str) String getText( ) JButton JButton( ) JButton(String str) void setLabel(String str) String getLabel( ) Object getSelectedValue( ) int getSelectedIndex( ) String[] getSelectedItems( ) JList JList() JList(String[] ) JRadioButton JRadioButton() JRadioButton(String text) JRadioButton(String text. Icon icon) boolean getState( ) void setState(boolean on) String getLabel( ) void setLabel(String str) String getText( ) void setText(String str) void canEdit) setEditable(boolean JTextField JTextField(int numChars) JTextField(String str. int columns) The JLabel Class Page 85 of 158 © Einstein college of engineering .CS55 PROGRAMMING PARADIGMS Swing Components javax. boolean on) JCheckBox(String text. int numChars) JTextArea(String str.swing Component JLabel Constructor JLabel() JLabel(String text) JLabel(String text. int index) void setEchoChar(char echo) JPasswordField JPasswordField(String text. int numChars) void append(String str) void insert(String str. boolean selected) JRadioButton(String text. boolean selected) JComboBox JComboBox() JComboBox(Object items[]) void add(String name) String getSelectedItem( ) int getSelectedIndex( ) JCheckbox JCheckbox( ) JCheckbox(String str) JCheckbox(String str. Icon icon.

The JRadioButton Class JRadioButtons. Text Input In Java.awt. A JCheckBox is usually rendered by showing a small box into which a "check" is placed when selected. both.awt. typically an asterisk (*). or none of the two check boxes.CS55 PROGRAMMING PARADIGMS Swing allows you to create labels that can contain text. The classes are called JTextField for single-line input and JTextArea for multiple lines of text. The JCheckBox Class It is used to allow the user to turn a given feature on or off. or both. 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. allowing users to make a single selection from a set of options. Page 86 of 158 © Einstein college of engineering . Instead. JButtons fire ActionEvents when they are clicked. Unlike java.Buttons. The Swing set supplies a JPasswordField class that implements such a text field. images.Label objects. To avoid nosy bystanders being able to glance at a password. The JPasswordField Class Password fields are a special kind of text field. The user could check either. The JButton Class They are typically used much like java. the characters that the user entered are not actually displayed. or to make multiple selections from a set of choices. two components are used to get text input:   JTextField JTextArea. each typed character is represented by an echo character. JLabel objects may consist of both text and graphics (icons).

It is very similar to the AWT Choice component. however. The user can be permitted. remember. The Swing JList component lifts this restriction. allowing the user to make either a single selection or multiple selections. The JComboBox Class A combo box component is actually a combination of a Swing list and a text field. List elements can now be strings.AWT limited the contents of its List component to strings. setting a layout manager (this can be set in the constructor and defaults to a FlowLayout).awt. Typically. which is usually copied into an editable component at the top. Unlike lists. using JPanel amounts to instantiating it. to manually enter in a selection as well. images. Page 87 of 158 © Einstein college of engineering . extends java. such as a text field. The JPanel Class JPanel is an extension of JComponent (which.CS55 PROGRAMMING PARADIGMS The JList Class A list is a graphical component from which the user can select choices.Container) used for grouping together other components. Lists typically display several items at a time. and adding components to it using the add() methods inherited from Container. a combo box only allows the user one selection at a time. It gets most of its implementation from its superclasses. JComboBox is the Swing version of a combo box component.

respectively. generic interface declarations. A method is generic if it declares one or more type variables. It defines one or more type variables that act as parameters. A generic class declaration defines a set of parameterized types. double and char in this example. These type variables are known as the formal type parameters of the method. 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. one for each possible invocation of the type parameter section. All of these parameterized types share the same class at runtime. a Double array and a Character array. All parameterized types share the same interface at runtime. These type variables are known as the formal type parameters of the constructor. We chose to use arrays of typeInteger. A constructor is generic if it declares one or more type variables. Double and Character to set up our generic method example. To motivate generic methods. because only reference types can be used with generic methods and classes. and by generic constructor declarations. independently of whether the class the constructor is declared in is itself generic. one for each possible invocation of the type parameter section. Page 88 of 158 © Einstein college of engineering . An interface is generic if it declares one or more type variables. 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. A class is generic if it declares one or more type variables. The form of the formal type parameter list is identical to a type parameter list of a generic class or interface. A generic interface declaration defines a set of types. It defines one or more type variables that act as parameters. These type variables are known as the type parameters of the interface.     Motivation for Generics: Overloaded methods are often used to perform similar operations on different types of data. Note that we could have used arrays of primitive types int. These type variables are known as the type parameters of the class. Type variables are introduced by generic class declarations. A constructor can be declared as generic.CS55 PROGRAMMING PARADIGMS Unit IV Generic Programming: Generics are a facility of generic programming that was added to the Java programming language. The form of the formal type parameter list is identical to a type parameter list of a class or interface. As per Java Language Specification:  A type variable is an unqualified identifier. generic method declarations.

3. 5. System. 5. 6.out. element ). 'L'.out. System.out. 6 }. Double[] doubleArray = { 1.println( "\nArray doubleArray contains:" ). 4. } // end method printArray // method printArray to print Double array public static void printArray( Double[] inputArray ) { // display array elements for ( Double element : inputArray ) System. 2. 3.out.1. // pass a Character array Page 89 of 158 © Einstein college of engineering . element ). System. 4.println( "Array integerArray contains:" ).2. printArray( characterArray ).println(). 7. // pass a Double array System.printf( "%s ".out. Character[] characterArray = { 'H'. Double and Character Integer[] integerArray = { 1. 'L'.printf( "%s ".out.6.println( "\nArray characterArray contains:" ).out. // pass an Integer array System. printArray( doubleArray ).5.printf( "%s ". 'E'.7 }. 3. 2.out.println(). 'O' }. } // end method printArray public static void main( String args[] ) { // create arrays of Integer.println().CS55 PROGRAMMING PARADIGMS public class OverloadedMethods { // method printArray to print Integer array public static void printArray( Integer[] inputArray ) { // display array elements for ( Integer element : inputArray ) System. printArray( integerArray ).out.4. } // end method printArray // method printArray to print Character array public static void printArray( Character[] inputArray ) { // display array elements for ( Character element : inputArray ) System. System. element ).

String>("mike". System. } public T getFirst() { return first. The generic type information is then removed via a process called type erasure.4 5. } This generic class can be used in the following way: Pair<String. Pair<String.toString() + ".toString() + ")". Integer> marks440 = new Pair<String. System. S> { public Pair(T f. S s) { first = f.toString()).7 Array characterArray contains: HELLO Generic class definitions Here is an example of a generic class: public class Pair<T. For example.out. " + second. } public String toString() { return "(" + first.3 4.1 2. Type erasure Generics are checked at compile-time for type correctness.println("grade:" + grade440. 100).out. } public S getSecond() { return second. List<Integer> will be Page 90 of 158 © Einstein college of engineering . private S second. "A"). Integer>("mike".5 6.toString()).6 7.CS55 PROGRAMMING PARADIGMS } // end main } // end class OverloadedMethods Array integerArray contains: 123456 Array doubleArray contains: 1. String> grade440 = new Pair<String.2 3. } private T first.println("marks:" + marks440. second = s.

there is no way to tell at runtime which type parameter is used on an object. Static variables and static methods are "outside" of the scope of the class's parameterized types. As a result. As a result.getClass()) // evaluates to true System. Static methods. the resulting code is guaranteed to be type correct. for(int k = 0. For example.println("Equal"). the Java compiler does not need to know which parameterized type is used because the type information is validated at compile-time and erased from the compiled code. ArrayList<Float> lf = new ArrayList<Float>(). static variables are shared among all the instances of the class. Furthermore. nonstatic methods. and constructors can all be parameterized in almost the same way as for classes and interfaces. when you examine an ArrayList at runtime. Java generics generate only one compiled version of a generic class or function regardless of the number of types used.k++) { System. Generic methods: Generic Methods Genericity is not limited to classes and interfaces. Generic methods are also invoked in the same way as non-generic methods. one cannot instantiate a Java class of a parameterized type because instantiation requires a call to a constructor. However. T instantiateElementType(List<T> arg) { return new T(). ArrayList<Integer> li = new ArrayList<Integer>(). there is no general way to tell whether it was an ArrayList<Integer> or an ArrayList<Float>. if the list is empty or if its elements are subtypes of the parameterized type. due to the compile-time check. as long as the code generated no unchecked compiler warnings. Java generics differ from C++ templates.k<c. but the syntax is a bit different.next()).CS55 PROGRAMMING PARADIGMS converted to the raw type (non-generic type) List. The exception to this is by using Reflection on existing list elements. The following code demonstrates that the Class objects appear the same.getClass() == lf.out.size(). if (li. which can contain arbitrary objects. even Reflection will not divulge the parameterized type. consider the following segment of code that prints out all the elements in a collection: public void printCollection(Collection c) { Iterator i = c. regardless of their type parameter. However.println(i. Before we see an example of a generics method. Consequently. the type parameter cannot be used in the declaration of static variables or in static methods.iterator(). //causes a compile error } Because there is only one copy of a generic class. which is not possible when the type is unknown at both compile-time and runtime. you can define generic methods. } Page 91 of 158 © Einstein college of engineering .out.

1 2.out.CS55 PROGRAMMING PARADIGMS } Using generics.6. 'O' }. // pass a Double array System. } } Example: public class GenericMethodTest { // generic method printArray public static < E > void printArray( E[] inputArray ) { // display array elements for ( E element : inputArray ) System. 7. printArray( characterArray ).out.println( "Array integerArray contains:" ). 'E'.2 3. For example.out. } // end method printArray public static void main( String args[] ) { // create arrays of Integer. printArray( integerArray ).println(). a method that operates on numbers might only Page 92 of 158 © Einstein college of engineering .3.6 7. Note that the Collection<?> is the collection of an unknown type. 3. 2. this can be re-written as follows.println(o). 4. 5.5. // pass a Character array } // end main } // end class GenericMethodTest Array integerArray contains: 1 2 3 4 5 6 Array doubleArray contains: 1. 4.4. Character[] charArray = { 'H'.println( "\nArray characterArray contains:" ). 6.2. Double and Character Integer[] intArray = { 1.4 5.printf( "%s ". element ).5 6.out.3 4. 'L'.7 Array characterArray contains: H E L L O Bounded Type Parameters: There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter.7 }. Double[] doubleArray = { 1.1. System. void printCollection(Collection<?> c) { for(Object o:c) { System.out. System. 2.println( "\nArray doubleArray contains:" ).out. 5 }. 'L'. printArray( doubleArray ). // pass an Integer array System. 3.

out.inspect("10"). followed by its upper bound. ^ 1 error To specify additional interfaces that must be implemented. compilation will now fail. public class Box<T> { private T t.getName()).out.lang. followed by the extends keyword. use the & character.CS55 PROGRAMMING PARADIGMS want to accept instances of Number or its subclasses.Integer> cannot be applied to (java. extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).String) integerBox. This is what bounded type parameters are for.t = t. list the type parameter's name. Exceptions may occur in any programming language. which in this example is Number. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing.java:21: <U>inspect(U) in Box<java. as in: <U extends Number & MyInterface> Exceptions: Exceptions are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program. } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(). System. integerBox.inspect("some text"). } public T get() { return t. since our invocation of inspect still includes a String: Box.println("T: " + t.println("U: " + u.getName()). } public <U extends Number> void inspect(U u){ System. public void add(T t) { this. integerBox.getClass(). Note that. in this context.add(new Integer(10)). // error: String! } } this is still By modifying our generic method to include this bounded type parameter. Page 93 of 158 © Einstein college of engineering .lang. To declare a bounded type parameter.getClass().

FileReader and opens the file. However if you do not provide the name of any existing file then the constructor throwsjava.io. Hence this exception will be caught by a well-written application and will also prompt to correct the file name. However Java provides mechanisms to handle such situations through its superb exception handling mechanism. Exception Hierarchy: There are three types of Exceptions: 1.These are the exceptions which occur during the compile time of the program. Here is the list of checked exceptions. These exceptions do not extend RuntimeException class and must be handled to avoid a compile-time error by the programmer. Remember that all the exceptions are checked exceptions unless and until those indicated by Error. Page 94 of 158 © Einstein college of engineering . These exceptions extend the java. Checked Exceptions .CS55 PROGRAMMING PARADIGMS Occurrence of any kind of exception in java applications may result in an abrupt termination of the JVM or simply the JVM crashes which leaves the user unaware of the causes of such anomalous conditions. Furthermore Checked exceptions are required to be caught. Then it passes the name to the constructor for java.Exception class These exceptional conditions should be anticipated and recovered by an application. RuntimeException or their subclasses.FileNotFoundException which abrupt the application to succeed.lang.io. For example if you call the readLine() method on a BufferedReader object then the IOException may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. The compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. The Java programming language uses Exception classes to handle such erroneous conditions and exceptional events.

divide by zero etc. such as logic errors or improper use of an API. IndexOutOfBoundsException ArrayIndexOutOfBoundsException ClassCastException ArithmeticException NullPointerException IllegalStateException SecurityException Page 95 of 158 © Einstein college of engineering .lang.CS55 PROGRAMMING PARADIGMS NoSuchFieldException InstantiationException IllegalAccessException ClassNotFoundException NoSuchMethodException CloneNotSupportedException InterruptedException 2. You must have encountered the most common exception in your program i.Exceptionclass. the constructor will throwNullPointerException if a logic error causes a null to be passed to the constructor.e. the ArithmeticException.Unchecked exceptions are the exceptions which occur during the runtime of the program. These type of exceptions are also calledRuntime exceptions that are usually caused by data errors. Unchecked exceptions are internal to the application and extend the java. Here is the list of unchecked exceptions. Lets take the same file name example as described earlier.RuntimeException that is inherited from java. These exceptions cannot be anticipated and recovered like programming bugs. like arithmetic overflow. However.lang. In that example the file name is passed to the constructor for FileReader. Well in this case the exception could be caught by the application but it would rather try to eliminate the bug due to which the exception has occurred. Similarly when an instance data member or method of a reference variable is to be accessed that hasn't yet referenced an object throws NullPointerException. Unchecked Exceptions . I am sure you must be familiar with the reason of its occurrence that is when something tries to divide by zero.

Error exceptions belong to Error and its subclasses are not subject to the catch or Specify requirement. Any statements following the "throw" statement are not executed. Most such errors are abnormal conditions. it has to declare the exception(s) thrown in the method signature. An Error indicates serious problems that a reasonable application should not try to catch.io. int numberToDivideBy) throws BadNumberException{ if(numberToDivideBy == 0){ throw new BadNumberException("Cannot divide by 0"). and then include a throw-statement in the method.CS55 PROGRAMMING PARADIGMS 3. In the example above the "return numberToDivide / numberToDivideBy. } return numberToDivide / numberToDivideBy. Throwing Exceptions If a method needs to be able to throw an exception. You can throw any type of exception from your code." statement is not executed if a BadNumberException is thrown. Here is an example: public void divide(int numberToDivide. Exceptions are regular Java classes that Page 96 of 158 © Einstein college of engineering . Catching exceptions is explained later.The errors in java are external to the application. } When an exception is thrown the method stops execution right after the "throw" statement. as long as your method signature declares it. You can also make up your own exceptions. Error . These are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered from. This error will cause the program to terminate but if an application wants then the error might be caught. Suppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.IOError would be thrown. Hence we conclude that Errors and runtime exceptions are together called as unchecked exceptions. The program resumes execution when the exception is caught somewhere by a "catch" block.

out.println("Division attempt done"). If an exception is thrown inside the catch-block and that exception is not caught. the calling method is forced to either pass the exception on.println(e. callDivide. for instance from the divide method. the catch-block is simply ignored.println(result). the catch-block is interrupted just like the try-block would have been. If an exception is thrown inside the try-block. } The BadNumberException parameter e inside the catch-clause points to the exception thrown from the divide method.Exception. or catch it.1). } catch (BadNumberException e) { //do something clever with the exception System.out. is interrupted just like the program flow inside divide.out.println(result). Page 97 of 158 © Einstein college of engineering . or any of the other built-in exception classes. Catching the exception is done using a try-catch block.out. Here is an example: public void callDivide(){ try { int result = divide(2. } System. System. It will not be executed.getMessage()). Catching Exceptions If a method calls another method that throws checked exceptions." statement will not get executed if an exception is thrown fromt the divide method. In the example above the "System. If no exeception is thrown by any of the methods called or statements executed inside the try-block. Instead program execution will resume inside the "catch (BadNumberException e) { }" block. the program flow of the calling method.CS55 PROGRAMMING PARADIGMS extends java.lang. If a method declares that it throws an exception A. if an exception is thrown. then it is also legal to throw subclasses of A. The program flow resumes at a catch-block in the call stack that can catch the thrown exception.

If you cannot do anything about the exception where the method throwing it is called." method will not get executed if an exception is thrown from the divide method.CS55 PROGRAMMING PARADIGMS When the catch block is finished the program continues with any statements following the catch block. If you do so the method calling the method that throws the exception must also declare to throw the exception. Page 98 of 158 © Einstein college of engineering .println("Division attempt done"). } Notice how the try-catch block is gone. The exception is propagated to the method that calls callDivide. Propagating Exceptions You don't have to catch exceptions thrown from other methods. Here is how the callDivide() method would look in that case. In the example above the "System.out. System.1). and the callDivide method now declares that it can throw a BadNumberException. public void callDivide() throws BadNumberException{ int result = divide(2. All methods in the call stack between the method throwing the exception and the method catching it have their execution stopped at the point in the code where the exception is thrown or propagated. The program execution is still interrupted if an exception is thrown from the divide method. Program execution doesn't resume until a catch-block somewhere in the call stack catches the exception.out.out.println(result). Example: Catching IOException's If an exception is thrown during a sequence of statements inside a try-catch block." statement will always get executed.println(result). This code can be interrupted by exceptions in several places: public void openFile(){ try { // constructor may throw FileNotFoundException FileReader reader = new FileReader("someFile"). the sequence of statements is interrupted and the flow of control will skip directly to the catch-block. you can just let the method propagate the exception up the call stack to the method that called this method. But now the program execution is not resumed inside the callDivide method. Thus the "System.

} If an exception is thrown from the reader.out.. the following System. statements.println("--.File End --").File End ---"). If the calling method also just throws the method on. Example: Propagating IOException's This code is a version of the previous method that throws the exceptions instead of catching them: public void openFile() throws IOException { FileReader reader = new FileReader("someFile").close(). the exception will be caught there.println("--. the calling method is also interrupted at the openFile() method call. System.println((char) i ). If the calling method has a try-catch block. and the exception is passed up the call stack to the method that called openFile().out.CS55 PROGRAMMING PARADIGMS int i=0.out.println((char) i ). System.read() method call throws an IOException.close().println("--. } reader.out..read(). while(i != -1){ i = reader. } catch clause.close() or the System. If the new FileReader("someFile"). Neither is the last reader. is not executed. Instead the program skips directly to the catch(IOException e){ .read() method then program execution is halted.read(). and the Page 99 of 158 © Einstein college of engineering .read() may throw IOException i = reader. constructor call throws an exception. } catch (FileNotFoundException e) { //do something clever with the exception } catch (IOException e) { //do something clever with the exception } } If the reader. none of the code inside the try-block is executed.out.println((char) i ). } reader.out. int i=0. System.File End ---"). while(i != -1){ //reader. System.

even if an exception is thrown from within the try or catch block. The exception is propagated up the call stack like this until some method catches the exception. or the Java Virtual Machine does.println("--.CS55 PROGRAMMING PARADIGMS exception passed on up the call stack. } } catch (IOException e) { //do something clever with the exception } finally { if(reader != null){ try { reader. the code inside the finally-block will get executed before returning from the method. while(i != -1){ i = reader.out. try { reader = new FileReader("someFile"). then that finally block is interrupted just like the try-block and catch-block is. The example above shows how the file reader is always closed. and it is not caught. } catch (IOException e) { //do something clever with the exception } } System. Here is how a finally clause looks: public void openFile(){ FileReader reader = null. System. If your code has a return statement inside the try or catch block. int i=0.File End ---"). That is why the previous example had the Page 100 of 158 © Einstein college of engineering . The code inside the finally clause will always be executed.println((char) i ). Note: If an exception is thrown inside a finally block.out. } } No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed.close().read(). Finally You can attach a finally-clause to a try-catch block. regardless of the program flow inside the try or catch block.

} } Page 101 of 158 © Einstein college of engineering . try { reader = new FileReader("someFile"). More about checked and unchecked in a later chapter.println((char) i ).close(). } catch (IOException e) { //do something clever with the exception } } System.println("--. } catch (IOException e) { //do something clever with the exception } } System. } That way the System.out.close().out. If no unchecked exceptions are thrown that is.read().println("--.close() method call in the finally block wrapped in a trycatch block: } finally { if(reader != null){ try { reader.CS55 PROGRAMMING PARADIGMS reader. You can have one of them or both of them with a try-block.out. method call will always be executed. This code doesn't catch the exception but lets it propagate up the call stack. Due to the finally block the code still closes the filer reader even if an exception is thrown.File End ---").File End ---").File End ---"). int i=0. You don't need both a catch and a finally block. but not none of them.println("--. while(i != -1){ i = reader. } } finally { if(reader != null){ try { reader. System.out. public void openFile() throws IOException { FileReader reader = null.

Applications make logging calls on Logger objects. For example. Some Handlers may direct output to other Handlers. By default all Loggers also send their output to their parent Logger. Loggers are organized in a hierarchical namespace and child Loggers may inherit some logging properties from their parents in the namespace. But Loggers may also be configured to ignore Handlers higher up the tree. Each Logger keeps track of a set of output Handlers. These Logger objects allocate LogRecord objects which are passed to Handler objects for publication. Via a logger you can save text to a central place to report on errors. provide additional information about your program. In such cases. Logging: The JDK contains the "Java Logging API". the MemoryHandler maintains an internal ring buffer of LogRecords and on trigger events it publishes its LogRecords through a target Handler.CS55 PROGRAMMING PARADIGMS Notice how the catch block is gone. When it is necessary to publish a LogRecord externally. etc. Page 102 of 158 © Einstein college of engineering . This logging API allows to configure how messages are written by which class with which priority Overview of Control Flow Applications make logging calls on Logger objects. Both Loggers and Handlers may use logging Levels and (optionally) Filters to decide if they are interested in a particular LogRecord. any formatting is done by the last Handler in the chain. a Handler can (optionally) use a Formatter to localize and format the message before publishing it to an I/O stream.

with the highest value). client code sends log requests to Logger objects. but is not required to follow it slavishly. The namespace is hierarchical and is managed by the LogManager. and discards log requests that are below this level. using dot-separated names such as "java. but it might also handle logging for classes in Page 103 of 158 © Einstein college of engineering . The namespace should typically be aligned with the Java packaging namespace.CS55 PROGRAMMING PARADIGMS The APIs are structured so that calls on the Logger APIs can be cheap when logging is disabled. localization and formatting (which are relatively expensive) are deferred until the Handler requests them. Log Levels Each log message has an associated log Level. For example.awt". with higher values indicating higher priorities. ranging from FINEST (the lowest priority. For example. The Level gives a rough guide to the importance and urgency of a log message.awt package. Loggers As stated earlier. then the Logger can make a cheap comparison test and return. If logging is enabled for a given log level. Log level objects encapsulate an integer value. If logging is disabled for a given log level. Each logger keeps track of a log level that it is interested in. a MemoryHandler can maintain a circular buffer of LogRecords without having to pay formatting costs. the Logger is still careful to minimize costs before passing the LogRecord into the Handlers.awt" might handle logging requests for classes in the java. In particular. with the lowest value) to SEVERE (the highest priority. Loggers are normally named entities. a Logger called "java. The Level class defines seven standard log levels.

A logger's parent is its nearest extant ancestor in the logging namespace. Anonymous loggers are all given the root logger as their parent... See section 1. then it will inherit any resource bundle name defined for its parent. For convenience. If a logger has a null resource bundle name. a logger may inherit:    Logging level." There are two different styles of logging methods. Second. These are intended for Page 104 of 158 © Einstein college of engineering . Thus rather than calling "logger.CS55 PROGRAMMING PARADIGMS sun. there are a set of methods that do not take explicit source class or source method names.awt that support the client-visible abstractions defined in the java. named after the logging level name. In particular. Logging Methods The Logger class provides a large set of convenience methods for generating log messages. Resource bundle names. By default a Logger will log any output messages to its parent's handlers. it is also possible to create anonymous Loggers that don't appear in the shared namespace. String msg).warning(.. Loggers keep track of their parent loggers in the logging namespace. These methods are intended for developers who want to be able to quickly locate the source of any given logging message." a developer can simply call the convenience method "logger.. and so on recursively up the tree. An example of this style is: void warning(String sourceClass. Handlers. In addition to named Loggers. there are methods that take an explicit source class name and source method name. The root Logger (named "") has no parent. String sourceMethod. there are methods for each logging level.awt package. If a Logger's level is set to be null then the Logger will use an effective Level that will be obtained by walking up the parent tree and using the first non-null Level. and so on recursively up the tree.WARNING.log(Constants. First.. Loggers may inherit various attributes from their parents in the logger namespace. to meet the needs of different communities of users.14.

Handlers J2SE provides the following Handlers:      StreamHandler: A simple handler for writing formatted records to an OutputStream. It is fairly straightforward to develop new Handlers. For this second set of methods. Page 105 of 158 © Einstein college of engineering .err FileHandler: A handler that writes formatted log records either to a single file. MemoryHandler: A handler that buffers log records in memory. XMLFormatter: Writes detailed XML-structured information. Developers requiring specific functionality can either develop a Handler from scratch or subclass one of the provided Handlers. void warning(String msg). the Logging framework will make a "best effort" to determine which class and method called into the logging framework and will add this information into the LogRecord. or to a set of rotating log files. The LogManager There is a global LogManager object that keeps track of global logging information.CS55 PROGRAMMING PARADIGMS developers who want easy-to-use logging and do not require detailed source information. it is important to realize that this automatically inferred information may only be approximate. The latest generation of virtual machines perform extensive optimizations when JITing and may entirely remove stack frames. ConsoleHandler: A simple handler for writing formatted records to System. making it impossible to reliably locate the calling class and method. This includes:  A hierarchical namespace of named Loggers. SocketHandler: A handler that writes formatted log records to remote TCP ports. As with Handlers. However. Formatters J2SE also includes two standard Formatters:   SimpleFormatter: Writes brief "human-readable" summaries of log records. it is fairly straightforward to develop new Formatters.

Level The log levels define the severity of a message.Logger.getName()).INFO).util. For example the following will set the logger to level info which means all messages with severe.setLevel(Level. warning and info will be logged. To create a logger in your Java coding.getLogManager method.logging. Create a logger The package java. There is a single LogManager object that can be retrieved using the static LogManager. private final static Logger LOGGER = Logger. Page 106 of 158 © Einstein college of engineering . This property allows container applications (such as EJB containers) to substitute their own subclass of LogManager in place of the default class. The class Level is used to define which messages should be written to the log. import java.CS55 PROGRAMMING PARADIGMS   A set of logging control properties read from the configuration file.class .util. Die Log Levels in descending order are:        SEVERE (highest) WARNING INFO CONFIG FINE FINER FINEST In addition to that you have also the levels OFF and ALL to turn the logging of or to log everything. LOGGER. based on a system property.getLogger(MyClass. This is created during LogManager initialization.logging provides the logging capabilities via the class Logger.

example2. import java.logging. The first thing we will do is actually generate a logging message. in the tradition of * Kernighan and Ritchie. */ public class HelloWorld { private static Logger theLogger = Logger. } private String theMessage. we need to create a Logger object.sayHello(). public class HelloWorld { public static void main(String[] args) { HelloWorld hello = new HelloWorld("Hello world!").sayHello(). Page 107 of 158 © Einstein college of engineering .CS55 PROGRAMMING PARADIGMS An Example To help motivate the use of the logging API. which represents theHelloWorld class. based on the idea of a "Hello World" program.err. } private String theMessage. /** * A simple Java Hello World program. This is straightforward.println(theMessage).getName()). } } We will expand upon this simple program in order to demonstrate and motivate the logging API.getLogger(HelloWorld. public HelloWorld(String message) { theMessage = message. like this: package logging. } public void sayHello() { System.util.Logger. hello.class. hello. public static void main(String[] args) { HelloWorld hello = new HelloWorld("Hello world!"). we will use a simple program.

hello. Since you typically use one logger per class. public static void main(String[] args) { HelloWorld hello = new HelloWorld("Hello world!").err. } public void sayHello() { theLogger. appear before our message of "Hello world!". public class HelloWorld { private static Logger theLogger = Logger.Logger. } public void sayHello() { System.err). System. let's actually use the Logger to try to generate a logging message: import java.finest("Hello logging!"). we can make it a static field of the HelloWorld class. So we would expect to see the string "Hello logging!". in the form of aLogRecord to the console (System.logging. } private String theMessage. Now. it provides a handler that will send logging messages. } } The logging API has a configuration file and by default. We use the fully qualified name of the HelloWorld class as the name of theLogger. } } This generates a Logger.class.getLogger(HelloWorld.getName()).println(theMessage). But if you run this program you only see "Hello world!": Page 108 of 158 © Einstein college of engineering .sayHello().util. public HelloWorld(String message) { theMessage = message. We'll look at the reasons for this in more detail later.err. which we can use to generate logging messages.println(theMessage).CS55 PROGRAMMING PARADIGMS public HelloWorld(String message) { theMessage = message.

which has the following definition in ANSI C: void assert(int expression) java logging. the line #define NDEBUG Page 109 of 158 © Einstein college of engineering . Any line that executes after the assert statement can safely assume that acct is not null. Thus. an AssertionError is thrown. indicates a bug in the code.. note that the program will be larger in size and therefore slower to load.example3. and easier to maintain. and it has no effect if the expression evaluates to true. // . assertions do not have to be removed from the program. Note that assertions can be compiled out. This mechanism provides a way to detect when a program starts falling into an inconsistent state. more readable. you can use assertions through the assert macro.. this means using the preprocessor. This asserts that acct is not null. Assertions are excellent for documenting assumptions and invariants about a class. If acct is null. if evaluated as false. When testing and debugging is completed.HelloWorld The program will be aborted if the expression evaluates to false. However. Assertions An assertion has a Boolean expression that. assertions improve the odds that the behavior of a class matches the expectations of its clients. Using assertions helps developers write code that is more correct. When assertions are no longer needed..CS55 PROGRAMMING PARADIGMS % Hello world What's going on here? The answer lies in the notion of logging levels.. In languages such as C/C++. Here is a simple example of assertion: BankAccount acct = null. In C/C++. // Check to ensure we have one assert acct != null. // Get a BankAccount object // .

} Page 110 of 158 © Einstein college of engineering .exit(1). In this sample implementation. System. I am checking whether the value of NDEBUG is on (true) or off (false). But if it evaluates to false. } public static void assert(boolean expression.printStackTrace(). t. assertions should be executed with the code only when you are debugging your program -. Here is an example of how you would roll your own assertion class. be provided as an ad hoc solution. Note that in the assert method. public class Assertion { public static boolean NDEBUG = true. then the assertion is to be executed. You should write assertions into software in a form that can be optionally compiled. The user of this class is able to set assertions on or off by toggling the value of NDEBUG. Code Sample 1 shows my implementation. Otherwise.3 and earlier versions have no built-in support for assertions.CS55 PROGRAMMING PARADIGMS is inserted at the beginning of the program. This causes the C/C++ preprocessor to ignore all assertions. it would have no effect. Thus. If NDEBUG sets to true. instead of deleting them manually. You can think of assertions as a uniform mechanism that replaces the use of ad hoc conditional tests. however. Here we have an assert method that checks whether a Boolean expression is true or false. They can. private static void printStack(String why) { Throwable t = new Throwable(why). Implementing Assertions in Java Technology J2SE 1. If the expression evaluates to true. the assert method prints the stack trace and the program aborts. then there is no effect. when assertions will really help flush out errors. this is a requirement for performance reasons.that is. String why) { if (NDEBUG && !expression) { printStack(why). In other words. a second argument for a string is used so that the cause of error can be printed.

out. If the age is greater than or equal to 18.IOException. import java. public class AssertionTest2 { public static void main(String argv[]) throws IOException { System.print("Enter your marital status: "). use -source 1.out.4. and may not be used as an identifier (try -source 1. But if the age is less than 18.util.java:11: as of release 1. public class AssertionTest1 { public static void main(String argv[]) throws IOException { Scanner reader = new Scanner(System.Scanner. String why) { ^ 1 error Code Sample 2 demonstrates how to use the Assertion class. // use age System.assert(age>=18. int c = System. Assertion.CS55 PROGRAMMING PARADIGMS } } Note: In order for Code Sample 1 to compile.print("Enter your age: ").IOException. and shows the stack trace.read(). Page 111 of 158 © Einstein college of engineering .in. you will get the following error message: C:\CLASSES>javac Assertion. an integer representing the user's age is read. In this example. Otherwise. It is important to note that in this example assertions are used to validate user input and that no invariant is being tested or verified. displays the message You are too young to vote.io.java Assertion. 'assert' is a keyword.nextInt().NDEBUG=false. and it will have no effect on the program execution. } } import java.out. The program then aborts. This is merely to demonstrate the use of assertions. the assertion evaluates to false.io. System. //Assertion. "You are too young to vote"). the assertion evaluates to true.3 because assert is a keyword as of J2SE 1.3 or lower to use 'assert' as an identifier) public static void assert(boolean expression. import java.4.println("You are eligible to vote").in). int age = reader.

The errorMessage is an optional string message that would be shown when an assertion fails. case 'm': case 'M': System.out.println("Married").out. default: Assertion. case 'm': case 'M': System. case 'd': case 'D': System. break.*. As an example. public class AssertionTest3 { public static void main(String argv[]) throws IOException { System. break. I will modify Code Sample 3 to use the assert statement instead of my Assertion class.CS55 PROGRAMMING PARADIGMS //Assertion. switch ((char) c) { case 's': case 'S': System. int c = System. The assert statement can have one of two forms: assert booleanExpression.out.out. assert booleanExpression : errorMessage.print("Enter your marital status: ").io.out. break. as shown in Code Sample 4.in.println("Single"). break. "Invalid Option").out. Using Assertions Use the assert statement to insert assertions at particular points in the code.println("Single"). case 'd': Page 112 of 158 © Einstein college of engineering .NDEBUG=false. break.read().println("Married").println("Divorced"). uncomment the line Assert. switch ((char) c) { case 's': case 'S': System. import java.assert(!true.NDEBUG = false. break. } } } In the three examples. if you do not want assertions to be executed as part of the code.

assertions are disabled at runtime. because it may start functioning inappropriately after a failure. if you enter an invalid character. by default. might be to terminate the application. when an assertion fails.java:15) When an assertion fails. The switch -disableassertion (or -da) can be used to disable assertions. To enable assertions. In this case. so you must not assume that the Boolean expression contained in an assertion will be evaluated. This. For example. an AssertionError is thrown. nothing will happen.4 AssertionTest3. however.main(AssertionTest3. Possible behaviors may include suspending the program or allowing it to continue to run.lang. your expressions must be free of side effects. to run the program MyClass with assertions disabled in class Hello. break. you will get a compiler error saying that assert is a new keyword as of release 1.out. A good behavior. This is because. assertions are disabled. it will work fine. However. it means that the application has entered an incorrect state. is most useful when you wish to disable assertions on classes from specific packages. you can use the following command: Page 113 of 158 © Einstein college of engineering .AssertionError: Invalid Option at AssertionTest3. If you now run the program using the command prompt> java AssertionTest3 and you enter a valid character. } } } prompt> javac -source 1.4 option.4. Therefore.java If you try to compile your assertion-enabled classes without using the -source 1. default: assert !true : "Invalid Option".CS55 PROGRAMMING PARADIGMS case 'D': System. use the switch -enableassertion (or -ea) as follows: prompt> java -ea prompt> java -enableassertion AssertionTest3 AssertionTest3 Following is a sample run: C:\CLASSES>java -ea AssertionTest3 Enter your marital status: w Exception in thread "main" java. break.println("Divorced"). Note: By default. however.

tests.phone MyClass Note that when switches are combined and applied to packages.. The condition that the stack must not be empty is a precondition. to run a program with assertions enabled in the com..tests. return stack[--num].tests. The examples are snippets of code from an integer stack.ui.javacourses.. they do not apply to system classes. Preconditions In order to retrieve an item from the stack. Switches can be combined.phone. Using Assertions for Design by Contract The assertion facility can help you in supporting an informal design-by-contract style of programming.ui. We will now see examples of using assertions for preconditions. they are applied to all classes. including system classes (which do not have class loaders). MyClass Note that the three-dot ellipsis (. -da:com.javacourses. the stack must not be empty.javacourses.. For example. This precondition can be programmed using assertions as follows: public int pop() { // precondition assert !isEmpty() : "Stack is empty". use the switches -enablesystemassertions (or -esa) and disablesystemassertions (or -dsa). you can use the following command: prompt> java -da:com.javacourses. and class invariants. Page 114 of 158 © Einstein college of engineering . If you wish to turn assertions on or off in system classes.tests package (and any subpackages) and disabled in the class com. you can use the following command: prompt> java -ea:com.Hello MyClass And to disable assertions in a specific package and any subpackages it may have.javacourses..) is part of the syntax. if you use the command prompt> java -ea MyClass then assertions are enabled in all classes except system classes. In other words. which provides operations such as push to add an item on the stack and pop to retrieve an item from the stack. postconditions.. But if you use them with no arguments (-ea or -da).javacourses.CS55 PROGRAMMING PARADIGMS prompt> java -da:com.

we need to ensure that invoking the push operation is working correctly. if you make a mistake and you write this statement as stack[num] = element then you have a bug. we need to make sure that the element has been added on the stack. These conditions. stack[num] = element. the invariant would be that the number of elements in the stack is greater than or equal to zero and the number of elements should not exceed the maximum capacity of the class. public void push(int element) { // precondition assert num<capacity : "stack is full". However. To add an item on the stack. the stack must not be full. we assign the element to be added to the next index in the stack as follows: stack[num++] = element. then postconditions should be evaluated before each of these return statements. The following snippet of code shows the push operation with a precondition and a postcondition. } Note that if a method has multiple return statements. // postcondition assert num == oldNum+1 && stack[num-1] == element : "problem with counter". Postconditions In order to push an item on the stack. precondition checking can still be performed by checks inside methods that result in exceptions such asIllegalArgumentException or NullPointerException.CS55 PROGRAMMING PARADIGMS } Note: Because assertions might be disabled in some cases. In this case. Class Invariants A class invariant is a predicate that must be true before and after any method completes. int oldNum = num. can be coded as follows: Page 115 of 158 © Einstein college of engineering . In the stack example. This is a precondition. So the postcondition here is to ensure that the new index in the stack is the old index plus one. for example. Also.

a thread is born. runs. For example.CS55 PROGRAMMING PARADIGMS private boolean inv() { return (num >= 0 && num < capacity). right before each return. started. Multitasking threads require less overhead than multitasking processes. A process consists of the memory space allocated by the operating system that can contain one or more threads. because idle time can be kept to a minimum. Page 116 of 158 © Einstein college of engineering . Each part of such a program is called a thread. UNIT V Multi Threading: Java provides built-in support for multithreaded programming. each public method and constructor should contain the assertion assert inv(). } To check that the stack should satisfy this predicate at all times. A multithreading is a specialized form of multitasking. Life Cycle of a Thread: A thread goes through various stages in its life cycle. and each thread defines a separate path of execution. it must be a part of a process. A process remains running until all of the non-daemon threads are done executing. A thread cannot exist on its own. A multithreaded program contains two or more parts that can run concurrently. and then dies. Following diagram shows complete life cycle of a thread. Multithreading enables you to write very efficient programs that make maximum use of the CPU.

which is declared like this: Page 117 of 158 © Einstein college of engineering . Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. Create Thread by Implementing Runnable: The easiest way to create a thread is to create a class that implements the Runnable interface.CS55 PROGRAMMING PARADIGMS Above mentioned stages are explained here:    New: A new thread begins its life cycle in the new state. the thread becomes runnable. itself. a class need only implement a single method called run( ). Runnable: After a newly born thread is started. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.   Creating a Thread: Java defines two ways in which this can be accomplished:   You can implement the Runnable interface. Waiting: Sometimes a thread transitions to the waiting state while the thread waits for another thread to perform a task. It is also referred to as a born thread. Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates. It remains in this state until the program starts the thread. To implement Runnable. You can extend the Thread class.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. A thread in this state is considered to be executing its task.

Here threadOb is an instance of a class that implements the Runnable interface and the name of the new thread is specified by threadName.out. System. The start( ) method is shown here: void start( ).println("Child thread: " + t).out. i > 0. t. } } class ThreadDemo { public static void main(String args[]) { new NewThread(). // Let the thread sleep for a while. } System. Thread defines several constructors."). you will instantiate an object of type Thread from within that class.start(). Thread. which is declared within Thread. second thread t = new Thread(this."). // Start the thread } public void run() { try { for(int i = 5.println("Child interrupted. NewThread() { // Create a new.CS55 PROGRAMMING PARADIGMS public void run( ) You will define the code that constitutes the new thread inside run() method.println("Child Thread: " + i).println("Exiting child thread. The one that we will use is shown here: Thread(Runnable threadOb. it will not start running until you call its start( ) method. "Demo Thread"). After you create a class that implements Runnable. } } catch (InterruptedException e) { System.out. After the new thread is created. i--) { System. just like the main thread can. use other classes. It is important to understand that run() can call other methods. and declare variables. // create a new thread try { Page 118 of 158 © Einstein college of engineering .out. String threadName). Example: Here is an example that creates a new thread and starts it running: class NewThread implements Runnable { Thread t.sleep(500).

which is the entry point for the new thread. Create Thread by Extending Thread: The second way to create a thread is to create a new class that extends Thread. Example: Here is the preceding program rewritten to extend Thread: class NewThread extends Thread { NewThread() { // Create a new. // Start the thread } // This is the entry point for the second thread. } System. public void run() { Page 119 of 158 © Einstein college of engineering . } } This would produce following result: Child thread: Thread[Demo Thread.out.main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread.out. and then to create an instance of that class. second thread super("Demo Thread").println("Child thread: " + this). It must also call start( ) to begin execution of the new thread.println("Main thread interrupted.println("Main thread exiting.out. } } catch (InterruptedException e) { System. The extending class must override the run( ) method. start().println("Main Thread: " + i).out.5.CS55 PROGRAMMING PARADIGMS for(int i = 5. Main Thread: 2 Main Thread: 1 Main thread exiting."). Thread. System. i--) { System."). i > 0.sleep(1000).

Main Thread: 2 Main Thread: 1 Main thread exiting. i > 0. } } This would produce following result: Child thread: Thread[Demo Thread. } System. i > 0.out.println("Main thread exiting. Thread.sleep(500). // Let the thread sleep for a while.println("Main Thread: " + i)."). i--) { System."). // create a new thread try { for(int i = 5. Thread Methods: Following is the list of important medthods available in the Thread class.main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. } } catch (InterruptedException e) { System.CS55 PROGRAMMING PARADIGMS try { for(int i = 5. i--) { System.println("Main thread interrupted.sleep(1000). Thread.println("Exiting child thread.out.out. } System.out.").5.println("Child Thread: " + i). } } catch (InterruptedException e) { System."). Page 120 of 158 © Einstein college of engineering . } } class ExtendThread { public static void main(String args[]) { new NewThread().out.out.println("Child interrupted.

which is any time after the thread has been started but before it runs to completion. Invoking one of the static methods performs the operation on the currently running thread SN Methods with Description public static void yield() 1 Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled public static void sleep(long millisec) 2 Causes the currently running thread to block for at least the specified number of milliseconds public static boolean holdsLock(Object x) 3 Returns true if the current thread holds the lock on the given Object. The possible values are between 1 and 10. The previous methods are invoked on a particular Thread object. public final void setDaemon(boolean on) 5 A parameter of true denotes this Thread as a daemon thread. The following methods in the Thread class are static. public final void join(long millisec) 6 The current thread invokes this method on a second thread. then invokes the run() method on this Thread object.CS55 PROGRAMMING PARADIGMS SN Methods with Description public void start() 1 Starts the thread in a separate path of execution. public static void dumpStack() 5 Prints the stack trace for the currently running thread. causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. public final boolean isAlive() 8 Returns true if the thread is alive. Example: The following ThreadClassDemo program demonstrates some of these methods of the Thread class: Page 121 of 158 © Einstein college of engineering . causing it to continue execution if it was blocked for any reason. public static Thread currentThread() 4 Returns a reference to the currently running thread. public void interrupt() 7 Interrupts this thread. the run() method is invoked on that Runnable object. public final void setPriority(int priority) 4 Sets the priority of this Thread object. which is useful when debugging a multithreaded application. which is the thread that invokes this method. There is also a getName() method for retrieving the name. public void run() 2 If this Thread object was instantiated using a separate Runnable target. public final void setName(String name) 3 Changes the name of the Thread object.

} public void run() { while(true) { System. } } } // File Name : GuessANumber. int guess = 0.out.CS55 PROGRAMMING PARADIGMS public class DisplayMessage implements Runnable { private String message.out.number = number.println(this.getName() + " in " + counter + " guesses. do { guess = (int) (Math.getName() + " guesses " + guess). public GuessANumber(int number) { this.println("** Correct! " + this. public DisplayMessage(String message) { this.**").println(message). }while(guess != number).java public class ThreadClassDemo { public static void main(String [] args) Page 122 of 158 © Einstein college of engineering .out.java // Create a thread to extentd Thread public class GuessANumber extends Thread { private int number. System. } public void run() { int counter = 0. counter++. System. } } // File Name : ThreadClassDemo.random() * 100 + 1).message = message.

Starting hello thread..println("Starting goodbye thread. System.")... try { thread3. Thread thread3 = new GuessANumber(27).setPriority(Thread.")..setDaemon(true).. }catch(InterruptedException e) { System. Runnable bye = new DisplayMessage("Goodbye"). Thread thread2 = new Thread(hello). Thread thread4 = new GuessANumber(75)..out. thread1..").MIN_PRIORITY). thread4.join()..println("Starting thread3. Hello Hello Hello Hello Hello Hello Hello Hello Page 123 of 158 © Einstein college of engineering .. } } This would produce following result.println("Starting thread4.start().out. System..out... thread2.println("main() is ending. thread1. thread2.setName("hello").out. Thread thread1 = new Thread(hello). System.out.CS55 PROGRAMMING PARADIGMS { Runnable hello = new DisplayMessage("Hello")..start()."). Starting goodbye thread. System.start(). thread1.").setDaemon(true). You can try this example again and again and you would get different result every time.."). thread3.out. thread2.println("Starting hello thread. } System.println("Thread interrupted.start().

CS55 PROGRAMMING PARADIGMS Hello Thread-2 guesses 27 Hello ** Correct! Thread-2 in 102 guesses.** Hello Starting thread4... Hello Hello ..........remaining result produced Interrupting thrreads: Interrupting a thread means stopping what it is doing before it has completed its task, effectively aborting its current operation. Whether the thread dies, waits for new tasks, or goes on to the next step depends on the application. Although it may seem simple at first, you must take some precautions in order to achieve the desired result. There are some caveats you must be aware of as well. First of all, forget the Thread.stop method. Although it indeed stops a running thread, the method is unsafe and was deprecated, which means it may not be available in future versions of the Java. Another method that can be confusing for the unadvised is Thread.interrupt. Despite what its name may imply, the method does not interrupt a running thread (more on this later), as Listing A demonstrates. It creates a thread and tries to stop it usingThread.interrupt. The calls to Thread.sleep() give plenty of time for the thread initialization and termination. The thread itself does not do anything useful. Listing A: class Example1 extends Thread { public static void main( String args[] ) throws Exception { Example1 thread = new Example1(); System.out.println( "Starting thread..." ); thread.start(); Thread.sleep( 3000 ); System.out.println( "Interrupting thread..." ); thread.interrupt(); Thread.sleep( 3000 ); System.out.println( "Stopping application..." ); System.exit( 0 ); } public void run() { while ( true ) { System.out.println( "Thread is running..." ); long time = System.currentTimeMillis(); Page 124 of 158 © Einstein college of engineering

CS55 PROGRAMMING PARADIGMS while ( System.currentTimeMillis()-time < 1000 ) { } } } }

If you run the code in Listing A, you should see something like this on your console: Starting thread... Thread is running... Thread is running... Thread is running... Interrupting thread... Thread is running... Thread is running... Thread is running... Stopping application... Even after Thread.interrupt() is called, the thread continues to run for a while. Really interrupting a thread The best, recommended way to interrupt a thread is to use a shared variable to signal that it must stop what it is doing. The thread must check the variable periodically, especially during lengthy operations, and terminate its task in an orderly manner.Listing B demonstrates this technique. Listing B:
class Example2 extends Thread { volatile boolean stop = false; public static void main( String args[] ) throws Exception { Example2 thread = new Example2(); System.out.println( "Starting thread..." ); thread.start(); Thread.sleep( 3000 ); System.out.println( "Asking thread to stop..." ); thread.stop = true; Thread.sleep( 3000 ); System.out.println( "Stopping application..." ); System.exit( 0 ); } public void run() { while ( !stop ) { System.out.println( "Thread is running..." ); long time = System.currentTimeMillis(); while ( (System.currentTimeMillis()-time < 1000) && (!stop) ) { } } System.out.println( "Thread exiting under request..." );

Page 125 of 158 © Einstein college of engineering

CS55 PROGRAMMING PARADIGMS
} }

Running the code in Listing B will generate output like this (notice how the thread exits in an orderly fashion): Starting thread... Thread is running... Thread is running... Thread is running... Asking thread to stop... Thread exiting under request... Stopping application... Although this method requires some coding, it is not difficult to implement and give the thread the opportunity to do any cleanup needed, which is an absolute requirement for any multithreaded application. Just be sure to declare the shared variable as volatile or enclose any access to it into synchronized blocks/methods. So far, so good! But what happens if the thread is blocked waiting for some event? Of course, if the thread is blocked, it can't check the shared variable and can't stop. There are plenty of situations when that may occur, such as calling Object.wait(),ServerSocket.accept(), and DatagramSocket.receive(), to name a few. They all can block the thread forever. Even if a timeout is employed, it may not be feasible or desirable to wait until the timeout expires, so a mechanism to prematurely exit the blocked state must be used. Unfortunately there is no such mechanism that works for all cases, but the particular technique to use depends on each situation. In the following sections, I'll give solutions for the most common cases. Interrupting a thread with Thread.interrupt() As demonstrated in Listing A, the method Thread.interrupt() does not interrupt a running thread. What the method actually does is to throw an interrupt if the thread is blocked, so that it exits the blocked state. More precisely, if the thread is blocked at one of the methods Object.wait, Thread.join, or Thread.sleep, it receives anInterruptedException, thus terminating the blocking method prematurely. So, if a thread blocks in one of the aforementioned methods, the correct way to stop it is to set the shared variable and then call the interrupt() method on it (notice that it is important to set the variable first). If the thread is not blocked, calling interrupt() will not hurt; otherwise, the thread will get an exception (the thread must be prepared to handle this condition) and escape the blocked state. In either case, eventually the thread will test Page 126 of 158 © Einstein college of engineering

sleep( 3000 ). try { Thread.. Thread running.println( "Stopping application..println( "Thread interrupted." ). } } As soon as Thread.. particularly if network communication is involved..stop = true. System...println( "Thread exiting under request. a server may be waiting for a request. } } System...start()." )..sleep( 1000 ). } catch ( InterruptedException e ) { System..CS55 PROGRAMMING PARADIGMS the shared variable and stop. System.. Interrupting an I/O operation But what happens if the thread is blocked on an I/O operation? I/O can block a thread for a considerable amount of time. Thread running.interrupt() is called in Listing C. thread..exit( 0 ).println( "Asking thread to stop." ). Thread. public static void main( String args[] ) throws Exception { Example3 thread = new Example3()... Page 127 of 158 © Einstein college of engineering . or a network application may be waiting for an answer from a remote host.. System. thread..out..println( "Thread running. Thread interrupted..println( "Starting thread... Listing C: class Example3 extends Thread { volatile boolean stop = false. Running this code produces output like this: Starting thread.out.out." ). Thread running.. Thread exiting under request..interrupt()..out. Stopping application.out..." ).sleep( 3000 )... Listing C is a simple example that demonstrates this technique. } public void run() { while ( !stop ) { System." ). Thread. System. For example.out. the thread gets an exception so that it escapes the blocked state and determines that it should stop. thread.. Asking thread to stop.

sleep( 3000 ). Thread..out.. System.println( "Stopping application. thread. System. the blocked thread will get a ClosedByInterruptException exception. Page 128 of 158 © Einstein college of engineering ." )..." ).CS55 PROGRAMMING PARADIGMS If you're using channels.println( "Waiting for connection.accept().start()....out.out. class Example4 extends Thread { public static void main( String args[] ) throws Exception { Example4 thread = new Example4().*. try { socket = new ServerSocket(7856). thread. much like theinterrupt() method causes an InterruptedException to be thrown.exit( 0 ). Listing D demonstrates that behavior.out. try { Socket sock = socket. Thread. } catch ( IOException e ) { System. In this case. the logic is the same as that used in the third example —only the exception is different. System.println( "Interrupting thread..interrupt()." ). the thread does not exit the blocked state.0. Listing D: import java. System.sleep( 3000 ).println( "Starting thread.out." ). if the thread is blocked in an I/O operation.io. } while ( true ) { System." ).4. since the new I/O is so recent and requires more work.println( "Could not create the socket.. } catch ( IOException e ) { System. In this case. Thread. } } } } Fortunately. But you might be using the traditional I/O available since Java 1.println( "accept() failed or interrupted. available with the new I/O API introduced in Java 1. the thread will get a SocketException exception. } public void run() { ServerSocket socket. the Java Platform provides a solution for that case by calling the close()method of the socket the thread is blocked in.. Although the interrupt() method is called. since the thread will not exit the blocked state.out." ).. return.. If that is the case.interrupt() doesn't help.

} catch ( IOException e ) { System.sleep( 3000 ).. import java. accept() failed or interrupted. public static void main( String args[] ) throws Exception { Example5 thread = new Example5().println( "Waiting for connection. System." ).. System.out.println( "Starting thread... Listing Edemonstrates this case.sleep( 3000 ).out. System.println( "Asking thread to stop..out.CS55 PROGRAMMING PARADIGMS The only caveat is that a reference to the socket must be available so that its close()method can be called.. } } System.. Waiting for connection. } while ( !stop ) { System. return.*.exit( 0 ).io." ).. Thread exiting under request..out.*. Thread.net.println( "Stopping application." ). Page 129 of 158 © Einstein college of engineering .. That means the socket object must also be shared. } catch ( IOException e ) { System.. class Example5 extends Thread { volatile boolean stop = false.println( "accept() failed or interrupted. Stopping application.." )." ). volatile ServerSocket socket.... Asking thread to stop.socket." )..accept().out. } } Starting thread...out. thread.out.start()..println( "Thread exiting under request... thread... try { Socket sock = socket. And here's the sample output you can expect from running Listing E: Listing E: import java. System." ).. thread.println( "Could not create the socket.close(). The logic is the same as in the examples presented so far.stop = true... } public void run() { try { socket = new ServerSocket(7856). Thread.

Thread thread2 = new Thread(new TestThread(2)). } catch (InterruptedException ex) { ex. Setting a threads priority can be very useful if one thread has more critical tasks to perform than another. Thread Priorities: Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled. but it presents its own set of challenges. thread1.CS55 PROGRAMMING PARADIGMS Multithreading is a powerful tool. thread2. Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). In the first example below no priorites are set. However. By default. try { thread1. Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads.join(). thread2. public class Main { public void setPrioritiesOnThreads() { Thread thread1 = new Thread(new TestThread(1)). these techniques make interrupting a thread no more difficult than using the built-in operations already provided by the Java Platform. which is passed to the constructor. One of these is how to interrupt a running thread. so both threads have the priority level 5.printStackTrace(). The priority level range from 1 (least important) to 10 (most important) and if no level is explicitly set. The TestThread class implements the Runnable interface and in its run() method loops from 1 to 10 and output the number along with its Thread id. thread priorities cannot guarantee the order in which threads execute and very much platform dependentant.start(). Page 130 of 158 © Einstein college of engineering .start(). The Thread class has a method called setPriority(int level) with which you can alter the priority a Thread instance has. a Thread instance has the priority level of 5. If properly implemented.join(). every thread is given priority NORM_PRIORITY (a constant of 5).

out.println("Thread" + id + ": " + i). the output will be a mix between them and could look like this: Thread2: 1 Thread1: 1 Thread2: 2 Thread1: 2 Thread2: 3 Thread1: 3 Thread2: 4 Thread1: 4 Thread2: 5 Thread1: 5 Thread2: 6 Thread1: 6 Thread2: 7 Thread2: 8 Page 131 of 158 © Einstein college of engineering . public TestThread(int id) { this.println("Done.id = id. } } } } Since both threads have the same priority. } class TestThread implements Runnable { int id.setPrioritiesOnThreads().out. } public void run() { for (int i = 1. } public static void main(String[] args) { new Main(). i++) { System.CS55 PROGRAMMING PARADIGMS } System. i <= 10.").

MIN_PRIORITY).").out. If we set the priority on the threads we still haven't got exact control of the execution.start(). } Page 132 of 158 © Einstein college of engineering . thread1. } public static void main(String[] args) { new Main().setPriority(Thread. thread2.setPriority(Thread. Thread thread2 = new Thread(new TestThread(2)).printStackTrace(). but at least we can tell the CPU which one we think is most important.start().CS55 PROGRAMMING PARADIGMS Thread2: 9 Thread2: 10 Thread1: 7 Thread1: 8 Thread1: 9 Thread1: 10 Done. thread2.join().MAX_PRIORITY). The output could look different from on execution to another since we have no control of how the CPU will prioritize them. The next example is identical to the one above except for the lines where the priority of the threads are set: public class Main { public void setPrioritiesOnThreads() { Thread thread1 = new Thread(new TestThread(1)). } System. } catch (InterruptedException ex) { ex. //Setting priorities on the Thread objects thread1. thread2.println("Done. try { //Wait for the threads to finish thread1.setPrioritiesOnThreads().join().

Page 133 of 158 © Einstein college of engineering . It is up to the CPU to decide.CS55 PROGRAMMING PARADIGMS class TestThread implements Runnable { int id.id = id.println("Thread" + id + ": " + i). } } } } The output from the code looked like this when executed: Thread1: 1 Thread1: 2 Thread1: 3 Thread1: 4 Thread1: 5 Thread1: 6 Thread1: 7 Thread1: 8 Thread1: 9 Thread1: 10 Thread2: 1 Thread2: 2 Thread2: 3 Thread2: 4 Thread2: 5 Thread2: 6 Thread2: 7 Thread2: 8 Thread2: 9 Thread2: 10 Done. It is however not certain that the first thread will be prioritized to finish before the second thread starts every time. i <= 10. public TestThread(int id) { this.out. i++) { System. } public void run() { for (int i = 1.

print("[" + msg). This is the general form of the synchronized statement: synchronized(object) { // statements to be synchronized } Here.out. } catch (InterruptedException e) { System. using a synchronized block within the run( ) method: class Callme { void call(String msg) { System. Here is an example. } } // File Name : Caller. object is a reference to the object being synchronized. } System. t = new Thread(this).println("Interrupted"). A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object's monitor. public Caller(Callme targ. msg = s. Callme target. } // synchronize calls to call() public void run() { Page 134 of 158 © Einstein college of engineering . a thread needs to obtain the corresponding object's lock.println("]"). Every Java object with a critical section of code gets a lock associated with the object.out. The synchronized keyword in Java creates a block of code referred to as a critical section.sleep(1000). To enter a critical section. The process by which this synchronization is achieved is called thread synchronization. t.java class Caller implements Runnable { String msg. String s) { target = targ.out. they need some way to ensure that the resource will be used by only one thread at a time.CS55 PROGRAMMING PARADIGMS Thread Synchronization : When two or more threads need access to a shared resource. try { Thread. Thread t.start().

} catch(InterruptedException e) { System. } } } // File Name : Synch. it would start polling. Page 135 of 158 © Einstein college of engineering . To make the problem more interesting.t. and so on.out.call(msg). the consumer would waste many CPU cycles while it waited for the producer to produce. "World"). ob2.join(). To avoid polling. "Hello"). wasting more CPU cycles waiting for the consumer to finish. In a polling system. Once the producer was finished. ob3. Caller ob3 = new Caller(target.join().CS55 PROGRAMMING PARADIGMS synchronized(target) { // synchronized block target. // wait for threads to end try { ob1.println("Interrupted"). } } } This would produce following result: [Hello] [World] [Synchronized] Interthread Communication: Consider the classic queuing problem. Caller ob2 = new Caller(target. this situation is undesirable. Java includes an elegant interprocess communication mechanism via the following methods:   wait( ): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). notify( ): This method wakes up the first thread that called wait( ) on the same object.java class Synch { public static void main(String args[]) { Callme target = new Callme().t. Caller ob1 = new Caller(target. suppose that the producer has to wait until the consumer is finished before it generates more data. Clearly. where one thread is producing some data and another is consuming it. "Synchronized").join().t.

} catch(InterruptedException e) { System. so all classes have them. } synchronized void put(int n) { if(valueSet) try { wait().out.out. Various forms of wait( ) exist that allow you to specify a period of time to wait. } } Page 136 of 158 © Einstein college of engineering . boolean valueSet = false.out. Example: The following sample program consists of four classes: Q. } System. return n. System. and PC. notify(). and Consumer.n = n. the queue that you're trying to synchronize.println("Put: " + n).CS55 PROGRAMMING PARADIGMS  notifyAll( ): This method wakes up all the threads that called wait( ) on the same object.println("InterruptedException caught").println("InterruptedException caught").c The highest priority thread will run first. valueSet = true. All three methods can be called only from within a synchronized context. } this. notify(). valueSet = false. as shown here: class Q { int n. The proper way to write this program in Java is to use wait( ) and notify( ) to signal in both directions. the threaded object that is producing queue entries. Producer. These methods are implemented as final methods in Object.println("Got: " + n). synchronized int get() { if(!valueSet) try { wait(). } catch(InterruptedException e) { System. Producer.out. Consumer. the tiny class that creates the single Q. These methods are declared within Object. the threaded object that is consuming queue entries.

and notify( ) is called. } } Inside get( ). while(true) { q.start(). new Thread(this. get( ) calls notify( ). "Consumer"). Producer(Q q) { this. wait( ) suspends execution until the Consumer has removed the item from the queue.q = q. new Consumer(q). When this happens. execution inside get( ) resumes. Inside put( ). new Thread(this.q = q.start(). This tells the Consumer that it should now remove it.put(i++)."). This causes its execution to suspend until the Producer notifies you that some data is ready. After the data has been obtained. This tells Producer that it is okay to put more data in the queue. wait( ) is called. new Producer(q). Page 137 of 158 © Einstein college of engineering . Consumer(Q q) { this.get().CS55 PROGRAMMING PARADIGMS class Producer implements Runnable { Q q. } } } class PCFixed { public static void main(String args[]) { Q q = new Q().out. When execution resumes. "Producer"). } public void run() { while(true) { q. } public void run() { int i = 0. the next item of data is put in the queue.println("Press Control-C to stop. System. } } } class Consumer implements Runnable { Q q.

foo").println(name + " entered A. Page 138 of 158 © Einstein college of engineering .currentThread().last()").println("A Interrupted"). it would have to release its own lock on Y so that the first thread could complete. The next example creates two classes. } System. If the thread in X tries to call any synchronized method on Y.sleep(1000).out. suppose one thread enters the monitor on object X and another thread enters the monitor on object Y. System.getName().last(). which pause briefly before trying to call a method in the other class. try { Thread. The main class. However. because to access X. which occurs when two threads have a circular dependency on a pair of synchronized objects. which shows the clean synchronous behavior: Put: 1 Got: 1 Put: 2 Got: 2 Put: 3 Got: 3 Put: 4 Got: 4 Put: 5 Got: 5 Thread Deadlock: A special type of error that you need to avoid that relates specifically to multitasking is deadlock. named Deadlock. it will block as expected. class A { synchronized void foo(B b) { String name = Thread. in turn. b. with methods foo( ) and bar( ). The foo( ) and bar( ) methods use sleep( ) as a way to force the deadlock condition to occur. if the thread in Y.out. A and B. For example. the thread waits forever. Example: To understand deadlock fully. and then starts a second thread to set up the deadlock condition. it is useful to see it in action. } catch(Exception e) { System. creates an A and a B instance. respectively.CS55 PROGRAMMING PARADIGMS Here is some output from this program.out.println(name + " trying to call B. tries to call any synchronized method on X.

a. B b = new B(). System.out. } System. "RacingThread").println("Back in main thread").CS55 PROGRAMMING PARADIGMS } synchronized void last() { System.foo RacingThread entered B.getName(). try { Thread.last() RacingThread trying to call A.println("Inside A.last").bar"). } synchronized void last() { System. System. } catch(Exception e) { System.println(name + " trying to call A. a. } } Here is some output from this program: MainThread entered A.last() Page 139 of 158 © Einstein college of engineering . } } class Deadlock implements Runnable { A a = new A().last().out.out.bar(a). // get lock on a in this thread.last").out. } public static void main(String args[]) { new Deadlock(). } } class B { synchronized void bar(A a) { String name = Thread.println("B Interrupted").foo(b). Thread t = new Thread(this.sleep(1000). t.setName("MainThread").println("Inside A.start().println("Back in other thread"). System.last()").currentThread(). // get lock on b in other thread.currentThread(). Deadlock() { Thread. } public void run() { b.out.println(name + " entered B.out.bar MainThread trying to call B.out.

println("New thread: " + t). t. suspendFlag = false. Thread. However. the deprecated method calls have been removed. The run( ) method contains a synchronized statement block that checks suspendFlag. Finally. name). boolean suspendFlag. This example is similar to the program in the previous section.println(name + ": " + i). public void run() { try { for(int i = 15. which is used to control the execution of the thread. MainThread owns a and is waiting to get b. deadlock is one of the first conditions that you should check for. As this example illustrates. Page 140 of 158 © Einstein college of engineering . resume( ). i > 0. the main( ) method has been modified to invoke the mysuspend( ) and myresume( ) methods. NewThread(String threadname) { name = threadname.CS55 PROGRAMMING PARADIGMS Because the program has deadlocked. The NewThread class contains a boolean instance variable named suspendFlag. This program will never complete. The mysuspend( ) method sets suspendFlag to true. if your multithreaded program locks up occasionally. // Start the thread } // This is the entry point for thread. If that variable is true. Example: // Suspending and resuming a thread for Java 2 class NewThread implements Runnable { String name. and stop( ) methods defined by Thread class seem to be a perfectly reasonable and convenient approach to managing the execution of threads. while it is waiting for the monitor on a. It is initialized to false by the constructor. Let us consider the operation of this program. i--) { System. the wait( ) method is invoked to suspend the execution of the thread. // name of thread Thread t.sleep(200). The myresume( ) method sets suspendFlag to false and invokes notify( ) to wake up the thread.start(). The following example illustrates how the wait( ) and notify( ) methods that are inherited from Object can be used to control the execution of a thread. You can see a full thread and monitor cache dump by pressing CTRL-BREAK on a PC . t = new Thread(this. At the same time. Thread Control: While the suspend( ). you need to press CTRL-C to end the program. You will see that RacingThread owns the monitor on b.out. System. they must not be used for new Java programs and obsolete in newer versions of Java.out.

out.join().println("Suspending thread One").println("Waiting for threads to finish. System. ob1.println(name + " interrupted. notify().").t."). ob2. } void mysuspend() { suspendFlag = true. NewThread ob2 = new NewThread("Two"). ob2.mysuspend().out. } } class SuspendResume { public static void main(String args[]) { NewThread ob1 = new NewThread("One").out.println("Main thread Interrupted").CS55 PROGRAMMING PARADIGMS synchronized(this) { while(suspendFlag) { wait(). ob2.myresume(). } catch (InterruptedException e) { Page 141 of 158 © Einstein college of engineering .println("Suspending thread Two").println("Resuming thread Two").println("Resuming thread One"). Thread. System.sleep(1000).sleep(1000).join(). System. try { Thread.out.myresume().t. ob1.sleep(1000).out. } // wait for threads to finish try { System. } catch (InterruptedException e) { System. Thread. } } } } catch (InterruptedException e) { System. ob1.mysuspend().out. System. } System.out.println(name + " exiting.").out. } synchronized void myresume() { suspendFlag = false.

main] Two: 15 One: 14 Two: 14 One: 13 Two: 13 One: 12 Two: 12 One: 11 Two: 11 Suspending thread One Two: 10 Two: 9 Two: 8 Two: 7 Two: 6 Resuming thread One Suspending thread Two One: 10 One: 9 One: 8 One: 7 One: 6 Resuming thread Two Waiting for threads to finish.println("Main thread Interrupted")."). } } Here is the output produced by the above program: New thread: Thread[One.main] One: 15 New thread: Thread[Two.5.out. Two: 5 One: 5 Two: 4 One: 4 Two: 3 One: 3 Two: 2 One: 2 Two: 1 One: 1 Two exiting. Page 142 of 158 © Einstein college of engineering .5. } System.out.CS55 PROGRAMMING PARADIGMS System.println("Main thread exiting.

} catch (InterruptedException e ) { System. In the previous example. After the threads are declared using the constructor of the MyThread class. If it is. } public void run() { try { System. The isAlive() method determines whether a thread is still running. Main thread exiting. This example is nearly the same as the previous example. The join() method works differently than the isAlive() method.out.start(). we estimated the time it takes for the child threads to complete processing. Page 143 of 158 © Einstein college of engineering . However. a child thread could terminate after the main thread terminates. Thread. Programmers use two other techniques to ensure that the main thread is the last thread to terminate. there isn’t any guarantee that the main thread won’t finish before a child thread finishes.println("Thread: " + tName ). the isAlive() method returns a Boolean true value. the main thread is the last thread to finish in a program. the join() method is called for each thread. However. t = new Thread (this. In addition.sleep(2000). the sleep technique isn’t the best one to use to guarantee that the main thread terminates last. The join() method causes the main thread to wait for all child threads to complete processing before the main thread terminates. Therefore. The value returned by the isAlive() method is then displayed on the screen. Using isAlive() and join(): Typically.CS55 PROGRAMMING PARADIGMS One exiting. a Boolean false is returned. tName). The following example illustrates how to use the isAlive() method and the join() method in your program. Next. These techniques involve calling the isAlive() method and the join() method. The difference lies in the main() method of the Demo class definition. If our estimate was too short. Both of these methods are defined in the Thread class. we told the main method to sleep until the child threads terminate. Thread t. the isAlive() method is called for each thread. You can use the isAlive() method to examine whether a child thread continues to run. class MyThread implements Runnable { String tName. t. The join() method waits until the child thread terminates and ―joins‖ the main thread. you can use the join() method to specify the amount of time you want to wait for a child thread to terminate. MyThread (String threadName) { tName = threadName.println("Exception: Thread " + tName + " interrupted"). otherwise.out.

isAlive()). System.t.isAlive()).t.out.t.out.println("Thread Status: Alive").println("Thread 2: " + thread2.isAlive()).t.").t.isAlive()).join().t.out.out.println("Threads Joining. System.t.println("Thread 1: " + thread1.out.t.println("Thread 3: " + thread3.isAlive()).isAlive()). } } class Demo { public static void main (String args []) { MyThread thread1 = new MyThread ("1"). System.out. thread4. System. System.join().out. System.out.println("Thread Status: Alive"). System.isAlive()). MyThread thread4 = new MyThread ("4").println("Thread 2: " + thread2. } } Page 144 of 158 © Einstein college of engineering . thread3. try { System.println("Thread 1: " + thread1.out. } catch (InterruptedException e) { System. MyThread thread3 = new MyThread ("3"). System.t.CS55 PROGRAMMING PARADIGMS } System. MyThread thread2 = new MyThread ("2").isAlive()).out. System.out.join(). thread1. thread2. } System."). System.t.t.t.out.println( "Exception: Thread main interrupted.println("Thread 4: " + thread4.println("Thread 3: " + thread3.out.println("Terminating thread: " + tName ).").out.join().println("Thread 4: " + thread4.println( "Terminating thread: main thread.

Thread Pools: Most of the executor implementations in java. Thread objects use a significant amount of memory. An important advantage of the fixed thread pool is that applications using it degrade gracefully.util. Thread: 1 Thread: 2 Thread: 3 Thread: 4 Terminating thread: 1 Terminating thread: 2 Terminating thread: 3 Terminating thread: 4 Thread Status: Alive Thread 1: false Thread 2: false Thread 3: false Thread 4: false Terminating thread: main thread. Using worker threads minimizes the overhead due to thread creation.concurrent use thread pools. if a thread is somehow terminated while it is still in use. To understand this. allocating and deallocating many thread objects creates a significant memory management overhead. With a limit on the number of the threads that can be created. but it will be servicing them as quickly as the system can sustain. and the system receives more requests than it can handle immediately. which consist of worker threads. the application will not be servicing HTTP requests as quickly as they come in. Page 145 of 158 © Einstein college of engineering . consider a web server application where each HTTP request is handled by a separate thread. and in a large-scale application. it is automatically replaced with a new thread. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.CS55 PROGRAMMING PARADIGMS Here is what is displayed on the screen when this program runs: Thread Status: Alive Thread 1: true Thread 2: true Thread 3: true Thread 4: true Threads Joining. If the application simply creates a new thread for every new HTTP request. This type of pool always has a specified number of threads running. the application will suddenly stop responding to all requests when the overhead of all those threads exceed the capacity of the system. which holds extra tasks whenever there are more active tasks than threads. One common type of thread pool is the fixed thread pool. Tasks are submitted to the pool via an internal queue.

ThreadPoolExecutor or java.util.. // autoboxing! } } java. Some of you may already have noticed that the ExecutorService API is biased to Callable objects .concurrent.   If none of the executors provided by the above factory methods meet your needs. } public Long call() { // perform complex calculation resulting in long long result = //... Several factory methods are ScheduledExecutorService versions of the above executors.. This executor is suitable for applications that launch many short-lived tasks.util.ScheduledThreadPoolExecutor will give you additional options.most specialized concurrency APIs already available (such as Foxtrot ) already have the concept of a runnable + return type (such as the foxtrot Task and Job classes). long value3) { // .concurrent. Callables: Callables are a tweak to the existing runnable construct. Callables differ only by having a generic return type .util. constructing instances of java.concurrent. The newSingleThreadExecutor method creates an executor that executes a single task at a time.concurrent Interface Callable<V> Type Parameters: V .the result type of method call Page 146 of 158 © Einstein college of engineering .and some may consider that a problem since they have a lot of code that already works with Runnable .util.Executors This class also provides the following factory methods:  The newCachedThreadPool method creates an executor with an expandable thread pool. public class ComplexCalculation implements Callable<Long> { public ComplexCalculation(int value1. return result.CS55 PROGRAMMING PARADIGMS A simple way to create an executor that uses a fixed thread pool is to invoke the newFixedThreadPool factory method in java. int value2.

concurrent. "C")). "A")). "D")). cdl3. This works well for small applications.await(). import java. Example: import java. class SimpExec { public static void main(String args[]) { CountDownLatch cdl = new CountDownLatch(5). es. or throws an exception if unable to do so. in that both are designed for classes whose instances are potentially executed by another thread. import java. CountDownLatch cdl3 = new CountDownLatch(5). try { cdl.await(). "B")).execute(new MyThread(cdl2. ExecutorService es = Executors. but in large-scale applications.util.await().CS55 PROGRAMMING PARADIGMS public interface Callable<V> A task that returns a result and may throw an exception. as defined by its Runnable object.concurrent. A Runnable.util. V call() Computes a result.concurrent. Implementors define a single method with no arguments called call. Objects that encapsulate these functions are known as executors.execute(new MyThread(cdl3. es. es.ExecutorService. es. Page 147 of 158 © Einstein college of engineering . The Executors class contains utility methods to convert from other common forms to Callable classes.Executors. it makes sense to separate thread management and creation from the rest of the application. CountDownLatch cdl4 = new CountDownLatch(5). cdl2.execute(new MyThread(cdl. Executors: There's a close connection between the task being done by a new thread.util. however.execute(new MyThread(cdl4.CountDownLatch.newFixedThreadPool(2). The Callable interface is similar to Runnable. as defined by a Thread object. CountDownLatch cdl2 = new CountDownLatch(5). does not return a result and cannot throw a checked exception. and the thread itself.

} es. potentially releasing a blocking acquirer.await(). Page 148 of 158 © Einstein college of engineering .util. including semaphores. new Thread(this).countDown(). i < 5. Each release() adds a permit. Each acquire() blocks if necessary until a permit is available.shutdown().CS55 PROGRAMMING PARADIGMS cdl4. } } class MyThread implements Runnable { String name. } public void run() { for (int i = 0. CountDownLatch latch. However. no actual permit objects are used. These classes are a apart of the java.println(exc). which facilitate coordination between threads.out. mutexes. MyThread(CountDownLatch c. i++) { latch. } catch (InterruptedException exc) { System. latches. the Semaphore just keeps a count of the number available and acts accordingly. and then takes it. and exchangers. String n) { latch = c. } } } Synchronizers: Java 5 introduces general purpose synchronizer classes. A brief description of each of these follows: Semaphores A counting semaphore maintains a set of permits.concurrent package. name = n. barriers.

nextInt(500)).util. busy(). } private void busy() { try { sleep(rand.util.println("Thread " + id + " is NON critical"). } catch (InterruptedException e) { } } private void noncritical() { System.out. } private void critical() { System. //Solving the mutual exclusion problem using Semaphore class class Process2 extends Thread { private static final Random rand = new Random(). private int id. public Process2(int i. Page 149 of 158 © Einstein college of engineering .out.println("Thread " + id + " entering critical section").println("Thread " + id + " leaving critical section").out. sem = s. import java. Example: import java. System. private Semaphore sem. busy().Semaphore. Semaphore s) { id = i.CS55 PROGRAMMING PARADIGMS Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource.concurrent.Random.

CS55 PROGRAMMING PARADIGMS } public void run() { for (int i = 0; i < 2; ++i) { noncritical(); try { sem.acquire(); } catch (InterruptedException e) { // ... } critical(); sem.release(); } } public static void main(String[] args) { final int N = 4; System.out.println("Busy waiting..."); //Semaphore(int permits, boolean fair) Semaphore sem = new Semaphore(N, true); Process2[] p = new Process2[N]; for (int i = 0; i < N; i++) { p[i] = new Process2(i, sem); p[i].start(); } } } 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.

Page 150 of 158 © Einstein college of engineering

CS55 PROGRAMMING PARADIGMS For the java.util.concurrent class see CyclicBarrier A barrier is a type of synchronization method. A barrier for a group of threads or processes in the source code means any thread/process must stop at this point and cannot proceed until all other threads/processes reach this barrier.[1] The basic Java synchronization mechanism centers on the keyword synchronized, which predicates methods. In java, all objects can be used like monitors (protected types). That means that given an object A, no more than one thread can execute a synchronized method of A at any time.  Barrier implementation /* * Given object A, no more than one thread can execute a synchronized method of A at any time. */ public class Barrier { public synchronized void block() throws InterruptedException { wait(); } public synchronized void release() throws InterruptedException { notify(); } public synchronized void releaseAll() throws InterruptedException { notifyAll(); } } And an example with two threads. class BarrierExample { static class MyThread1 implements Runnable { public MyThread1(Barrier barrier) { this.barrier = barrier; }

Page 151 of 158 © Einstein college of engineering

CS55 PROGRAMMING PARADIGMS public void run() { try { Thread.sleep(1000); System.out.println("MyThread1 waiting on barrier"); barrier.block(); System.out.println("MyThread1 has been released"); } catch (InterruptedException ie) { System.out.println(ie); } } private Barrier barrier; } static class MyThread2 implements Runnable { Barrier barrier; public MyThread2(Barrier barrier) { this.barrier = barrier; } public void run() { try { Thread.sleep(3000); System.out.println("MyThread2 releasing blocked threads\n"); barrier.release(); System.out.println("MyThread1 releasing blocked threads\n"); } catch (InterruptedException ie) { System.out.println(ie); } } } public static void main(String[] args) throws InterruptedException { Barrier BR = new Barrier(); Page 152 of 158 © Einstein college of engineering

Exchanger. Page 153 of 158 © Einstein college of engineering .start(). t2. String str. } } Exchangers A synchronization point at which two threads can exchange objects. new UseString(exgr).util.concurrent.join().MyThread1(BR)).join(). class ExgrDemo { public static void main(String args[]) { Exchanger<String> exgr = new Exchanger<String>(). } } class MakeString implements Runnable { Exchanger<String> ex. MakeString(Exchanger<String> c) { ex = c.start(). new Thread(this).start(). Example: import java. t1. } public void run() { char ch = 'A'. t1.MyThread2(BR)). Each thread presents some object on entry to the exchange method. str = new String(). and receives the object presented by the other thread on return. t2. Thread t2 = new Thread(new BarrierExample. new MakeString(exgr).CS55 PROGRAMMING PARADIGMS Thread t1 = new Thread(new BarrierExample.

} catch (InterruptedException exc) { System. new Thread(this). i++) { try { str = ex. UseString(Exchanger<String> c) { ex = c.CS55 PROGRAMMING PARADIGMS for (int i = 0. j++) str += (char) ch++. System. A CountDownLatch is initialized with a given count.exchange(new String()).println(exc).println("Got: " + str). i < 3. } public void run() { for (int i = 0. i < 3. i++) { for (int j = 0. String str.out. try { str = ex. j < 5. The await methods block until the current count reaches zero due to Page 154 of 158 © Einstein college of engineering .exchange(str).out. } } } } Latches A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. } catch (InterruptedException exc) { System.start().out. } } } } class UseString implements Runnable { Exchanger<String> ex.println(exc).

printStackTrace().util.out.name = name. import java. public class LatchTest { private static final int COUNT = 10.*.countDown(). after which all waiting threads are released and any subsequent invocations of await return immediately. String name.concurrent. This provides a way to start several threads and have them wait until a signal is received from a coordinating thread. but doesn't let any thread start until all the threads are created. CountDownLatch stopLatch.startLatch = startLatch. stopLatch.await().stopLatch = stopLatch. Latching variables specify conditions that once set never change. this.CS55 PROGRAMMING PARADIGMS invocations of the countDown() method. } System. } public void run() { try { startLatch. private static class Worker implements Runnable { CountDownLatch startLatch. } } Page 155 of 158 © Einstein college of engineering . // wait until the latch has counted down to // zero } catch (InterruptedException ex) { ex. this. Worker(CountDownLatch startLatch. CountDownLatch stopLatch. [1] The following program creates a set of threads.println("Running: " + name). String name) { this.

you don't have to worry about threads. CountDownLatch stopSignal = new CountDownLatch(COUNT). all components that it contains are realized. A Swing component that's a top-level window is realized by having one of these methods invoked on it: setVisible(true). Another way to realize a component is to add it to a container that's already realized. i++) { new Thread(new Worker(startSignal. for (int i = 0.println("Done"). } catch (InterruptedException ex) { ex. let's define two terms: realized and event-dispatching thread. } System.start(). i < COUNT. but for many simple programs. This rule might sound scary. the paint() and actionPerformed() methods are automatically executed Page 156 of 158 © Einstein college of engineering .toString(i))) .countDown(). show(). stopSignal. or (this might surprise you) pack(). You'll see examples of realizing components later.await().printStackTrace(). Before we go into detail about how to write Swing code. all code that might affect or depend on the state of that component should be executed in the event-dispatching thread. try { stopSignal. Integer. CountDownLatch startSignal = new CountDownLatch(1). } } Thread and event driven programming: The single-thread rule: Here's the rule: Once a Swing component has been realized. Once a window is realized. Realized means that the component's paint() method has been or might be called. The event-dispatching thread is the thread that executes drawing and event-handling code.CS55 PROGRAMMING PARADIGMS public static void main(String args[]) { // CountDownLatch(int count) // Constructs a CountDownLatch initialized with the given count.println("Go"). For example. startSignal.out.out. } System.

swing.swing.SwingUtilities.setVisible(true).swing.CS55 PROGRAMMING PARADIGMS in the event-dispatching thread. import javax.sleep(3000). Example: import java. import javax.lang. Page 157 of 158 © Einstein college of engineering .InvocationTargetException.getName(). public class InvokeAndWaitDemo extends Object { private static void print(String msg) { String name = Thread.setContentPane(panel). print("creating code block for event thread").setText("New text!").add(label).FlowLayout. import javax.JFrame. JFrame f = new JFrame("InvokeAndWaitDemo"). } public static void main(String[] args) { final JLabel label = new JLabel("--------"). import javax. Another way to execute code in the event-dispatching thread is to use the SwingUtilities invokeLater() method. f. Runnable setTextRun = new Runnable() { public void run() { print("about to do setText()").awt. label. Thread.currentThread(). import java. f.setSize(300. f.JLabel.swing. try { print("sleeping for 3 seconds").JPanel.out. panel. System. 100). JPanel panel = new JPanel(new FlowLayout()).reflect.println(name + ": " + msg).

} } } Page 158 of 158 © Einstein college of engineering .invokeAndWait(setTextRun). } catch (InvocationTargetException x) { print("exception thrown from run()").CS55 PROGRAMMING PARADIGMS } }. print("back from invokeAndWait()"). print("about to invokeAndWait()"). SwingUtilities. } catch (InterruptedException ix) { print("interrupted while waiting on invokeAndWait()").

Sign up to vote on this title
UsefulNot useful