You are on page 1of 120

MCA June 2007 Solved Paper

Unit1
Q.1(a) What are differences between applications and applets? Is the compilation process different for applications and applets? Write in brief about Applet viewer.

Application Applet An application runs stand1 alone, with the support of a An applet runs under the control of a browser. virtual machine. The true power of Java lies Applets are great for creating dynamic and interactive 2 in writing full blown web applications applications. In an application execution 3 Applets don't have the main method. starts with the main method. The applications run on Applets are designed for the client site programming 4 Desktop. purpose, downloaded and run on Browser. The java applications are Applets are designed just for handling the client site 5 designed to work with the problems. client as well as server. Applications are designed to 6 The applets can run in secure and unsecured environment exist in a secure area. Does not require to inherit 7 Applet need to inherit java.awt.Applet class any class Static block is called at time init() method is called at time of applet creation and 8 of application call destroy() method is called at time of applet destruction Does not have any other life Has init(), start(), paint(), stop(), destroy() life cycle 9 cycle methods methods

Applet:import java.awt.*; import java.applet.*;

class ClassName extends Applet { public void init() { System.out.println("This is init method"); //called only once } public void start() { System.out.println("This is Start method"); //Called again and again when applet is activated (browser window is maximized) } public void stop() { System.out.println("This is Start method"); //Called again and again when applet is deactivated (browser window is minimized) } public void paint(Graphics g) { System.out.println("This is Paint method"); //Called again and again when applet is rendered } }

Application:public class ClassName { public static void main(String args[]) { System.out.println("Hello Application"); } } Compilation process : It is same for Applet and Application. There are no differences. javac command is used to compile both. AppletViewer : It is a standalone, command line program from Sun to run Java applets. Appletviewer is generally used by developers for testing their applets before being deployed to a website. As a Java developer, it is a preferred option for running Java applets that doesn't involve the use of a Web browser. Even though the applet viewer logically takes the place of a Web browser, it functions very differently than a Web browser. The applet viewer operates on HTML documents, but all it looks for is embedded applet tags; any other

HTML code in the document is ignored. Each time the applet viewer encounters an applet tag in an HTML document, it launches a separate applet viewer window containing the respective applet. The only drawback to using the applet viewer is that it won't show you how an applet will run within the confines of a real Web setting. Because the applet viewer ignores all HTML codes except applet tags, it doesn't even attempt to display any other information contained in the HTML document. Appletviewer is included with Sun's JDK package, but not with Sun's JRE package. (b) Why is it unnecessary for constructors to have return types? How many parameters does a default constructor require? Why can we call a dynamically binded method in a constructor? Constructor is a special method in java. The purpose of the constructor is to assign initial values to the instance variable of the class. Constructor is always called by new operator. Constructors are declared just like as we declare methods, except that the constructors dont have any return type. Since constuctors are called by JVM at runtime during object instantiation so it does not required any return value. Default constructor does not require any parameter. It is called default constructor only because it does not receive any parameter. If the parameters are passed in the constructor then it will no longer be a default constructor. If no constructor is defined then JVM will create a default constructor. If a developer creates a constructor with parameters then developer need to define default constuctor, JVM will not create it. Dynamic binding is happned when polymorphism is occued due to Inheritence, method overloading, and method overriding. A constructor is called when an object is instantiated. One constructor can call another constructor. If no other constructor is called then its super class constructor is called automatically. In other words, parent class constructor is always called when a child is instantiated , because of that dynamically binded methods are called. (c) What is the use of this and super keyword? Illustrate through suitable examples. The keyword 'this' and 'super' are used in java programs to call different classes of java at runtime. The keyword this is used for pointing the current class instance. It can be used with variables or methods. Look into the following example: class Test{ private int i=10;

public void m(){ System.out.println(this.i); } } In the above code this is used for the current instance. Since this is instance of a class it cannot be used inside a static method, as the static method has only one instance of it i.e. it loaded in the memory only once at the time of execution. The keyword super is used with a parent and child relationship for pointing the super class instance i.e. to point the parent class instance. See the following example. class Parent { int k = 10; } class Child extends Parent { public void m() { System.out.println(super.k); } } In the above example the super keyword is used for accessing the parent class variable. Q.2(a) Write a program in java that contains a method strip vowels(), that extracts and processes the current input line. The method returns, as a string, the consonant portion of the input. (b) Explain the following example:(i) dynamic method dispatch Dynamic method dispatch is the process the Java runtime system uses to determine which method implementation to call in an inheritance hierarchy. For example, the Object class has a toString() method that all subclasses inherit, but the String class overrides this method to return its string content. If a String or other object type is assigned to an Object reference using application logic, the Java compiler cannot know in advance where a call to the toString() method will be resolved, it must be determined dynamically at runtime. (ii) method overriding When a method with same name and set of parameters is defined in parent(super) class and child class then child method is called overridden method and process is called method overriding. When an overridden method is called from within a subclass, it will

always refer to the version of that method defined by the subclass. The version in the superclass will be hidden. If you wish to access the superclass version of an overridden method, you can do so by using super keyword.

Fig. showing Method Overriding In order to make a method overridden:


The

return type, method name, type and order of arguments must be identical to those of a method in a parent class. The accessibility must not be more restrictive than original method. The method must not throw checked exceptions of classes that are not possible for the original method Copyright (c)

Unit2
Q.3(a) What is an interface? How is it declared and implemented? Give a suitable example is there any differences between an abstract class and interface? An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. Because an interface has simply a list of unimplemented methods, therefore these methods are also know as abstract methods, you might wonder how an interface differs from an abstract class. The differences are significant.
An

interface cannot implement any methods, whereas an abstract class

can. A class can implement many interfaces but can have only one superclass. An interface is not part of the class hierarchy. Unrelated classes can implement the same interface. An interface is simply declared by using keyword interface before the class name i.e. public interface className{ public user add(); public address add(); } To implement above interface, the name of your class would change (to classImp, for example), and you'd use the implements keyword in the class declaration: Yes there are many difference between an Interface & Abstract Class we can understand some difference with the help of this Exp:Example of Abstract Class public abstract class Hello ( public void sayHello () { System.out.println (Hello World); }

public abstract void shakHand(); }

Example of Interface Public interface Hello{ Public void sayHello(); public void shakHand(); } (b) In what situation a runnable interface is required to launch threads? Give a suitable example. How do you create a thread group can you control an individual thread in a thread group? We can create a thread in Java by extending Thread Class. A better way to create a thread in Java is to implement Runnable interface. A thread can be created by extending Java Thread class also. Now the question arises why implementing Runnable interface is a better approach? Answer is, if the thread class you are creating is to be subclass of some other class, it cant extend from the Thread class. This is because Java does not allow a class to inherit from more than one class. In such a case one can use Runnable interface to implement threads. We can create new threads with the 'Thread' class and runnable objects, which are created with classes that implements the 'Runnable' interface. The second way to create a new thread is to:
Implement Implement

the "Runnable" interface in your own class. the run () method defined in the "Runnable" interface in your own

class. Instantiate a runnable object of your own class. Instantiate a thread object of the "Thread" class with the runnable object specified. Call the start () method on the new object. class HelloRunnable implements Runnable { public static void main (String [] a) { HelloRunnable r = new HelloRunnable (); Thread t = new Thread(r); t.start (); System.out.println ("Hello world! - From the main program."); } public void run () {

for(int i=0;i<50;i++){ System.out.println (i+"Hello world."); } } } Q.4(a) What is meant by daemon thread? In java runtime, what is its role? Write a class whose objects hold a current value and have a method to add to that value, printing the new value. Write a program that creates such an object, creates multiple threads , and invokes the adding method repeatedly from each 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. Daemon thread will remain in JVM until there will be no thread other then daemon thread remain. The role of daemon thread in java runtime is that it do garbage collector and thread scheduling. (b) Differentiate throws in exception handling. Write a sample code to throw and handle an exception by you? Exceptions provide a way to react to exceptional circumstances (like runtime errors) in our program by transferring control to special functions called handlers. To catch exceptions we must place a portion of code under exception inspection. This is done by enclosing that portion of code in a try block. When an exceptional circumstance arises within that block, an exception is thrown that transfers the control to the exception handler. If no exception is thrown, the code continues normally and all handlers are ignored. An exception is thrown by using the throw keyword from inside the try block. Exception handlers are declared with the keyword catch, which must be placed immediately after the try block: public class FamilyNoTwo { public static void main(String[] args) { try { dad(); } catch (LoginException exp) { System.out.println("Handled by main " + exp.getMessage()); exp.printStackTrace(); } }

public static void dad() throws LoginException { you(); } public static void you() throws LoginException { LoginException e = new LoginException(); throw e; } } To handle an exception one must first throw the exception. The keyword throw is used to throw an exception which is passed to its method which uses keyword throws to throw the exception to its parent method if the parent method do not have a try catch block to handle the exception then it will throws to its parent method and so no till the main method of the class which can have a try catch block in it. Copyright (c)

Unit 3
Q.5(a) Explain the life-cycle of an applet. Write an apple that will be passed name of a person and sex as M or F through parameters in HTML file. Your applet should display the name as Mr.Name Or Ms.Name depending upon sex. An applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a webpage and runs in the context of the browser. An applet must be a subclass of the java.applet.Applet class, which provides the standard interface between the applet and the browser environment. Swing provides a special subclass of Applet, called javax.swing.JApplet, which should be used for all applets that use Swing components to construct their GUIs.By calling certain methods, a browser manages an applet life cycle, if an applet is loaded in a web page. Life Cycle of an Applet: Basically, there are four methods in the Applet class on which any applet is built.
init: This

method is intended for whatever initialization is needed for your applet. It is called after the param attributes of the applet tag.

start:

This method is automatically called after init method. It is also called whenever user returns to the page containing the applet after visiting other pages. stop: This method is automatically called whenever the user moves away from the page containing applets. You can use this method to stop an animation. destroy: This method is only called when the browser shuts down normally.

Thus, the applet can be initialized once and only once, started and stopped one or more times in its life, and destroyed once and only once. Below is the program of given problem:HTML:<html> <body> <H1> Displace Name Applet </H1> <APPLET CODE="NameApplet.class" WIDTH=200 HEIGHT=100 > <PARAM NAME="name" VALUE="VIJAY"> <PARAM NAME="sex" VALUE="M"> </APPLET> </body> </html> Applet:import java.applet.Applet; import java.awt.Graphics; public class NameApplet extends Applet { public void paint(Graphics g) { String sex = getParameter("sex"); String title = "M".equals(sex) ? "Mr. " : "Ms. " ; title += getParameter("name"); g.drawString(title, 20, 20); }

} (b) Describe the AWT class hierarchy. Write in brief about its components. The classes and interfaces of the Abstract Windowing Toolkit (AWT) are used to develop stand-alone applications and to implement the GUI controls used by applets. These classes support all aspects of GUI development, including event handling.

The Component and Container classes are two of the most important classes in the java.awt package. The Component class provides a common superclass for all classes that implement GUI controls. The Container class is a subclass of the Component class and can contain other AWT components. It is well worth your while to familiarize yourself with the API description of these two classes. The Window class is a subclass of the Container class that provides a common set of methods for implementing windows. The Window class has two subclasses, Frame and Dialog that are used to create Window objects. The Frame class is used to create a main application window, and the Dialog class is used to implement dialog boxes.

Java.lang.Object :- Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. Java.awt.Component:- A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface. The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. Class Component can also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native opaque window.

Java.awt.Container:- A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).

Java.awt.Panel:- Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels. The default layout manager for a panel is the FlowLayout layout manager. Java.applet.Applet:- An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application. The Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class provides a standard interface between applets and their environment. Q.6(a) What are the major components of javas event delegation model? Explain the working of event delegation model by giving suitable example. Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated. A Listener is an object that implements a specific EventListener interface extended from the generic java.util.EventListener. An EventListener interface defines one or more methods which are to be invoked by the event source in response to each specific event type handled by the interface. An Event Source is an object which originates or "fires" events. The source defines the set of events it emits by providing a set of set<EventType>Listener (for single-cast) and/or add<EventType>Listener (for mult-cast) methods which are used to register specific listeners for those events. In an AWT program, the event source is typically a GUI component and the listener is commonly an "adapter" object which implements the appropriate listener (or set of listeners) in order for an application to control the flow/handling of events. The listener object could also be another AWT component which implements one or more listener interfaces for the purpose of hooking GUI objects up to each other. Event Listeners An EventListener interface will typically have a separate method for each distinct event

type the event class represents. So in essence, particular event semantics are defined by the combination of an Event class paired with a particular method in an EventListener. For example, the FocusListener interface defines two methods, focusGained() and focusLost(), one for each event type that FocusEvent class represents. The API attempts to define a balance between providing a reasonable granularity of Listener interface types and not providing a separate interface for every single event type. The low-level listener interfaces defined by the AWT are as follows: java.util.EventListener java.awt.event.ComponentListener java.awt.event.ContainerListener java.awt.event.FocusListener java.awt.event.KeyListener java.awt.event.MouseListener java.awt.event.MouseMotionListener java.awt.event.WindowListener The semantic listener interfaces defined by the AWT are as follows: java.util.EventListener java.awt.event.ActionListener java.awt.event.AdjustmentListener java.awt.event.ItemListener java.awt.event.TextListener (b) Explain the following by writing small programs: (i) Adapter classes Some listener interfaces contain more than one method. For example, the MouseListener interface contains five methods: mousePressed, mouseReleased, mouseEntered, mouseExited, and mouseClicked. Even if you care only about mouse clicks, if your class directly implements MouseListener, then you must implement all five MouseListener methods. Methods for those events you do not care about can have empty bodies. The resulting collection of empty method bodies can make code harder to read and maintain. To help you avoid implementing empty method bodies, the API generally includes an adapter class for each listener interface with more than one method. (The Listener API Table lists all the listeners and their adapters.) For example, the MouseAdapter class implements the MouseListener interface. An adapter class implements empty versions of all its interface's methods. To use an adapter, you create a subclass of it and override only the methods of interest, rather than directly implementing all methods of the listener interface. Here is an example of modifying the preceding code to extend MouseAdapter. By extending MouseAdapter, it inherits empty definitions of all five of the methods that MouseListener contains. public class MyClass extends MouseAdapter { ... someObject.addMouseListener(this);

