You are on page 1of 131

MEENAKSHI SUNDARAJAN ENGINEERING COLLEGE, DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CS2305- PROGRAMMING PARADIGMS (Question Bank Key)

2-MARK Questions and Answers UNIT I OBJECT-ORIENTED PROGRAMMING FUNDAMENTALS 1) What is meant by Object Oriented Programming? OOP is a method of programming in which programs are organised as cooperative collections of objects. Each object is an instance of a class and each class belong to a hierarchy. 2) What is a Class? Class is a template for a set of objects that share a common structure and a common behaviour. 3) What is an Object? Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class. 4) What is an Instance? An instance has state, behaviour and identity. The structure and behaviour of similar classes are defined in their common class. An instance is also called as an object. 5) What are the core OOPs concepts? Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOPs concepts. 6) What is meant by abstraction? Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model. 7) What is meant by Encapsulation? Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

8) What are Encapsulation, Inheritance and Polymorphism? Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions. 9) What are methods and how are they defined? Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A methods signature is a combination of the first three parts mentioned above. 10) What are different types of access modifiers (Access specifiers)? Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing privileges to parts of a program such as functions and variables. These are: public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private cant be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package. 11) What is an Object and how do you allocate memory to it? Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it. 12) Explain the usage of Java packages. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes. 13) What is method overloading and method overriding? Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding: When a method in a class having the same method name with same arguments is said to be method overriding.

14) What gives java its write once and run anywhere nature? All Java programs are compiled into class files that contain byte codes. These byte codes can be run in any platform and hence java is said to be platform independent. 15) What is a constructor? What is a destructor? Constructor is an operation that creates an object and/or initialises its state. Destructor is an operation that frees the state of an object and/or destroys the object itself. In Java, there is no concept of destructors. Its taken care by the JVM. 16) What is the difference between constructor and method? Constructor will be automatically invoked when an object is created whereas method has to be called explicitly 17) What are Static member classes? A static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class. 18) What is Garbage Collection and how to call it explicitly? When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly 19) In Java, How to make an object completely encapsulated? All the instance variables should be declared as private and public getter and setter methods should be provided for accessing the instance variables. 20) What is static variable and static method? Static variable is a class variable which value remains constant for the entire class static method is the one which can be called with the class itself and can hold only the staic variables 21) What is finalize() method? finalize () method is used just before an object is destroyed and can be called just prior to garbage collection. 22) What is the difference between String and String Buffer? a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings. 23) What is the difference between Array and vector? Array is a set of related data type and static whereas vector is a growable array of objects and dynamic

24) What is a package? A package is a collection of classes and interfaces that provides a highlevel layer of access protection and name space management. 25) What is the difference between this() and super()? this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor. 26) Explain working of Java Virtual Machine (JVM)? JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes. UNIT II OBJECT-ORIENTED PROGRAMMING INHERITANCE 1) What is meant by Inheritance? Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines is-a hierarchy among classes in which one subclass inherits from one or more generalised superclasses. 2) What is meant by Inheritance and what are its advantages? Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses. 3) What is the difference between superclass and subclass? A super class is a class that is inherited whereas sub class is a class that does the inheriting. 4) Differentiate between a Class and an Object? The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program. The Class class is used to obtain information about an object's design. A Class is only a definition or prototype of real life object whereas an object is an instance or living representation of real life object. Every object belongs to a class and every class contains one or more related objects. 5) What is meant by Binding? Binding denotes association of a name with a class

6) What is meant by Polymorphism? Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class. 7) What is Dynamic Binding? Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance. 8) What is final modifier? The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.

final Classes- A final class cannot have subclasses. final Variables- A final variable cannot be changed once it is initialized. final Methods- A final method cannot be overridden by subclasses.

9) What is an Abstract Class? Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations. 10) What are inner class and anonymous class? Inner class: classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class: Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors 11) What is an Interface? Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and secrets of its behaviour. 12) What is a base class? Base class is the most generalised class in a class structure. Most applications have such root classes. In Java, Object is the base class for all classes. 13) What is reflection in java? Reflection allows Java code to discover information about the fields, methods and constructors of loaded classes and to dynamically invoke them.

14) Define superclass and subclass? Superclass is a class from which another class inherits. Subclass is a class that inherits from one or more classes. 15) What is meant by Binding, Static binding, Dynamic binding? Binding: Binding denotes association of a name with a class. Static binding: Static binding is a binding in which the class association is made during compile time. This is also called as Early binding. Dynamic binding: Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding. 16) What is reflection API? How are they implemented? Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method. 17) What is the difference between a static and a non-static inner class? A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances. 18) What is the difference between abstract class and interface? a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods. c) Abstract class must have subclasses whereas interface cant have subclasses. 19) Can you have an inner class inside a method and what variables can you access? Yes, we can have an inner class inside a method and final variables can be accessed. 20) What are interfaces and its use? Interface is similar to a class which may contain methods signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for: a) Declaring methods that one or more classes are expected to implement b) Capturing similarities between unrelated classes without forcing a class relationship.

c) Determining an objects programming interface without revealing the actual body of the class. 21) How is polymorphism achieved in java? Inheritance, Overloading and Overriding are used to achieve Polymorphism in java. 22) What modifiers may be used with top-level class? public, abstract and final can be used for top-level class. 23) What is a cloneable interface and how many methods does it contain? It is not having any method because it is a TAGGED or MARKER interface. 24) What are the methods provided by the object class? The Object class provides five methods that are critical when writing multithreaded Java programs:

notify notifyAll wait (three versions)

25) Define: Dynamic proxy. A dynamic proxy is a class that implements a list of interfaces, which you specify at runtime when you create the proxy. To create a proxy, use the static method java.lang.reflect.Proxy::newProxyInstance(). This method takes three arguments:

The class loader to define the proxy class An invocation handler to intercept and handle method calls A list of interfaces that the proxy instance implements

26) What is object cloning? It is the process of duplicating an object so that two identical objects will exist in the memory at the same time. UNIT III EVENT-DRIVEN PROGRAMMING

What is the relationship between the Canvas class and the Graphics class? A Canvas object provides access to a Graphics object via its paint() method. 2) How would you create a button with rounded edges? Theres 2 ways. The first thing is to know that a JButtons edges are drawn by a Border. so you can override the Buttons paintComponent(Graphics) method and draw a circle or rounded rectangle (whatever), and turn off the border. Or you can create a custom border that draws a circle or rounded rectangle around any component and set the buttons border to it. 1) What is the difference between the Font and FontMetrics class? 2) The Font Class is used to render glyphs - the characters you see on the screen. FontMetrics encapsulates information about a specific font on a specific Graphics object. (width of the characters, ascent, descent) 3) What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. Which containers use a border Layout as their default layout? The window, Frame and Dialog classes use a border layout as their default layout. 6) What is the difference between applications and applets? a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. c)Application starts execution with its main method whereas applet starts execution with its init method. d)Application can run with or without graphical user interface whereas applet must run within a graphical user interface. 7) Difference between Swing and Awt? AWT are heavy-weight components. Swings are light-weight components. Hence swing works faster than AWT. 8) What is a layout manager and what are different types of layout managers available in java AWT? A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and GridBagLayout.

9) How are the elements of different layouts organized? FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. The default Layout Manager of Panel and Panel sub classes is FlowLayout. 10) Why would you use SwingUtilities.invokeAndWait or SwingUtilities.invokeLater? I want to update a Swing component but Im not in a callback. If I want the update to happen immediately (perhaps for a progress bar component) then Id use invokeAndWait. If I dont care when the update occurs, Id use invokeLater. 11) What is an event and what are the models available for event handling? An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model 12) What is the difference between scrollbar and scrollpane? A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its own events and perform its own scrolling. 13) Why wont the JVM terminate when I close all the application windows? The AWT event dispatcher thread is not a daemon thread. You must explicitly call System.exit to terminate the JVM. 14) What is meant by controls and what are different types of controls in AWT? Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, and Text Components. These controls are subclasses of Component. 15) What is the difference between a Choice and a List? A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

16) What is the purpose of the enableEvents() method? The enableEvents() method is used to enable an event for a particular object. Normally,an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their eventdispatch methods. 17) What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. 18) What is the lifecycle of an applet? init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applets page. destroy() method - Can be called when the browser is finished with the applet. 19) What is the difference between a MenuItem and a CheckboxMenuItem? The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. 20) What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy. 21) What is source and listener? source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. 22) Explain how to render an HTML page using only Swing. Use a JEditorPane or JTextPane and set it with an HTMLEditorKit, then load the text into the pane. 23) How would you detect a keypress in a JComboBox? This is a trick. most people would say add a KeyListener to the JComboBox - but the right answer is add a KeyListener to the JComboBoxs editor component. 24) What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. 25) How can I create my own GUI components?

Custom graphical components can be created by producing a class that inherits from java.awt.Canvas. Your component should override the paint method, just like an applet does, to provide the graphical features of the component. UNIT IV GENERIC PROGRAMMING 1) What is an exception? An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. 2) What is error? An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself. 3) Which is superclass of Exception? "Throwable", the parent class of all exception related classes. 4) What are the advantages of using exception handling? Exception handling provides the following advantages over "traditional" error management techniques:

Separating Error Handling Code from "Regular" Code. Propagating Errors Up the Call Stack. Grouping Error Types and Error Differentiation.

5) What are the types of Exceptions in Java There are two types of exceptions in Java, unchecked exceptions and checked exceptions. Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception. Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked. 6) Why Errors are Not Checked? A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly.

7) How does a try statement determine which catch clause should be used to handle an exception? When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored. 8) What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. 9) What is the difference between checked and Unchecked Exceptions in Java? All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try.. catch () block or we should throw the exception using throws clause. If you dont, compilation of program will fail. 10) What is the difference between exception and error? The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered. 11) What is the catch or declare rule for method declarations? If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. 12) When is the finally clause of a try-catch-finally statement executed? The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause. 13) What if there is a break or return statement in try block followed by finally block? If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes. 14) What are the different ways to handle exceptions? There are two ways to handle exceptions:

Wrapping the desired code in a try block followed by a catch block to catch the exceptions. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.

15) How to create custom exceptions? By extending the Exception class or one of its subclasses. Example: class MyException extends Exception { public MyException() { super(); } public MyException(String s) { super(s); } } 16) Can we have the try block without catch block? Yes, we can have the try block without catch block, but finally block should follow the try block. Note: It is not valid to use a try clause without either a catch clause or a finally clause. 17) What is the difference between swing and applet? Swing is a light weight component whereas Applet is a heavy weight Component. Applet does not require main method, instead it needs init method. 18) What is the use of assert keyword? Assert keyword validates certain expressions. It replaces the if block effectively and throws an AssertionError on failure. The assert keyword should be used only for critical arguments (means without that the method does nothing). 19) How does finally block differ from finalize() method? Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected method in the Object class which is called by the JVM just before an object is garbage collected. 20) What is the difference between throw and throws clause? throw is used to throw an exception manually, where as throws is used in the case of checked exceptions, to tell the compiler that we haven't handled the exception, so that the exception will be handled by the calling function. 21) What are the different ways to generate and Exception? There are two different ways to generate an Exception. 1. Exceptions can be generated by the Java run-time system. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. 2. Exceptions can be manually generated by your code. Manually generated exceptions are typically used to report some error condition to the caller of a method.

22) Where does Exception stand in the Java tree hierarchy?


java.lang.Object java.lang.Throwable java.lang.Exception java.lang.Error

23) What is StackOverflowError? The StackOverFlowError is an Error Object thorwn by the Runtime System when it Encounters that your application/code has ran out of the memory. It may occur in case of recursive methods or a large amount of data is fetched from the server and stored in some object. This error is generated by JVM. e.g. void swap(){ swap(); } 24) Explain the exception hierarchy in java. The hierarchy is as follows: Throwable is a parent class off all Exception classes. They are two types of Exceptions: Checked exceptions and UncheckedExceptions. Both type of exceptions extends Exception class 25) How do you get the descriptive information about the Exception occurred during the program execution? All the exceptions inherit a method printStackTrace() from the Throwable class. This method prints the stack trace from where the exception occurred. It prints the most recently entered method first and continues down, printing the name of each method as it works its way down the call stack from the top. UNIT V CONCURRENT PROGRAMMING 1) Explain different way of using thread? The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance the only interface can help. 2) What are the different states of a thread? The different thread states are ready, running, waiting and dead. 3) Why are there separate wait and sleep methods?

The static Thread.sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. The wait method gives up control over thread execution indefinitely so that other threads can run. 4) What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined? Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for interthread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object. 5) What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. 6) How does multithreading take place on a computer with a single CPU? The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. 7) What is the difference between process and thread? Process is a program in execution whereas thread is a separate path of execution in a program. 8) What happens when you invoke a thread's interrupt method while it is sleeping or waiting? When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an Interrupted Exception is thrown. 9) How can we create a thread? A thread can be created by extending Thread class or by implementing Runnable interface. Then we need to override the method public void run(). 10) What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. 11) How can i tell what state a thread is in?

Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two. 12) What is synchronized keyword? In what situations you will use it? Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. To understand synchronization we need to look into thread execution manner. 13) What is serialization? Serialization is the process of writing complete state of java object into output stream, that stream can be file or byte array or stream associated with TCP/IP socket. 14) What does the Serializable interface do? Serializable is a tagging interface; it prescribes no methods. It serves to assign the Serializable data type to the tagged class and to identify the class as one which the developer has designed for persistence. ObjectOutputStream serializes only those objects which implement this interface. 15) When you will synchronize a piece of your code? When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption. 16) What is daemon thread and which method is used to create the daemon thread? Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread. 17) What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. 18) What is casting? There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. 19) What classes of exceptions may be thrown by a throw statement? A throw statement may throw any expression that may be assigned to the Throwable type. 20) A Thread is runnable, how does that work?

The Thread class' run method normally invokes the run method of the Runnable type it is passed in its constructor. However, it is possible to override the thread's run method with your own. 21) Can I implement my own start() method? The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method. 22) Do I need to use synchronized on setValue(int)? It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues. 23) What is thread priority? Thread Priority is an integer value that identifies the relative order in which it should be executed with respect to others. The thread priority values ranging from 1- 10 and the default value is 5. But if a thread have higher priority doesn't means that it will execute first. The thread scheduling depends on the OS. 24) What are the different ways in which a thread can enter into waiting state? There are three ways for a thread to enter into waiting state. By invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. 25) How would you implement a thread pool? The ThreadPool class is a generic implementation of a thread pool, which takes the following input Size of the pool to be constructed and name of the class which implements Runnable (which has a visible default constructor) and constructs a thread pool with active threads that are waiting for activation. once the threads have finished processing they come back and wait once again in the pool. 26) What is a thread group? A thread group is a data structure that controls the state of collection of thread as a whole managed by the particular runtime environment.

Part B (16 marks questions key) UNIT I OBJECT-ORIENTED PROGRAMMING FUNDAMENTALS


1. (a) (i) What is a constructor? What is the use of new method? [Marks 4]

