Post on 07-Apr-2018
8/4/2019 MCA_solve_paper by Ritesh Dalvi
1/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
1An application runs stand-alone, with the support of avirtual machine.
An applet runs under the control of a browser.
2
The true power of Java lies
in writing full blown
applications.
Applets are great for creating dynamic and interactive
web applications
3In an application executionstarts with the main method.
Applets don't have the main method.
4The applications run on
Desktop.
Applets are designed for the client site programming
purpose, downloaded and run on Browser.
5The java applications aredesigned to work with theclient as well as server.
Applets are designed just for handling the client siteproblems.
6Applications are designed to
exist in a secure area.The applets can run in secure and unsecured environment
7Does not require to inheritany class
Applet need to inherit java.awt.Applet class
8Static block is called at time
of application call
init() method is called at time of applet creation and
destroy() method is called at time of applet destruction
9
Does not have any other life
cycle methods
Has init(), start(), paint(), stop(), destroy() life cycle
methods
Applet:-
import java.awt.*;import java.applet.*;
8/4/2019 MCA_solve_paper by Ritesh Dalvi
2/120
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 isactivated (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 isrendered}
}
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 aWeb 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
8/4/2019 MCA_solve_paper by Ritesh Dalvi
3/120
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 itwon'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 newoperator. Constructors are declared just like as wedeclare methods, except that the constructors dont have any return type.
Since constuctors are called by JVM at runtime during object instantiation so it does notrequired any return value.
Default constructor does not require any parameter. It is called default constructor onlybecause 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 iscalled 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 javaat 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;
8/4/2019 MCA_solve_paper by Ritesh Dalvi
4/120
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 classit cannot be used inside a static method, as the static method has only one instance of iti.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 superclass 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 extractsand 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 Objectreference 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) classand 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
8/4/2019 MCA_solve_paper by Ritesh Dalvi
5/120
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)
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-june-2007-solved-paper/TIJ309.png?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
6/120
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 themethods 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 differsfrom 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, forexample), 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);}
8/4/2019 MCA_solve_paper by Ritesh Dalvi
7/120
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 JavaThread 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 aclass 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 createdwith classes that implements the 'Runnable' interface.
The second way to create a new thread is to:
Implement the "Runnable" interface in your own class.
Implement 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 () {
8/4/2019 MCA_solve_paper by Ritesh Dalvi
8/120
for(int i=0;i
8/4/2019 MCA_solve_paper by Ritesh Dalvi
9/120
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 tothrow 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 technologycan 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 thebrowser environment.
Swing provides a special subclass of Applet, called javax.swing.JApplet, which should beused 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 whichany 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.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
10/120
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:-
Displace Name Applet
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);
}
8/4/2019 MCA_solve_paper by Ritesh Dalvi
11/120
}
(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. Theseclasses 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 thatimplement 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 mainapplication 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 alightweight component. A lightweight component is a component that is not associated
with a native opaque window.
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-june-2007-solved-paper/1classes.gif?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
12/120
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 specifiedwhen 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 whichan 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 itsown, 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 Webpage 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. Anevent 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 setListener (for single-cast)
and/or addListener (for mult-cast) methods which are used to registerspecific 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 oflisteners) 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
8/4/2019 MCA_solve_paper by Ritesh Dalvi
13/120
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() andfocusLost(), 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.EventListenerjava.awt.event.ComponentListener
java.awt.event.ContainerListener
java.awt.event.FocusListener
java.awt.event.KeyListenerjava.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.ActionListenerjava.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 generallyincludes 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 exampleof 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);
8/4/2019 MCA_solve_paper by Ritesh Dalvi
14/120
...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 thelook 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 abyte 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 andtransient 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.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
15/120
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 tobe 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 applicationprogram. 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 odbcsubprotocol. Before a connection can be established, the bridge driver class,
sun.jdbc.odbc.JdbcOdbcDriver, must either be added to the java.lang.System propertynamed 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");
8/4/2019 MCA_solve_paper by Ritesh Dalvi
16/120
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 objectrs, 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 whichaccepting 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, itssupported 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", "", "");
8/4/2019 MCA_solve_paper by Ritesh Dalvi
17/120
// Created statement.Statement stmt = conn.createStatement();
//An SQL that will insert a record into table
String sql = "SELECT rollNo,name,phy,che,maths fromMarksheet";
ResultSet rs = null;
// executeQuery method will return all records fromthe 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 inDatabase 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 connectionstmt.close();conn.close();
}
}
Copyright (c)
8/4/2019 MCA_solve_paper by Ritesh Dalvi
18/120
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
1
Reliability: TCP is connection-oriented
protocol. When a file or message send
it will get delivered unless connectionsfails. If connection lost, the server will
request the lost part. There is no
corruption while transferring a
message.
Reliability: UDP is connectionless
protocol. When you a send a data or
message, you don't know if it'll get there,it could get lost on the way. There may
be corruption while transferring a
message.
2
Ordered:- If you send two messages
along a connection, one after the other,you know the first message will get
there first. You don't have to worryabout data arriving in the wrong order.
Ordered:- If you send two messages out,you don't know what order they'll arrive
in i.e. no ordered
3
Heavyweight:- when the low level
parts of the TCP "stream" arrive in the
wrong order, resend requests have tobe sent, and all the out of sequence
parts have to be put back together, so
requires a bit of work to piece together.
Lightweight:- No ordering of messages,
no tracking connections, etc. It's just fire
and forget! This means it's a lot quicker,and the network card / OS have to do
very little work to translate the data back
from the packets.
4
Streaming:- Data is read as a "stream,"with nothing distinguishing where one
packet ends and another begins. There
may be multiple packets per read call.
Datagrams: Packets are sent individuallyand are guaranteed to be whole if they
arrive. One packet per one read call.
5
Examples: World Wide Web (Apache
TCP port 80), e-mail (SMTP TCP port
25 Postfix MTA), File TransferProtocol (FTP port 21) and Secure
Shell (OpenSSH port 22) etc.
Examples: Domain Name System (DNSUDP port 53), streaming media
applications such as IPTV or movies,
Voice over IP (VoIP), Trivial FileTransfer Protocol (TFTP) and online
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 andcomponent that consumes services is called Client object.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
19/120
rmic compile generates two addtional components stud and skeleton that wraps networksockets 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.
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-june-2008-solved-paper/RMI.JPG?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
20/120
The RMISecurityManager class provides additional security semantics required for
RMI interactions.
The MarshalledObject class is used during remote method calls for certain methodarguments. 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 Socketclass 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 notbeing 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 theserver 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):
8/4/2019 MCA_solve_paper by Ritesh Dalvi
21/120
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, theaccept 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 requestson 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 forsorting and manipulating groups of data as a single unit, a collection.
The Collection Framework provides a standard programming interface to many of themost 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 groupsof 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 actualcollection 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.
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-june-2007-solved-paper/colls-coreInterfaces.gif?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
22/120
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 valuesstored by keys.
When designing software with the Collection Framework, it is useful to remember thefollowing 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
keyso 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 istypically used to pass collections around and manipulate them where maximum
generality is desired.
All general-purpose Collection implementation classes (which typically implementCollection 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 collectionwith 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 uncheckedexception, typically NullPointerException or ClassCastException.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
23/120
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:
TheJava Virtual Machine
TheJava 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 normallygenerated 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 thejavac
compiler. A.class
file
contains bytecodes. Bytecode is the machine language of the JVM.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
24/120
An overview of the software development process.
Java API (Application Programming Interface) : The JVM is distributed along with aset of standard class libraries that implement the Java API (Application Programming
Interface).
An application programming interface is what a computer system, library or applicationprovides 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 manyuseful capabilities. It is grouped into libraries of related classes and interfaces; these
libraries are known aspackages.
(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 hasmultiple println methods.
Polymorphism is achieved through method overloading . When an overloaded method iscalled, 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 typeconversion only if no exact match is found.
The important points to note:
A difference in return type only is not sufficient to constitute an overloadand 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
8/4/2019 MCA_solve_paper by Ritesh Dalvi
25/120
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 thesuperclass 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 Overriding
1
Defined in a class with same name
and different set of parameters
Defined in Parent and Child classes with same
name and same set of parameters
2 Return type may be different Return type must be same as parent class
3Overloaded method can throw
checked Exception
Overridden method can not throw checked
Exception if not thrown by Parent
4Overloaded method can have
narrow access modifierIt 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 byindexing. Each element has the same data type and the
array occupies a contiguous area of memory.
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-dec-2008-solved-paper/fig3.JPG?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
26/120
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 ofintegersanArray = new String[10]; // allocates memory for 10integersanArray[0] = "One"; // initialize first elementanArray[1] = "Two"; // initialize second elementanArray[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 importstatements.
Explicitly imported names may not be redefined later in the package. When explicit
8/4/2019 MCA_solve_paper by Ritesh Dalvi
27/120
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 encounterambiguous 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 namethrough its package
More examples
import java.lang.*;import java.util.*;import java.sql.*;import java.io.*;
(ii) Public and default class
JAVA got four access modifiers
1. private2. 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 Can Access?Same package Yes
Other Package Yes
Child Class 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
8/4/2019 MCA_solve_paper by Ritesh Dalvi
28/120
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 Applet
1An application runs stand-alone, withthe support of a virtual machine.
An applet runs under the control of abrowser.
2The true power of Java lies in writing
full blown applications.
Applets are great for creating dynamic and
interactive web applications
3 Applets don't have the main methodIn an application execution starts with themain method.
4The applications don't have such type of
criteria
Applets are designed for the client site
programming purpose.
5The java applications are designed to
work with the client as well as server.
Applets are designed just for handling the
client site problems.
6Applications are designed to exist in asecure area.
The applets are typically used.
(iv) Java and C++
C++:-
1. C++ is object based language.
2. In C++, if value of one variable is changed then the change invalue 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 codegenerated 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 usedover 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.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
29/120
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 makesure 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 concretemethods. 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 itsproperties 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 Interfacesupports multiple Inheritance.
6. An Interface can only have public members whereas an abstractclass 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 classneed not implement any of the methods defined in the abstract class.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
30/120
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 anabstract 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 findcorresponding 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 otherwisetotally 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 toprevent these errors is synchronization.
The facility provided by java to handle concurrent access of a common data structure bytwo or more threads is done by the help of Synchronizations.
There are two types of synchronization in threads:-
1. Method2. 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() {
8/4/2019 MCA_solve_paper by Ritesh Dalvi
31/120
return c;}
}
If count is an instance of Synchronized Counter, then making these methodssynchronized 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 invokesynchronized 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 ofa 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 aconstructor 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 aredescribed in the section on Liveness.) Without synchronized statements, there would
have to be a separate, unsynchronized method for the sole purpose of invokingnameList.add.
Synchronized statements are also useful for improving concurrency with fine-grainedsynchronization
8/4/2019 MCA_solve_paper by Ritesh Dalvi
32/120
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 Dept-
name 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 voidmain(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 11thelement 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 handlingan 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
8/4/2019 MCA_solve_paper by Ritesh Dalvi
33/120
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 withthe first statement of that catch clause.
try-catch syntax is
try{ //throw an exception }catch(Exception1 e1){ //called when Exception1 occurred }catch(Exception2 e2){ //called when Exception1 occurred}finally{ // call 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.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
34/120
Applet hierarchy
Java.lang.Object :- Class Object is the root of the class hierarchy. Every class hasObject 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 ofcomponents 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 acomponent 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 specifiedwhen 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
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-dec-2008-solved-paper/1classes.gif?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
35/120
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 accessibilitypackage 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 receivingnotifications 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 classimplementing 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 toidentify 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);}
}}
8/4/2019 MCA_solve_paper by Ritesh Dalvi
36/120
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 explicitlyfor 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 gapbetween 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.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
37/120
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 canhave 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 andalso 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" fromone 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 essentiallytwo 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 behandled 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
propagationFor 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
8/4/2019 MCA_solve_paper by Ritesh Dalvi
38/120
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 processunhandled events, as is the case of the event-inheritance model.
Copyright (c)
8/4/2019 MCA_solve_paper by Ritesh Dalvi
39/120
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 updatedfile.writeInt(123); // Employee Code
file.writeChars("Narayan Murti"); // Employee Namefile.writeChars("Diretor"); // Designationfile.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 writeprimitive data types.
Importent methods ofDataOutputStream are
writeInt(5);writeDouble(5.5);writeString("sunRays");
8/4/2019 MCA_solve_paper by Ritesh Dalvi
40/120
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 aftera 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 theclient?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.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
41/120
(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 levelsof 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 areenclosed 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
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-dec-2008-solved-paper/JDBC-Driver.JPG?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
42/120
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 classResultSet 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 isusually generated by executing a statement that queries the database.
The type of a ResultSet object determines the level of its functionality in two areas: theways 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)
8/4/2019 MCA_solve_paper by Ritesh Dalvi
43/120
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 eachothers 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 doesnot 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. Stubresides at Client JVM.
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-june-2008-solved-paper/RMI.JPG?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
44/120
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 UnicastRemoteObjectimplements 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();
8/4/2019 MCA_solve_paper by Ritesh Dalvi
45/120
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 isA 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 orsometimes tunneling proxy.
A proxy server can be placed in the user's local computer or at various points between theuser and the destination servers or the Internet. A reverse proxy is a proxy used as a front-
end 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 SDKdoes 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 maximumgenerality is desired.
8/4/2019 MCA_solve_paper by Ritesh Dalvi
46/120
Key Classes and Interfaces
Interface Set List Map
ImplementationHashSet HashMap ArrayList
TreeSet Treemap
LinkedList
Historical Vector Stack Hashtable Properties
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 collectionwith 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 uncheckedexception, 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 thelatter. 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. Suchexceptions are marked as "optional" in the specification for this interface.
http://home.sunrays.co.in/Home/applied-core-java/collection-framework/test-array-listhttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testvectorhttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testhashsethttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testtreesethttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testhashmaphttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testhashtablehttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testiteratorhttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testenumerationhttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/test-array-listhttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testvectorhttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testhashsethttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testtreesethttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testhashmaphttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testhashtablehttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testiteratorhttp://home.sunrays.co.in/Home/applied-core-java/collection-framework/testenumeration8/4/2019 MCA_solve_paper by Ritesh Dalvi
47/120
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 theInternet 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 otherhosts 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 formallydefined 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 unreliableservice 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 orperformed in the application, avoiding the overhead of such processing at the networkinterface 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 allon 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)
http://home.sunrays.co.in/Home/solved-papers-1/solved-papers/mca-dec-2008-solved-paper/img015.JPG?attredirects=08/4/2019 MCA_solve_paper by Ritesh Dalvi
48/120
(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 domainnames meaningful to humans into the numerical (binary) identifiers associated with
networking equipment for the purpose of locating and addressing these devices world-
wide. 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. Becauseof this, World-Wide Web (WWW) hyperlinks and Internet contact information can
remain consistent and constant even if the current Internet routing arrangements changeor 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 eachdomain. 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 needfor 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 world-wide, 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 ofthe Internet Protocol Suite (TCP/IP).
8/4/2019 MCA_solve_paper by Ritesh Dalvi
49/120
(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 routeddifferently, and may arrive in any order.
UDP broadcasts sends are always enabled on a DatagramSocket. In order to receivebroadcast 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 anddoes 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, acollection.
The Collection Framework provides a standard programming interface to many of the
most common abstractions, without burd