... public void mouseClicked(MouseEvent e) { ...//Event listener implementation goes here... } (ii) Canvas A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user. An application must subclass the Canvas class in order to get useful functionality such as creating a custom component. The paint method must be overridden in order to perform custom graphics on the canvas. (iii) Insets An Insets object is a representation of the borders of a container. It specifies the space that a container must leave at each of its edges. The space can be a border, a blank space, or a title. (iv) Java menus A Menu object is a pull-down menu component that is deployed from a menu bar. A menu can optionally be a tear-off menu. A tear-off menu can be opened and dragged away from its parent menu bar or menu. It remains on the screen after the mouse button has been released. The mechanism for tearing off a menu is platform dependent, since the look and feel of the tear-off menu is determined by its peer. On platforms that do not support tear-off menus, the tear-off property is ignored. Each item in a menu must belong to the MenuItem class. It can be an instance of MenuItem, a submenu (an instance of Menu), or a check box (an instance of CheckboxMenuItem). Copyright (c)

Unit 4
Q.7(a) What is object serialization ? What useful purpose does it serve? The object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. Serialization is used for lightweight persistence and for communication via sockets or Remote Method Invocation (RMI). The default encoding of objects protects private and transient data, and supports the evolution of the classes. A class may implement its own external encoding and is then solely responsible for the external format.

Serialization now includes an API that allows the serialized data of an object to be specified independently of the fields of the class and allows those serialized data fields to be written to and read from the stream using the existing protocol to ensure compatibility with the default writing and reading mechanisms. (b) Write a program that reads the contents of a file , one character at a time and counts the number of occurrences of vowels. File name should be passed as command line argument.

import java.io.FileReader; public class CountFile { public static void main(String[] args) throws Exception { FileReader in = new FileReader(args[0]); int vowelsCount = 0; int ch = in.read(); while (ch != -1) { if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { vowelsCount++; } } System.out.println("Vowels : " + vowelsCount); } } Q.8) Write brief about the following : (i) JDBC-ODBC Bridge The JDBC-ODBC Bridge is a JDBC driver that implements JDBC operations by translating them into ODBC operations. To ODBC it appears as a normal application program. The Bridge implements JDBC for any database for which an ODBC driver is available. The Bridge is implemented as the sun.jdbc.odbc Java package and contains a native library used to access ODBC. The Bridge is used by opening a JDBC connection using a URL with the odbc subprotocol. Before a connection can be established, the bridge driver class, sun.jdbc.odbc.JdbcOdbcDriver, must either be added to the java.lang.System property named jdbc.drivers, or it must be explicitly loaded using the Java class loader. Explicit loading is done with the following line of code: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

When loaded, the ODBC driver creates an instance of itself and registers this with the JDBC driver manager. (ii) Resultsetmetadata An object that can be used to get information about the types and properties of the columns in a ResultSet object. The following code fragment creates the ResultSet object rs, creates the ResultSetMetaData object rsmd, and uses rsmd to find out how many columns rs has and whether the first column in rs can be used in a WHERE clause. Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, name, designation FROM Employee"); while (rs.next()) { int id = rs.getInt(1); String n = rs.getString(2); String d = rs.getString(3); } (iii) Classforname() The use of class.forName is to loading the driver class i.e. to load the driver of database in the java program to run JDBC commands. The forName is a static method which accepting a string argument represented as the driver. (iv) Connection A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection. A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method. By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement. If auto-commit mode has been disabled, the method commit must be called explicitly in order to commit changes; otherwise, database changes will not be saved. (b) Write a JDBC program. For student marklist processing. public class DisplayMarksheetList { public static void main(String[] args)throws Exception { // Load database driver. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Create a database connection. Connection conn = DriverManager.getConnection("jdbc:odbc:sunrays", "", "");

// Created statement. Statement stmt = conn.createStatement(); //An SQL that will insert a record into table String sql = "SELECT rollNo,name,phy,che,maths from Marksheet"; ResultSet rs = null; // executeQuery method will return all records from the table rs = stmt.executeQuery(sql); System.out.println("RollNo\tName\tPhysics\tChemistry\tMaths "); System.out.println("--\t----\t-----\t------\t------"); // while loop will print all records present in Database table while (rs.next()) { System.out.print(rs.getString(1)); System.out.print("\t" + rs.getString(2)); System.out.print("\t" + rs.getString(3)); System.out.println("\t"+rs.getString(4)); System.out.println("\t"+rs.getString(5)); } // Close statement and connection stmt.close(); conn.close(); } } Copyright (c)

Unit 5
Q.9 (a) What are the differences between TCP/IP AND UDP/IP? Write a program for simple chatting using UDP. # TCP/IP UDP/IP Reliability: TCP is connection-oriented Reliability: UDP is connectionless protocol. When a file or message send protocol. When you a send a data or it will get delivered unless connections message, you don't know if it'll get there, fails. If connection lost, the server will it could get lost on the way. There may request the lost part. There is no be corruption while transferring a corruption while transferring a message. message. Ordered:- If you send two messages along a connection, one after the other, Ordered:- If you send two messages out, you know the first message will get you don't know what order they'll arrive there first. You don't have to worry in i.e. no ordered about data arriving in the wrong order. Heavyweight:- when the low level Lightweight:- No ordering of messages, parts of the TCP "stream" arrive in the no tracking connections, etc. It's just fire wrong order, resend requests have to and forget! This means it's a lot quicker, be sent, and all the out of sequence and the network card / OS have to do parts have to be put back together, so very little work to translate the data back requires a bit of work to piece together. from the packets. Streaming:- Data is read as a "stream," Datagrams: Packets are sent individually with nothing distinguishing where one and are guaranteed to be whole if they packet ends and another begins. There arrive. One packet per one read call. may be multiple packets per read call. Examples: Domain Name System (DNS Examples: World Wide Web (Apache UDP port 53), streaming media TCP port 80), e-mail (SMTP TCP port applications such as IPTV or movies, 25 Postfix MTA), File Transfer Voice over IP (VoIP), Trivial File Protocol (FTP port 21) and Secure Transfer Protocol (TFTP) and online Shell (OpenSSH port 22) etc. multiplayer games etc

(b) What do you understand by RMI ? Why standard RMI package is used with JAVA? Explain Two remote JAVA objects, those lying on two different JVMs can communicate to each others with help of RMI protocol. RMI hides the network communication complexity between these components. Component that provides services is called Server object and component that consumes services is called Client object.

rmic compile generates two addtional components stud and skeleton that wraps network sockets and hide network communication complexity. The stub is a client-side object that represents (or acts as a proxy for) the remote object. Stub and remote object both impelemt the same interface. However when the client calls a stub method, the stub forwards the request to the remote object (via the skeleton), which actually executes it. The skeleton object takes care of all remote calls for remote obect. Remote object does not need to worry about network comminication Stud and Skeleton are created at server by rmic.exe. Skeleton is remain at server with remote server object and stub is sent to client JVM along with remote client object. Stub resides at Client JVM.

RMI Standard Package The java.rmi package is the main RMI package; it contains the principle objects used in RMI clients and servers. The Remote interface and the Naming class define and locate RMI objects over the network.

The RMISecurityManager class provides additional security semantics required for RMI interactions. The MarshalledObject class is used during remote method calls for certain method arguments. In addition, this core package contains a number of basic RMI exception types used during remote object lookups and remote method calls. Q.10(a) What are differences between server socket and a client socket? How does the following happen? (i) client initiate a connection (ii) server accept a connection (iii) data is transferred between a client and a server Socket class is meant for client side, so in a client side u need to make a object of Socket class for any networking application, whereas for server side networking application ServerSocket class is used, in this class method named as serversocket_object.accept() is used by server to listen to clients at specific port addresses, for local computer it is either "localhost" or "127.0.0.1" and might be u'r subnet address in case of some LAN. The server program begins by creating a new ServerSocket object to listen on a specific port (see the statement in bold in the following code segment). When writing a server, choose a port that is not already dedicated to some other service. KnockKnockServer listens on port 4444 because 4 happens to be my favorite number and port 4444 is not being used for anything else in my environment: try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port: 4444"); System.exit(-1); } ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). In this case, the KnockKnockServer has no choice but to exit. If the server successfully binds to its port, then the ServerSocket object is successfully created and the server continues to the next step--accepting a connection from a client (shown in bold):

Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); } The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has it's remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests. (b) What is the purpose of a collection framework? What is collection interface? Illustrate its usage. The Collection Framework provides a well-designed set if interface and classes for sorting and manipulating groups of data as a single unit, a collection. The Collection Framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces. The Collection Framework is made up of a set of interfaces for working with the groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific, implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code.

In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys. When designing software with the Collection Framework, it is useful to remember the following hierarchical relationship of the four basic interfaces of the framework.
Collection-A

collection represents a group of objects known as its elements Set - cannot contain duplicate elements. o Ex SET [1,2,4,5,6,7,8] List- ordered collection, can contain duplicate elements. o Ex LIST [1,2,4,5,7,3,3,4,5] Queue - hold multiple elements prior to processing. a Queue provides additional insertion, extraction, and inspection operations. o Ex QUEUE [1,2,4,5,7,3,3,4,5] Map - an object that maps keys to values. A Map cannot contain duplicate keys o Ex MAP [{1,ONE},{2,TWO},{3,THREE}, {4,THREE}] SortedSet a Set that maintains its elements in ascending order. SortedMap a Map that maintains its mappings in ascending key order Collection interface: - A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. It has Set, List and Queue child interfaces. This interface is typically used to pass collections around and manipulate them where maximum generality is desired. All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to copy any collection, producing an equivalent collection of the desired implementation type. Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException.

MCA Dec 2007 Solved Paper

Unit 1
Q.1(a) What are the components of java architecture ? Explain in detail. The Java architecture has two components:
The The

Java Virtual Machine Java Application Programming Interface (API)

JAVA Architecture Java Virtual Machine : It is an "execution engine" that executes the byte codes in Java class files on a microprocessor. JVM operates on Java bytecode, which is normally generated from Java source code. a JVM can also be used to implement programming languages other than Java. For example, Ada source code can be compiled to Java bytecode, which may then be executed by a JVM. The JVM is a crucial component of the Java Architecture. Because JVMs are available for many hardware and software platforms. JVM makes a Java program "compile once, run anywhere". JAVA source files are compiled into .class files by the javac compiler. A .class file contains bytecodes. Bytecode is the machine language of the JVM.

An overview of the software development process. Java API (Application Programming Interface) : The JVM is distributed along with a set of standard class libraries that implement the Java API (Application Programming Interface). An application programming interface is what a computer system, library or application provides in order to allow data exchange between them. As the Web API is the Web version of this interface, the JVM and API have to be consistent with each other. They are bundled together as the Java Runtime Environment. The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. (b) Compare and contrast method overloading and method overriding. Overloading When multiple methods with the same name and with different parameters are wrriten in a sigle class then It is called method overloading. For example PrintWriter class has multiple println methods. Polymorphism is achieved through method overloading . When an overloaded method is called, JAVA uses the type and/or number of arguments to decide which version of the overloaded method will be called. Overloaded methods may or may not have different return types. When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. However, this match need not always be exact. In some cases javas automatic type conversions can play a role in overload resolution. Java will employ its automatic type conversion only if no exact match is found. The important points to note:
A

difference in return type only is not sufficient to constitute an overload and is illegal. It is required when a basic functionality is performed with different set of parameters. Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list. Overriding When a method with same name and set of parameters is defined in parent(super) class

and child class then child method is called overridden method and process is called method overriding. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version in the superclass will be hidden. If you wish to access the superclass version of an overridden method, you can do so by using super keyword. In order to make a method overridden:
The

return type, method name, type and order of arguments must be identical to those of a method in a parent class. The accessibility must not be more restrictive than original method. The method must not throw checked exceptions of classes that are not possible for the original method. # 1 2 3 4 Overloading Defined in a class with same name and different set of parameters Return type may be different Overloaded method can throw checked Exception Overloaded method can have narrow access modifier Overriding Defined in Parent and Child classes with same name and same set of parameters Return type must be same as parent class Overridden method can not throw checked Exception if not thrown by Parent It can not have narrow access modifies