-Defn of constructor -syntax for a constructor -Invocation of the constructor USE OF NEW METHOD: -Dynamic memory allocation -Instantiation of the class -Syntax for new method ii) Give the syntax for static method and its initialization. -Syntax for static method -Example static method: 1.public static int abs(int a) 2.public static void main(String[] args) Example Program: import java.io.*; class StaticTest { static double multiply(double a,double b) { return(a*b); } static double add(double a,double b) { return(a+b); } static double sub(double a,double b) {

[Marks 4]

return(a-b); } static double div(double a,double b) { return(a/b); } } public class mytest { Public static void main(String[] args) { double x=statictest.multiply(10,5); double y=statictest.add(10,5); double z=statictest.sub(10,5); double w=statictest.div(10,5); System.out.println(x+,+y+,+z+,+w); } } Output: 50,15,5,2 iii)Explain arrays in Java [ Marks 8] -Defn of Arrays -Types of Array 1.Single Dimensional Array -Syntax -How we assign values -Command line arguments -Declaration of array -Problem in copying an array (oly for 16 mark) -Methods in util.Arrays 2.Multi Dimensional Array -Syntax -Assigning values into arrays -Diplaying the contents -Example program ( oly for 16 marks) 3. short notes on ragged arrays -About the memory structure -Swapping of rows as a whole 2. (b) (i) What is class? How do you define a class in java? [Marks 4] -Defn of Classes in Java -Defining the Class Syntax: [access_specifier] [modifier] class <class_name>

{ Datatype instance_var1; Datatype instance_var2; ------------------------Datatype instance_var3; Datatype methodname 1(parameter list) { //body of the method } ---------------------------------------------Datatype methodname n(parameter list) { //body of the method } } ii)Explain the following in Strings: 1)Concatenation 2)Substrings [Marks 4] -Concatenation: -Explain about the operation. -Example Snippet Eg: String s1=Java; String s2=Programming String s3=s1.Concat(s2); (or) String s3=s1+s2; -Substring: -Explain about the operation -Two forms 1.substring(int n) 2.substring(int m,int n) -Example Program Program: class subtest { public static void main(String[] args) { String test=abcdefgh; System.out.println(Given String is:+test); System.out.println(Substring from 3 to end+test.substring(3)); System.out.println(Substring from 03+test.substring(0,3)); System.out.println(Substring from 2-

4+test.substring(2,4)); System.out.println(Substring from 33+test.substring(3,3)); } } Output: Given String is:abcdefgh Substring from 3 to end defgh Substring from 0-3 abc Substring from 2-4 cd Substring from 3-3 (iii) Explain any four methods available in string handling. [Marks 4] -Explain any of the four methods with snippet Example 1.Concatenation-concat(); 2.ChangingCase -toUpperCase() and toLowerCase(); 3.Substring- substring(int m) Substring(int m,int n) 4.length() 5.indexOf() 6.charAt() 7.equals() 8.trim() 9.hashCode() 10.toString() (iv)What is a package? How does a compiler locate packages [Marks 4] -Defn of package -Types of Java Packages 1.Java API Packages 2.User-Defined Packages -Some of the Predefined Packages java.io,java.net,java.applet,javax.swing -Use of Packages 1.Relation of classes 2. Binding of Related Functions 3.Creation of new namespace 3. (i) Write a Java program to compute the division of two without using any arithmetical operator? [Marks 4] Class DivofTwo { Public static void main(String[] args) {

int n; System.out.println(Enter the Number:); Scanner in=new Scanner(System.in); n=in.nextInt(); System.out.println(Division of Number by 2:+n<<2); //Division without using the arithmetical operator } } Output: Enter the Number: 4 Division of Number by 2: 2 (ii) Give the precedence and associativity of Java operator Rules:

[Marks 6]

Expressions inside parentheses are evaluated first Nested parentheses are evaluated from the innermost to the outermost parentheses. Operators higher in the chart have higher precedence Operators in the same row in the chart have equal precedence. Their associativity (e.g. L to R) determines tie breakers. Parentheses may be used control order of evaluation Operators () [] . expr++ expr-++expr --expr +expr -expr ! ~ (type) */% +<< >> >>> < <= > >= instanceof == != & ^ Associativity L to R R to L R to L L to R L to R L to R L to R L to R L to R L to R

Description parentheses, array subscript, member selection unary post-increment and post-decrement other unary operators: pre-increment, predecrement, plus, minus, logical negation, bitwise complement, type cast multiplication, division, mod addition, subtraction bitwise shift operators: left, right with sign extension, right with 0 extension relational less/greater than operators, instanceof for type comparison relational equality operators bitwise AND bitwise exclusive OR

bitwise inclusive OR logical AND logical OR Conditional Assignment (iii) List the basic data types used in Java.

| && || ?: = += -= *= /= %= &= ^= |= <<= >>= >>>=

L to R L to R L to R R to L R to L [Marks 6]

-Two types of DataType 1.Primitive 2.Non-Primitive -Primitive DataTypes -Byte (8 bits) -Short (16 bits) -int (32 bits) -long(64 bits) -float (32 bits) Single Precision floating point number -double (64 bits) Double Precision floating point number -char (16 bit Unicode Character Format) -boolean (8 bit Boolean value) -Non-Primitive Data Type Class Array Interface 4. (i) Demonstrate the use of StringBuffer class to sort the names of Employees in alphabetical order. [Marks 10] Program: import java.io.*; import java.lang.*; class Namesort { StringBuffer temp; int n; public static void main(String args[]) { try { StringBuffer[] str=new StringBuffer[30]; System.out.println(Enter the number of employees); DataInputStream dr=new DataInputStream(System.in);

temp=dr.readLine(); n=new Integer(temp).intValue(); System.out.println("Enter the names to sort:"); for(int i=0;i<n;i++) { System.out.flush(); str[i]=dr.readLine(); } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { If(str[i].compareTo(str[j])>0) { temp=str[i]; str[i]=str[j]; str[j]=temp; } } } System.out.println(Sorted Name List of Employees); for(int i=0;i<n;i++) { System.out.println(str[i]); } } //try block over Catch(IOException e) { System.out.println(e); } } } Output: Enter the number of Employees: 3 Enter the names to sort: Kartik Madhan Hari Sorted Name List of Employees Hari

Kartik Madhan ii) List the three types of constructor and explain with an example. [Marks 6] -Default Constructor -Explanation about default Constructor -Syntax: Classname class_variable (or)object_name=new Classname(); -Example for default constructor -Parametrized -Explanation about Parametrized/Argument Constructor -Syntax: Classname class_variable (or)object_name=new Classname(list of parameters); -Example for Parametrized Constructor -Copy Constructor -Explanation about Copy Constructor -Syntax: Classname (Class_name Copy_Constructor_name); Eg: A a=new A(); A b=new A(b); -Program : Class copy { int a,b; public copy() //Default Constructor { a=0;b=0; } public copy(int a1,int b1)//Parametrized Constructor { a=a1;b=b1; } public copy(copy c)//copy constructor { a=c.a;b=c.b; } public void display() { System.out.println(a:+a+b:+b); } } Class copyTest { public static void main(String[] args)

{ copy test=new copy(10,20); test.display(); copy test1=new copy(test); test1.display(); } } Output: a:10 b:20 a:10 b:20 5. (i) Explain the use of JavaDoc comments in a Java program. [Marks 10] -Single Line Comment -Use of double slash(//) Eg: int a=10; //assign 10 to a Book b=new Book(); //Creates the object -Multiline Comment -This is used when it exceeds more than one line -We start with /* and ends with */ Eg: /* this is the second java program called this filesecond.java */ -Anything between the comment symbol is ignored by the compiler. -Documentation Comment -Begins with the /** and ends with */ -used in javadoc utility program to extract the information and out in to the HTML file. -The javadoc utility recognizes the following tags: TAG @author class @deprecated @exception method @return @see @throws @version Method returns the value Specific link to another topic Same as exception Specifies the version of class Specification for deprecation Any exception thrown by MEANING Identifies the author of the

Eg: /** @author name @version 1.6.0 */ //Javadoc ignores this comment line public class Test { public static void main(String[] args) { int a,b,c; a=5; //assigns the value 5 to a b=10; //assigns the value 10 to b c=a+b; //add /** The above three variables are of type integer */ System.out.println(a+b=+c); } } (ii) What is the need for finalize method in Java? [Marks 6] -Use of finalize() method -Called immediately before the class is garbage-collected. -Freeing the memory for new storage -The finalizers are used to close, open file (or) connections in the network. -Ensures that related task are completed before the object is forgotten. -General Form: protected void finalize() { Finalization code } -Its impossible to determine exactly when an object will be garbagecollected. 6. (i) What are the applications of Wrapper classes? [Marks 6] -Defn for Wrapper Class -importing java.lang package PRIMITIVE DATATYPE boolean

WRAPPER CLASS Boolean

byte char short int long double

Byte Character Short Integer Long Double

-There is a wrapper class for every primitive in Java. For instance, the wrapper class for int is Integer, the class for float is Float, and so on. Remember that the primitive name is simply the lowercase name of the wrapper except for char, which maps to Character, and int, which maps to Integer. -Example Java Program to demonstrate Wrapper Classes. (ii) Write a Java program to generate the sum of series 1 + 2 + 3 + 4 +n [Marks 10] import java.io.*; import java.lang.*; class TestSum { public static void main(String args[]) { String s; DataInputStream dr=new DataInputStream(System.in); try { System.out.println("Enter the value of n:"); s=dr.readLine(); int n=new Integer(s).intValue(); int sum=(n(n+1))/2; System.out.println("Sum of n numbers is:"+sum); } catch(Exception e) { System.out.println(e); } } } Output: Enter the value of n: 5 Sum of n numbers is: 15

UNIT II OBJECT-ORIENTED PROGRAMMING INHERITANCE

1. (i) Explain Inheritance and class hierarchy. [Marks 6] INHERITANCE Inheritance is the one in which one class extends the other class. The derived class inherits all the properties of the parent class. The is a relationship is implemented in inheritance.

TYPES OF INHERITANCE

SINGLE INHERITANCE: Here there is only one super class for a derived class.

MULTIPLE INHERITANCE There are multiple Parent classes for one derived class

MULTILEVEL INHERITANCE Java supports multilevel hierarchy in which we can construct hierarchy that contains several layers of inheritance.

SUPER KEYWORD When a sub class refers its immediate supr class u may need keyword super.

The sub class can call the constructor defined by the super class by the given for super(parameter-list)

1.(ii) Define Polymorphism. [Marks 4] POLYMORPHISM

Polymorphism is the ability of a single object to operate on different types. Println statement is the example of polymorphism in Java

Int x=10; System.out.println(x) //integer System.out.println(x) //string Here the single object println works on different objects. 1.(iii) Write briefly on Abstract classes with an example. [Marks 6] The class or method declared as abstract is not complete. If you give the keyword abstract to the class the class cannot be instantiated because it is incomplete.

abstract class x { abstract void printme(); void printmetoo(); { System.out.println(ordinary method) ; } }

class y extends x { void printme() { System.out.println(abstract method is implemented in class y); } } class abstract { public static void main(String args[]) { Y s= new y(); s.printme(); s.printmetoo(); } }

OUTPUT abstract method is implemented in class y ordinary method

2.i)(1) The cloneable interface CLONABLE INTERFACE

[Marks 6]

The clone method is a protected method of Object, which means that your code cannot simply call it.

Only the Employee class can clone Employee objects. There is a reason for this restriction. If all data fields in the object are numbers or other basic types, copying the fields is just fine. But if the object contains references to subobjects, then copying the field gives you another reference to the subobject, so the original and the cloned objects still share some information.

An example for clonable interface is 1. importjava.util.*; 2. 3. /** 4. * This program demonstrates cloning. 5. * @version 1.10 2002-07-01 6. * @author Cay Horstmann 7. */ 8. public class CloneTest 9. { 10. public static void main(String[] args) 11. { 12. try 13. { 14. Employee original = new Employee("John Q. Public", 50000); 15. original.setHireDay(2000, 1, 1); 16. Employee copy = original.clone(); 17. copy.raiseSalary(10); 18. copy.setHireDay(2002, 12, 31); 19. System.out.println("original=" + original); 20. System.out.println("copy=" + copy); 21. } 22. catch (CloneNotSupportedException e) 23. { 24. e.printStackTrace(); 25. } 26. } 27. } 28. 29. class Employee implements Cloneable 30. { 31. public Employee(String n, double s) 32. { 33. name = n;

34. salary = s; 35. hireDay = new Date(); 36. } 37. 38. public Employee clone() throws CloneNotSupportedException 39. { 40. // call Object.clone() 41. Employee cloned = (Employee) super.clone(); 43. // clone mutable fields 44. cloned.hireDay = (Date) hireDay.clone(); 45. 46. return cloned; 47. } 48. 49. /** 50. * Set the hire day to a given date. 51. * @param year the year of the hire day 52. * @param month the month of the hire day 53. * @param day the day of the hire day 54. */ 55. public void setHireDay(int year, int month, int day) 56. { 57. Date newHireDay = new GregorianCalendar( year, month - 1, day).getTime(); 58. 59. // Example of instance field mutation 60. hireDay.setTime(newHireDay.getTime()); 61. } 62. 63. public void raiseSalary(double byPercent) 64. { 65. double raise = salary * byPercent / 100; 66. salary += raise; 67. } 68. 69. public String toString() 70. { 71. return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; 72. } 73. 74. private String name; 75. private double salary; 76. private Date hireDay; 77. } 2.i)(2) The Proxy interface. [Marks 6] The proxy class can create brand-new classes at runtime. Such a

proxy class implements the interfaces that you specify. In particular, the proxy class has the following methods: All methods required by the specified interfaces; and All methods defined in the Object class (toString, equals, and so on). However, you cannot define new code for these methods at runtime. Instead, you must supply an invocation handler. An invocation handler is an object of any class that implements the InvocationHandler interface. That interface has a single method: Object invoke(Object proxy, Method method, Object[] args) To create a proxy object, you use the newProxyInstance method of the Proxy class. The method has three parameters: A class loader. As part of the Java security model, different class loaders for system classes, classes that are downloaded from the Internet, and so on, can be used. We discuss class loaders in Chapter 9 of Volume II. For now, we specify null to use the default class loader. An array of Class objects, one for each interface to be implemented. An invocation handler. The proxies can be demonstrated by a Program 1. importjava.lang.reflect.*; 2. importjava.util.*; 3. 4. /** 5. * This program demonstrates the use of proxies. 6. * @version 1.00 2000-04-13 7. * @author Cay Horstmann 8. */ 9. public class ProxyTest 10. { 11. public static void main(String[] args) 12. { 13. Object[] elements = new Object[1000]; 14. 15. // fill elements with proxies for the integers 1 ... 1000 16. for (int i = 0; i <elements.length; i++) 17. { 18. Integer value = i + 1; 19. InvocationHandler handler = new TraceHandler(value); 20. Object proxy = Proxy.newProxyInstance(null, new Class[] { Comparable.class } , handler); 21. elements[i] = proxy; 22. } 23. 24. // construct a random integer

25. Integer key = new Random().nextInt(elements.length) + 1; 26. 27. // search for the key 28. int result = Arrays.binarySearch(elements, key); 29. 30. // print match if found 31. if (result >= 0) System.out.println(elements[result]); 32. } 33. } 34. 35. /** 36. * An invocation handler that prints out the method name and parameters, then 37. * invokes the original method 38. */ 39. classTraceHandler implements InvocationHandler 40. { 41. /** 42. * Constructs a TraceHandler 43. * @param t the implicit parameter of the method call 44. */ 45. publicTraceHandler(Object t) 46. { 47. target = t; 48. } 49. 50. public Object invoke(Object proxy, Method m, Object[] args) throws Throwable 51. { 52. // print implicit argument 53. System.out.print(target); 54. // print method name 55. System.out.print("." + m.getName() + "("); 56. // print explicit arguments 57. if (args != null) 58. { 59. for (int i = 0; i <args.length; i++) 60. { 61. System.out.print(args[i]); 62. if (i <args.length - 1) System.out.print(", "); 63. } 64. } 65. System.out.println(")"); 66. 67. // invoke actual method 68. returnm.invoke(target, args); 69. } 70.

71. private Object target; 72. } 2.(ii) What is a static Inner class? Explain with example. [Marks 4] a) When we need to use an inner class to hide one class inside another, we use static inner class. b) This suppresses the generation of the reference to the outer class object. c) Only inner classes can be declared static. d) It is like any other inner class, except that the object of it does not have a reference to the outer class that generated it. e) Consider an example where the minimum and maximum values have to be found from an array. f) The minmax function returns an object of type Pair that holds two values(min and max). g) The class name Pair can lead to potential name clash and hence, it is made as a public static inner class inside the class ArrayAlg. h) Hence, no reference is created for the outer class. 3. Explain with a Java program to exhibit the properties of Reflection to analyze the behavior of a class. [Marks 16] Ans ) The usage of three important classes are demonstrated : a) Field b) Method c) Constructor
1) getName : returns the name of the item. 2) getType : returns an object of type Class that describes the field type. 3) getModifiers : returns an integer, that describes the modifiers used (public and

static).
4) isPublic : whether the method or constructor was public. 5) isPrivate : whether the method or constructor was private. 6) isFinal : whether the method or constructor was final. 7) Modifier.toString : to print the modifiers.