Q.2 (a) What do you understand by array of objects ? Write a program to illustrate it. An array is a data structure consisting of a group of elements that are accessed by indexing. Each element has the same data type and the array occupies a contiguous area of memory.

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the above illustration, numbering begins with 0. The 9th element An array may contain primitive data type variables and any class type objects. When an array stores only objects then it is called 'array of objects'. class ArrayDemo { public static void main(String[] args) { String[] anArray; // declares an array of integers anArray = new String[10]; // allocates memory for 10 integers anArray[0] = "One"; // initialize first element anArray[1] = "Two"; // initialize second element anArray[2] = "Three"; // etc. anArray[3] = "Four"; anArray[4] = "Five"; anArray[5] = "Six"; anArray[6] = "Seven"; anArray[7] = "Eight"; anArray[8] = "Nine"; anArray[9] = "Ten"; System.out.println("Element at index 0: " + anArray[0]); System.out.println("Element at index 1: " + anArray[1]); System.out.println("Element at index 2: " + anArray[2]); System.out.println("Element at index 3: " + anArray[3]); System.out.println("Element at index 4: " + anArray[4]); System.out.println("Element at index 5: " + anArray[5]); System.out.println("Element at index 6: " + anArray[6]); System.out.println("Element at index 7: " + anArray[7]); System.out.println("Element at index 8: " + anArray[8]); System.out.println("Element at index 9: " + anArray[9]); } } (b) Write differences between the following:(i) Implicit and explicit import statement Explicit:- An import statement that mentions package.className is called explicit import. For example java.util.ArrayList is an explicit import statement. An explicit import statements take precedence over implicitly import statements. Explicitly imported names may not be redefined later in the package. When explicit

names are provided to import, the name of the package will not be bound unless the using-name keyword is also specified. For example: - we have to import as follows import java.util.Map; import java.util.HashMap; import java.util.TreeMap; Implicit:- When a package is imported with wildcard caharcter, it is called implicit import statement. For example import java.util.* will import all classes of java.util package. (*) represent all the sub-classes in java.util package. If multiple packages are imported through implicit import, it is possible to encounter ambiguous name references. if any attempt is made to refer to a class name that is implicitly imported from two or more packages, the compiler will produce an AmbiguousNameError. Such errors can be avoided by referring to the class name through its package More examples import import import import java.lang.*; java.util.*; java.sql.*; java.io.*;

(ii) Public and default class JAVA got four access modifiers 1. private 2. protected 3. default 4. public Public:- Fields, methods and constructors those are declared 'public' within a 'public class' are visible to any other class. Other class may belong to same package or some other package, or may be a child class. Other Class Same package Other Package Child Class Can Access? Yes Yes Yes

Default:-In default access modifier, fields,methods and constructors can be accessed by classes which are in the same package. When no modifier is specified then it is

considered default modifier.The default modifier has the same functionality that of a protected access modifier,therefore default modifier and protected modifier are said to be same. (iii) Application and applet # Application An application runs stand-alone, with 1 the support of a virtual machine. The true power of Java lies in writing 2 full blown applications. 3 4 5 6 Applet An applet runs under the control of a browser. Applets are great for creating dynamic and interactive web applications In an application execution starts with the Applets don't have the main method main method. The applications don't have such type of Applets are designed for the client site criteria programming purpose. The java applications are designed to Applets are designed just for handling the work with the client as well as server. client site problems. Applications are designed to exist in a The applets are typically used. secure area.

(iv) Java and C++ C++:1. C++ is object based language. 2. In C++, if value of one variable is changed then the change in value of that variable is reflected in other areas also where that variable is used. 3. C++ is confined to a particular system and thus the object code generated by the compiler of C++ can't be used on other machines. 4. C++ is not a secure language and may contain malicious code. 5. C++ can't be used on distributed systems and also, it can't be used over the web. 6. C++ supports multiple inheritance. Java :1. Java is a pure object oriented language except primitive data type. 2. Java doesn't allows pointers, rather it manages all the memory handling tasks by itself, thus freeing the user from memory handling complexities and provides security. 3. Java ensures that if value of one variable has been changed in one area then in other area the change is not reflected.

4. Java is a portable language that allows execution of the code on any machine where JVM (Java Virtual Machine) is installed. 5. Java is a secure language that uses a Bytecode verifier to make sure that code doesn't contain malicious code within it. 6. Java can be run on distributed systems and over the web. 7. Java no such thing is done, everything is done within the class. 8. Java doesn't support multiple inheritance as it leads to ambiguity. Copyright (c)

Unit 2
Q.3(a) What is the differences between an abstract class an interface ? Can abstract class and interface be used interchangeably? 1. Abstract class is a class which contains one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also i.e. abstract class may contain concrete methods. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present. 2. Abstract class definition begins with the keyword "abstract" keyword followed by Class definition. An Interface definition begins with the keyword "interface". 3. Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses 4. All variables in an Interface are by default - public static final while an abstract class can have instance variables. 5. An interface is also used in situations when a class needs to extend an other class apart from the abstract class. In such situations its not possible to have multiple inheritance of classes. An interface on the other hand can be used when it is required to implement one or more interfaces. Abstract class does not support Multiple Inheritance whereas an Interface supports multiple Inheritance. 6. An Interface can only have public members whereas an abstract class can contain private as well as protected members. 7. A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

8. The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those methods in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

9. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast 10. Interfaces are often used to describe the peripheral abilities of a class, and not its central identity, E.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects. (b) What do you understand by thread synchronization? What are synchronized method and objects? illustrate by giving examples. Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization. The facility provided by java to handle concurrent access of a common data structure by two or more threads is done by the help of Synchronizations. There are two types of synchronization in threads:1. 2. Method Statements, Object or Block

Method Synchronization:- To make a method synchronized, simply add the synchronized keyword to its declaration: public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() {

return c; } }

If count is an instance of Synchronized Counter, then making these methods synchronized has two effects: 1. First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. 2. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads. The constructors cannot be synchronized using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed. Statements, Object or Block Synchronization:- Another way to create synchronized code is with synchronized statements or block. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock: public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name); } In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods. (Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add. Synchronized statements are also useful for improving concurrency with fine-grained synchronization

Q.4(a) Write a program in java . A class TEACHER contains two fields name and qualification. Extend this class to Department,it contains Dept-no and Deptname name. An interface named as college contains one field name of college. Using the above classes and interface get the appropriate information and display it. public class Department { public String dept_no; public String dept_name; } public class Teacher extends Department{ public String name; public String qualification; } public interface College { public String nameOfCollege = "SUNRAYS Technologies"; } public class TestDepartment { public static void main(String[] args) { Teacher t = new Teacher(); System.out.println(t.dept_no); System.out.println(t.dept_name); System.out.println(t.name); System.out.println(t.qualification); System.out.println(College.nameOfCollege); } } (b) What is exception ? Explain the steps that are to be followed for exception handling in java. Give the suitable program to illustrate Exception: - An abnormal condition occurred in program is called Exception. When a method encounters an abnormal condition like a number is divided by zero, or 11th element is accessed of 10 element size array, then program will throw an exception. Handling Exception:- To handle an abnormal condition and display a user friendly message JAVA provides an mechanism that is called Exception Handling. To handling an exception in Java, you write a try block with one or more catch clauses. Each catch clause specifies one exception type that it is prepared to handle. The try block contains statements those are suppose to raise exceptions and catch block has its alternate

statements. If try block throws an exception, then associated catch clauses will be examined by the Java virtual machine. If the virtual machine finds a catch clause that is prepared to handle the thrown exception, the program continues execution starting with the first statement of that catch clause.

try-catch syntax is try{ //throw an catch(Exception1 catch(Exception2 finally{ // call exception } e1){ //called when Exception1 occurred } e2){ //called when Exception1 occurred} in all cases}

The simple example of Exception public class TestException{ public static void main (String [] args) { int x=0,y=1; try{ int z=y/x; } catch (ArithmeticException e) { System.out.println("Divident can not be Zero"); } } }

Unit 3
Q.5(a) Write the class hierarchy of applets. What are the interfaces available in applet class?what is the default layout of an applet? Every applet is implemented by creating a subclass of the Applet class. The following figure shows the inheritance hierarchy of the Applet class. This hierarchy determines much of what an applet can do and how, as you'll see on the next few pages.

Applet hierarchy

Java.lang.Object :- Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. Java.awt.Component:- A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface. The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. Class Component can also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native opaque window. Java.awt.Container:- A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order). Java.awt.Panel:- Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels.The default layout manager for a panel is the FlowLayout layout manager. Java.applet.Applet:- An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application. The Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class provides a standard

interface between applets and their environment. The interfaces available in applet class are:1. Accessible:- Interface Accessible is the main interface for the accessibility package. All components that support the accessibility package must implement this interface. It contains a single method, getAccessibleContext(), which returns an instance of the class AccessibleContext. 2. ImageObserver:- An asynchronous update interface for receiving notifications about Image information as the Image is constructed. 3. MenuContainer:- The super class of all menu related containers. 4. Serializable:- Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable. (b) Write an applet to display an image and move the image from left to right and back to its original position. import java.applet.Applet; import java.awt.Graphics; import java.awt.Image; public class ImageApplet extends Applet { Image img = null; public void init() { img = getImage(getCodeBase(), "coffee.jpg"); } public void paint(Graphics g) { int i = 0; for (i = 0; i < 200; i += 25) { g.drawImage(img, i, 0, this); } for (; i >=0 ; i -= 25) { g.drawImage(img, i, 0, this); } } }

Q.6(a) In java how will you set the layout? Explain about five layout classes available in java? Layouts tell Java where to put components in containers (Panel, content pane, etc). Every panel (and other container) has a default layout, but it's better to set the layout explicitly for clarity. Swing/AWT Layout managers are used to arrange components in a Panel/Window. A simple program of Creating buttons with Flowlayout:import java.awt.*; public class TestLayout { public static void main(String[] args) { Frame frame = new Frame("Meri First Window"); FlowLayout layout = new FlowLayout(FlowLayout.LEFT); frame.setLayout(layout); Button b1 = new Button("Button1"); frame.add(b1); Button b2 = new Button("Button2"); frame.add(b2); frame.setSize(400, 200); frame.setVisible(true); } } Several AWT and Swing classes provide layout managers for general use they are:1. FlowLayout:-FlowLayout arranges components from left-to-right and top-to-bottom, centering components horizontally with a five pixel gap between them. When a container size is changed (eg, when a window is resized), FlowLayout recomputes new positions for all components subject to these constraints. 2. BorderLayout:-BorderLayout divides a container (eg, JPanel) into 5 geographical sections: North, South, East, West, and Center. This is a very commonly used layout.

3. GridLayout:- GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns. 4. GridBagLayout:- GridBagLayout is a sophisticated, flexible layout manager. It aligns components by placing them within a grid of cells, allowing components to span more than one cell. The rows in the grid can have different heights, and grid columns can have different widths 5. BoxLayout:- The BoxLayout class puts components in a single row or column. It respects the components' requested maximum sizes and also lets you align components

(b) Explain the Event delegation model in detail? In order for a program to catch and process GUI events, it must subclass GUI components and override either action() or handleEvent() methods. Returning "true" from one of these methods consumes the event so it is not processed further; otherwise the event is propagated sequentially up the GUI hierarchy until either it is consumed or the root of the hierarchy is reached. The result of this model is that programs have essentially two choices for structuring their event-handling code: 1. Each individual component can be subclassed to specifically handle its target events. The result of this is a plethora of classes. 2. All events for an entire hierarchy (or subset thereof) can be handled by a particular container; the result is that the container's overridden action() or handleEvent() method must contain a complex conditional statement in order to process the events. Goals of Event Delegation Model The primary design goals of the new Delegation model in the AWT are the following:
Simple and easy to learn Support a clean separation between application and GUI code Facilitate the creation of robust event handling code which is less

errorprone (strong compile-time checking) Flexible enough to enable varied application models for event flow and propagation For visual tool builders, enable run-time discovery of both events that a component generates as well as the events it may observe Support backward binary compatibility with the old model The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design

and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. Copyright (c)

Unit 4
Q.7(a) Create a random access file stream for the file"emp.dat" for updating the employee information file. import java.io.RandomAccessFile; public class TestRandomAccessFile { public static void main(String[] args) throws Exception { RandomAccessFile file = new RandomAccessFile("emp.dat", "rw"); file.seek(100); // Go to record that need to be updated file.writeInt(123); // Employee Code file.writeChars("Narayan Murti"); // Employee Name file.writeChars("Diretor"); // Designation file.writeDouble(100000.00); file.close(); } } (b) What are the differences between the following: (i) Byte streams and character streams:Byte Stream - A contiguous flow of bytes is called Byte stream. InputStream and OutputStream classes read and write byte streams from its source or destinations. Charter Stream - A contiguous flow of Charters is called Character stream. Reader and Writer classes read and write charter streams from its source or destinations. (ii) Data output stream and print streams:Data output stream:- A data output stream lets an application write primitive Java data types to an output stream in a portable way. An application can then use a data input stream to read the data back in. java.io.DataOutputStream class is used to write primitive data types. Importent methods of DataOutputStream are

writeInt(5); writeDouble(5.5); writeString("sunRays");

Print streams:- A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written. All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes. Q.8(a) Write in detail about various JDBC drivers. There are many possible implementations of JDBC drivers. These implementations are categorized as follows: Type 1 - drivers that implement the JDBC API as a mapping to another data access API, such as ODBC. Drivers of this type are generally dependent on a native library, which limits their portability. The JDBC-ODBC Bridge driver is an example of a Type 1 driver. Type 2 - drivers that are written partly in the Java programming language and partly in native code. These drivers use a native client library specific to the data source to which they connect. Again, because of the native code, their portability is limited. Type 3 - drivers that use a pure Java client and communicate with a middleware server using a database-independent protocol. The middleware server then communicates the client?s requests to the data source. Type 4 - drivers that are pure Java and implement the network protocol for a specific data source. The client connects directly to the data source.

(b) Write a short notes on JDBC exception classes and result set. The Exception are the set of condition that occurred when an abnormal condition try to interrupt the normal flow of the code during the execution of program. Database programs are critical applications, and it is imperative that errors be caught and handled gracefully. Programs should recover and leave the database in a consistent state. Rollback-s used in conjunction with Java exception handlers are a clean way of achieving such a requirement. The client (program) accessing a server (database) needs to be aware of any errors returned from the server. JDBC give access to such information by providing two levels of error conditions: SQLException and SQLWarning. SQLExceptions are Java exceptions which, if not handled, will terminate the application. SQLWarnings are subclasses of SQLException, but they represent nonfatal errors or unexpected conditions, and as such, can be ignored. In Java, statements which are expected to ``throw'' an exception or a warning are enclosed in a try block. If a statement in the try block throws an exception or a warning, it can be ``caught'' in one of the corresponding catch statements. Each catch statement specifies which exceptions it is ready to ``catch''. Example to show how to handle exceptions

try { con.setAutoCommit(false) ; . con.commit() ; con.setAutoCommit(true) ; }catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()) ; con.rollback() ; con.setAutoCommit(true) ; } Result Set JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. In addition, the Statement methods executeQuery and getResultSet both return a ResultSet object, as do various DatabaseMetaData methods. ResultSet is an interface. The ResultSet interface provides methods for retrieving and manipulating the results of executed queries, and ResultSet objects can have different functionality and characteristics. These characteristics are result set type, result set concurrency, and cursor holdability. A table of data representing a database result set is usually generated by executing a statement that queries the database. The type of a ResultSet object determines the level of its functionality in two areas: the ways in which the cursor can be manipulated, and how concurrent changes made to the underlying data source are reflected by the ResultSet object. The following code demonstrates declaring the ResultSet object rs and assigning the results of our query to it by using the executeQuery method. Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, name, designation FROM Employee"); while (rs.next()) { int id = rs.getInt(1); String n = rs.getString(2); String d = rs.getString(3); } Copyright (c)

Unit 5
Q.9(a) Explain the concept of RMI with suitable example. Write a student class in which division() is a method which gives the division from aggregate marks . Write an application which runs this method remotely using RMI . Two remote JAVA objects, those lying on two different JVMs can communicate to each others with help of RMI protocol. RMI hides the network communication complexity between these components. Component that provides services is called Server object and component that consumes services is called Client object. The stub is a client-side object that represents (or acts as a proxy for) the remote object. Stub and remote object both impelemt the same interface. However when the client calls a stub method, the stub forwards the request to the remote object (via the skeleton), which actually executes it. The skeleton object takes care of all remote calls for remote obect. Remote object does not need to worry about network comminication Stud and Skeleton are created at server by rmic.exe. Skeleton is remain at server with remote server object and stub is sent to client JVM along with remote client object. Stub resides at Client JVM.

Example /** * Remote Interface */ import java.rmi.*; public interface StudentInt extends Remote { public int division() throws RemoteException; } /** * Remote Server Implementation */ import java.rmi.*; import java.rmi.server.*; public class StudentImpl extends UnicastRemoteObject implements StudentInt { int aggMarks = 65; public StudentImpl() throws RemoteException { } public int division() throws RemoteException { if (aggMarks > 65) { return 1; } else if (aggMarks > 50) { return 2; } else { return 3; } } } /** * Remote Server */ import java.rmi.Naming; public class StudentServer { public static void main(String args[]) throws Exception { StudentImpl s = new StudentImpl();

Naming.rebind("StudentServer", s); } } /** * Remote Client */ import java.rmi.Naming; public class StudentClient { public static void main(String args[]) throws Exception { String url = "rmi://127.0.0.1:1099/StudentServer"; StudentInt std = (StudentInt) Naming.lookup(url); System.out.println("Division : " + std.division()); } } (b)Explain the following: (i) Proxy server Proxy server:- A proxy server is a server that acts as a go-between for requests from clients seeking resources from other servers. A client connects to the proxy server, requesting some service, such as a file, connection, web page, or other resource, available from a different server. The proxy server evaluates the request according to its filtering rules. For example, it may filter traffic by IP address or protocol. If the request is A proxy server has two purposes: 1. To keep machines behind it anonymous (mainly for security). 2. To speed up access to a resource (via caching). It is commonly used to cache web pages from a web server. A proxy server that passes requests and replies unmodified is usually called a gateway or sometimes tunneling proxy. A proxy server can be placed in the user's local computer or at various points between the user and the destination servers or the Internet. A reverse proxy is a proxy used as a frontend to accelerate and cache in-demand resources. (ii) Collection classes A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The SDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.

Key Classes and Interfaces Interface Implementation Set HashSet TreeSet LinkedList Historical Vector Stack Hashtable Properties List ArrayList Treemap Map HashMap

ArrayList - A dynamic duplicate element list. Vector - A dynamic duplicate element list. It is thread safe. HashSet - A dynamic unique element set TreeSet - A dynamic unique element sorted set. HashMap - A dynamic index map. Hashtable - A dynamic index map. It is thread safe. Iterator - Access elements sequentially from a SET and LIST Enumeration - Access elements sequentially from a Vector and Hashtable All general-purpose Collection implementation classes should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to copy any collection, producing an equivalent collection of the desired implementation type. Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the collection may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

Q.10 Write short notes on the following:(i) UDP/IP UDP/IP :- The User Datagram Protocol (UDP), is one of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network without requiring prior communications to set up special transmission channels or data paths. UDP is sometimes called the Universal Datagram Protocol. The protocol was designed by David P. Reed in 1980 and formally defined in RFC 768. UDP uses a simple transmission model without implicit hand-shaking dialogues for guaranteeing reliability, ordering, or data integrity. Thus, UDP provides an unreliable service and datagrams may arrive out of order, appear duplicated, or go missing without notice. UDP assumes that error checking and correction is either not necessary or performed in the application, avoiding the overhead of such processing at the network interface level. Time-sensitive applications often use UDP because dropping packets is preferable to using delayed packets

UDP's stateless nature is also useful for servers that answer small queries from huge numbers of clients. Unlike TCP, UDP is compatible with packet broadcast (sending to all on local network) and multicasting (send to all subscribers). Common network applications that use UDP include: the Domain Name System (DNS), streaming media applications such as IPTV, Voice over IP (VoIP), Trivial File Transfer Protocol (TFTP)

(II) DNS DNS:- It is know as Domain Name System (DNS) .The DNS protocol was developed and defined in the early 1980s and published by the Internet Engineering Task Force. The Domain Name System (DNS) is a hierarchical naming system for computers, services, or any resource participating in the Internet. It associates various information with domain names assigned to such participants. Most importantly, it translates domain names meaningful to humans into the numerical (binary) identifiers associated with networking equipment for the purpose of locating and addressing these devices worldwide. An often used analogy to explain the Domain Name System is that it serves as the "phone book" for the Internet by translating human-friendly computer hostnames into IP addresses. For example, www.example.com translates to 208.77.188.166. The Domain Name System makes it possible to assign domain names to groups of Internet users in a meaningful way, independent of each user's physical location. Because of this, World-Wide Web (WWW) hyperlinks and Internet contact information can remain consistent and constant even if the current Internet routing arrangements change or the participant uses a mobile device. Internet domain names are easier to remember than IP addresses such as 208.77.188.166. The Domain Name System distributes the responsibility of assigning domain names and mapping those names to IP addresses by designating authoritative name servers for each domain. Authoritative name servers are assigned to be responsible for their particular domains, and in turn can assign other authoritative name servers for their sub-domains. This mechanism has made the DNS distributed, fault tolerant, and helped avoid the need for a single central register to be continually consulted and updated. In general, the Domain Name System also stores other types of information, such as the list of mail servers that accept email for a given Internet domain. By providing a worldwide, distributed keyword-based redirection service, the Domain Name System is an essential component of the functionality of the Internet. Other identifiers such as RFID tags, UPC codes, International characters in email addresses and host names, and a variety of other identifiers could all potentially utilize DNS [1]. The Domain Name System also defines the technical underpinnings of the functionality of this database service. For this purpose it defines the DNS protocol, a detailed specification of the data structures and communication exchanges used in DNS, as part of the Internet Protocol Suite (TCP/IP).

(iii) Data gram socket Data gram socket:- A datagram socket is the sending or receiving point for a packet delivery service. Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently, and may arrive in any order. UDP broadcasts sends are always enabled on a DatagramSocket. In order to receive broadcast packets a DatagramSocket should be bound to the wildcard address. In some implementations, broadcast packets may also be received when a DatagramSocket is bound to a more specific address. Packets send by DatagramSocket will be complete and independent from each others.Packets are sent as DatagramPacket objects. DatagramSocket sends packet through UDP protocol. UDP is unreliable protocol and does not give grantee of arrival of a packet. (iv) Collection framework Collection framework:- The Collection Framework provides a well-designed set if interface and classes for sorting and manipulating groups of data as a single unit, a collection. The Collection Framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces. The Collection Framework is made up of a set of interfaces for working with the groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific, implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code.

In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys.

When designing software with the Collection Framework, it is useful to remember the following hierarchical relationship of the four basic interfaces of the framework.
Collection-A

collection represents a group of objects known as its elements Set - cannot contain duplicate elements. o Ex SET [1,2,4,5,6,7,8] List- ordered collection, can contain duplicate elements. o Ex LIST [1,2,4,5,7,3,3,4,5] Queue - hold multiple elements prior to processing. a Queue provides additional insertion, extraction, and inspection operations. o Ex QUEUE [1,2,4,5,7,3,3,4,5] Map - an object that maps keys to values. A Map cannot contain duplicate keys o Ex MAP [{1,ONE},{2,TWO},{3,THREE}, {4,THREE}] SortedSet a Set that maintains its elements in ascending order. SortedMap a Map that maintains its mappings in ascending key order

MCA June 2008 Solved Paper

Unit 1
Q.1 (a) What is a method ?
A method is a function or procedure which is defined in a class. A method can access the internal variables of an object and can perform some operations on variables. Types of methods:
Instance

Method :- an instance method is associated with an object. It can be called with object. o this method can be defined as public String methodName() {..} Class Methods :- A class method can access only class variables(attributes). A class method is defined by a keyword static. o It syntax is public static void methodName(){}
Helper

Method :- Helper methods are exclusive to a class; only other methods in the same class can call this type of method. Constructor method :- Constructors are special methods those do not have return type. They are called at time object instantiation, in other words they are called at time of object memory allocation to initialize instance variables. public class constructorMethod(){} (b) What is an encapsulation ?

The process of gathering all related attributes (variables) and methods(functions) in a class is called encapsulation. Encapsulation is the ability of an object to be a container (or capsule) for related properties (i.e. data variables) and methods (ie. functions).

Older languages did not enforce any property/method relationships. This often resulted in side effects at the time of object re usability. Encapsulation is one of three fundamental principles in object oriented programming. (c) What is difference between a byte and a Byte ? byte: A byte is a primitive data type that occupy a byte to store an integer number. Default value of byte is 0. It can store -127 to +128 numbers. Byte is class that is found in java.lang package. Byte is called wrapper class. Wrapper class is used to convert primitive data types into Object to store in Collection Frameworks. consist of 8 bits. Each bit stores a binary value 1 or 0. Byte is consists of 8 bits and represent a number. (d) What do you understand by portability of code? Are java programs portable ? justify your answer? Portability means writing your program (code) in such a way that the same code works on different environments i.e. different processors, different operating systems, different versions of libraries etc. If your program is portable, you just need to copy your program in another environment and run it without any changes. Portability is important because non-portable code causes lots of problems in maintenance - managing multiple versions, poor readability / understandability of the code to name a few. Yes, Java programs are portable. Java programs are compiled to an intermediate form called byte-code. Byte-code are platform independent that can be run on any operating system. Java Virtual Machine (JVM) is work like an interpreter and interpret byte-code into machine-code and run on a specific platform. Thus only diffrent JVMs are required on different platforms but byte-code will be same. Byte-code is stored in a .class file. Or

Q.2 (a) Differentiate between the following? 20 (i) Method overloading and Method overriding Overloading When multiple methods with the same name and with different parameters are wrriten in a sigle class then It is called method overloading. For example PrintWriter class has multiple println methods. Polymorphism is achieved through method overloading . When an overloaded method is called, JAVA uses the type and/or number of arguments to decide which version of the overloaded method will be called. Overloaded methods may or may not have different return types. When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. However, this match need not always be exact. In some cases javas automatic type conversions can play a role in overload resolution. Java will employ its automatic type conversion only if no exact match is found. The important points to note:
A

difference in return type only is not sufficient to constitute an overload and is illegal. It is required when a basic functionality is performed with different set of parameters. Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list. Overriding When a method with same name and set of parameters is defined in parent(super) class and child class then child method is called overridden method and process is called method overriding. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version in the superclass will be hidden. If you wish to access the superclass version of an overridden method, you can do so by using super keyword. In order to make a method overridden:

The

return type, method name, type and order of arguments must be identical to those of a method in a parent class. The accessibility must not be more restrictive than original method. The method must not throw checked exceptions of classes that are not possible for the original method. # Overloading Defined in a class with same name and 1 different set of parameters 2 Retrun type may be different Overloaded method can throw checked 3 Exception Overloaded method can have narrow 4 access modifier Overriding Defined in Parent and Child classes with same name and same set of parameters Return type must be same as parent class Overridden method can not throw checked Exception if not thrown by Parent It can not have narrow access modifier

(ii) Static and Instance members of a class When a number of objects are created from the same class, they each have their own distinct copies of instance variables. For example in the case of the Circle class, the instance variables are radius, borderWidth, and color. Each Circle object has its own values for these variables, stored in different memory locations. Instance variables are defined as private double radius = 0.0; Instance methods are defined as public double getRadius() { return radius; } Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. JVM assigns memory to class (static) variables only once in the life. Class variables can be accessed by any object. Any object can change the value of a class variable. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class Class variables are defined as private static double PI = 3.14; Class methods are defined as public static double getPi(){ return PI ; } Following combinations of instance and class variables and methods are allowed:
Instance

methods can access instance variables and instance methods

directly.

Instance

methods can access class variables and class methods directly.

Class Class

methods can access class variables and class methods directly. methods cannot access instance variables or instance methods directly. (b) What do you understand by polymorphism? Briefly explain Dynamic Method Dispatch with the help of example? Polymorphism in Greek meaning "having multiple forms" is the characteristic of being able to assign a different meaning or usage to something in different contexts specifically, to allow an entity such as a variable, a function, or an object to have more than one form. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true objectoriented programming language. Dynamic method dispatch is the process that the Java runtime system uses to determine which method implementation to call in an inheritance hierarchy. For example, the Object class has a toString() method that all subclasses inherit, but the String class overrides this method to return its string content. If a String or other object type is assigned to an Object reference using application logic, the Java compiler cannot know in advance where a call to the toString() method will be resolved, it must be determined dynamically at runtime. Copyright (c)

Unit 2
Q.3 (a) Write a program to create a thread A, which creates two child threads BandC .A must terminate after both B and C have terminated.BandC must print their own names 100 times and then terminate. public class MyThread extends Thread { private String name = null; public MyThread(String n){ name = n;

} public void run(){ for(int i=0;i<100;i++){ System.out.println(name); } } } class A { public static void main(String[] args) throws Exception{ MyThread b = new MyThread("B"); MyThread c = new MyThread("C"); b.start(); c.start(); b.join(); c.join(); System.out.println("A is finished"); } } (b) Explain the Thread Life cycle?

A thread is a lightweight process bacause threads can share the resources . The life cycle of thread is as follows 1. New state After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. 2. Runnable (Ready-to-run) state A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 3. Running state A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. 4. Dead state A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.

5. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.

Or Q.4 (a) What do you understand by multithreading? What facilities are provided by java to handle concurrent access of a common data structure by two or more threads? Multithreading is the ability of a program or an operating system process to serve more than one user at a time and to even manage multiple requests by the same user without having to have multiple copies of the processes running in the computer. Each user request for a program or system service (and here a user can also be another program) is kept track of as a thread with a separate identity. As programs work on behalf of the initial request for that thread and are interrupted by other requests, the status of work on behalf of that thread is kept track of until the work is completed. Multi-threading is achieved in JAVA with help of java.lang.Thread class and java.lang.Runnable interface. The facility provided by java to handle concurrent access of a common data structure by two or more threads is done by the help of Synchronizations. There are two types of synchronization in threads;1. 2. Method Statements or Block

Method Synchronization:- To make a method synchronized, simply add the synchronized keyword to its declaration:

public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; } } If count is an instance of Synchronized Counter, then making these methods synchronized has two effects: 1. First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. 2. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads. The constructors cannot be synchronized using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed. Statements or Block Synchronization:- Another way to create synchronized code is with synchronized statements or block. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock: public void addName(String name) { synchronized(this) {

lastName = name; nameCount++; } nameList.add(name); } In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods. (Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add. Synchronized statements are also useful for improving concurrency with fine-grained synchronization (b) How are the following codesegments handled by java? (i) int x=0,y=1;int z=y/x; (ii)try{..} Catch(Exception e) {System.out.println(Exception Caught);} catch(ArithmeticException e){System.out.println(ArithmeticException Caught);} (i) Since value of x is Zero and a number divided by Zero produce an infinity so expression int z=y/x will raise a runtime exception. This exception is called arithmetic exception. JVM create an object of java.lang.ArithmeticException class for this exception. (II) ArithemeticException is child of Exception class. As per try-catch syntax, child class catch must come first in order than parent class. Since code fragement has catch(Exception e) first and catch(ArithmeticExcetion e) later so program will raise compilation error. Copyright (c)

Unit 3
Q.5(a) Discuss about the Event Delegation model in java. Discuss the role of Listener in Event Delegation model. 20 Event types are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener and passing in the instance of the event subclass which defines the event type generated. A Listener is an object that implements a specific EventListener interface extended from the generic java.util.EventListener. An EventListener interface defines one or more methods which are to be invoked by the event source in response to each specific event type handled by the interface. An Event Source is an object which originates or "fires" events. The source defines the set of events it emits by providing a set of set<EventType>Listener (for single-cast) and/or add<EventType>Listener (for mult-cast) methods which are used to register specific listeners for those events. In an AWT program, the event source is typically a GUI component and the listener is commonly an "adapter" object which implements the appropriate listener (or set of listeners) in order for an application to control the flow/handling of events. The listener object could also be another AWT component which implements one or more listener interfaces for the purpose of hooking GUI objects up to each other. Event Listeners An EventListener interface will typically have a separate method for each distinct event type the event class represents. So in essence, particular event semantics are defined by the combination of an Event class paired with a particular method in an EventListener. For example, the FocusListener interface defines two methods, focusGained() and focusLost(), one for each event type that FocusEvent class represents. The API attempts to define a balance between providing a reasonable granularity of Listener interface types and not providing a separate interface for every single event type. The low-level listener interfaces defined by the AWT are as follows: java.util.EventListener java.awt.event.ComponentListener java.awt.event.ContainerListener java.awt.event.FocusListener java.awt.event.KeyListener java.awt.event.MouseListener java.awt.event.MouseMotionListener java.awt.event.WindowListener The semantic listener interfaces defined by the AWT are as follows: java.util.EventListener java.awt.event.ActionListener

java.awt.event.AdjustmentListener java.awt.event.ItemListener java.awt.event.TextListener (b )AWT, What do the following terms mean and how are they related to each other? (i) Component (ii) Container(iii) Panel(iv) Window 1. Component: - A component is an object having a graphical representation that can be displayed on the screen and that can interact with the user. Examples of components are the buttons, checkboxes, and scrollbars of a typical graphical user interface.The Component class is the abstract superclass of the nonmenu-related Abstract Window Toolkit components. Class Component can also be extended directly to create a lightweight component. A lightweight component is a component that is not associated with a native opaque window. Container, Panel and Window are Components. 2. Container: - A generic Abstract Window Toolkit (AWT) container object is a component that can contain other AWT components. Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order). Panel and Window are container classes. 3. Panel: - Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels.The default layout manager for a panel is the FlowLayout layout manager. 4. Window: - A Window object is a top-level window with no borders and no menubar. The default layout for a window is BorderLayout. A window must have either a frame, dialog, or another window defined as its owner when it's constructed.In a multi-screen environment, you can create a Window on a different screen device by constructing the Window with Window(Window, GraphicsConfiguration). The GraphicsConfiguration object is one of the GraphicsConfiguration objects of the target screen device.AWT component class contains the container class which contains panel class and window class

Q.6(a) Design an applet "Cliker"that displays a button and a text text field on the screen. The text field must display the number of times the button is pressed. 20 import java.applet.Applet; import java.awt.*; import java.awt.event.*; public class Clicker extends Applet implements ActionListener { private Button b = new Button("Click Me"); private TextField tf = new TextField("00000000000000000"); public Clicker() { this.setLayout(new FlowLayout()); b.addActionListener(this); add(b); tf.setEnabled(false); add(tf); } public void actionPerformed(ActionEvent event) { int counter = Integer.parseInt(tf.getText()); counter++; tf.setText(String.valueOf(counter)); } }

(b) What do you understand by AWT Controls ? What are the various controls supported by AWT? AWT controls are components that allow a user to interact with your application and the various controls support by AWT are as following:
Labels Buttons Checkbox Choice Lists Scrollbars TextField Components.

These controls are subclasses of Component.

Labels: - A Label object is a component for placing text in a container. A label displays a single line of read-only text. The text can be changed by the application, but a user cannot edit it directly. Buttons: - This class creates a labeled button. The application can cause some action to happen when the button is pushed. Checkbox: - A check box is a graphical component that can be in either an "on" (true) or "off" (false) state. Clicking on a check box changes its state from "on" to "off," or from "off" to "on." Choice: - The Choice class presents a pop-up menu of choices. The current choice is displayed as the title of the menu. Lists: - The List component presents the user with a scrolling list of text items. The list can be set up so that the user can choose either one item or multiple items. Scrollbars: - A scroll bar provides a convenient means for allowing a user to select from a range of values. TextField: - A TextField object is a text component that allows for the editing of a single line of text. Copyright (c)