8) getFields, getMethods, getConstructors : return arrays of the public fields,methods,

and constructors that the class supports.(including public members of superclasses).


9) getDeclaredFields,getDeclaredMethods, and getDeclaredConstructors : return

arrays consisting of all fields, methods, and constructors that are declared in the class(includes private and public and excluding superclasses members).
10)

getParamTypes : returns an array of parameter types.

PROGRAM : 1. import java.util.*; 2. import java.lang.reflect.*; 3. 4. /** 5. * This program uses reflection to print all features of a class. 6. * @version 1.1 2004-02-21 7. * @author Cay Horstmann 8. */ 9. public class ReflectionTest 10. { 11. public static void main(String[] args) 12. { 13. // read class name from command line args or user input 14. String name; 15. if (args.length > 0) name = args[0]; 16. else 17. { 18. Scanner in = new Scanner(System.in); 19. System.out.println("Enter class name (e.g. java.util.Date): "); 20. name = in.next(); 21. } 22. 23. try 24. { 25. // print class name and superclass name (if != Object) 26. Class cl = Class.forName(name); 27. Class supercl = cl.getSuperclass(); 28. String modifiers = Modifier.toString(cl.getModifiers()); 29. if (modifiers.length() > 0) System.out.print(modifiers + " "); 30. System.out.print("class " + name); 31. if (supercl != null && supercl != Object.class) System.out.print(" extends " 32. + supercl.getName()); 33. 34. System.out.print("\n{\n"); 35. printConstructors(cl);

36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81.

System.out.println(); printMethods(cl); System.out.println(); printFields(cl); System.out.println("}"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.exit(0); } /** * Prints all constructors of a class * @param cl a class */ public static void printConstructors(Class cl) { Constructor[] constructors = cl.getDeclaredConstructors(); for (Constructor c : constructors) { String name = c.getName(); System.out.print(" "); String modifiers = Modifier.toString(c.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print(name + "("); // print parameter types Class[] paramTypes = c.getParameterTypes(); for (int j = 0; j < paramTypes.length; j++) { if (j > 0) System.out.print(", "); System.out.print(paramTypes[j].getName()); } System.out.println(");"); } } /** * Prints all methods of a class * @param cl a class */ public static void printMethods(Class cl) {

82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. }

Method[] methods = cl.getDeclaredMethods(); for (Method m : methods) { Class retType = m.getReturnType(); String name = m.getName(); System.out.print(" "); // print modifiers, return type, and method name String modifiers = Modifier.toString(m.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.print(retType.getName() + " " + name + "("); // print parameter types Class[] paramTypes = m.getParameterTypes(); for (int j = 0; j < paramTypes.length; j++) { if (j > 0) System.out.print(", "); System.out.print(paramTypes[j].getName()); } System.out.println(");"); } } /** * Prints all fields of a class * @param cl a class */ public static void printFields(Class cl) { Field[] fields = cl.getDeclaredFields(); for (Field f : fields) { Class type = f.getType(); String name = f.getName(); System.out.print(" "); String modifiers = Modifier.toString(f.getModifiers()); if (modifiers.length() > 0) System.out.print(modifiers + " "); System.out.println(type.getName() + " " + name + ";"); } }

4. Explain the use of Object, System and Class classes with examples.

[Marks 16]

Ans: SYSTEM CLASS System class provides a standard interface to standard input,output and error. Has 3 variables in,out,err which represent input,output and error. getProperties() method gets system details and java platform being used. Eg:System.getProperty(os.name);System.getProperty(java.vendor);

//program for system class import java.lang.*; import java.io.*; class sys { public static void main(String args[])//Main Method { byte alpha[]={65,66,67,68,97,98}; byte beta[]={69,69,69,70,70,70}; System.out.println("Alpha="+new String(alpha)); System.out.println("Beta="+new String(beta)); System.arraycopy(alpha,0,beta,0,alpha.length); System.out.println("Now Alpha="+new String(alpha)); System.out.println("Now Beta="+new String(beta)); } } OUTPUT: Alpha=ABCDab Beta=EEEFFF Now Alpha=ABCDab Now Beta=ABCDab CLASS class: Used to find runtime state of an object or interface Objects of type class are created automatically when classes are loaded getName() returns complete name of clas or interface of invoking object getSuperClass() returns super class of invoking object

//program for class class import java.lang.*; import java.io.*; class A { int x; int y; }

class B extends A { int x; } class find { public static void main(String args[])//Main Method { A a1=new A(); B b1=new B(); System.out.println("a1 is object of type"+a1.getClass()); System.out.println("b1 is object of type"+b1.getClass()); } } OUTPUT: a1 is object of typeclass A b1 is object of typeclass B OBJECT CLASS The Object Class is the super class for all classes in Java. The Object class is the ultimate ancestorevery class in Java extends Object Some of the object class methods are: equals() toString() wait() notify() notifyAll() hashcode() clone() The equals Method The equals method in the Object class tests whether one object is considered equal to another. The equals method, as implemented in the Object class, determines whether two object references are identical static boolean equals(type[] a, type[] b) 5.0 The hashCode Method A hash code is an integer that is derived from an object. Hash codes should be scrambled if x and y are two distinct objects, there should be a high probability that x.hashCode() and y.hashCode() are different here is a hashCode method for the Employee class: class Employee { public int hashCode() { return 7 * name.hashCode() + 11 * new Double(salary).hashCode()

+ 13 * hireDay.hashCode(); } ... } The toString Method Another important method in Object is the toString method that returns a string representing the value of this object. Example: The toString method of the Point class returns a string like this: java.awt.Point[x=10,y=20] an implementation of the toString method for the Employee class: public String toString() { return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; } implements the equals, hashCode, and toString methods for the Employee and Manager classes. import java.util.*; /** * This program demonstrates the equals method. * @version 1.11 2004-02-21 * @author Cay Horstmann */ public class EqualsTest { public static void main(String[] args) { Employee alice1 = new Employee("Alice Adams", 75000, 1987, 12, 15); Employee alice2 = alice1; Employee alice3 = new Employee("Alice Adams", 75000, 1987, 12, 15); Employee bob = new Employee("Bob Brandson", 50000, 1989, 10, 1); System.out.println("alice1 == alice2: " + (alice1 == alice2)); System.out.println("alice1 == alice3: " + (alice1 == alice3));. System.out.println("alice1.equals(alice3): " + alice1.equals(alice3)); System.out.println("alice1.equals(bob): " + alice1.equals(bob)); System.out.println("bob.toString(): " + bob); Manager carl = new Manager("Carl Cracker", 80000, 1987, 12, 15); Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); boss.setBonus(5000); System.out.println("boss.toString(): " + boss); System.out.println("carl.equals(boss): " + carl.equals(boss));

System.out.println("alice1.hashCode(): " + alice1.hashCode()); System.out.println("alice3.hashCode(): " + alice3.hashCode()); System.out.println("bob.hashCode(): " + bob.hashCode()); System.out.println("carl.hashCode(): " + carl.hashCode()); } } class Employee { public Employee(String n, double s, int year, int month, int day) { name = n; salary = s; GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); hireDay = calendar.getTime(); } public String getName() { return name; } public double getSalary() { return salary; } public Date getHireDay() { return hireDay; } public void raiseSalary(double byPercent) { double raise = salary * byPercent / 100; salary += raise; }public boolean equals(Object otherObject) { // a quick test to see if the objects are identical if (this == otherObject) return true; // must return false if the explicit parameter is null if (otherObject == null) return false; // if the classes don't match, they can't be equal if (getClass() != otherObject.getClass()) return false; // now we know otherObject is a non-null Employee Employee other = (Employee) otherObject; // test whether the fields have identical values return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay); } public int hashCode()

{ return 7 * name.hashCode() + 11 * new Double(salary).hashCode() + 13 * hireDay.hashCode(); } public String toString() { return getClass().getName() + "[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; } private String name; private double salary; private Date hireDay; } class Manager extends Employee { public Manager(String n, double s, int year, int month, int day) { super(n, s, year, month, day); bonus = 0; } public double getSalary() { double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b) { bonus = b; } public boolean equals(Object otherObject) { if (!super.equals(otherObject)) return false; Manager other = (Manager) otherObject; // super.equals checked that this and other belong to the same class return bonus == other.bonus; } public int hashCode() { return super.hashCode() + 17 * new Double(bonus).hashCode(); } public String toString() { return super.toString() + "[bonus=" + bonus + "]"; } private double bonus;

} Class getClass() returns a class object that contains information about the object. As you see later in this chapter, Java has a runtime representation for classes that is encapsulated in the Class class. boolean equals(Object otherObject) compares two objects for equality; returns true if the objects point to the same area of memory, and false otherwise. You should override this method in your own classes. String toString() returns a string that represents the value of this object. You should override this method in your own classes. Object clone() creates a clone of the object. The Java runtime system allocates memory for the new instance and copies the memory allocated for the current object. String getName() returns the name of this class. Class getSuperclass() returns the superclass of this class as a Class object. 5. Enumerate with an example the usage of the cloneable interface in Java. [Marks 16] The clone method is a protected method of Object, which means that your code cannot simply call it. Only the Employee class can clone Employee objects. There is a reason for this restriction. If all data fields in the object are numbers or other basic types, copying the fields is just fine. But if the object contains references to subobjects, then copying the field gives you another reference to the subobject, so the original and the cloned objects still share some information.

An example for clonable interface is 1. importjava.util.*; 2. 3. /** 4. * This program demonstrates cloning. 5. * @version 1.10 2002-07-01 6. * @author Cay Horstmann

7. */ 8. public class CloneTest 9. { 10. public static void main(String[] args) 11. { 12. try 13. { 14. Employee original = new Employee("John Q. Public", 50000); 15. original.setHireDay(2000, 1, 1); 16. Employee copy = original.clone(); 17. copy.raiseSalary(10); 18. copy.setHireDay(2002, 12, 31); 19. System.out.println("original=" + original); 20. System.out.println("copy=" + copy); 21. } 22. catch (CloneNotSupportedException e) 23. { 24. e.printStackTrace(); 25. } 26. } 27. } 28. 29. class Employee implements Cloneable 30. { 31. public Employee(String n, double s) 32. { 33. name = n; 34. salary = s; 35. hireDay = new Date(); 36. } 37. 38. public Employee clone() throws CloneNotSupportedException 39. { 40. // call Object.clone() 41. Employee cloned = (Employee) super.clone(); 43. // clone mutable fields 44. cloned.hireDay = (Date) hireDay.clone(); 45. 46. return cloned; 47. } 48. 49. /** 50. * Set the hire day to a given date. 51. * @param year the year of the hire day 52. * @param month the month of the hire day 53. * @param day the day of the hire day

54. */ 55. public void setHireDay(int year, int month, int day) 56. { 57. Date newHireDay = new GregorianCalendar( year, month - 1, day).getTime(); 58. 59. // Example of instance field mutation 60. hireDay.setTime(newHireDay.getTime()); 61. } 62. 63. public void raiseSalary(double byPercent) 64. { 65. double raise = salary * byPercent / 100; 66. salary += raise; 67. } 68. 69. public String toString() 70. { 71. return "Employee[name=" + name + ",salary=" + salary + ",hireDay=" + hireDay + "]"; 72. } 73. 74. private String name; 75. private double salary; 76. private Date hireDay; 77. } 6. (i) Write a Java program to showcase Method overriding and Method overloading [Marks 8] import java.io.*; class a { void test(int x) { System.out.println("x="+x); } } class b extends a { void test(int y)//Method Overriding { System.out.println("y="+y); } void test(boolean b)//Method Overloading { System.out.println("the boolean value is:"+b);

} } class mfinal { public static void main(String args[])//Main Method { b b1=new b(); b1.test(8); a a1=new a(); a1.tets(2); b1.test(true); } } OUTPUT: x=8 y=2 the boolean value is:true 6.ii) Write a Java program to find the Volume of Cone and Sphere using interfaces. [Marks8] import java.io.*; public interface shape//defining interface { double volume(double a,double b); float pi=3.14f; } public class cone implements shape { public double volume(double a,double b) { return(0.33*pi*a*a*b); } } public class cylinder implements shape { public double volume(double a,double b) { return(pi*a*a*h); } } class interfacetest { public static void main(String args[])//Main Method { cone s=new cone();

cylinder c=new cylinder(); shape s1; s1=s;//Shape points to cone System.out.println("volume of cone:"+s1.volume(3.0,5.5)+"cubic units");; s1=c;//Shape points to cylinder System.out.println("volume of cylinder:"+s1.volume(4.0,3.0)+"cubic units"); } } OUTPUT: volume of cone:51.2919cubic units volume of cylinder:1657.92cubic units 7. Differentiate call by reference and call by value in Java. Write separate programs in Java to implement the two concepts. Ans:CALLBYVALUE CALLBYREFERENCE
1. Original value cannot be changed 2. Called method gets only a copy of the variable 3. Copy of the argument is maintained at different memory location. 1.Original value gets changed 2.called method gets the actual variable 3.Formal and actual parameters have a separate memory location

CALLBYVALUE import java.util.*; class myfunccall { void change(int i) { i=i*20; System.out.println("inside method"+i); } } class callbyval { public static void main(String args[])//Main Method { int x; myfunccall m=new myfunccall(); Scanner in=new Scanner(System.in); x=in.nextInt(); System.out.println("before call:"+x); m.change(x);//calling method of call by value System.out.println("after call:"+x); } } CALLBYREFERENCE

import java.util.*; class myfunccall { int i; myfunccall(int j) { i=j; } void change(myfunccall m) { m.i=m.i*20; System.out.println("inside method"+m.i); } } class callbyref { public static void main(String args[])//Main Method { int x; myfunccall m1=new myfunccall(x); Scanner in=new Scanner(System.in); x=in.nextInt(); System.out.println("before call:"+x); m1.change(m1);//calling method of call by reference System.out.println("after call:"+x); } } 8. Implement a Java program for (a) Inner classes (b) Local Inner classes [Marks 16] a)INNERCLASS import java.io.*; public class DataArray//Outer class { private final static int SIZE=15; private int[] arrInt=new int[SIZE]; public DataArray()//constructor { for(int i=0;i<SIZE;i++) { arrInt[i]=i; } } public void PrintEven()

{ InnerIterator ir=this.new InnerIterator(); while(ir.hasnext()) { System.out.println("even numbers are:"+ir.getnext()); } } public class InnerIterator//Inner class { private int next=2; public boolean hasnext() { return (next<=SIZE-1); } public int getnext() { int resval=arrInt[next]; next+=2; return resval; } } public static void main(String args[])//Main Method { DataArray ar=new DataArray(); ar.PrintEven(); } } OUTPUT: even numbers are:2 even numbers are:4 even numbers are:6 even numbers are:8 even numbers are:10 even numbers are:12 even numbers are:14 b)LOCAL INNERCLASS import java.io.*; import java.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import java.swing.Timer; class Innertest { public static void main(String args[]) {

TalkingClock cl=new TalkingClock(1000,true); } } class TalkingClock { private int interval; private boolean beep; public TalkingClock(int interval,boolean beep) { this.interval=interval; this.beep=beep; } public void start() { public class TimePrinter implements ActionListener { public void actionPerformed(ActionEvent e) { Date now=new Date(); System.out.println("At the tone the time is:"+now); if(beep) Toolkit.getDefaultToolkit().beep(); } } ActionListener l=new TimePrinter(); Timer t=new interval(interval,l); t.start(); } } 9. What is the use of a Static Inner class? Explain with an example program in Java. [Marks 16] import java.io.*; import java.util.*; class staticinnertest { public static void main(String args[]) //Main Method { double[] d=new double[10]; for(int i=0;i<d.length;i++) d[i]=100*Math.random(); ArrayAlg.Pair p=ArrayAlg.minmax(d); System.out.println("minimum value:"+p.getfirst());

System.out.println("maximum value:"+p.getsecond()); } } class ArrayAlg //Outer class { public static class Pair //Static Inner Class { private double first; private double second; Pair(double f,double s) { first=f; second=s; } public double getfirst() { return first; } public double getsecond() { return second; } } public static Pair minmax(double[] values) { double min=Double.MAX_VALUE; double max=Double.MIN_VALUE; for(double v:values) { if(min>v)min=v; if(max<v)max=v; } return new Pair(min,max); } } OUTPUT: minimum value:14.30054105417713 maximum value:58.747298592653664 10. What is the need for a Proxy in Java? Explore its use with an example. [Marks 16] The proxy class can create brand-new classes at runtime. Such a proxy class implements the interfaces that you specify. In particular, the proxy class has the following methods: All methods required by the specified interfaces; and

All methods defined in the Object class (toString, equals, and so on). However, you cannot define new code for these methods at runtime. Instead, you must supply an invocation handler. An invocation handler is an object of any class that implements the InvocationHandler interface. That interface has a single method: Object invoke(Object proxy, Method method, Object[] args) To create a proxy object, you use the newProxyInstance method of the Proxy class. The method has three parameters: A class loader. As part of the Java security model, different class loaders for system classes, classes that are downloaded from the Internet, and so on, can be used. We discuss class loaders in Chapter 9 of Volume II. For now, we specify null to use the default class loader. An array of Class objects, one for each interface to be implemented. An invocation handler. The proxies can be demonstrated by a Program 1. importjava.lang.reflect.*; 2. importjava.util.*; 3. 4. /** 5. * This program demonstrates the use of proxies. 6. * @version 1.00 2000-04-13 7. * @author Cay Horstmann 8. */ 9. public class ProxyTest 10. { 11. public static void main(String[] args) 12. { 13. Object[] elements = new Object[1000]; 14. 15. // fill elements with proxies for the integers 1 ... 1000 16. for (int i = 0; i <elements.length; i++) 17. { 18. Integer value = i + 1; 19. InvocationHandler handler = new TraceHandler(value); 20. Object proxy = Proxy.newProxyInstance(null, new Class[] { Comparable.class } , handler); 21. elements[i] = proxy; 22. } 23. 24. // construct a random integer 25. Integer key = new Random().nextInt(elements.length) + 1; 26. 27. // search for the key 28. int result = Arrays.binarySearch(elements, key);

29. 30. // print match if found 31. if (result >= 0) System.out.println(elements[result]); 32. } 33. } 34. 35. /** 36. * An invocation handler that prints out the method name and parameters, then 37. * invokes the original method 38. */ 39. classTraceHandler implements InvocationHandler 40. { 41. /** 42. * Constructs a TraceHandler 43. * @param t the implicit parameter of the method call 44. */ 45. publicTraceHandler(Object t) 46. { 47. target = t; 48. } 49. 50. public Object invoke(Object proxy, Method m, Object[] args) throws Throwable 51. { 52. // print implicit argument 53. System.out.print(target); 54. // print method name 55. System.out.print("." + m.getName() + "("); 56. // print explicit arguments 57. if (args != null) 58. { 59. for (int i = 0; i <args.length; i++) 60. { 61. System.out.print(args[i]); 62. if (i <args.length - 1) System.out.print(", "); 63. } 64. } 65. System.out.println(")"); 66. 67. // invoke actual method 68. returnm.invoke(target, args); 69. } 70. 71. private Object target; 72. } Properties of Proxy Classes

All proxy classes extend the class Proxy . A proxy class has only one instance fieldthe Invocation handler, which is defined in the Proxy superclass. Any additional data that are required to carry out the proxy objects tasks must be stored in the invocation handler. All proxy classes override the toString, equals, and hashCode methods of the Object class. Like all proxy methods, these methods simply call invoke on the invocation handler. The other methods of the Object class (such as clone and getClass) are not redefined. The names of proxy classes are not defined. The Proxy class in Suns virtual machine generates class names that begin with the string $Proxy. There is only one proxy class for a particular class loader and ordered set of interfaces. That is, if you call the newProxyInstance method twice with the same class loader and inter-face array, then you get two objects of the same class. You can also obtain that class with the getProxyClass method:

Class proxyClass = Proxy.getProxyClass(null, interfaces); A proxy class is always public and final. Object invoke(Object proxy, Method method, Object[] args) . define this method to contain the action that you want carried out whenever a method was invoked on the proxy object. static Class getProxyClass(ClassLoader loader, Class[] interfaces) returns the proxy class that implements the given interfaces. static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler

handler) constructs a new instance of the proxy class that implements the given interfaces. All methods call the invoke method of the given handler object. static booleanisProxyClass(Class c) returns true if c is a proxy class.

UNIT III EVENT-DRIVEN PROGRAMMING 1. (i) Explain the AWT Event handling in detail. [ Marks 8]

EventObject class has a subclass AWT Event, which is the parent of all AWT event classes. Some of the Swing components generate event objects of yet more event types; these directly extend EventObject, not AWT Event. The event objects encapsulate information about the event that the event source communicates to its listeners.

Defn of LOW LEVEL & SEMANTIC EVENTS A semantic event is one that expresses what the user is doing, such as clicking that button; hence, an Action-Event is a semantic event. Low-level events are those events that make this possible. In the case of a button click, this is a mouse down, a series of mouse moves, and a mouse up SEMANTIC EVENTS: ActionListener AdjustmentListener ItemListener

LOW LEVEL EVENTS: KeyListener MouseListener

MouseMotionListener MouseWheelListener WindowListener

(explain this if asked for 16 marks)

(ii) Give the methods available in graphics for COLOR. (iii) List the methods available to draw shapes. DRAWING A 2D LINE Line2D <object>=new Line2D.Double(Startpoint,End point) Line2D <object>=new Line2D.Float(Startpoint,End point) DRAWING A 2D RECTANGLE

[Marks 4] [Marks 4]

Rectangle2D <object>=new Rectangle2D.Double(leftX,TopY,width,height) Rectangle2D <object>=new Rectangle2D.Float(leftX,TopY,width,height) DRAWING A 2D ELLIPSE Ellipse2D <object>=new Ellipse2D.Double(leftX,TopY,width,height) Ellipse2D <object>=new Ellipse2D.Float(leftX,TopY,width,height) 2. (i) Explain the characteristics of Model View Controller design patterns. Every component has three characteristics: Its content, such as the state of a button (pushed in or not), or the text in a text field Its visual appearance (color, size, and so on) Its behavior (reaction to events) Implement three separate classes: The model, which stores the content The view, which displays the content

The controller, which handles user input. The model stores the content and has no

user interface.

(ii) Explain the advantage and explain the methods in Model view controller. [Marks 8]

3. (i) Explain the methods available to draw 2DShapes using a Swing program. [Marks 16] Methods available: DRAWING A 2D LINE Line2D <object>=new Line2D.Double(Startpoint,End point) Line2D <object>=new Line2D.Float(Startpoint,End point) DRAWING A 2D RECTANGLE Rectangle2D <object>=new Rectangle2D.Double(leftX,TopY,width,height) Rectangle2D <object>=new Rectangle2D.Float(leftX,TopY,width,height) DRAWING A 2D ELLIPSE Ellipse2D <object>=new Ellipse2D.Double(leftX,TopY,width,height) Ellipse2D <object>=new Ellipse2D.Float(leftX,TopY,width,height) //Program import java.awt.*; import java.awt.geom.*; import javax.swing.*; /** * @version 1.32 2007-04-14 * @author Cay Horstmann */ public class DrawTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { DrawFrame frame = new DrawFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } .

/** * A frame that contains a panel with drawings */ class DrawFrame extends JFrame { public DrawFrame() { setTitle("DrawTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add panel to frame DrawComponent component = new DrawComponent(); add(component); } public static final int DEFAULT_WIDTH = 400; public static final int DEFAULT_HEIGHT = 400; } /** * A component that displays rectangles and ellipses. */ class DrawComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; // draw a rectangle double leftX = 100; double topY = 100; double width = 200; double height = 150; Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height); g2.draw(rect); // draw the enclosed ellipse Ellipse2D ellipse = new Ellipse2D.Double(); ellipse.setFrame(rect); g2.draw(ellipse); // draw a diagonal line g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height)); // draw a circle with the same center double centerX = rect.getCenterX(); double centerY = rect.getCenterY(); double radius = 150; Ellipse2D circle = new Ellipse2D.Double(); circle.setFrameFromCenter(centerX,centerY,centerX + radius,centerY +radius); g2.draw(circle); }

(ii)Write a code snippet to display the Fonts available in the System.

[Marks 6]

call the getAvailable-FontFamilyNames method of the GraphicsEnvironment class. Method returns an array of strings that contains the names of all available fonts. import java.awt.*; public class ListFonts { public static void main(String[] args) { String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyN ames(); for (String fontName : fontNames) System.out.println(fontName); } } 4. (i) How will you use the FontRenderContext class to display a string Hello World in the center of the Frame Window. [Marks 16] import java.awt.*; import java.awt.font.*; import java.awt.geom.*;

import javax.swing.*; /** * @version 1.33 2007-04-14 * @author Cay Horstmann */ public class FontTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { FontFrame frame = new FontFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * A frame with a text message component */ class FontFrame extends JFrame { public FontFrame() { setTitle("FontTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add component to frame FontComponent component = new FontComponent(); add(component); } public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; } /** * A component that shows a centered message in a box. */ class FontComponent extends JComponent { public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; String message = "Hello, World!"; Font f = new Font("Serif", Font.BOLD, 36);

g2.setFont(f); // measure the size of the message FontRenderContext context = g2.getFontRenderContext(); Rectangle2D bounds = f.getStringBounds(message, context); // set (x,y) = top-left corner of text double x = (getWidth() - bounds.getWidth()) / 2; double y = (getHeight() - bounds.getHeight()) / 2; // add ascent to y to reach the baseline double ascent = -bounds.getY(); double baseY = y + ascent; // draw the message g2.drawString(message, (int) x, (int) baseY); g2.setPaint(Color.LIGHT_GRAY); // draw the baseline g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY)); // draw the enclosing rectangle Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight()); g2.draw(rect); } }

5. Develop an AWT program to demonstrate the use of Choice and List to change the background color of the Frame window. [Marks 16] CHOICE : import java.awt.*; import java.awt.event.*; public class choicedemo extends Frame { String selected[]; Choice c; Button display; public choicedemo()

{ setTitle("CHOICE"); setLayout(new FlowLayout()); c=new Choice(4,true); c.addItem("VIOLET"); c.addItem("INDIGO"); c.addItem("BLUE"); c.addItem("GREEN"); c.addItem("YELLOW"); c.addItem("ORANGE"); c.addItem("RED"); add(c); display=new Button("CHANGE"); add(display); display.addActionListener(this); } public boolean Action(Event e,Object arg) { selected=new selected[7]; if(arg.equals("CHANGE")) selected=getchangeItems(); repaint(); return(super.action(e,arg)); } public void paint(Graphics g) { int x,i; for(i=0,x=25;i<7;i++,x+=25) g.drawString(selected[i],100,150+x); } public boolean handleEvent(Event e) { if(e.id==Event.WINDOW_DESTROY) System.exit(0); return(super.handleEvent(e)); } public static void main(String args[]) { new choicedemo(); } } LIST import java.awt.*; import java.awt.event.*; public class multiselection extends Frame

{ String selected[]; List l; Button display; public multiselection() { setTitle("MULTI SELECTION LIST BOX"); setLayout(new FlowLayout()); l=new List(4,true); l.addItem("VIOLET"); l.addItem("INDIGO"); l.addItem("BLUE"); l.addItem("GREEN"); l.addItem("YELLOW"); l.addItem("ORANGE"); l.addItem("RED"); add(l); display=new Button("SELECT"); add(display); display.addActionListener(this); } public boolean Action(Event e,Object arg) { selected=new selected[7]; if(arg.equals("SELECT")) selected=getSelectedItems(); repaint(); return(super.action(e,arg)); } public void paint(Graphics g) { int x,i; for(i=0,x=25;i<7;i++,x+=25) g.drawString(selected[i],100,150+x); } public boolean handleEvent(Event e) { if(e.id==Event.WINDOW_DESTROY) System.exit(0); return(super.handleEvent(e)); } public static void main(String args[]) { new multiselection(); } }

6. Develop an AWT program to demonstrate the use of Checkbox and CheckboxGroup to change the background color of the window. [Marks 16] CHECKBOX: import java.awt.*; import java.awt.event.*; public class checkboxdemo extends Frame { Checkbox r; Checkbox g; Checkbox b; public checkboxdemo() { setTitle("CHECK BOX DEMO"); setSize(300,600); r=new Checkbox("RED"); g=new Checkbox("GREEN"); b=new Checkbox("BLUE"); add(r); add(g); add(b); r.reshape(300,100,25,50); g.reshape(300,150,25,50); b.reshape(300,200,25,50); } public boolean action (Event e,Object arg) { if((r.getState())&&(!g.getState())&&(!b.getState())) setBackground(new Color(255,0,0)); if((!r.getState())&&(g.getState())&&(!b.getState())) setBackground(new Color(0,255,0)); if((!r.getState())&&(!g.getState())&&(b.getState())) setBackground(new Color(0,0,255)); if((r.getState())&&(g.getState())&&(!b.getState())) setBackground(new Color(255,255,0)); if((!r.getState())&&(g.getState())&&(b.getState())) setBackground(new Color(0,255,255)); if((r.getState())&&(!g.getState())&&(b.getState())) setBackground(new Color(255,0,255)); if((r.getState())&&(g.getState())&&(b.getState())) setBackground(new Color(255,255,255)); if((!r.getState())&&(!g.getState())&&(!b.getState())) setBackground(new Color(0,0,0)); repaint(); return(super.action(e,arg)); } public static void main(String args[])

{ new checkboxdemo(); } } CHECKBOX GROUP: import java.awt.*; import java.awt.event.*; public class checkgroup extends Frame { Checkbox v; Checkbox i; Checkbox g; Checkbox b; Checkbox y; Checkbox o; Checkbox r; public checkgroup() { setTitle("CHECK BOX GROUP DEMO"); setSize(300,600); CheckboxGroup cbg=new CheckboxGroup(); v=new Checkbox("VIOLET"); i=new Checkbox("INDIGO"); b=new Checkbox("BLUE"); g=new Checkbox("GREEN"); y=new Checkbox("YELLOW"); o=new Checkbox("ORANGE"); r=new Checkbox("RED"); add(cbg); add(v); add(i); add(b); add(g); add(y); add(o); add(r); v.reshape(300,100,25,50); i.reshape(300,150,25,50); g.reshape(300,200,25,50); b.reshape(300,250,25,50); y.reshape(300,300,25,50); o.reshape(300,350,25,50); r.reshape(300,400,25,50); } public boolean Action (Event e,Object arg)

{ if(v.getState()) setBackground(Color.VIOLET); if(i.getState()) setBackground(Color.INDIGO); if(b.getState()) setBackground(Color.BLUE); if(g.getState()) setBackground(Color.GREEN); if(y.getState()) setBackground(Color.YELLOW); if(o.getState()) setBackground(Color.ORANGE); if(r.getState()) setBackground(Color.RED); repaint(); return (super.Action(e,arg)); } public static void main(String args[]) { new checkgroup(); } } 7. What is a Layout? Explain the use of Border Layout and Card Layout with example programs [ Marks 16] A layout manager is an object that is used to organize components in a container. BORDER LAYOUT This is the default layout manager of the content pane of every JFrame. Unlike the flow layout manager, which completely controls the position of each component, the border layout manager lets us choose where we want to place each component. We can choose to place the component in the center, north, south, east, or west of the content pane The diagram discribes this layout //Program to illustrate Border layout import java.awt.*; class Borderlayout extends Frame { Button b;

public Borderlayout(String s) { super(s); setSize(300,140); setBackground(Color.red); setForeground(Color.blue); setCursor(Frame.HAND_CURSOR); show(); setLayout(new BorderLayout()); add(new Button("NORTH"),BorderLayout.NORTH); add(new Button("SOUTH"),BorderLayout.SOUTH); add(new Button("EAST"),BorderLayout.EAST); add(new Button("WEST"),BorderLayout.WEST); add(new Button("CENTER"),BorderLayout.CENTER); setVisible(true); } public Insets getInsets() { return new Insets(50,30,25,20); } public static void main(String args[]) { new Borderlayout("BORDER LAYOUT"); System.out.println("Press CTRL+C to quit"); } } OUTPUT:

CARD LAYOUT import java.awt.*; import java.awt.event.*; import java.applet.*; /* <APPLET CODE="Cardlayone.class" WIDTH="200"HEIGHT="500"> </APPLET> */ public class Cardlayone extends Applet implements ActionListener,MouseListener { Checkbox wnt,wxp,macos,solaris; Panel p;

Button windows,others; CardLayout c; public void init() { windows=new Button("WINDOWS"); others=new Button("OTHERS"); add(windows); add(others); p=new Panel(); c=new CardLayout(); p.setLayout(c); wnt=new Checkbox("WINDOWS NT/2000",null,true); wxp=new Checkbox("WINDOWS XP"); macos=new Checkbox("MACOS"); solaris=new Checkbox("SOLARIS"); Panel winpan=new Panel(); winpan.add(wnt); winpan.add(wxp); Panel otherpan=new Panel(); otherpan.add(macos); otherpan.add(solaris); p.add(winpan,"Windows"); p.add(otherpan,"Others"); add(p); windows.addActionListener(this); others.addActionListener(this); addMouseListener(this); } public void mousePressed(MouseEvent me) { c.next(p); } public void mouseClicked(MouseEvent me){} public void mouseEntered(MouseEvent me){} public void mouseExited(MouseEvent me){} public void mouseReleased(MouseEvent me){} public void actionPerformed(ActionEvent ae) { if(ae.getSource()==windows) c.show(p,"Windows"); else c.show(p,"Others"); } } OUTPUT:

8. With example programs explain the need for a Flow layout and Grid layout. Flow layout import java.awt.*; class FlowLay extends Frame { Button b; public FlowLay(String s) { super(s); setSize(300,140); setBackground(Color.red); setForeground(Color.blue); setCursor(Frame.HAND_CURSOR); show(); FlowLayout f=new FlowLayout(FlowLayout.RIGHT); setLayout(f); for(int i=1;i<=10;i++) { add(new Button("Button"+i)); } setVisible(true); } public static void main(String args[]) { new FlowLay("FLOW LAYOUT"); System.out.println("Press CTRL+C to quit"); } } OUTPUT

Grid layout import java.awt.*; class Gridlay extends Frame { Button b; public Gridlay(String s) { super(s); setSize(300,140); setBackground(Color.red); setForeground(Color.blue); setCursor(Frame.HAND_CURSOR); show(); setLayout(new GridLayout(4,4)); for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { int number=i*4+j; if(number>0) { add(new Button("Button"+number)); } } } setVisible(true); } public static void main(String args[]) { new Gridlay("GRID LAYOUT"); System.out.println("Press CTRL+C to quit"); } } OUTPUT

9. Explain the methods available to change the Swings LookAndFeel such as Metal, CDE/Motif and GTK+ using a Swing program. [Marks 16 ] import java.awt.EventQueue; import java.awt.event.*; import javax.swing.*; /** * @version 1.32 2007-06-12 * @author Cay Horstmann */ public class PlafTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { PlafFrame frame = new PlafFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * A frame with a button panel for changing look and feel */ class PlafFrame extends JFrame { public PlafFrame() { setTitle("PlafTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); buttonPanel = new JPanel(); UIManager.LookAndFeelInfo[] infos = UIManager.getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo info : infos) makeButton(info.getName(), info.getClassName()); add(buttonPanel); }

/** * Makes a button to change the pluggable look and feel. * @param name the button name * @param plafName the name of the look and feel class */ void makeButton(String name, final String plafName) { // add button to panel JButton button = new JButton(name); buttonPanel.add(button); // set button action button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { // button action: switch to the new look and feel try { UIManager.setLookAndFeel(plafName); SwingUtilities.updateComponentTreeUI(PlafFrame.this); } catch (Exception e) { e.printStackTrace(); } } }); } private JPanel buttonPanel; public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; } OUTPUT Metal:

CDE/Motif

Windows

Windows Classic

10. Explain the methods available to display an Image on a Frame using a Swing program. [Marks 16] ImageIO.read(newFile("E:\Javasample\blue_ball.gif")): This method can be used to read a new image file from the specified location g.copyArea(imgwidth,imgheight,i*imgwidth,j*imgheight);

This method can be used to copy the entire image several number of times to fill the entire space. import java.awt.*; import java.io.*; import javax.imageio.*; import javax.swing.*; /** * @version 1.33 2007-04-14 * @author Cay Horstmann */ public class ImageTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { ImageFrame frame = new ImageFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLO SE); frame.setVisible(true); } }); } } /** * A frame with an image component */ class ImageFrame extends JFrame { public ImageFrame() {

setTitle("ImageTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // add component to frame ImageComponent component = new ImageComponent(); add(component); } public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; } /** * A component that displays a tiled image */ class ImageComponent extends JComponent { public ImageComponent() { // acquire the image try { image = ImageIO.read(new File("blue-ball.gif")); } catch (IOException e) { e.printStackTrace(); } } public void paintComponent(Graphics g) { if (image == null) return; int imageWidth = image.getWidth(this); int imageHeight = image.getHeight(this); // draw the image in the top-left corner

g.drawImage(image, 0, 0, null); // tile the image across the component for (int i = 0; i * imageWidth <= getWidth(); i++) for (int j = 0; j * imageHeight <= getHeight(); j++) if (i + j > 0) g.copyArea(0, 0, imageWidth, imageHeight, i * imageWidth, j* imageHeight); } private Image image; } OUTPUT

11. (i) Explain the use of Mouse Events.

[Marks 10]

(ii) What is an Adapter class? Explain its use.

[Marks 6]

Kind of classes that avoids all implementation methods associated with the events

import javax.swing.*; import java.awt.*; public class Windowadapterdemo { public static void main(String args[]) { EventQueue.invokeLater(new Runnable() { public void run() { WindowFrame frame = new WindowFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } class WindowFrame extends JFrame

{ public WindowFrame() { setTitle("ImageTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); addWindowListener(new WindowAdapter() { void WindowClosing(WindowEvent we) { if(useragrees) { System.exit(0); } } }); } }

UNIT IV GENERIC PROGRAMMING 1. (i) Explain the concept of finally block in Exception with examples. [Marks 10]
Finally clause properly dispose the resource used by the try block

The code in the finally clause executes whether or not an exception was caught.

Here we show you how to properly dispose of a Graphics object. Graphics g = image.getGraphics(); try { // 1 code that might throw exceptions // 2 } catch (IOException e) { // 3 show error dialog // 4 } finally { // 5 g.dispose(); } // 6 Let us look at the three possible situations in which the program will execute the finally clause. 1. The code throws no exception, execution passes through points 1, 2, 5, and 6. 2. When exception is caught- In this scenario, execution passes through points 1, 3, 4, 5, and 6 3. No appropriate catch block- Execution passes through points 1 and 5 only. You can use the finally clause without a catch clause. InputStream in = ...; try { code that might throw exceptions } finally { in.close(); }

The in.close() statement in the finally clause is executed whether or not an exception is encountered in the try block. Sometimes the finally clause gives you grief, namely if the cleanup method can also throw an exception.

At last, the finally block executes, and the close method is called. That method can itself throw an IOException. When it does,then the original exception is lost and the IOException is thrown instead.

(ii) Explain the exception hierarchy [Marks 6]

In the Java programming language, an exception object is always an instance of a classderived from Throwable. Figure 1 is a simplified diagram of the exception hierarchy in Java.

Fig 1- Exception Hierarchy The Error hierarchy describes internal errors and resource exhaustion. The Exception hierarchy also splits into two branches: exceptions that derive from RuntimeException and those that do not. A RuntimeException - programming errors. Any other exception occurs because a bad thing, such as an I/O error. Exceptions that inherit from RuntimeException include such problems as A bad cast An out-of-bounds array access ArrayIndexOutOfBoundsException A null pointer access-NullPointerException Exceptions that do not inherit from RuntimeException include

Trying to read past the end of a file EOFException Trying to open a malformed URL MalformedURLException Trying to find a Class object for a string that does not denote an existing class -ClassNotFoundException

RuntimeException an unchecked exception. All other exceptions are called

checked exceptions.

Checked exception- The compiler provide exception handlers for all checked

exceptions. A method must declare all the checked exceptions that it might throw. Unchecked exceptions are either beyond your control (Error).

2. (i) Explain the concept of throwing and having multiple catch exceptions in Java. [Marks 6] Throwing Exceptions: We are allowed to throw any type of exceptions we want. We need to decide what exception type to throw. Syntax: throw new ExceptionObject; Ex: throw new EOFException(); or EOFException e = new EOFException(); throw e; String readData(Scanner in) throws EOFException { ... while (. . .) { if (!in.hasNext()) // EOF encountered { if (n < len) throw new EOFException(); } ... } return s; } The steps in throwing the exception is as follows 1. Find an appropriate exception class. 2. Make an object of that class. 3. Throw it. Once a method throws an exception, the method does not return to its caller. Catching Multiple Exceptions: We can catch multiple exception types in a try block and handle each type differently. Use a separate catch clause for each type as in the following example: try { code that might throw exceptions

} catch (MalformedURLException e1) { emergency action for malformed URLs } catch (UnknownHostException e2) { emergency action for unknown hosts } catch (IOException e3) { emergency action for all other I/O problems } The exception object (e1, e2, e3) may contain information about the nature of the exception. To find out more about the object, try e3.getMessage() To get the detailed error message (if there is one), or e3.getClass().getName() to get the actual type of the exception object. (ii) State the situations where assertions are not used. [Marks 4] Assertion failures are intended to be fatal, unrecoverable errors. So should not use assertions unnecessarily. Assertion checks are turned on only during development and testing. W e should not use it for other phases. It should not be used for user communication. (iii) Give an overview of Rethrowing or Chained exceptions. [Marks 4] We can throw an exception in a catch clause.

Rethrowing is used in subsystem failure Ex: ServletException.

catch an exception and rethrow it: try { access the database } catch (SQLException e) { throw new ServletException("database error: " + e.getMessage()); } Set the original exception as the cause of the new exception: try { access the database

} catch (SQLException e) { Throwable se = new ServletException("database error"); se.initCause(e); throw se; } When the exception is caught, the original exception can be retrieved: Throwable e = se.getCause(); 3. Explore in detail the use of StackTrace for a factorial program in Java. StackTraceTest.java 1. import java.util.*; 2. 3. /** 4. * A program that displays a trace feature of a recursive method call. 5. * @version 1.01 2004-05-10 6. * @author Cay Horstmann 7. */ 8. public class StackTraceTest 9. { 10. /** 11. * Computes the factorial of a number 12. * @param n a nonnegative integer 13. * @return n! = 1 * 2 * . . . * n 14. */ 15. public static int factorial(int n) 16. { 17. System.out.println("factorial(" + n + "):"); 18. Throwable t = new Throwable(); 19. StackTraceElement[] frames = t.getStackTrace(); 20. for (StackTraceElement f : frames) 21. System.out.println(f); 22. int r; 23. if (n <= 1) r = 1; 24. else r = n * factorial(n - 1); 25. System.out.println("return " + r); 26. return r; 27. } 28. 29. public static void main(String[] args) 30. { 31. Scanner in = new Scanner(System.in);

32. System.out.print("Enter n: "); 33. int n = in.nextInt(); 34. factorial(n); 35. } 36. } OUTPUT: factorial(3): StackTraceTest.factorial(StackTraceTest.java:18) StackTraceTest.main(StackTraceTest.java:34) factorial(2): StackTraceTest.factorial(StackTraceTest.java:18) StackTraceTest.factorial(StackTraceTest.java:24) StackTraceTest.main(StackTraceTest.java:34) factorial(1): StackTraceTest.factorial(StackTraceTest.java:18) StackTraceTest.factorial(StackTraceTest.java:24) StackTraceTest.factorial(StackTraceTest.java:24) StackTraceTest.main(StackTraceTest.java:34) return 1 return 2 return 6 4. (i) State and explain the programmers tips on using Exceptions. [Marks 10] 1. Exception handling is not supposed to replace a simple test. Testcase: if (!s.empty()) s.pop(); Using Exceptions: try() { s.pop(); } catch (EmptyStackException e) { } Timing Data Test - 646 milliseconds Throw/Catch- 21,739 milliseconds. Use exceptions for exceptional circumstances only. 2. Do not micromanage exceptions.

Many programmers wrap every statement in a separate try block. OutputStream out; Stack s; for (i = 0; i < 100; i++) { try { n = s.pop(); } catch (EmptyStackException s) { // stack was empty } try { out.writeInt(n); } catch (IOException e) { // problem writing to file } } It is better to write the code with less number of try and catch block, as follows: try { for (i = 0; i < 100; i++) { n = s.pop(); out.writeInt(n); } } catch (IOException e) { // problem writing to file } catch (EmptyStackException s) { // stack was empty } 3. Make good use of the exception hierarchy. Dont just throw a RuntimeException. Find an appropriate subclass or create your own. Dont just catch Throwable. It makes your code hard to read and maintain. Do not hesitate to turn an exception into another exception that is more appropriate.

For example, when you parse an integer in a file, catch the NumberFormatException and turn it into a subclass of IOException or MySubsystemException. 4. Do not squelch exceptions. Do not want to put it in the throws list because then the compiler will whine about all the methods that call your method. public Image loadImage(String s) { try { code that threatens to throw checked exceptions } catch (Exception e) {} // so there } 5. When you detect an error, tough love works better than indulgence. It is better to throw a EmptyStackException at the point of failure than to have a NullPointerException occur at later time. 6. Propagating exceptions is not a sign of shame. Often,it is actually better to propagate the exception instead of catching it: public void readStuff(String filename) throws IOException // not a sign of shame! { InputStream in = new FileInputStream(filename); ... } (ii) Explain how Assertions can be used for parameter checking? [Marks 4] Assertions can be used for parameter checking. Example of sorting an array is give below: /** Sorts the specified range of the specified array into ascending numerical order. The range to be sorted extends from fromIndex, inclusive, to toIndex, exclusive. @param a the array to be sorted. @param fromIndex the index of the first element (inclusive) to be sorted. @param toIndex the index of the last element (exclusive) to be sorted. @throws IllegalArgumentException if fromIndex > toIndex @throws ArrayIndexOutOfBoundsException if fromIndex < 0 or toIndex > a.length */ static void sort(int[] a, int fromIndex, int toIndex)

The documentation states that the method throws an exception if the index values are incorrect. The method contract had been slightly different: @param a the array to be sorted. (Must not be null) It is illegal to call the method with a null array. Then the method may start with the assertion assert a != null; Computer scientists call this kind of contract a precondition. 5. Briefly explain the use of Logging in Java with the help of a sample program. [Marks 16] Basic Logging: The logging system manages a default logger Logger.global that you can use instead of System.out. Use the info method to log an information message: Logger.global.info("File->Open menu item selected"); By default, the record is printed like this: May 10, 2004 10:12:15 PM LoggingImageViewer fileOpen INFO: File->Open menu item selected 1. import java.awt.*; 2. import java.awt.event.*; 3. import java.io.*; 4. import java.util.logging.*; 5. import javax.swing.*; 6. 7. /** 8. * A modification of the image viewer program that logs various events. 9. * @version 1.02 2007-05-31 10. * @author Cay Horstmann 11. */12. public class LoggingImageViewer 13. { 14. public static void main(String[] args) 15. { 16. if (System.getProperty("java.util.logging.config.class") == null 17. && System.getProperty("java.util.logging.config.file") == null) 18. { 19. try 20. { 21. Logger.getLogger("com.horstmann.corejava").setLevel(Level.ALL);

22. final int LOG_ROTATION_COUNT = 10; 23. Handler handler = new FileHandler("%h/LoggingImageViewer.log", 0, LOG_ROTATION_COUNT); 24. Logger.getLogger("com.horstmann.corejava").addHandler(handler); 25. } 26. catch (IOException e) 27. { 28. Logger.getLogger("com.horstmann.corejava").log(Level.SEVERE, 29. "Can't create log file handler", e); 30. } 31. } 32. 33. EventQueue.invokeLater(new Runnable() 34. { 35. public void run() 36. { 37. Handler windowHandler = new WindowHandler(); 38. windowHandler.setLevel(Level.ALL); 39. Logger.getLogger("com.horstmann.corejava").addHandler(windowHandler); 40. 41. JFrame frame = new ImageViewerFrame(); 42. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 43. 44. Logger.getLogger("com.horstmann.corejava").fine("Showing frame"); 45. frame.setVisible(true); 46. } 47. }); 48. } 49. } 50. 51. /** 52. * The frame that shows the image. 53. */ 54. class ImageViewerFrame extends JFrame 55. { 56. public ImageViewerFrame() 57. { 58. logger.entering("ImageViewerFrame", "<init>"); 59. setTitle("LoggingImageViewer"); 60. setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); 61. 62. // set up menu bar 63. JMenuBar menuBar = new JMenuBar(); 64. setJMenuBar(menuBar); 65. 66. JMenu menu = new JMenu("File"); 67. menuBar.add(menu);

68. 69. JMenuItem openItem = new JMenuItem("Open"); 70. menu.add(openItem); 71. openItem.addActionListener(new FileOpenListener()); 72. 73. JMenuItem exitItem = new JMenuItem("Exit"); 74. menu.add(exitItem); 75. exitItem.addActionListener(new ActionListener() 76. { 77. public void actionPerformed(ActionEvent event) 78. { 79. logger.fine("Exiting."); 80. System.exit(0); 81. } 82. }); 83. 84. // use a label to display the images 85. label = new JLabel(); 86. add(label); 87. logger.exiting("ImageViewerFrame", "<init>"); 88. } 89. 90. private class FileOpenListener implements ActionListener 91. { 92. public void actionPerformed(ActionEvent event) 93. { 94. logger.entering("ImageViewerFrame.FileOpenListener", "actionPerformed", event); 95. 96. // set up file chooser 97. JFileChooser chooser = new JFileChooser(); 98. chooser.setCurrentDirectory(new File(".")); 99. 100. // accept all files ending with .gif 101. chooser.setFileFilter(new javax.swing.filechooser.FileFilter() 102. { 103. public boolean accept(File f) 104. { 105. return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory(); 106. } 107. 108. public String getDescription() 109. { 110. return "GIF Images"; 111. }

112. }); 113. 114. // show file chooser dialog 115. int r = chooser.showOpenDialog(ImageViewerFrame.this); 116. 117. // if image file accepted, set it as icon of the label 118. if (r == JFileChooser.APPROVE_OPTION) 119. { 120. String name = chooser.getSelectedFile().getPath(); 121. logger.log(Level.FINE, "Reading file {0}", name); 122. label.setIcon(new ImageIcon(name)); 123. } 124. else logger.fine("File open dialog canceled."); 125. logger.exiting("ImageViewerFrame.FileOpenListener", "actionPerformed"); 126. } 127. } 128. 129. private JLabel label; 130. private static Logger logger = Logger.getLogger("com.horstmann.corejava"); 131. private static final int DEFAULT_WIDTH = 300; 132. private static final int DEFAULT_HEIGHT = 400; 133. } 134. 135. /** 136. * A handler for displaying log records in a window. 137. */ 138. class WindowHandler extends StreamHandler 139. { 140. public WindowHandler() 141. { 142. frame = new JFrame(); 143. final JTextArea output = new JTextArea(); 144. output.setEditable(false); 145. frame.setSize(200, 200); 146. frame.add(new JScrollPane(output)); 147. frame.setFocusableWindowState(false); 148. frame.setVisible(true); 149. setOutputStream(new OutputStream() 150. { 151. public void write(int b) 152. { 153. } // not called 154. 155. public void write(byte[] b, int off, int len) 156. {

157. output.append(new String(b, off, len)); 158. } 159. }); 160. } 161. 162. public void publish(LogRecord record) 163. { 164. if (!frame.isVisible()) return; 165. super.publish(record); 166. flush(); 167. } 168. 169. private JFrame frame; 170. } 6. Define Generic programming and explain the need for generics with a sample program to sort Strings. [Marks 16] Generic Programming Definition: Generic programming means to write code that can be reused for objects of many different types. The following program is to sort string objects with generic programming: PairTest.java 1. /** 2. * @version 1.00 2004-05-10 3. * @author Cay Horstmann 4. */ 5. public class PairTest1 6. { 7. public static void main(String[] args) 8. { 9. String[] words = { "Mary", "had", "a", "little", "lamb" }; 10. Pair<String> mm = ArrayAlg.minmax(words); 11. System.out.println("min = " + mm.getFirst()); 12. System.out.println("max = " + mm.getSecond()); 13. } 14. } 15. 16. class ArrayAlg 17. { 18. /** 19. * Gets the minimum and maximum of an array of strings. 20. * @param a an array of strings 21. * @return a pair with the min and max value, or null if a is null or empty 22. */

23. public static Pair<String> minmax(String[] a) 24. { 25. if (a == null || a.length == 0) return null; 26. String min = a[0]; 27. String max = a[0]; 28. for (int i = 1; i < a.length; i++) 29. { 30. if (min.compareTo(a[i]) > 0) min = a[i]; 31. if (max.compareTo(a[i]) < 0) max = a[i]; 32. } 33. return new Pair<String>(min, max); 34. } 35. }

A generic class is a class with one or more type variables.Pair class as an example The Pair class introduces a type variable T, enclosed in angle brackets < >, after the class name. A generic class can have more than one type variable.

We instantiate the generic type by substituting types for the type variables, such as Pair<String> We can think of the result as an ordinary class with constructors Pair<String>() Pair<String>(String, String) and methods String getFirst() String getSecond() void setFirst(String) void setSecond(String) In other words, the generic class acts as a factory for ordinary classes. The static minmax method traverses an array and simultaneously computes the minimum and maximum value. It uses a Pair object to return both results. Returns 0- Identical Positive value - Comes after Negative value Comes before.

7. Explain the use of Bounded types and wild card types in Generics with a Java program. [Marks 16] Bounded Types: Bounded types is to a to place restrictions on type variables on a class or method.

The notation <T extends BoundingType> expresses that T should be a subtype of the bounding type. Both T and the bounding type can be either a class or an interface. A type variable or wildcard can have multiple bounds. For example: T extends Comparable & Serializable The bounding types are separated by ampersands (&) because commas are used to separate type variables. 1. import java.util.*; 2. 3. /** 4. * @version 1.00 2004-05-10 5. * @author Cay Horstmann 6. */ 7. public class PairTest2 8. { 9. public static void main(String[] args) 10. { 11. GregorianCalendar[] birthdays = 12. { 13. new GregorianCalendar(1906, Calendar.DECEMBER, 9), // G. Hopper 14. new GregorianCalendar(1815, Calendar.DECEMBER, 10), // A. Lovelace 15. new GregorianCalendar(1903, Calendar.DECEMBER, 3), // J. von Neumann 16. new GregorianCalendar(1910, Calendar.JUNE, 22), // K. Zuse 17. }; 18. Pair<GregorianCalendar> mm = ArrayAlg.minmax(birthdays); 19. System.out.println("min = " + mm.getFirst().getTime()); 20. System.out.println("max = " + mm.getSecond().getTime()); 21. } 22. } 23. 24. class ArrayAlg 25. { 26. /** 27. Gets the minimum and maximum of an array of objects of type T. 28. @param a an array of objects of type T 29. @return a pair with the min and max value, or null if a is 30. null or empty 31. */ 32. public static <T extends Comparable> Pair<T> minmax(T[] a) 33. { 34. if (a == null || a.length == 0) return null; 35. T min = a[0]; 36. T max = a[0];

37. for (int i = 1; i < a.length; i++) 38. { 39. if (min.compareTo(a[i]) > 0) min = a[i]; 40. if (max.compareTo(a[i]) < 0) max = a[i]; 41. } 42. return new Pair<T>(min, max); 43. } 44. } Wildcard Types: The wildcard type Pair<? extends Employee> denotes any generic Pair type whose type parameter is a subclass of Employee, such as Pair<Manager>, but not Pair<String>. Supertype Bounds for Wildcards We can specify a supertype bound, like this: ? super Manager This wildcard is restricted to all supertypes of Manager. For example, Pair<? super Manager> has methods void setFirst(? super Manager) ? super Manager getFirst() The compiler doesnt know the exact type of the setFirst method but can call it with any object of type Manager, Employee, or Object, but not a subtype such as Executive. public interface Comparable<T> { public int compareTo(T other); } Here, the type variable indicates the type of the other parameter. For example, the String class implements Comparable<String>, and its compareTo method is declared as public int compareTo(String other)

1. import java.util.*; 2. 3. /** 4. * @version 1.00 2004-05-10 5. * @author Cay Horstmann 6. */ 7. public class PairTest3

8. { 9. public static void main(String[] args) 10. { 11. Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15); 12. Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15); 13. Pair<Manager> buddies = new Pair<Manager>(ceo, cfo); 14. printBuddies(buddies); 15. 16. ceo.setBonus(1000000); 17. cfo.setBonus(500000); 18. Manager[] managers = { ceo, cfo }; 19. 20. Pair<Employee> result = new Pair<Employee>(); 21. minmaxBonus(managers, result); 22. System.out.println("first: " + result.getFirst().getName() 23. + ", second: " + result.getSecond().getName()); 24. maxminBonus(managers, result); 25. System.out.println("first: " + result.getFirst().getName() 26. + ", second: " + result.getSecond().getName()); 27. } 28. 29. public static void printBuddies(Pair<? extends Employee> p) 30. { 31. Employee first = p.getFirst(); 32. Employee second = p.getSecond(); 33. System.out.println(first.getName() + " and " + second.getName() + " are buddies."); 34. } 35. 36. public static void minmaxBonus(Manager[] a, Pair<? super Manager> result) 37. { 38. if (a == null || a.length == 0) return; 39. Manager min = a[0]; 40. Manager max = a[0]; 41. for (int i = 1; i < a.length; i++) 42. { 43. if (min.getBonus() > a[i].getBonus()) min = a[i]; 44. if (max.getBonus() < a[i].getBonus()) max = a[i]; 45. } 46. result.setFirst(min); 47. result.setSecond(max); 48. } 49. 50. public static void maxminBonus(Manager[] a, Pair<? super Manager> result) 51. { 52. minmaxBonus(a, result);

53. PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type 54. } 55. } 56. 57. class PairAlg 58. { 59. public static boolean hasNulls(Pair<?> p) 60. { 61. return p.getFirst() == null || p.getSecond() == null; 62. } 63. 64. public static void swap(Pair<?> p) { swapHelper(p); } 65. 66. public static <T> void swapHelper(Pair<T> p) 67. { 68. T t = p.getFirst(); 69. p.setFirst(p.getSecond()); 70. p.setSecond(t); 71. } 72. } 73. 74. class Employee 75. { 76. public Employee(String n, double s, int year, int month, int day) 77. { 78. name = n; 79. salary = s; 80. GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day); 81. hireDay = calendar.getTime(); 82. } 83. 84. public String getName() 85. { 86. return name; 87. } 88. 89. public double getSalary() 90. { 91. return salary; 92. } 93. 94. public Date getHireDay() 95. { 96. return hireDay; 97. } 98.

99. public void raiseSalary(double byPercent) 100. { 101. double raise = salary * byPercent / 100; 102. salary += raise; 103. } 104. 105. private String name; 106. private double salary; 107. private Date hireDay; 108. } 109. 110. class Manager extends Employee 111. { 112. /** 113. @param n the employee's name 114. @param s the salary 115. @param year the hire year 116. @param month the hire month 117. @param day the hire day 118. */ 119. public Manager(String n, double s, int year, int month, int day) 120. { 121. super(n, s, year, month, day); 122. bonus = 0; 123. } 124. 125. public double getSalary() 126. { 127. double baseSalary = super.getSalary(); 128. return baseSalary + bonus; 129. } 130. 131. public void setBonus(double b) 132. { 133. bonus = b; 134. } 135. 136. public double getBonus() 137. { 138. return bonus; 139. } 140. 141. private double bonus; 142. } 8. Write short note on:-

(i) Virtual Machine and Generics (ii) Use of Raw type in Generic

[Marks 16]

i)Virtual Machine: The virtual machine does not have objects of generic typesall objects belong to ordinary classes. The backward compatibility was only abandoned fairly late in the development for Java generics. Whenever you define a generic type, a corresponding raw type is automatically provided. For example, the raw type for Pair<T> looks like this: public class Pair { public Pair(Object first, Object second) { this.first = first; this.second = second; } public Object getFirst() { return first; } public Object getSecond() { return second; } public void setFirst(Object newValue) { first = newValue; } public void setSecond(Object newValue) { second = newValue; } private Object first; private Object second; } T is an unbounded type variable, it is simply replaced by Object. The compiler translates the method call into two virtualmachine instructions: o A call to the raw method Pair.getFirst o A cast of the returned Object to the Employee type o Casts are also inserted when you access a generic field.

ii)Use of Raw types in Generics: The raw type replaces type variables with the first bound, or Object if no bounds are given. For example, the type variable in the class Pair<T> has no explicit bounds, hence the raw type replaces T with Object. Suppose we declare a slightly different type: public class Interval<T extends Comparable & Serializable> implements Serializable { public Interval(T first, T second) { if (first.compareTo(second) <= 0) { lower = first; upper = second; } else { lower = second; upper = first; } }

... private T lower; private T upper; } The raw type Interval looks like this: public class Interval implements Serializable { public Interval(Comparable first, Comparable second) { . . . } ... private Comparable lower; private Comparable upper; } The name of the raw type is simply the name of the generic type, with the type parameters removed. 9. (i) Explain how Generics and Inheritance are related. [Marks 6] (ii) Write a sample program to demonstrate the use of Reflection and Generics. [Marks 10] i) Generics and Inheritance:

Consider the situation

Manager[] topHonchos = . . .; Pair<Employee> result = ArrayAlg.minmax(topHonchos); // ERROR

The minmax method returns a Pair<Manager>, not a Pair<Employee>, and it is illegal to assign one to the other. we were allowed to convert a Pair<Manager> to a Pair<Employee>. Consider this code: Pair<Manager> managerBuddies = new Pair<Manager>(ceo, cfo); Pair<Employee> employeeBuddies = managerBuddies; // illegal, but suppose it wasn't employeeBuddies.setFirst(lowlyEmployee);

Clearly, the last statement is legal. But employeeBuddies and managerBuddies refer to the same object. We can always convert a parameterized type to a raw type. For example, Pair<Employee> is a subtype

ii. Sample Program to demonstrate Reflection and Generics How to relate Generics and Reflection the use of the various interface types are explained

1. import java.lang.reflect.*; 2. import java.util.*; 3. 4. /** 5. * @version 1.10 2004-05-15 6. * @author Cay Horstmann 7. */ 8. public class GenericReflectionTest 9. { 10. public static void main(String[] args) 11. { 12. // read class name from command-line args or user input 13. String name; 14. if (args.length > 0) name = args[0]; 15. else 16. { 17. Scanner in = new Scanner(System.in); 18. System.out.println("Enter class name (e.g. java.util.Collections): "); 19. name = in.next(); 20. } 21. 22. try

23. { 24. // print generic info for class and public methods 25. Class cl = Class.forName(name); 26. printClass(cl); 27. for (Method m : cl.getDeclaredMethods()) 28. printMethod(m); 29. } 30. catch (ClassNotFoundException e) 31. { 32. e.printStackTrace(); 33. } 34. } 35. 36. public static void printClass(Class cl) 37. { 38. System.out.print(cl); 39. printTypes(cl.getTypeParameters(), "<", ", ", ">", true); 40. Type sc = cl.getGenericSuperclass(); 41. if (sc != null) 42. { 43. System.out.print(" extends "); 44. printType(sc, false); 45. } 46. printTypes(cl.getGenericInterfaces(), " implements ", ", ", "", false); 47. System.out.println(); 48. } 49. 50. public static void printMethod(Method m) 51. { 52. String name = m.getName(); 53. System.out.print(Modifier.toString(m.getModifiers())); 54. System.out.print(" "); 55. printTypes(m.getTypeParameters(), "<", ", ", "> ", true); 56. 57. printType(m.getGenericReturnType(), false); 58. System.out.print(" "); 59. System.out.print(name); 60. System.out.print("("); 61. printTypes(m.getGenericParameterTypes(), "", ", ", "", false); 62. System.out.println(")"); 63. } 64. 65. public static void printTypes(Type[] types, String pre, String sep, String suf, 66. boolean isDefinition) 67. {

68. if (pre.equals(" extends ") && Arrays.equals(types, new Type[] { Object.class })) return; 69. if (types.length > 0) System.out.print(pre); 70. for (int i = 0; i < types.length; i++) 71. { 72. if (i > 0) System.out.print(sep); 73. printType(types[i], isDefinition); 74. } 75. if (types.length > 0) System.out.print(suf); 76. } 77. 78. public static void printType(Type type, boolean isDefinition) 79. { 80. if (type instanceof Class) 81. { 82. Class t = (Class) type; 83. System.out.print(t.getName()); 84. } 85. else if (type instanceof TypeVariable) 86. { 87. TypeVariable t = (TypeVariable) type; 88. System.out.print(t.getName()); 89. if (isDefinition) 90. printTypes(t.getBounds(), " extends ", " & ", "", false); 91. } 92. else if (type instanceof WildcardType) 93. { 94. WildcardType t = (WildcardType) type; 95. System.out.print("?"); 96. printTypes(t.getUpperBounds(), " extends ", " & ", "", false); 97. printTypes(t.getLowerBounds(), " super ", " & ", "", false); 98. } 99. else if (type instanceof ParameterizedType) 100. { 101. ParameterizedType t = (ParameterizedType) type; 102. Type owner = t.getOwnerType(); 103. if (owner != null) 104. { 105. printType(owner, false); 106. System.out.print("."); 107. } 108. printType(t.getRawType(), false); 109. printTypes(t.getActualTypeArguments(), "<", ", ", ">", false); 110. } 111. else if (type instanceof GenericArrayType) 112. {

113. GenericArrayType t = (GenericArrayType) type; 114. System.out.print(""); 115. printType(t.getGenericComponentType(), isDefinition); 116. System.out.print("[]"); 117. } 118. 119. } 120. } Listing 124 UNIT V CONCURRENT PROGRAMMING 1. (i) What is a thread? Explain its states and methods. [Marks 8]

Threads are more lightweight than processesit takes less overhead to create and destroy individual threads than it does to launch new processes. Threads can be in one of six states: New Runnable Blocked Waiting Timed waiting Terminated wait() sleep() I/O blocking resume() notify() suspend() Blocked stop() run() ends

New

start()

Runnabl stop() e run() ends

stop() run() ends New Threads

Dead

A thread enters the newly created by using a new operator. When a thread is in the new state,the program has not started executing code inside of it.

Runnable Threads

Once you invoke the start method, the thread is in the runnable state. It is subdivided into wo states-RUNNING and QUEUED state. When the thread is in running state,it is assigned by CPU cycles and is actually running. When it is in queued state,it is waiting in the queue and competing for its turn to spend CPU cycles.

Runni ng state

yield() yield()

Queue d state

Blocked and Waiting Threads When a thread is blocked or waiting, it is temporarily inactive. The blocked state is entered when one of the following events occur: 1. The thread itself or another thread calls the suspend() method. 2. The thread calls an objects wait() method. 3. The thread itself calls the sleep() method. 4. The thread is waiting for some I/O operation to complete. Terminated Threads A thread is terminated for one of two reasons: 1. It dies a natural death because the run method exits normally. 2. It dies abruptly because an uncaught exception terminates the run method. MethodsgetName() Obtain the thread name. setName() Set the name of a thread. isAlive() Determine if the thread is still running. join() Wait for thread to terminate. sleep() Suspend a thread for specified time. start() Start a thread by calling its run method. wait() This is used to make a thread wait.

notify() This is used to make a thread that is waiting. notifyall() This is used to make all the threads that is waiting. (ii) Explain thread properties. Thread Properties Properties of threads are thread priorities daemon threads, thread groups and handlers for uncaught exceptions. Thread Priorities In the Java programming language, every thread has a priority. By default, a thread inherits the priority of the thread that constructed it. You can increase or decrease thepriority of any thread with the setPriority method. You can set the priority to any value between MIN_PRIORITY (defined as 1 in the Thread class) and MAX_PRIORITY (defined as 10).NORM_PRIORITY is defined as 5. Daemon Threads You can turn a thread into a daemon thread by calling t.setDaemon(true); A daemon is simply a thread that has no other role in life than to serve others. Examples are timer threads that send regular timer ticks to other threads or threads that clean up stale cache entries. Two methods1. isDaemon() 2. setDaemon(boolean b) //PROGRAM import java.io.*; class DaemonThread { public void run() { for(int i=1;i<=3;i++) { System.out.println(Daemon Thread+i); } } } class DaemonDemo { public static void main(string args[])

[Marks 8]

{ try { DaemonThread dt=new DaemonThread(); dt.setDameon(true); if(dt.isDaemon()) { System.out.println(Daemon Thread); } dt.seDaemon(false); } catch(InterruptedException ie) {} } } Handlers for Uncaught Exceptions The handler must belong to a class that implements the Thread.UncaughtExceptionHandler interface. That interface has a single method, void uncaughtException(Thread t, Throwable e) As of Java SE 5.0, you can install a handler into any thread with the setUncaughtException- Handler method. You can also install a default handler for all threads with the static method setDefaultUncaughtExceptionHandler of the Thread class. [Marks 8]

2. (i) Explain the methods of interrupting threads in Java.


The interrupt method can be used to request termination of a thread. When the interrupt method is called on a thread, the interrupted status of the thread is set. This is a boolean flag that is present in every thread. Each thread should occasionally check whether it has been interrupted. To find out whether the interrupted status was set, first call the static Thread.currentThread method to get the current thread and then call the isInterrupted method: while (!Thread.currentThread().isInterrupted() && more work to do) { do more work }

When the interrupt method is called on a thread that blocks on a call such as sleep or wait, the blocking call is terminated by an InterruptedException.

The currentThread() method returns a reference to the thread in which it is called.

public void run() { try { ... while (more work to do) { do more work Thread.sleep(delay); } } catch(InterruptedException e) { // thread was interrupted during sleep } finally { cleanup, if required } // exiting the run method terminates the thread } (ii)What is the need for Multi-threaded programming? Explain. [Marks 8]

Multithreaded programs extend the idea of multitasking by taking it one level lower: individual programs will appear to do multiple tasks at the same time. Each task is usually called a threadwhich is short for thread of control. Programs that can run more than one thread at once are said to be multithreaded. Multithreading is extremely useful in practice. 1. For example, a browser should be able to simultaneously download multiple images. 2. A web server needs to be able to serve concurrent requests. 3. Graphical user interface (GUI) programs have a separate thread for gathering user interface events from the host operating environment. Multithreading changed dramatically in Java SE 5.0, with the addition of a large number of classes and interfaces that provide high-quality implementations of the mechanisms that most application programmers will need. [Marks 10]

3. (i) Explain the steps to create a User-defined Thread? 1. Extend the java.lang.Thread Class.

2. Override the run( ) method in the subclass from the Thread class to define the code executed by the thread. 3. Create an instance of this subclass. This subclass may call a Thread class constructor by subclass constructor. 4. Invoke the start( ) method on the instance of the class to make the thread eligible for running. The following program demonstrates a single thread creation extending the "Thread" Class: class MyThread extends Thread { String s=null; MyThread(String s1) { s=s1; start(); } public void run() { System.out.println(s); } } public class RunThread { public static void main(String args[]) { MyThread m1=new MyThread("Thread started...."); } } OUTPUT: T Thread started........ read (ii) Write down the steps to create a Daemon thread in Java. Daemon Threads You can turn a thread into a daemon thread by calling t.setDaemon(true); A daemon is simply a thread that has no other role in life than to serve others. Examples are timer threads that send regular timer ticks to other threads or threads that clean up stale cache entries. Two methods3. isDaemon() 4. setDaemon(boolean b) //PROGRAM

[Marks 6]

import java.io.*; class DaemonThread { public void run() { for(int i=1;i<=3;i++) { System.out.println(Daemon Thread+i); } } } class DaemonDemo { public static void main(string args[]) { try { DaemonThread dt=new DaemonThread(); dt.setDameon(true); if(dt.isDaemon()) { System.out.println(Daemon Thread); } dt.seDaemon(false); } catch(InterruptedException ie) {} } } 4. (i) Write a Java program to display a digital clock using Threads. import java.util.*; public class time { public static void main(String args[]) { System.out.println(\t\t\tDIGITAL CLOCK); System.out.println(\t\t\t------------------------); System.out.println(\n Press Ctrl+C for Stop the Clock); ClockThread t1=new ClockThread(); Thread mythread=new Thread(t1); Mythread.start(); } } class ClockThread implements Runnable [Marks 8]

{ Thread t; Stringclock; String ampm[]={AM,PM}; GregorianCalendar c=new GregorianCalendar(); public void start() { If(t==null) { T=new Thread(this); t.start(); } } public void run() { System.out.println(Now Time is); while(true) { try { for(;;) { Date day=new Date(); c.setTime(day); clock= c.get(Calendar.HOUR) + :+c.get (Calendar. MINUTE)+ :+ c.get(Calendar.SECOND) ++ampm[c.get(Calendar.AM_PM)]; System.out.print(clock+\r); t.sleep(1000); } } catch(InterruptedException e) {} } } public void stop() { t=null; } } OUTPUT: DIGITAL CLOCK -----------------------Press Ctrl+C for Stop the Clock Now Time is

9:27:56 PM (ii) State the use of Reentrant locks in threaded applications.

[Marks 6]

There are two mechanisms for protecting a code block from concurrent access. The Java language provides a synchronized keyword for this purpose, and Java SE 5.0 introduced the ReentrantLock class. The synchronized keyword automatically provides a lock as well as an associated condition, which makes it powerful and convenient for most cases that require explicit locking. The basic outline for protecting a code block with a ReentrantLock is: myLock.lock(); // a ReentrantLock object try { critical section } finally { myLock.unlock(); // make sure the lock is unlocked even if an exception is thrown } This construct guarantees that only one thread at a time can enter the critical section. As soon as one thread locks the lock object, no other thread can get past the lock statement. When other threads call lock, they are deactivated until the first thread unlocks the lock object. PROGRAM: (uses a lock to protect the transfer method of the Bank class) public class Bank { public void transfer(int from, int to, int amount) { bankLock.lock(); try { System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); } finally { bankLock.unlock(); } }

... private Lock bankLock = new ReentrantLock(); // ReentrantLock implements the Lock interface } 5. Explain the use of Synchronization using Reentrant locks for a Banking application in Java. [Marks 14] The synchronized keyword automatically provides a lock as well as an associated condition, which makes it powerful and convenient for most cases that require explicit locking.

//PROGRAM import java.util.concurrent.locks.*; /** * A bank with a number of bank accounts that uses locks for serializing access. * @version 1.30 2004-08-01 * @author Cay Horstmann */ public class Bank { /** * Constructs the bank. * @param n the number of accounts * @param initialBalance the initial balance for each account */ public Bank(int n, double initialBalance) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) accounts[i] = initialBalance; bankLock = new ReentrantLock(); sufficientFunds = bankLock.newCondition(); } /** * Transfers money from one account to another. * @param from the account to transfer from * @param to the account to transfer to * @param amount the amount to transfer */ public void transfer(int from, int to, double amount) throws InterruptedException { bankLock.lock(); try {

while (accounts[from] < amount) sufficientFunds.await(); System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); sufficientFunds.signalAll(); } finally { bankLock.unlock(); } } /** * Gets the sum of all account balances. * @return the total balance */ public double getTotalBalance() { bankLock.lock(); try { double sum = 0; for (double a : accounts) sum += a; return sum; } finally { bankLock.unlock(); } } /** * Gets the number of accounts in the bank. * @return the number of accounts */ public int size() { return accounts.length; } private final double[] accounts; private Lock bankLock; private Condition sufficientFunds; }

6. Explain (i) Synchronization using Reentrant Locks Synchronization using Reentrant Locks : - Defn of Synchronization The Java language provides i. a synchronized keyword ii. ReentrantLock class Defn of Reentrant Locks

[Marks 8]

Methods used by Reentrant Locks ReentrantLock() - constructs a reentrant lock that can be used to protect a critical section. ReentrantLock(boolean fair) - constructs a lock with the given fairness policy. A fair lock favors the thread that has been waiting for the longest time. However, this fairness guarantee can be a significant drag on performance. Therefore, by default, locks are not required to be fair. //Program to demonstrate Synchronization using Reentrant Locks import java.util.concurrent.locks.*; /** * A bank with a number of bank accounts that uses locks for serializing access. * @version 1.30 2004-08-01 * @author Cay Horstmann */ public class Bank { /** * Constructs the bank. * @param n the number of accounts * @param initialBalance the initial balance for each account */ public Bank(int n, double initialBalance) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) accounts[i] = initialBalance; bankLock = new ReentrantLock(); sufficientFunds = bankLock.newCondition(); }

/** * Transfers money from one account to another. * @param from the account to transfer from * @param to the account to transfer to * @param amount the amount to transfer */ public void transfer(int from, int to, double amount) throws InterruptedException { bankLock.lock(); try { while (accounts[from] < amount) sufficientFunds.await(); System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); sufficientFunds.signalAll(); } finally { bankLock.unlock(); } } /** * Gets the sum of all account balances. * @return the total balance */ public double getTotalBalance() { bankLock.lock(); try { double sum = 0; for (double a : accounts) sum += a; return sum; } finally { bankLock.unlock(); } }

/** * Gets the number of accounts in the bank. * @return the number of accounts */ public int size() { return accounts.length; } private final double[] accounts; private Lock bankLock; private Condition sufficientFunds; } In the above program , the transfer method calls the getTotalBalance method, which also locks the bankLock object, which now has a hold count of 2. When the getTotalBalance method exits, the hold count is back to 1. When the transfer method exits, the hold count is 0, and the thread relinquishes the lock. (ii) Using the synchronization keyword. [Marks 6] If a method is declared with the synchronized keyword, then the objects lock protects the entire method. That is, to call the method, a thread must acquire the intrinsic object lock. Syntax : public synchronized void method() { //method body } is the equivalent of public void method() { this.intrinsicLock.lock(); try { //method body } finally { //this.intrinsicLock.unlock(); } }

For example, you can implement the Bank class in Java like this: class Bank { public synchronized void transfer(int from, int to, int amount) throws InterruptedException { while (accounts[from] < amount) wait(); // wait on intrinsic object lock's single condition accounts[from] -= amount; accounts[to] += amount; notifyAll(); // notify all threads waiting on the condition } public synchronized double getTotalBalance() { . . . } private double[] accounts; } Using the synchronized keyword yields code that is much more concise. It is a need to know that each object has an intrinsic lock, and that the lock has an intrinsic condition. The lock manages the threads that try to enter a synchronized method. The condition manages the threads that have called wait. It is also legal to declare static methods as synchronized. If such a method is called, it acquires the intrinsic lock of the associated class object. For example, if the Bank class has a static synchronized method, then the lock of the Bank.class object is locked when it is called. As a result, no other thread can call this or any other synchronized static method of the same class. //Program to demonstrate use of Synchronized Keyword /** * A bank with a number of bank accounts that uses synchronization primitives. * @version 1.30 2004-08-01 * @author Cay Horstmann */ public class Bank { /** * Constructs the bank. * @param n the number of accounts * @param initialBalance the initial balance for each account */ public Bank(int n, double initialBalance) { accounts = new double[n]; for (int i = 0; i < accounts.length; i++) accounts[i] = initialBalance; }

/** * Transfers money from one account to another. * @param from the account to transfer from * @param to the account to transfer to * @param amount the amount to transfer */ public synchronized void transfer(int from, int to, double amount) throws InterruptedException { while (accounts[from] < amount) wait(); System.out.print(Thread.currentThread()); accounts[from] -= amount; System.out.printf(" %10.2f from %d to %d", amount, from, to); accounts[to] += amount; System.out.printf(" Total Balance: %10.2f%n", getTotalBalance()); notifyAll(); } /** * Gets the sum of all account balances. * @return the total balance */ public synchronized double getTotalBalance() { double sum = 0; for (double a : accounts) sum += a; return sum; } /** * Gets the number of accounts in the bank. * @return the number of accounts */ public int size() { return accounts.length; } private final double[] accounts; } Limitations

Preventing Limitations

7. Write a Java program to demonstrate ball bouncing in a window application using Swing and Threads. [Marks 16] //Program to demonstrate bouncing ball import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Shows an animated bouncing ball. * @version 1.33 2007-05-17 * @author Cay Horstmann */ public class Bounce { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new BounceFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * The frame with ball component and buttons. */ class BounceFrame extends JFrame { /** * Constructs the frame with the component for showing the bouncing ball and Start and * Close buttons */ public BounceFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setTitle("Bounce");

comp = new BallComponent(); add(comp, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); addButton(buttonPanel, "Start", new ActionListener() { public void actionPerformed(ActionEvent event) { addBall(); } }); addButton(buttonPanel, "Close", new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); add(buttonPanel, BorderLayout.SOUTH); } /** * Adds a button to a container. * @param c the container * @param title the button title * @param listener the action listener for the button */ public void addButton(Container c, String title, ActionListener listener) { JButton button = new JButton(title); c.add(button); button.addActionListener(listener); } /** * Adds a bouncing ball to the panel and makes it bounce 1,000 times. */ public void addBall() { try { Ball ball = new Ball(); comp.add(ball); for (int i = 1; i <= STEPS; i++) {

ball.move(comp.getBounds()); comp.paint(comp.getGraphics()); Thread.sleep(DELAY); } } catch (InterruptedException e) { } } private BallComponent comp; public static final int DEFAULT_WIDTH = 450; public static final int DEFAULT_HEIGHT = 350; public static final int STEPS = 1000; public static final int DELAY = 3; }

OUTPUT:
-

Running Bouncing Ball Window

Explanation [Marks 10]

8. (i) Explain the use of Thread Executors in Java Definition of Executors

Executors Factory Methods Method newCachedThreadPool newFixedThreadPool newSingleThreadExecutor Description New threads are created as needed; idle threads are kept for 60 seconds. The pool contains a fixed set of threads; idle threads are kept indefinitely. A pool with a single thread that executes the submitted tasks sequentially.

newScheduledThreadPool newSingleThreadScheduledExecutor

A fixed-thread pool for scheduled execution; a replacement for java.util.Timer. A single-thread pool for scheduled execution.

Thead Pools : Definition of Thread Pools Reasons for using ThreadPools

Explanation of newCachedThreadPool newFixedThreadPool newSingleThreadExecutor These three methods return an object of the ThreadPoolExecutor class that implements the ExecutorService interface.

Methods for submitting Runnable or Callable to an ExecutorService : Future<?> submit(Runnable task) Future<T> submit(Runnable task, T result) Future<T> submit(Callable<T> task)

To use a connection pool:

Scheduled Execution : The ScheduledExecutorService interface has methods for scheduled or repeated execution of tasks. It is a generalization of java.util.Timer that allows for thread pooling. The newScheduledThreadPool and newSingleThreadScheduledExecutor methods of the Executors class return objects that implement the ScheduledExecutorService interface. Controlling Groups of Tasks : An executor is used for a more tactical reason, simply to control a group of related tasks. For example, you can cancel all tasks in an executor with the shutdownNow method.
-

invokeAny method invokeAll method

Disadvantage [Marks 6]

(ii) Write down the use of Thread Safe collections Defn of Thread Safe Collections

Efficient Maps, Sets, and Queues Copy on Write Arrays

Efficient Maps, Sets, and Queues :


-

The java.util.concurrent package supplies ConcurrentHashMap ConcurrentSkipListMap ConcurrentSkipListSet ConcurrentLinkedQueue

weakly consistent iterators Explanation

Copy on Write Arrays : The CopyOnWriteArrayList and CopyOnWriteArraySet are thread-safe collections in which all mutators make a copy of the underlying array. This arrangement is useful if the number of threads that iterate over the collection greatly outnumbers the threads that mutate it. When you construct an iterator, it contains a reference to the current array. If the array is later mutated, the iterator still has the old array, but the collections array is replaced. As a consequence, the older iterator has a consistent view that it can access without any synchronization expense. Older Thread-Safe Collections : Any collection class can be made thread-safe by means of a synchronization wrapper: List<E> synchArrayList = Collections.synchronizedList(new ArrayList<E>()); Map<K, V> synchHashMap = Collections.synchronizedMap(new HashMap<K, V>());

The methods of the resulting collections are protected by a lock, providing threadsafe access. 9. (i) Give a brief description about the use of Synchronizers in Java Synchronizers Defn of Synchronizers Class CyclicBarrier What It Does Allows a set of threads to wait until a predefined count of them has reached a common barrier, and then optionally executes a barrier action Allows a set of threads to wait until a count has been decremented to 0. [Marks 10]

When To Use When a number of threads need to complete before their results can be used.

CountDownLatch

When one or more threads need to wait until a specified number of events have occurred.

Exchanger

Allows two threads to When two threads work on exchange objects when both two instances of the same are ready for the exchange. data structure, one by filling an instance and the other by emptying the other. Allows a set of threads to wait until permits are available for proceeding To restrict the total number of threads that can access a resource. If permit count is one, use to block threads until another thread gives permission To send an object from one thread to another when both are ready, without explicit synchronization

Semaphore

SynchronousQueue

Allows a thread to hand off an object to another thread.

Semaphores : -

Defn of Semaphores Conceptually, a semaphore manages a number of permits. The semaphore simply keeps a count

This generality makes semaphores both very flexible and potentially confusing. They are powerful enough to solve many common thread synchronization problems.

Countdown Latches : Barriers : Defn of Bariers Construct a barrier, giving the number of participating threads: Defn of Countdown Latch Special Case Example

CyclicBarrier barrier = new CyclicBarrier(nthreads); Each thread does some work and calls await on the barrier upon completion: public void run() { doWork(); barrier.await(); ... } The await method takes an optional timeout parameter: barrier.await(100, TimeUnit.MILLISECONDS);

Runnable barrierAction = . . .; CyclicBarrier barrier = new CyclicBarrier(nthreads, barrierAction); The action can harvest the result of the individual threads. The barrier is called cyclic because it can be reused after all waiting threads have been released. In this regard, it differs from a CountDownLatch, which can only be used once. Exchangers : An Exchanger is used when two threads are working on two instances of the same data buffer. Typically, one thread fills the buffer, and the other consumes its contents. When both are done, they exchange their buffers.

Synchronous Queues :

A synchronous queue is a mechanism that pairs up producer and consumer threads. When a thread calls put on a SynchronousQueue, it blocks until another thread calls take, and vice versa. Unlike the case with an Exchanger, data are only transferred in one direction, from the producer to the consumer. Even though the SynchronousQueue class implements the BlockingQueue interface, it is not conceptually a queue. It does not contain any elements. Its size method always returns 0.

(ii) How Threads can be related with Event Driven programming? Explain [Marks 6]

You might also like