Unit 4
Q.7(a) What are the similarity and differences between JDBC and ODBC? What is JDBC-ODBC bridge driver? 20 Similarity: - Both JDBC and ODBC are database drivers used to access data from database in an application or program. Differences: JDBC - Java Database Connectivity 1. JDBC standard java interface to communicate with a database. 2. JDBC drivers are written in java and JDBC code is automatically installable, secure, and portable on all platforms. 3. JDBC is designed to keep things simple while allowing advanced capabilities. 4. JDBC did not use pointers, which have been removed totally from Java. ODBC - Open Database Connectivity 1. ODBC from Microsoft developed interface to communicate with a database 2. ODBC is mostly used on Windows platforms (if you want to connect with a database from C++ Delphi etc.) but there are also ODBC drivers for Linux available 3. ODBC makes use of pointers. 4. ODBC requires manual installation of the ODBC driver manager and driver on all client machines. 5. ODBC mixes simple and advanced features together and has complex options for simple queries. JDBC-ODBC bridge driver: The JDBC-ODBC Bridge is a JDBC driver that implements JDBC operations by translating them into ODBC operations. To ODBC it appears as a normal application program. The Bridge implements JDBC for any database for which an ODBC driver is available. The Bridge is implemented as the sun.jdbc.odbc Java package and contains a native library used to access ODBC. The Bridge is used by opening a JDBC connection using a URL with the odbc subprotocol. Before a connection can be established, the bridge driver class, sun.jdbc.odbc.JdbcOdbcDriver, must either be added to the java.lang.System property named jdbc.drivers, or it must be explicitly loaded using the Java class loader. Explicit loading is done with the following line of code:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); When loaded, the ODBC driver creates an instance of itself and registers this with the JDBC driver manager. (b) Make comparison between NestedSQLException and RuntimesSQLException? NetsedSQLException:- It include references to the exception that caused them. When a layer catches an exception and throws a new one, the new exception should include a reference to the earlier cause. It is checked exception. RuntimesSQLException:- Is unchecked exception which occurred at runtime i.e. when the program or application is running and the database communication via SQL query throws an exception. Q.8(a) Explain the following: (i) File input stream (ii ) Character stream (i)File input stream: - A FileInputStream is a class that is founf in java.io package. It obtains input bytes from a file in a file system. FileInputStream is meant for reading streams of raw bytes such as image data. FileInputStream has predefined methods which are use to read the data , some importent methids are 1. read() :- Reads a byte of data from this input stream. 2. read(byte[] b) :- Reads up to b.length bytes of data from this input stream into an array of bytes. 3. close():-Closes this file input stream and releases any system resources associated with the stream. (ii) Character stream: - Character streams are like byte streams, but they contain 16-bit Unicode characters rather than eight-bit bytes. They are implemented by the Reader and Writer classes and their subclasses. Readers and Writers support essentially the same operations as InputStreams and OutputStreams, except that where byte-stream methods operate on bytes or byte arrays, character-stream methods operate on characters, character arrays, or strings.Most of the functionality available for byte streams is also provided for character streams. The primary advantage of character streams is that they make it easy to write programs

that are not dependent upon a specific character encoding, and are therefore easy to internationalize.

(b) Explain the following API of Java sql package: (i) DriverManager class (ii) SQLPermission class (iii) Driver interface (iv) Connection interface (i) DriverManager class:- The DriverManager class is the traditional management layer of JDBC, working between the user and the drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. In addition, the DriverManager class attends to things like driver login time limits and the printing of log and tracing messages. The only method in the DriverManager class that a general programmer needs to use directly is DriverManager.getConnection(URL, LOGIN, PASSWORD);. As its name implies, this method establishes a connection to a database. (ii) SQLPermission class:- A SQLPermission object contains a name (also referred to as a target name) but no actions list, there is either a named permission or there is not. The target name is the name of the permission. The naming convention follows the hierarchical property naming convention. SQLPermission class extends BasicPermission class in which permission for the SecurityManager will check when code that is running in an applet calls the DriverManager.setLogWriter method or the DriverManager.setLogStream (deprecated) method. If there is no SQLPermission object, these methods throw a java.lang.SecurityException as a runtime exception. (iii) Driver interface:- Driver interface is a Java SQL framework which allows for multiple database drivers. It is a interface that every driver class must implement. Each driver should supply a class that implements the Driver interface. The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to connect to the target URL. It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast quantities of supporting code. When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a driver by calling Class.forName("com.mysql.jdbc.Driver")

(iv) Connection interface:- It is used for connection or session with a specific database. Within the context of a Connection, SQL statements are executed and results are returned. A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method. By default the Connection automatically commits changes after executing each statement. If auto commit has been disabled, the method commit must be called explicitly, otherwise the database changes will not be saved. Copyright (c)

Unit 5
Q.9 (a) When a client Java application communicates to java server using RMI,a stub is created . Explain which part of the application creates the stub, where the stub resides and how it is used. 20 Two remote JAVA objects, those lying on two different JVMs can communicate to each others with help of RMI protocol. RMI hides the network communication complexity between these components. Component that provides services is called Server object and component that consumes services is called Client object. rmic compile generates two addtional components stud and skeleton that wraps network sockets and hide network communication complexity. The stub is a client-side object that represents (or acts as a proxy for) the remote object. Stub and remote object both impelemt the same interface. However when the client calls a stub method, the stub forwards the request to the remote object (via the skeleton), which actually executes it. The skeleton object takes care of all remote calls for remote obect. Remote object does not need to worry about network comminication Stud and Skeleton are created at server by rmic.exe. Skeleton is remain at server with remote server object and stub is sent to client JVM along with remote client object. Stub resides at Client JVM.

Example import java.net.*; import java.rmi.*; public class AddClient { public static void main(String args[]) throws Exception{ String url = "rmi://127.0.0.1:1099/AddServer"; AddServerIntf obj = (AddServerIntf) Naming.lookup(url); //lookup the stub object double d = obj.add(50, 60); //Call stub method that will go to skeleton System.out.println("Sum is " + d); } }

(b) Briefly explain what functions do the socket API socket() and send() perform. The functions socket API socket() and send() perform are :-

socket():- A socket is an endpoint for communication between two machines. The socket is created by a socket class with its method socket(). The socket() function shall create an unbound socket in a communications domain, and return a file descriptor that can be used in later function calls that operate on sockets. The socket() function takes the following arguments:
Domain:

- Specifies the communications domain in which a socket is to be created. Type:-Specifies the type of socket to be created. Protocol: - Specifies a particular protocol to be used with the socket. Specifying a protocol of 0 causes socket() to use an unspecified default protocol appropriate for the requested socket type. send(): - The send() function is used to send data through a connected socket. Parameters used by send() are
socket_descriptor:- The socket descriptor that need Buffer:- The pointer to the buffer in which the data

to be written. that is to be written is

stored. buffer_length:-The length of the buffer. Flags:-A flag value that controls the transmission of the data. The flags value is either zero, or is obtained by performing an OR operation on the following constants: MSG_OOB :- Send data as out-of-band data. Valid only for sockets with an address family of AF_INET and type SOCK_STREAM. MSG_DONTROUTE :- Bypass routing. Valid only for sockets with address family of AF_NS or AF_INET. It is ignored for other address families.

Return Value :send() returns an integer. Possible values are: 1. -1 (unsuccessful) 2. n (successful), where n is the number of bytes sent.

Q.10 (a) Describe the purpose/functionality of the socket(s)used as the server in reliable , connection-oriented socket-based with a client. (you need notdiscuss client side functionality). TCP ( Transmission Control Protocol ) is used to stabe a reliable and connection-oriented connection with remote client. A Socket is made of IP address and port number.

java.net.ServerSocket class is used to stable server side socket and java.net.Socket class is used to stable cliemt side socket. A server runs on a specific computer and has a socket that is bound to a specific port number. Port number is assigned by Operating System. The server just waits, listening to the socket for a client to make a connection request. On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client sends request to server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system. If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client. On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. The client and server can now communicate by writing to or reading from their sockets.

Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by wellknown services such as HTTP and FTP and other system services. These ports are called well-known ports. Your applications should not attempt to bind to them.

(b) Write notes on the following: (i)Proxy server:- A proxy server is a server that acts as a go-between for requests from clients seeking resources from other servers. A client connects to the proxy server, requesting some service, such as a file, connection, web page, or other resource, available from a different server. The proxy server evaluates the request according to its filtering rules. For example, it may filter traffic by IP address or protocol. If the request is validated by the filter, the proxy provides the resource by connecting to the relevant

server and requesting the service on behalf of the client. A proxy server may optionally alter the client's request or the server's response, and sometimes it may serve the request without contacting the specified server. In this case, it 'caches' responses from the remote server, and returns subsequent requests for the same content directly. A proxy server has two purposes: 1. To keep machines behind it anonymous (mainly for security). 2. To speed up access to a resource (via caching). It is commonly used to cache web pages from a web server. A proxy server that passes requests and replies unmodified is usually called a gateway or sometimes tunneling proxy. A proxy server can be placed in the user's local computer or at various points between the user and the destination servers or the Internet. A reverse proxy is a proxy used as a frontend to accelerate and cache in-demand resources. (ii)Collection interface:- A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. It has Set, List and Queue child interfaces. This interface is typically used to pass collections around and manipulate them where maximum generality is desired. All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to copy any collection, producing an equivalent collection of the desired implementation type. Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Importent methods add(o) Add a new element addAll(c) Add a collection clear() Remove all elements contains(o) Membership checking. containsAll(c) Inclusion checking isEmpty() Whether it is empty iterator() Return an iterator

remove(o) Remove an element removeAll(c) Remove a collection retainAll(c) Keep the elements size() The number of elements

MCA June 2009 Solved Paper

UNIT-I
1.(a) Compare between recursion and iteration . Write a recursive method and an iterative method To find the greatest common divisor of two given integers. When writing code to do repetitive tasks, the two primary approaches are iteration and recursion. Generally you can use either one interchangeably, but potentially with different performance and complexity. A recursive function calls itself (possibly more than once), with different parameters, and defines an exit clause that is guaranteed to be reached. An iterative function includes a loop, which iterates a pre-determined number of times, or checks for an exit clause every time through. Program to find Greatest Common Divisor import java.io.*; public class Gcd { public static void main(String args[])throws IOException { int c; System.out.print("Enter the 1st Number :"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int a=Integer.parseInt(br.readLine()); System.out.print("Enter the 2nd Number :"); int b=Integer.parseInt(br.readLine()); c=a%b; if(c==0) { System.out.println("GCD is :"+b); }

else{ do { a=b; b=c; c=a%b; }while(c!=0); System.out.println("GCD is :"+b); } }

OUTPUT-: Enter the 1st Number :24 Enter the 2nd Number :4 GCD is :4 (b)What are the differences between C+ + and Java? Features Paradigms C++ Procedural, OOP, Generic Programming JAVA OOP, Generic Programming (from Java 5)

Form of Executable Native Compiled Source Java bytecode Code Code Memory Managed, using a garbage Manual management collector Yes, very commonly No pointers; references are used Pointers used, but some form of instead references available too. Preprocessor Yes No Character arrays, String Type Objects objects Complex Data Structures, unions, Classes Types classes Multiple class Single class inheritance, multiple Inheritance inheritance interface implementation Operator Yes No Overloading Automatic Yes, with warnings if Not at all if loss could occur; msut coercions loss could occur cast explicitly Goto Statement Yes No There is no virtual keyword in virtual keyword Support By C++ Java

2.(a) Write short notes on the following: (i)Finalizer-:The garbage collector knows only how to release memory allocated with new, so it wont know how to release the objects special memory. To handle this case, Java provides a method called finalize( ) that you can define for your class. Heres how its supposed to work. When the garbage collector is ready to release the storage used for your object, it will first call finalize( ), and only on

the next garbage-collection pass will it reclaim the objects memory. So if you choose to use finalize( ), it gives you the ability to perform some important cleanup at the time of garbage collection . This method can be overridden to perform some tidying up tasks when an object is garbage collected. Syntax: protected void finalize() throws Throwable {} (ii)Transient-: By default all the variables in the object is converted into the persistent. In some cases, you may want to avoid persisting some variables because you don't have the necessity to persist those varibale. So, you can declare those variables as transient. If the variable is declared as transient, then it will not be persisted. It is the main purpose of the transient keyword. The transient keyword is applicable to the member variables of a class. The transient keyword is used to indicate that the member variable should not be serialized when the class instance containing that transient variable is needed to be serialized. Declaring an transient variable private transient String password; (iii)Abstract -:The abstract keyword can be used on classes and methods. A class declared with the abstract keyword cannot be instantiated, and that is the only thing the abstract keyword does. When a class is declared abstract, then, its methods may also be declared abstract. When a method is declared abstract, the method can not have a definition. This is the only effect the abstract keyword has on method. Here's a example of a abstract method: public abstract int get_person_id (String name); Abstract classes and abstract methods are like skeletons. It defines a structure, without any implementation. Note that, only abstract classes can have abstract methods. Abstract class does not necessarily require its methods to be all abstract. Classes declared with the abstract keyword are solely for the purpose of extension (inheritance) by other classes.

(iii)Volatile-:Volatile modifier is used when you are working with multiple threads.. When multiple threads using the same variable, each thread will have its own copy of the local cache for that variable. So, when it's updating the value, it is actually updated in the local cache not in the main variable memory. The other thread which is using the same variable doesn't know anything about the values changed by the another thread. To avoid this problem, if you declare a variable as volatile, then it will not be stored in the local cache. Whenever threads are updating the values, it is updated to the main memory. So, other threads can access the same updated value.

(b)Compare and contrast overloading and overriding. 10 Overloading-:When multiple methods with the same name and with different parameters are wrriten in a sigle class then It is called method overloading. For example PrintWriter class has multiple println methods. Polymorphism is achieved through method overloading . When an overloaded method is called, JAVA uses the type and/or number of arguments to decide which version of the overloaded method will be called. Overloaded methods may or may not have different return types. When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. However, this match need not always be exact. In some cases javas automatic type conversions can play a role in overload resolution. Java will employ its automatic type conversion only if no exact match is found. The important points to note: A difference in return type only is not sufficient to constitute an overload and is illegal. It is required when a basic functionality is performed with different set of parameters. Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list. Overriding -: When a method with same name and set of parameters is defined in parent(super) class and child class then child method is called overridden method and process is called method overriding. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version in the superclass will be hidden. If you wish to access the superclass version of an overridden method, you can do so by using super keyword. In order to make a method overridden: The return type, method name, type and order of arguments must be identical to those of a method in a parent class. The accessibility must not be more restrictive than original method. The method must not throw checked exceptions of classes that are not possible for the original method. # Overloading 1 Defined in a class with same name and different set of parameters Overriding Defined in Parent and Child classes with same name and same set of parameters Return type must be same as parent class

2 Retrun type may be different

3 4

Overloaded method can throw checked Exception

Overridden method can not throw checked Exception if not thrown by Parent

Overloaded method can have narrow It can not have narrow access modifier access modifier

UNIT- II
3.(a)what is the difference between a class and an interface? What is the use of interface? Write a Program in java to illustrate the use of an interface. 10 An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior. Because an interface has simply a list of unimplemented methods, therefore these methods are also know as abstract methods, you might wonder how an interface differs from an abstract class. The differences are significant.
An interface cannot implement any methods, whereas an abstract class can. A class can implement many interfaces but can have only one superclass. An interface is not part of the class hierarchy. Unrelated classes can implement

the same interface. An interface is simply declared by using keyword interface before the class name i.e. public interface Transaction{ public user add(); public address delete(); } To above interface, implemented by any class & that class have to mandatory to define all the abstract methods of that interface: Exp-: public class Handle implements Transaction{ public user add(){} public address delete(){} } Yes there are many difference between an Interface & Abstract Class we can understand some difference with the help of this Exp:Example of Abstract Class-: public abstract class Hello ( public void sayHello () { System.out.println (Hello World); } public abstract void shakHand(); } Example of Interface-:

Public interface Hello{ Public void sayHello(); public void shakHand(); } (b) Describe the Java throwable class hierarchy and the types of exception. Can you claim multiple exceptions in a method declaration? Illustrate by means of an example. The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or of one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause. Class hierarchy of Throwable class:

Yes one try {} block can caught by multiple catchblock {}.In a one try block multiple exception can occurs like NullPointerException,ArrayIndexOutofBoundException & so for handle these different exception we can define multiple catchblock{} . Multiple Catch Block with one Try Block Example: public class CheckException{ public static void main(String []args) { String name = "Vijay Dinanth Chohan"; try { System.out.println("Length of name is "+ name.length()); System.out.println("Charter at 7 position is "+ name.charAt(25)); } catch (StringIndexOutOfBoundsException e) { System.out.println("String abhi choti he"); } catch (NullPointerException e) { System.out.println("Name can not be null"); } finally { System.out.println(">>>I am Ambhitabh"); }

} } 4.(a)Compare the following: (i)Multithreading and multiprocessing-: Multi-threading refers to an application with multiple threads running within a process. These processes are called Light Weight Processes. Multithreading allows two parts of the same program to run concurrently. Multi-processing is an application organized across multiple OS-level processes. (ii)Yielding and sleeping-: Yielding-: yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Sleeping-: The sleep () method is actually an overloaded method within the Thread class. It can be passed either a long that represents the time in milliseconds that you want the thread to cease execution, or it can be passed a long and an int that represents the time in milliseconds plus the time in nanoseconds that a thread will sleep. We want the thread to sleep for 100 milliseconds. Ex-:public void run() { try { Thread.sleep(100); } catch (InterruptedException e) {} } (iv)Daemon thread and selfish thread-: In Java, any thread can be a Daemon thread. Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits. setDaemon(true/false) This method is used to specify that a thread is daemon thread. public boolean isDaemon() This method is used to determine the thread is daemon thread or not. (b)What is the importance of thread synchronization in multithreading? Give some examples of resource corruption when multiple thread conflict. How do you synchronize conflicting thread? 10 With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors. E.g. synchronizing a function: public synchronized void Method1 () { // method code. } E.g. synchronizing a block of code inside a function: public Method2 (){ synchronized (this) { // synchronized code here. } }

UNIT- III
5.(a)Explain the life cycle of an applet. What are the interfaces available in applet in applet class? An applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a webpage and runs in the context of the browser. An applet must be a subclass of the java.applet.Applet class, which provides the standard interface between the applet and the browser environment. Swing provides a special subclass of Applet, called javax.swing.JApplet, which should be used for all applets that use Swing components to construct their GUIs.By calling certain methods, a browser manages an applet life cycle, if an applet is loaded in a web page. Life Cycle of an Applet: Basically, there are four methods in the Applet class on which any applet is built.
init:

This method is intended for whatever initialization is needed for your applet. It is called after the param attributes of the applet tag.
start:

This method is automatically called after init method. It is also called whenever user returns to the page containing the applet after visiting other pages.
stop:

This method is automatically called whenever the user moves away from the page containing applets. You can use this method to stop an animation.
destroy:

This method is only called when the browser shuts down normally.

Thus, the applet can be initialized once and only once, started and stopped one or more times in its life, and destroyed once and only once.
java.applet.AppletContext-: java.applet.AppletStub-: When

an applet is first created, an applet stub is attached to it using the applet's setStub method. This stub serves as the interface between the applet and the browser environment or applet viewer environment in which the application is running. java.applet.AudioClip-:

(b)Describe how a listener object is registered and how a listner interface is implemented? How do you override a method defined in listner interface? TODO

6.(a)What is AWT? Give the component hierarchy of AWT. What are the various types of menus available in java? Explain with suitable example. AWT stands for Abstract Window Toolkit. The Abstract Window Toolkit supports GUI Java programming. It is a portable GUI library for stand-alone applications and/or applets. The Abstract Window Toolkit provides the connection between your application and the native GUI. The AWT provides a high level of abstraction for your Java program since it hides you from the underlying details of the GUI your program will be running on. AWT features include :
A A

rich set of user interface components. robust event-handling model. and imaging tools, including shape, color, and font classes.

Graphics Layout

managers, for flexible window layouts that don't depend on a particular window size or screen resolution.
The

AWT components depend on native code counterparts (called peers) to handle their functionality. Thus, these components are often called "heavyweight" components Top of Form. Component Hierarchy of an AWT Interfaces

(b) What is event delegation model? What are its basic components? Write a program to simulate a simple calculator using AWT. In order for a program to catch and process GUI events, it must subclass GUI components and override either action() or handleEvent() methods. Returning "true" from one of these methods consumes the event so it is not processed further; otherwise the event is propagated sequentially up the GUI hierarchy until either it is consumed or the root of the hierarchy is reached. The result of this model is that programs have essentially two choices for structuring their event-handling code:
Each

individual component can be subclasses to specifically handle its target events. The result of this is a plethora of classes. All events for an entire hierarchy (or subset thereof) can be handled by a particular container; the result is that the container's overridden action() or handleEvent() method must contain a complex conditional statement in order to process the events. Goals of Event Delegation Model The primary design goals of the new Delegation model in the AWT are the following:
Simple

and easy to learn

Support a clean separation between application and GUI code Facilitate the creation of robust event handling code which is less

error-prone (strong compile-time checking) Flexible enough to enable varied application models for event flow and propagation For visual tool builders, enable run-time discovery of both events that a component generates as well as the events it may observe Support backward binary compatibility with the old model The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.

Unit- IV
7.(a) What is the difference between the reader/writer class hierarchy and the input/output stream class hierarchy? Which stream must always be used to process external files?

The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented. Reader/writer belongs to the charecter stream I/P and O/P belongs to the byte stream. Reader/writer support only cahracter and input/output stream support only bytes input stram and the java reader class has only one differnce and that is input stream only support bytes and the reader class only supports the character.

(b)Write a program in Java that will count the number of characters, words and lines in a file. The file name should be passed as a command line argument. 10 // Program to read from a text file & print no if Character,Line,words import java.io.FileReader; public class FileRead { public static void main(String[] args) throws Exception { FileReader reader = new FileReader(args[0]);

int c=0,w=0,l=0; int ch = reader.read(); char chr; while(ch!=-1){ chr =(char)ch; c++; if((chr==' ')||(chr=='\n')){ w++; } if(chr=='\n'){ l++; } ch = reader.read(); } System.out.println("No of Character in File="+c); System.out.println("No of Words in File="+w); System.out.println("No of Line in File ="+l); } } 8.(a)Explain the following with examples: 10 (i)Callable statement (ii)Result set (iii)Connection (iv)Result set metadata (i)Callable Statement-: Execute a call to a database stored procedure. CallableStatement prepareCall (String sql) returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements. CallableStatement extends PreparedStatement. CallableStatement is used to execute SQL Stored Procedures or Stored Function. JDBC provides a stored procedure SQL escape that allows stored procedures to be called in a standard way for all RDBMS's. This escape syntax has one form that includes a result parameter and one that does not. If used, the result parameter must be registered as an OUT parameter. The other parameters may be used for input, output or both. Parameters are refered to sequentially, by number. The first parameter is 1. {?= call <procedure-name>[<arg1>,<arg2>, ...]} {call <procedure-name>[<arg1>,<arg2>, ...]} IN parameter values are set using the set methods inherited from PreparedStatement. The type of all OUT parameters must be registered prior to executing the stored procedure; their values are retrieved after execution via the get methods provided here. A Callable statement may return a ResultSet or multiple ResultSets. Multiple ResultSets are handled using operations inherited from Statement.For maximum portability, a call's

ResultSets and update counts should be processed prior to getting the values of output parameters. Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root"); CallableStatement callStmt = conn.prepareCall("{CALL ProTest(?)}"); callStmt.registerOutParameter(1, Types.INTEGER); callStmt.execute(); (ii)Result set-: JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. In addition, the Statement methods executeQuery and getResultSet both return a ResultSet object, as do various DatabaseMetaData methods. ResultSet is an interface. The ResultSet interface provides methods for retrieving and manipulating the results of executed queries, and ResultSet objects can have different functionality and characteristics. These characteristics are result set type, result set concurrency, and cursor holdability. A table of data representing a database result set is usually generated by executing a statement that queries the database. The type of a ResultSet object determines the level of its functionality in two areas: the ways in which the cursor can be manipulated, and how concurrent changes made to the underlying data source are reflected by the ResultSet object. The following code demonstrates declaring the ResultSet object rs and assigning the results of our query to it by using the executeQuery method. Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, name, designation FROM Employee"); while (rs.next()) { int id = rs.getInt(1); String n = rs.getString(2); String d = rs.getString(3); } (iii)Connection-: It is used for connection or session with a specific database. Within the context of a Connection, SQL statements are executed and results are returned. A Connection's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method. By default the Connection automatically commits changes after executing each statement. If auto commit has been disabled, the method commit must be called explicitly, otherwise the database changes will not be saved. (iv)Result set metadata-: The ResultSetMetaData class represents the result of the compilation of a single Miner SQL statement. If the statement was executed, the ResultSetMetaData object will contain a row count.

The ResultSetMetaData object returned from a compilation will contain one array of output Columns representing the columns in the result set that is returned when the statement executes. If the statement does not return a result set, the array will be empty (outputs. length = = 0). The ResultSetMetaData object also contains an array of input columns representing parameters for a PreparedStatement or CallableStatement. Not that all this array contains all parameters of a CallableStatement, including OUT and INOUT parameters. If the statement does not have any parameters, the inputs array will be empty (inputs. length = = 0). The ResultSetMetaData object will also contain a hashtable with column names so that individual input or output columns can be accessed by name. (b)Write a JDBC Program for student marklist processing.

UNIT - V
9.(a)what are the differences between a server socket and a client socket? How do you create a server socket? What port numbers can be used? Can a port connect to multiple clients? What happens if a requested socket number is already in use? 10 Socket class is meant for client side, so in a client side u need to make a object of Socket class for any networking application, whereas for server side networking application ServerSocket class is used, in this class method named as serversocket_object.accept() is used by server to listen to clients at specific port addresses, for local computer it is either "localhost" or "127.0.0.1" and might be u'r subnet address in case of some LAN. The server program begins by creating a new ServerSocket object to listen on a specific port (see the statement in bold in the following code segment). When writing a server, choose a port that is not already dedicated to some other service. KnockKnockServer listens on port 4444 because 4 happens to be my favorite number and port 4444 is not being used for anything else in my environment: try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port: 4444"); System.exit(-1); } ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). In this case, the KnockKnockServer has no choice but to exit.

If the server successfully binds to its port, then the ServerSocket object is successfully created and the server continues to the next step--accepting a connection from a client (shown in bold): Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); } The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has it's remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests. (b)Write an applet to show the number of visits made to a web page. The count should be stored on a server side in a file. Every time a page is visited the applet should send a request to the server and the server should increase the count and send that count to the applet. The applet should then display the count in a message. 10.(a)Write steps to create RMI application. Give appropriate example. (b)Explain the following: (i)Collections framework (ii)Collections interface (iii)Collection classes (iv)Proxy servers Collection Framework-:The Collection Framework provides a well-designed set if interface and classes for sorting and manipulating groups of data as a single unit, a collection. The Collection Framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces. The Collection Framework is made up of a set of interfaces for working with the groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you

always need to create specific, implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code. In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys. When designing software with the Collection Framework, it is useful to remember the following hierarchical relationship of the four basic interfaces of the framework. Collection-A collection represents a group of objects known as its elements

Set - cannot contain duplicate elements.

Ex SET [1,2,4,5,6,7,8]

List- ordered collection, can contain duplicate elements.

Ex LIST [1,2,4,5,7,3,3,4,5] Queue - hold multiple elements prior to processing. a Queue provides additional insertion, extraction, and inspection operations.

Ex QUEUE [1,2,4,5,7,3,3,4,5] Map - an object that maps keys to values. A Map cannot contain duplicate keys{4,THREE}]

Ex MAP [{1,ONE},{2,TWO},{3,THREE}, SortedSet a Set that maintains its elements in ascending order. SortedMap a Map that maintains its mappings in ascending key order

(ii)Collections interface-: A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. It has Set, List and Queue child interfaces. This interface is typically used to pass collections around and manipulate them where maximum generality is desired. All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to

copy any collection, producing an equivalent collection of the desired implementation type. Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. (iii)Collection classes-: The collection classes in java.util include some of the most commonly used classes in Java. The most commonly used collection types are List and Map. Concrete implementations of List include ArrayList and Vector, which are variable size lists ideal for building, storing and manipulating a list of elements of any type of object. Lists are ideal when you want to access elements by numerical index. Maps provide a more general way of storing elements. The Map collection type allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Conceptually, you could consider Lists as Maps which have numeric keys. However in practice there no direct connection between Lists and Maps except that they are both defined in java.util. In this article, we will focus on the Maps that are available with the core Java distribution, and also consider how to adapt or implement specialized Maps that are more optimal for your application specific data. (iv)Proxy servers -:A proxy server is basically an intermediary forwarding station between two computers, a client and a server. The way that it works is fairly simple and straightforward. The proxy server sits and waits, listening to a particular port on the local machine where it is running. Once a request is made to that port, the proxy then establishes a connection to a specified port on a specified remote host. Any data transferred from the client to the proxy is forwarded from the proxy to the remote host. Likewise, any responses received from the remote host by the proxy are forwarded to the client. In this way, the proxy server acts as a "middle man" between the client and the remote host. It recieves all the data from each, and forwards it to the other. Both the client and the remote host have no idea that the proxy is between them, as it is invisible to each. They send their requests and responses, and the proxy takes care of the connections between both. As such, the proxy must act as both a client and a server. It is a server to the original client requesting data from the remote host. The proxy intercepts this request as if it were the server, and then sends this same request to the remote host, acting as if it were a client. When the remote host sends it's response, the proxy recieves it as a client, and then send it to the client as if it were the server.

MCA June 2010 Solved Paper

UNIT-I
1.(a) What are the differences between array declarations in C+ + and Java ? Illustrate with examples the declaration of multidimensional arrays in Java. 1.(b) What is the purpose of garbage collection ? When is an object subjected to garbage collection ? How many times may an objects finalize() method be invoked by the garbage collector ? Garbage Collection is process of discarding orphan objects and releasing primary memory locations occupied by these objects. An object os called orphan object when its program is finished and it does not have any use. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. Garbage collection is done by a daemon thread that is called GARBAGE COLLECTOR. Garbage collector thread is started by JVM when any JAVA program execution started. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. finalize method is called only once in the life. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects,but there is no guarantee when all the objects will garbage collected.Garbage collection is an automatic process and can't be forced. There is no guarantee that Garbage collection will start immediately upon request of System.gc().

2.(a) Explain various class modifiers and member modifiers with proper examples. The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. Java provides a number of access modifiers to set the level of access for classes as well as the fields, methods and constructors in classes. A member has package or defaultaccessibility when no accessibility modifier is specified. Access Modifiers or Access Specifier or Visibility Mode 1. private 2. protected 3. default 4. public 1. public access modifier Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package. 2. private access modifier The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them. 3. protected access modifier The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a super class can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected members class.

2.(b) With suitable examples explain the concept of method overriding. What restrictions are placed on method overloading? Overloading-:When multiple methods with the same name and with different parameters are wrriten in a single class then It is called method overloading. For example PrintWriter class has multiple println methods. Polymorphism is achieved through method overloading . When an overloaded method is called, JAVA uses the type and/or number of arguments to decide which version of the overloaded method will be called. Overloaded methods may or may not have different return types. When java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. However, this match need not always be exact. In some cases javas automatic type conversions can play a role in overload resolution. Java will employ its automatic type conversion only if no exact match is found. The important points to note: A difference in return type only is not sufficient to constitute an overload and is illegal. It is required when a basic functionality is performed with different set of parameters. Overloaded methods may call one another simply by providing a normal method call with an appropriately formed argument list. Overriding -: When a method with same name and set of parameters is defined in parent(super) class and child class then child method is called overridden method and process is called method overriding. When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version in the superclass will be hidden. If you wish to access the superclass version of an overridden method, you can do so by using super keyword. In order to make a method overridden: The return type, method name, type and order of arguments must be identical to those of a method in a parent class. The accessibility must not be more restrictive than original method. The method must not throw checked exceptions of classes that are not possible for the original method.

# Overloading 1 Defined in a class with same name and different set of parameters 2 Retrun type may be different 3 Overloaded method can throw checked Exception

Overriding Defined in Parent and Child classes with same name and same set of parameters Return type must be same as parent class Overridden method can not throw checked Exception if not thrown by Parent

4 Overloaded method can have narrow It can not have narrow access modifier access modifier

UNIT- II
3. (a) List various user interface components. Write a program to create a user interface that perform arithmetic. The interface should contain labels and text field for number 1, number 2 and result. The program should have four buttons labeled add, subtract, multiply, divide. A menu should also be created to perform the same operation. User can choose the operation either from buttons or from menu selections. Ans : in progress. (b) Explain try-throw-catch-finally in Java. Write examples. What is the use of finally clause ? 10 try-catch block : It is used to handle an exception within the the method. When an exception is raised in try block then control goes to its catch block. catch block has exception handling code to handle abnormal condition. Example : public class TestArithmeticException { public static void main(String[] args) { int k = 0; int i = 15; try {

/** Divide by Zero and raise exception */ double div = i / k; System.out.println("Div is " + div); } catch (ArithmeticException e) { // Handle exceptional condition and print custom message System.out.println("Divident can not be Zero"); } } } throws clause : It is used when an exception is propagated to its calling method. Many times due to some coding standards a method does not hands it raised exception and just propagate exception to its calling method. Called method uses throws clause in its method signature to propagate exception. Example public class AccountService { private static int balance = 100; public static void main(String[] args) { try { fundTransfer(200); } catch (Exception e) { System.out.println("Please provide sufficient balance"); } } public static void fundTransfer(int amount) throws Exception { if (balance < amount) { throw new Exception("Insufficient Balance"); } } } The finally Block The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.This block is known for recovering and preventing from resources leak.On closing of the file and recovering of a file, you need to place the expression in the finally block.

public class TestArithmetic { public static void main(String[] args) {

int k = 0; int i = 15; try { double div = i / k; System.out.println("Div is " + div); } catch (ArithmeticException e) { System.out.println("Division can not be Zero"); }finally { System.out.println("This is Finally Block"); } } } 4.(a) What do you mean by a thread group ? What is its significance ? Write suitable examples. Thread groups :- offer a convenient way to manage groups of threads as a unit. This is particularly valuable in situations in which you want to suspend and resume a number of related threads. For example, imagine a program in which one set of threads is used for printing a document, another set is used to display the document on the screen, and another set saves the document to a disk file. If printing is aborted, you will want an easy way to stop all threads related to printing. Thread groups are defined by the java.lang.ThreadGroup class.Every thread you create automatically belongs to a default thread group that the Java virtual machine sets up on your behalf. Every thread we've looked at so far belongs to this existing thread group, which is known as the "main" thread group.The virtual machine also has a "system" thread group. This thread group contains the threads that handle finalization and weak references. This group does not contain all threads of the virtual machine: some system-level threads (such as the garbage collection thread(s)) have no corresponding Java thread object and do not exist in any Java thread group.

An (incomplete) thread group hierarchy

public class ThreadGroupTest{ public static void main(String[] args){ ThreadGroup squares = new ThreadGroup("Squares"); Thread t1 = new Thread(squares, new ThreadDemo(), "t1"); Thread t2 = new Thread(squares, new ThreadDemo(), "t2"); t1.start(); t2.start(); System.out.println("ThreadGroup name is: " + squares.getName()); System.out.println("There are currently " + squares.activeCount() + " threads running"); System.out.println("The maximum priority of a Thread that can be contained within " + squares.getName() + " is " + squares.getMaxPriority()); System.out.println("There are currently " + squares.activeGroupCount() + " active groups"); System.out.println(squares.getName() + " parent is " + squares.getParent()); } } class ThreadDemo implements Runnable{ private int square;

public void run(){ for(int i = 1; i < 5; i++){ square = i * i; System.out.println("Thread " + Thread.currentThread().getName() + " has a priority of " + Thread.currentThread().getPriority() + ": " + square); } } }

(b) Write a class whose objects hold a current value and have a method to add to that value, printing the new value. Write a program that creates such an object creates multiple threads and invokes the adding method repeatedly from each thread. Write the class such that no addition can be lost. Ans: In Progress. UNIT- III 5.(a) Distinguish between java application and applet. Explain the life cycle of an applet. Write a Java program that can run as an application and as an applet. An applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run. An applet is typically embedded inside a web-page and runs in the context of the browser. An applet must be a subclass of the java.applet.Applet class, which provides the standard interface between the applet and the browser environment. Swing provides a special subclass of Applet, called javax.swing.JApplet, which should be used for all applets that use Swing components to construct their GUIs.By calling certain methods, a browser manages an applet life cycle, if an applet is loaded in a web page. Life Cycle of an Applet: Basically, there are four methods in the Applet class on which any applet is built.
init:

This method is intended for whatever initialization is needed for your applet. It is called after the param attributes of the applet tag.
start:

This method is automatically called after init method. It is also called whenever user returns to the page containing the applet after visiting other pages.

stop:

This method is automatically called whenever the user moves away from the page containing applets. You can use this method to stop an animation.
destroy:

This method is only called when the browser shuts down

normally. Thus, the applet can be initialized once and only once, started and stopped one or more times in its life, and destroyed once and only once.

# Application Applet 1 An application runs stand- An applet runs under the control of a browser. alone, with the support of a virtual machine. 2 The true power of Java lies Applets are great for creating dynamic and in writing full blown interactive web applications applications. 3 In an application execution Applets don't have the main method. starts with the main method. 4 The applications run on Applets are designed for the client site programming Desktop. purpose, downloaded and run on Browser. 5 The java applications are Applets are designed just for handling the client site designed to work with the problems. client as well as server. 6 Applications are designed The applets can run in secure and unsecured to exist in a secure area. environment 7 Does not require to inherit Applet need to inherit java.awt.Applet class any class 8 Static block is called at init() method is called at time of applet creation and time of application call destroy() method is called at time of applet destruction 9 Does not have any other Has init(), start(), paint(), stop(), destroy() life cycle life cycle methods methods

Applet:import java.awt.*; import java.applet.*; class ClassName extends Applet { public void init() { System.out.println("This is init method"); //called only once } public void start() { System.out.println("This is Start method"); //Called again and again when applet is activated (browser window is maximized) } public void stop() { System.out.println("This is Start method"); //Called again and again when applet is deactivated (browser window is minimized) } public void paint(Graphics g) { System.out.println("This is Paint method"); //Called again and again when applet is rendered } } Application:public class ClassName { public static void main(String args[]) { System.out.println("Hello Application"); } } (b) Write an applet that randomly places a specified number of rectangles of random sizes and colors at least partially inside the applet visible area. Read the number of rectangles to be drawn through PARAM tags. 10 TODO

6.(a) Explain about various basic user interface components available in Java. 10 AWT stands for Abstract Window Toolkit. The Abstract Window Toolkit supports GUI Java programming. It is a portable GUI library for stand-alone applications and/or applets. The Abstract Window Toolkit provides the connection between your application and the native GUI. The AWT provides a high level of abstraction for your Java program since it hides you from the underlying details of the GUI your program will be running on. AWT features include :
A A

rich set of user interface components. robust event-handling model. and imaging tools, including shape, color, and font classes.

Graphics Layout

managers, for flexible window layouts that don't depend on a particular window size or screen resolution.
The

AWT components depend on native code counterparts (called peers) to handle their functionality. Thus, these components are often called "heavyweight" components Top of Form. Component Hierarchy of an AWT Interfaces

(b) Write a program to get character input from the keyboard and to put the characters where the mouse points.

Unit- IV
7.(a) Write a program to read the contents of a text file one line at time and print the lines with line numbers.

The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented. Reader/writer belongs to the charecter stream I/P and O/P belongs to the byte stream. Reader/writer support only cahracter and input/output stream support only bytes input stram and the java reader class has only one differnce and that is input stream only support bytes and the reader class only supports the character.

// Program to read from a text file & print no if Character,Line,words

import java.io.FileReader; public class FileRead { public static void main(String[] args) throws Exception { FileReader reader = new FileReader(args[0]); int c=0,w=0,l=0; int ch = reader.read(); char chr; while(ch!=-1){ chr =(char)ch; c++; if((chr==' ')||(chr=='\n')){ w++; } if(chr=='\n'){ l++; } ch = reader.read(); } System.out.println("No of Character in File="+c); System.out.println("No of Words in File="+w); System.out.println("No of Line in File ="+l); } }

(b) What is the purpose of JDBC to ODBC bridge driver ? Write procedure to connect to and query a MYSQL database with JDBC.

Ans: JDBC-ODBC Bridge:The JDBC-ODBC Bridge is a JDBC driver that implements JDBC operations by translating them into ODBC operations. To ODBC it appears as a normal application program. The Bridge implements JDBC for any database for which an ODBC driver is available. The Bridge is implemented as the sun.jdbc.odbc Java package and contains a native library used to access ODBC.The Bridge is used by opening a JDBC connection using a URL with the odbc subprotocol. Before a connection can be established, the bridge driver class, sun.jdbc.odbc.JdbcOdbcDriver, must either be added to the java.lang.System property named jdbc.drivers, or it must be explicitly loaded using the Java class loader. Explicit loading is done with the following line of code:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); When loaded, the ODBC driver creates an instance of itself and registers this with the JDBC driver manager. import java.sql.*; public class TestMSDBCity { public static void main(String args[]) throws Exception { // testUpdate(); testSelect(); } public static void testSelect() throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection("jdbc:odbc:BATCH24SEPT", "", ""); Statement stmt = conn.createStatement(); ResultSet rs = null; rs = stmt.executeQuery("SELECT id,name System.out.println("ID\tName"); System.out.println("--\t----"); while (rs.next()) { System.out.print(rs.getString(1)); System.out.println("\t" + rs.getString("name")); } stmt.close(); conn.close(); } public static void testUpdate() throws Exception { // Class.forName("com.mysql.jdbc.Driver").newInstance(); from city");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Connection conn = // DriverManager.getConnection("jdbc:mysql://localhost/test? user=root&password=root"); Connection conn = DriverManager.getConnection("jdbc:odbc:BATCH06", "", ""); /* * Statement stmt = conn.createStatement(); int recCount = * stmt.executeUpdate("insert into employee values(3,'Nikku','Verma')"); */ PreparedStatement ps = conn .prepareStatement("insert into employee values(?,?,?)"); ps.setInt(1, 6); ps.setString(2, "Chandra"); ps.setString(3, "Joshi"); int recCount = ps.executeUpdate(); System.out.println("# of Records" + recCount); // stmt.close(); ps.close(); conn.close(); } }

8.(a)Explain the following 5 each

(a) JDBC exception classes The Exception are the set of condition that occurred when an abnormal condition try to interrupt the normal flow of the code during the execution of program.

Database programs are critical applications, and it is imperative that errors be caught and handled gracefully. Programs should recover and leave the database in a consistent state. Rollback-s used in conjunction with Java exception handlers are a clean way of achieving such a requirement. The client (program) accessing a server (database) needs to be aware of any errors returned from the server. JDBC give access to such information by providing two levels of error conditions: SQLException and SQLWarning. SQLExceptions are Java exceptions which, if not handled, will terminate the application. SQLWarnings are subclasses of SQLException, but they represent nonfatal errors or unexpected conditions, and as such, can be ignored. In Java, statements which are expected to ``throw'' an exception or a warning are enclosed in a try block. If a statement in the try block throws an exception or a warning, it can be ``caught'' in one of the corresponding catch statements. Each catch statement specifies which exceptions it is ready to ``catch''. Exceptions a). SQLException: It is thrown by the mehods whenever there is a problem while accessing the data or any other things. b). SQLWarning: This exception is thrown to indicate the warning. c). BatchUpdateException: This exception is thrown to indicate that all commands in a batch update are not executed successfully. d). DataTruncation: It is thrown to indicate that the data may have been truncated. Example to show how to handle exceptions try { con.setAutoCommit(false) ; . con.commit() ; con.setAutoCommit(true) ; }catch(SQLException ex) { System.err.println("SQLException: " + ex.getMessage()) ; con.rollback() ; con.setAutoCommit(true) ; }

(b) Java SQL package This package provides the APIs for accessing and processing data which is stored in the database especially relational database by using the java programming language. It includes a framework where we different drivers can be installed dynamically to access different databases especially relational databases. This java.sql package contains API for the following : 1. Making a connection with a database with the help of DriverManager class DriverManager class: It helps to make a connection with the driver. 2. Sending SQL Parameters to a database a). Statement interface: It is used to send basic SQL statements. b). PreparedStatement interface: It is used to send prepared statements or derived SQL statements from the Statement object. c). CallableStatement interface : This interface is used to call database stored procedures. d). Connection interface : It provides methods for creating statements and managing their connections and properties. e). Savepoint : It helps to make the savepoints in a transaction. 3 Updating and retrieving the results of a query: ResultSet interface: This object maintains a cursor pointing to its current row of data. The cursor is initially positioned before the first row. The next method of the resultset interface moves the cursor to the next row and it will return false if there are no more rows in the ResultSet object. By default ResultSet object is not updatable and has a cursor that moves forward only. 4. Providing Standard mappings for SQL types to classes and interfaces in Java Programming language. 5. Metadata a). DatabaseMetaData interface: It keeps the data about the data. It provides information about the database. b). ResultSetMetaData: It gives the information about the columns of a ResultSet object. c). ParameterMetaData: It gives the information about the parameters to the PreparedStatement command 6 Exceptions

a). SQLException: It is thrown by the mehods whenever there is a problem while accessing the data or any other things. b). SQLWarning: This exception is thrown to indicate the warning. c). BatchUpdateException: This exception is thrown to indicate that all commands in a batch update are not executed successfully. d). DataTruncation: It is thrown to indicate that the data may have been truncated. (c) Serialization Serialization is the process of converting a object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network in same or another computer environment. Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the state from being written to the stream and from being restored during deserialization. Java provides classes to support writing objects to streams and restoring objects from streams. Only objects that support the java.io.Serializable interface can be written to streams. public interface Serializable
o o

The Serializable interface has no methods or fields. (Marker Interface) Only objects of classes that implement java.io.Serializable interface can be serialized or deserialized

(d) Print streams

Print streams:- A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkError method. Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written. All characters printed by a PrintStream are converted into bytes using the platform's default character encoding. The PrintWriter class should be used in situations that require writing characters rather than bytes

UNIT - V
9.(a)what are the differences between a server socket and a client socket? How do you create a server socket? What port numbers can be used? Can a port connect to multiple clients? What happens if a requested socket number is already in use? Socket class is meant for client side, so in a client side we need to make a object of Socket class for any networking application, whereas for server side networking application ServerSocket class is used, in this class method named as accept() is used by server to listen to clients at specific port addresses, for local computer it is either "localhost" or "127.0.0.1". The server program begins by creating a new ServerSocket object to listen on a specific port . When writing a server, choose a port that is not already dedicated to some other service. KnockKnockServer listens on port 4444 and port 4444 is not being used for anything else in my environment: try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port: 4444"); System.exit(-1); } ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). In this case, the KnockKnockServer has no choice but to exit.

If the server successfully binds to its port, then the ServerSocket object is successfully created and the server continues to the next step--accepting a connection from a client (shown in bold) and one server may connected to multiple client. Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); } The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has it's remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests. The port numbers in the range from 0 to 1023 are the well-known ports. They are used by system processes that provide widely-used types of network services. The range above the registered ports contains dynamic, or private, ports that cannot be registered with IANA. It is used for custom or temporary purposes and for automatic allocation of ephemeral ports.

(b) Write steps to create RMI application. Give appropriate example. Two remote JAVA objects, those lying on two different JVMs can communicate to each others with help of RMI protocol. RMI hides the network communication complexity between these components. Component that provides services is called Server object and component that consumes services is called Client object. The stub is a client-side object that represents (or acts as a proxy for) the remote object. Stub and remote object both impelemt the same interface. However when the client calls a stub method, the stub forwards the request to the remote object (via the skeleton), which actually executes it. The skeleton object takes care of all remote calls for remote obect. Remote object does not need to worry about network comminication

Stud and Skeleton are created at server by rmic.exe. Skeleton is remain at server with remote server object and stub is sent to client JVM along with remote client object. Stub resides at Client JVM.

Example /** * Remote Interface */ import java.rmi.*; public interface StudentInt extends Remote { public int division() throws RemoteException; } /** * Remote Server Implementation */ import java.rmi.*; import java.rmi.server.*; public class StudentImpl extends UnicastRemoteObject implements StudentInt { int aggMarks = 65;

public StudentImpl() throws RemoteException { } public int division() throws RemoteException { if (aggMarks > 65) { return 1; } else if (aggMarks > 50) { return 2; } else { return 3; } } } /** * Remote Server */ import java.rmi.Naming; public class StudentServer { public static void main(String args[]) throws Exception { StudentImpl s = new StudentImpl(); Naming.rebind("StudentServer", s); } } /** * Remote Client */ import java.rmi.Naming; public class StudentClient { public static void main(String args[]) throws Exception { String url = "rmi://127.0.0.1:1099/StudentServer"; StudentInt std = (StudentInt) Naming.lookup(url); System.out.println("Division : " + std.division()); } }

10.Explain the following: 5 each (i) Collection framework (ii) TCP sockets (iii) Collection classes (iv) Proxy servers (i)Collection Framework -:The Collection Framework provides a well-designed set if interface and classes for sorting and manipulating groups of data as a single unit, a collection. The Collection Framework provides a standard programming interface to many of the most common abstractions, without burdening the programmer with too many procedures and interfaces. The Collection Framework is made up of a set of interfaces for working with the groups of objects. The different interfaces describe the different types of groups. For the most part, once you understand the interfaces, you understand the framework. While you always need to create specific, implementations of the interfaces, access to the actual collection should be restricted to the use of the interface methods, thus allowing you to change the underlying data structure, without altering the rest of your code. In the Collections Framework, the interfaces Map and Collection are distinct with no lineage in the hierarchy. The typical application of map is to provide access to values stored by keys. When designing software with the Collection Framework, it is useful to remember the following hierarchical relationship of the four basic interfaces of the framework. Collection-A collection represents a group of objects known as its elements

Set - cannot contain duplicate elements. Ex SET [1,2,4,5,6,7,8]

List- ordered collection, can contain duplicate elements. Ex LIST [1,2,4,5,7,3,3,4,5]

Queue - hold multiple elements prior to processing. a Queue provides additional insertion, extraction, and inspection operations. Ex QUEUE [1,2,4,5,7,3,3,4,5]

Map - an object that maps keys to values. A Map cannot contain duplicate keys{4,THREE}]

Ex MAP [{1,ONE},{2,TWO},{3,THREE},

SortedSet a Set that maintains its elements in ascending order. SortedMap a Map that maintains its mappings in ascending key order

(ii)Collections interface-: A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. It has Set, List and Queue child interfaces. This interface is typically used to pass collections around and manipulate them where maximum generality is desired. All general-purpose Collection implementation classes (which typically implement Collection indirectly through one of its subinterfaces) should provide two "standard" constructors: a void (no arguments) constructor, which creates an empty collection, and a constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument. In effect, the latter constructor allows the user to copy any collection, producing an equivalent collection of the desired implementation type. Some collection implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. (iii)Collection classes-: The collection classes in java.util include some of the most commonly used classes in Java. The most commonly used collection types are List and Map. Concrete implementations of List include ArrayList and Vector, which are variable size lists ideal for building, storing and manipulating a list of elements of any type of object. Lists are ideal when you want to access elements by numerical index. Maps provide a more general way of storing elements. The Map collection type allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Conceptually, you could consider Lists as Maps which have numeric keys. However in practice there no direct connection between Lists and Maps except that they are both defined in java.util. In this article, we will focus on the Maps that are available with the core Java distribution, and also consider how to adapt or implement specialized Maps that are more optimal for your application specific data. (iv)Proxy servers -:A proxy server is basically an intermediary forwarding station between two computers, a client and a server. The way that it works is fairly simple and straightforward. The proxy server sits and waits, listening to a particular port on the local machine where it is running.

Once a request is made to that port, the proxy then establishes a connection to a specified port on a specified remote host. Any data transferred from the client to the proxy is forwarded from the proxy to the remote host. Likewise, any responses received from the remote host by the proxy are forwarded to the client. In this way, the proxy server acts as a "middle man" between the client and the remote host. It recieves all the data from each, and forwards it to the other. Both the client and the remote host have no idea that the proxy is between them, as it is invisible to each. They send their requests and responses, and the proxy takes care of the connections between both. As such, the proxy must act as both a client and a server. It is a server to the original client requesting data from the remote host. The proxy intercepts this request as if it were the server, and then sends this same request to the remote host, acting as if it were a client. When the remote host sends it's response, the proxy recieves it as a client, and then send it to the client as if it were the server.

MCA June 2010

1 UNIT-I
1.1 1. (a) What are the differences between array 10

declarations in C+ + and Java ? Illustrate with examples the declaration of multidimensional arrays in Java. 1.2 1.

(b) What is the purpose of garbage collection ? When is 10

an object subjected to garbage collection ? How many times may an objects finalize() method be invoked by the garbage collector ? OR 1.3 2. (a) Explain various class modifiers and member 10

modifiers with proper examples.

1.4 2.

(b) With suitable examples explain the concept of 10

method overriding. What restrictions are placed on method overloading?

2 UNIT- II
3 3. (a) List various user interface components. Write a

program to create a user interface that perform arithmetic. The interface should contain labels and text field for number 1, number 2 and result. The program should have four buttons labeled add, choose the operation selections. 3.1 (b) Explain try-throw-catch-finally in Java. Write 10 subtract, multiply, divide. A menu should also be created to perform the same operation. User can either from buttons or from menu 10

examples. What is the use of finally clause ? OR 3.2 4. (a) What do you mean by a thread group ? What is its

significance ? Write suitable examples. 3.2.1 3 .3 An (incomplete) thread group hierarchy

10

(b) Write a class whose objects hold a current value and

have a method to add to that value, printing the new value. Write a program that creates such an object creates multiple threads and invokes the adding method repeatedly from each thread. Write the class addition can be lost. such that no 10

4 UNIT- III
4.1 5. (a) Distinguish between java application and applet. 10

Explain the life cycle of an applet. Write a Java program that can run as an application and as an applet. 4.2 (b) Write an applet that randomly places a specified

number of rectangles of random sizes and colors at least partially inside the

applet visible area. Read the number of rectangles to be drawn through PARAM tags. OR 4 .3 6. (a) Explain about various basic user interface 10 10

components available in Java. 4.4 (b) Write a program to get character input from the

keyboard and to put the characters where the mouse points.

10

5 Unit- IV
5.1 7. (a) Write a program to read the contents of a text file one line 10

at time and print the lines with line numbers. 5.2

(b) What is the purpose of JDBC to ODBC bridge driver ?

Write procedure to connect to and query a MYSQL database with JDBC. 10 OR 5.3 8. 5.4 5.5 5.6 5.7 (a) (b) (c) (d) (a)Explain the following 5 each JDBC exception classes Java SQL package Serialization Print streams

6 UNIT - V
6 .1 9. (a)what are the differences between a server socket and a

client socket? Ho w do you create a server socket? What port numbers can be used? Can a port connect to multiple clients? What happens if a requested socket number is already in use? 10

6.2 example.

(b) Write steps to create RMI application. Give appropriate 10 OR

6.3 10. 6.4 (i)

Explain the following: 5 each Collection framework (iv) Proxy servers (ii) TCP sockets

(iii) Collection classes

You might also like