Sunteți pe pagina 1din 47

SUBJECT: ADVANCE JAVA (MCA – 5) 1/47

Section – A 2 Marks Questions [QUESTIONS


1 TO 28] [PAGE 1 TO 3]
Q1. How a catch block is defined?
Ans. The following statement is used to define catch block in java.
catch (Exception Class object)
{
Body of catch block
}
Q2. What is a class?
Ans. Class is blue print or a template that can use to store properties of the object and accessible
with help of object methods store in the class.
Q3. What is a method?
Ans. Methods are used for message passing and provide functionality to handle class objects. The
properties of the object stored in the class can be modified with the help of methods. These
objects work on the specific contract and that contract tells the purpose of that method.
Q4. Is it necessary to catch all type of exception?
Ans. Yes, it is necessary to catch all type of exception to get accurate result from the program.
Although there is an exception that we can’t handle StackOverflow exception in our program.
Q5. Identify correctly constructed package declarations, import statements, and method
declarations.
Ans. Package packagename; is correct package declaration
import packagename.*; or import packagename.Classname ; is the correct import statement.
public /private methodname([argumentlist]) is correct declaration for methods.
Q6. What is the relationship between the Canvas class and the Graphics class?
Ans. Graphics and Canvas class are defined under the same package called AWT. Canvas class is
extended to create layout where we can draw something and Graphics class provides the
method to draw something on the canvas.
Q7. Differentiate between Component and Container?
Ans. Component is an abstract class that encapsulates all of the attributes of a visual component.
All user interface elements that are displayed on the screen and that interact with user.
Container classes provide container to the components where we can place different
Components. All the Containers like window, panel, Frame, all are the sub classes of
container class.
Q8. What are adapter classes?
Ans. Java provides a special feature called an adapter class that can simplify the creation of event
handlers. Adapter classes are useful when you want to receive only some of the events that
are handled by a particular event listener.
Q9. How can you display a message on the status bar of an applet window?
Ans. To display message on status bar of the applet window, the showStatus method of
Applet class is used. It has the following.
Syntax
Void showStatus() ;
Q10. What is the use of getDocumentBase() and getCodeBase() methods?
Ans. Java provides the facility to applet to load data from the directory holding the HTML file that
starts the applet and the directory from which the applet’s class file was loaded. These
directory are retruned as URL objects by the getDocumentBase() and getCodeBase()
methods.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 2/47

Q11. List all the event provided by awt. event package.


Ans. ActionEvent, ContainerEvent , FocusEvent , ComponentEvent
InputEvent, ItemEvent, KeyEvent, MouseEvent , TextEvent, WindowEvent.

Q12. What is the difference between Choice and List?


Ans.
Choice List
Choice creates a popup List from which List create a list having scrollbars and u
You can select only single item at a time Can select multiple items at a time.

Only shows u the selected item U can view all the item whether it is selected
or deselected.

Q13. Can you overload a constructor? If yes, how?


Ans. Yes, we can overload the constructors. To overload the constructor, we must have different
list of parameters in every constructor definition.
Q14. Explain the five rules for using across attributes.
Ans.
1. Public data is defined by public keyword so that it can be used by any package.
2. To defined private data private keyword is used so that data cannot be used outside the
class.
3. Default Access specification need not to be defined with any data type.
4. Define protected members so that these members of the class are accessible within the
subclasses of same and different packages.
Q15. How do you compile and run applet?
Ans. To compile an applet the java appletname command is used.
To run the applet applet viewer command is used.
Q16. Give two examples of event.
Ans. Events are the actions performed on the components. There are different types of
events in Java. Two of them are
1. Action Event
2. Item Event
ACTION EVENT-: Action Events is used to handled single click on button, menu
and double click on list.
ITEM EVENT-; Item event is used to handle event on choice,listbox,checkbox,radio
button etc.
Q17. What are exceptions in java?
Ans. All the exceptions are the classes caused by run time errors. All the exception classes extends
exception class and exception class extends the throwable class.
Q18. What is a HTML tag?
Ans. <HTML> tag is an element of html file that tells us the beginning of html code block and
ends with closing html tag </HTML>. It help us to put various components of the web page
and create a file known as HTML file.
Q19. Explain which components and containers are supported by the AWT.
Ans. Different types of containers and components are supported by AWT. Like Applet, Frame and
Panels comes under container category and Label, TextField, Buttons, Menus and many more
form designing components.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 3/47

Q20. Illustrate how components and containers are assembled into applets and applications.
Ans. Components are added to containers and then container can be added to the applet or
application.
E.g.
TextField t=new TextField();
Button b=new Button(“click me”);
Panel p=new Panel();
p.add(t);
p.add(b);
add(p)
Q21. Explain which classes and interfaces support layouts and event handling.
Ans. All LayoutManager classes provides the different layout to arrange component in the
container. These classes are FlowLayout, GridLayout, BorderLayout, CardLayout
Event handling is provided by different event classes to handle these events. Java also
provides interfaces and support event delegation model. These classes and interfaces are
Classes
ActionEvent, MouseEvent, AdjustmentEvent, KeyEvent , FocusEvent, ItemEvent etc.
Interfaces
ActionListener, MouseMotionListener, MouseListener, AdjustmentListener, KeyListener,
FocusListener, ItemListener etc.
Q22. Describe how layout managers simplify the process of organizing GUI components.
Ans. Layout managers provided by the java helps to organize the components on container.
Different types of Layout managers provide different types of layout to place the components.
User can choose according his requirement.
Q23. Why can’t my applet connect via sockets, or bind to a local port and what are socket
option, and why should I use them?
Ans. Applets are the small program executed on client machine by the server. But these are not
connected with the socket because applet is more secure program provided by java. Once it
launch from the server machine to client no transaction is possible from server to client. No
additional information we can send. So we cannot attach Socket to the applet.
Applets are used for secure, small animation or dynamic messages on the web page.
Q24. Define Panel.
Ans. The Panel class is a concrete sub class of container. It doesn’t add any new methods; It simply
implements Container. A Panel may be thought of as a recursively nestable, concrete screen
component. It is super class of Applet. It is a window that does not contain a title bar, menu
bar , or border.
Q25. What is Frame?
Ans. It is a sub class of Window and has a title bar, menu bar, and border and resizing corners.
When we create a Frame object within an Applet a warning message appears, commonly
Frames are used to implement Application programming using awt controls.
Q26. What are Dialog Boxes?
Ans. A Dialog box is used to hold a set of related controls. Dialog boxes are primarily used to
obtain user input. They are similar to frame window, except that dialog boxes are always
child windows of a top-level window.
Q27. What is File Dialog?
Ans. Java provides a built in dialog box that lets the user specify a file this is called FileDialog
box.. To create Filedialog box, instantiate an object of type FileDialog. This causes the File
dialog to be displayed.
Q28. How an Image can be loaded on the Applet window?

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 4/47

Ans. To load the Image on the Applet window the getImage method is defined by the applet class.
It has the following forms.
Image getImage(URL url);
Image getImage(URL url, String imageName)

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 5/47

Section – A 5 Marks Questions [QUESTIONS


1 TO 21] [PAGE 4 TO 14]

Q1. How does applets differ from application program? Why do applet class need to be
declared as public? Write the applet tag with arguments.
Ans.
Applet Application
1. Applet executes on web browser 1. Executes on Command prompt
2. No need of main function to 2. Every application program need to
execute. define main () function in the program
3. No command line argument is 3. We can pass command line arguments
passed. in an application
4. A fast and small program executed 4. Program those does not support web
on the internet. browsers

Applet class need to declare public because applets are launched by the applet tag and that tag
can be defined within the same program and in different .html files. It is declared public
because it can be called outside the package in which it is declared.
<applet code=abc.class height=200 width=200>
<param name=”name” value=”raj”>
<param name=”rollno” value=1>
<param name=”class” value=12>
</applet>
Q2. Write an applet that takes an integer and reverse that egg. 756 to 657.
Ans.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class app1 extends Applet implements ActionListener
{
/*<applet code=app1 height=200 width=200></applet> */
TextField t,t1;
Label l,r;
Button b;
public void init()
{
l=new Label("Enter no");
r=new Label("Result");
t=new TextField(10);
t1=new TextField(10);
b=new Button("click");
add(l);
add(t);
add(r);
add(t1);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent g)
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 6/47

{
String s=t.getText();
int i=Integer.parseInt(s);
int r1=0;
while(i>0)
{
r1=r1*10+i%10;
i/=10;
}
t1.setText(" "+r1);
}
}
Q3. Write a Java program to create a Fibonacci series.
Ans.
class feb
{
public static void main(String ap[])
{
int a=1,b=0,c=0;
while(c<=21)
{
System.out.println(c);
c=a+b;
a=b;
b=c;
}.
}
Q4. What do you mean by Layout Manager? What are the various types of Layout?
Ans. A layout refers to arranging and placing of the component in a container. A Layout manager
will determines how components will be arranged when they are added to a container.
Types of Layout
1. FlowLayout: - The default layout of the container. The FlowLayout class is the simplest of
layout manager. It layouts the components in similar way as Word place data in there pages.
It provides the following constructor
FlowLayout(), FlowLayout(FlowLayout.LEFT);
2. GridLayout: - The GridLayout manager arranges components into a grid of rows and
columns. Components are added first to the top row of the grid.
The following constructor are provided by GridLayout
GridLayout(),GridLayout(row,col), GridLayout(row,col,hrz,vert);
3. BorderLayout: - Divide the container into five different section these sections are .
SOUTH, EAST, WEST, NORTH, CENTER.
Provide two constructors
BorderLayout()
BorderLayout(int,int);
4. CardLayout: - In CardLayout the components are arranged in the card style and some of
the components can be hidden or viewed using this layout. In this layout other layout can be
mixed to manage different container components inside the main container.
Q5. Write an application/applet to implement the binary search technique.
Ans. class xyz
{
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 7/47

public static void main(String ap[])


{
int t=0, beg=0,end=7,mid=0,i,f=0,j,a[]={5,2,3,4,5,7,9,23},item;
end=a.length-1;
for(i=0;i<a.length;i++)
{
for(j=i+1;j<a.length;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
item=4;
mid=(beg+mid)/2;
while(beg<=end)
{
if(a[mid]==item)
{
f=1;
break;
}
else if(item>a[mid])
beg=mid+1;
else
end=mid-1;
}

if(f==1)
System.out.println(mid);
else
System.out.println("no match found");
}
}
Q6. Write an applet, which takes the input, and compute the factorial.
Ans.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class fact1 extends Applet implements ActionListener
{
/*<applet code=fact1 height=200 width=300></applet> */
Label l,l1;
TextField t,t1;
Button b;
public void init()
{
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 8/47

l=new Label("enter number for factorial");


l1=new Label("result");
t=new TextField(10);
t1=new TextField(10);
b=new Button("factorial");
add(l);
add(t);
add(l1);
add(t1);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s=t.getText();
int n=Integer.parseInt(s);
int f=1;
while(n>1)
{
f=f*n;
n--; }
t1.setText(""+f);
} }
Q7. What do you mean by AWT? What components and containers are used by AWT?
Ans. AWT stands for abstract widows toolkit. It is one of the package defined in java which
provides the graphical user interface defining different types of containers and components
implementing different types of listeners for event handling. In the AWT class hierarchy
component class is at the top of all classes , container comes after then window and panel
classes.
AWT used different types of containers and components.
Containers:
1.window 2.frame 3.panel
Components:
1.Label 2.TextField 3.Button 4.Choice 5.MenuItems 6.List 7.TextArea 8.scrollbar
Q8. What do you mean by java’s event delegation model?
Ans. The java.awt.event package defines a rich hierarchy of event types. Through this package,
instances of various event classes are constructed when users use GUI components. It is up to
the programmer to decide how to handle the event that is generated. When a user clicks on a
button, the system constructs an instance of the class ActionEvent, in which it stores detail
about the event. At that point the programmer has the three options:
1. Ignore the event
2. Have the event handle components
3. Delegate event handling to some other objects called listeners.
Java defines different types of Event classes in java.awt.event package to handle different
events. These events are as listed below
1.ActionEvent 2.ItemEvent 3.AdjustmentEvent 4.WindowEvent 5.MouseEvent 6.TextEvent.
7.FocusEvent 8.KeyEvents
To implement these events on the different controls java provides different types of listener in
the same package

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 9/47

1. ActionListener 2.ItemListener 3.AdjustmentListener 4.WindowListener


5.MouseMotionListener 6.MouseListener 7.KeyListener 8.FocusListener etc.
Q9. Write an application program to print 1 to 100 prime numbers.
Ans. class my
{ public static void main(String ap[])
{
int n,i,f=0;
for(n=1;n<=100;n++)
{ f=0;
for(i=2;i<n&&f==0;i++)
{
if(n%i==0)
f=1; }
if(f==0)
System.out.print(“ “+n);
} } }
Q10. Write a program to display current system time on the Left hand corner of the
GUI application.
Ans. import java.util.*;
import java.awt. *;
class My frame extends Frame
{
Date d;
String s = “ ”;
public Myframe()
{
d= new Date ();
st = d.getHours() + “:” + d.getMinutes() + “:” + d.getSeconds();
}
public void paint (Graphics g)
{
g.drawstring (“current time:” + s, 0,0);
}
}
class M
{
public state void main (String up [])
{
Myframe f = new Myframe ();
f.setSize (100,200);
f.setVisible (true);
}
}
Q11. Write a program to draw parallogram.
Ans.
import java.awt. *;
import java.applet. *;
class pr extends Applet
{
public void init()
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 10/47

{
int x[] = {10,100,150,50};
int y[] = {10,10,100,100};
g.drawPolygon (x,y,z);
}
}
Q12. What is Event Handling?
Ans. Almost all programs must respond to commands from the user in order to be useful. Java's
AWT uses event driven programming to achieve processing of user actions: once that
underlies all modern window systems programming. Within the AWT, all user actions belong
to an abstract set of things called events. An event describes, in sufficient detail, a particular
user action. Rather than the program actively collecting user-generated events, the Java run
time notifies the program when an event occurs. Programs that handles user interaction in this
fashion are said to be event driven.
There are three parts to the event model in Java:
Event object - this is an instance of a Java class that contains the characteristics of the event.
For example, if the event is generated from clicking a mouse button, the event object would
contain information such as the coordinates of the mouse cursor, which button was clicked,
how many times it was clicked, etc.

Dispatching class/method - this is an object, which detects that an event has occurred and is
then responsible for notifying other objects of the event, passing the appropriate event object
to those objects. These other objects are "listeners" for the event. Most AWT components,
such as Button, List, TextField, etc. are examples of dispatching classes.
A Button, for instance, is capable of notifying other components when it is "pushed." These
classes will typically have a set of two methods that can be invoked by would-be "listeners":
one to tell the class that the object wants to listen and another to tell the class that the object
no longer wants to listen.
These methods are conventionally named i.e. addxxListener (to add an object as a listener) or
removexxListener (to remove the object as a listener). Here ‘xx’ is the specific type of event
to listen for. In the case of the Button, this would be "Action" to indicate the action of pushing
the button. (So the methods would be addActionListener and removeActionListener).
Listener Interface - for the dispatching to work properly, the dispatching class must be able
to rely on each of its listeners to contain the method that it executes when the event occurs.
This is easily accomplished in Java through the use of an Interface class. The important point
is that a class, which is going to be a listener, must implement that interface.
Q13. What advantages do java’s Layout Managers provides over traditional windowing
system?
Ans. Layout Mangers in java provides us the way to arrange components in windows programming
or applet programming. There are different types of layout Manager provided by java using
java.awt package.
1. Flow Layout
2. BorderLayout.
3. GridLayout.
4. Cardlayout.
Layout Manager helps us to place the components on the container, as we want to place.
Every layout provides different types of style, to place the components and make easy to
arrange component on traditional windowing system.
• Flow layout is the default layout Manager for java window application.
• Using layout managers we can align components to left and right.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 11/47

• Using Layout Manager we can place different component in different position like center,
left, top, right and bottom. For this we can use, BorderLayout.
• Required components can be hidden using CardLayout.
• Components can be arranged in tabular form using GridLayout.
Q14. Describe how layout managers simplify the process of organizing GUI components.
Ans. A layout refers to arranging and placing of the components in a container, much like
arranging the furniture in a house. To design a user interface, a programmer has to specify
row, column, position of all the objects used in the interface. Based on this input the
programming environment will create the user interface and display it on screen.
A Layout Manager determines how components will be arranged when they are added to a
container. Different types of LayoutManager provide different type of Layout setting. These
are of followings.
1. FlowLayout: - FlowLayout Manager, which is the default Layout for applet window, place
the components on the window as they are added on the window. We specify the alignment of
these components as left, right or center.
2. GridLayout: - GridLayout Manager divide the whole area of the window into rows and
columns to display the components in matrix form with specified space distance the
components.
3. BorderLayout: - Divide the whole window into different border like North, East, South ,
West and Center. The specified is displayed on the specified area.
4. CardLayout: - To view the specified component on the top of the other components.
Q15. Explain how listeners and adapters are used to implement the event-delegation model.
Ans. Listener: -A Listener object can listen object and passing the event object to the method as an
argument. A Listener object can listen for events for a particular object. Just a single button
for instance, Or it can listen for several different objects. This mechanism for handling events
using listeners is very flexible, and very efficient, particularly for GUI events. Any number
of listeners can receive a particular event. However, a particular event is only passed to the
listener that have registered to receive it, so interested parties are involved in responding to
each event. This is the way in which events are handled in java, using listener objects and it
provides event delegation model.
Adapter classes: - Java provides a special feature called an adapter class that can simplify the
creation of event handlers in certain situations. An adapter class provides an empty
implementation of all methods in an event listener interface. Adapter classes are useful when
you want to receive and process only some of the events that are handled by a particular event
listener interface. You can define a new class to act as an event listener by extending one of
the adapter classes and implementing only those events in which you are interested. Which
helps you implements partial listener interface in this way adapter classes provides event
delegation model to delegate the listener object.
Q16. Illustrate how components and containers are assembled into applets and applications.
Ans. Panel class, which is the sub class of container, a window that does not contain a title bar,
menu bar, or border. Can contain different components those are assembled on applet
window.
Following example will show you how component and container are assembled on the applet
window.
In this example there are two text fields and button placed on the panel and panel is added on
applet window.
import java.awt.*;
import java.applet.*;
public class myapp extends Applet

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 12/47

{
TextField t,t1;
Button b;
public void init()
{
t=new TextField(10);
t1=new TextField(10);
b=new Button(“ok”);
Panel p=new Panel();
p.add(t);
p.add(t1);
p.add(b);
add(p);
}
}

Q17. Describe how a client applet or application read a file from a server through a URL
connection?
Ans. In java we can create application for web page and application for single Machine. The
application for Web page is created with the help of applet and application using the Java.awt
Frame.
In java we can create two types of applets.
1. Local
2. Remote

Local applet means: - Clients and server program both are on the same machine.

Remote applet means: - Applet is available on the different machine (on the server) and
client requests for that applet from different machine. These diagrams show the local and
Remote applets.

Local Computer

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 13/47

Loading Remote Applet

Internet
Client

Client Remote applet Server


To access the remote applet we have to specify the URL address in CODEBASE attribute of
the applet tag on the client machine.
E.g.
<applet code = Applet class Codebase= http://www.netserver.com/applet>
Q18. Define life cycle of an applet.
Ans. The life cycle of an applet consists of initialization, starting, stopping, destroying, painting
etc.
1. Initialization: - initialization occurs when the applet is first loaded . The initialization of
an applet might include reading and parsing any parameters of the applet, creating any helper
objects it needs, setting up an initial state, or loading images or fonts. To control the behavior
of the applet, override the init() method in the applet class.
public void init() { }
2. Starting
After an applet is initialized it starts. Starting is different from initialization because it can
happen many times during an applet’s lifetime, whereas initialization happens only once.
Starting an applet also occur if the applet was previously stopped.
Public void start(){}
3. Stopping
Stopping and starting go hand by hand, stopping occurs when the reader leaves the page that
contains a currently running objects, or by calling the stop() method. By default when the
reader leaves a page, any threads the applet had started will continue running by overriding
the stop(). One can suspend the execution of these threads and then restart them if the applet
is viewed again.
public void stop(){ }
4. Destroying
Destroying enables the applet perform a clean up job just before it is destroyed or the browser
exits. This object is to destroy an applet from the memory.
5. Painting
Painting is the way an applet actually draws something on the screen, any drawing object or
text can be placed on the screen using draw object painting may occur number of times during
an applets life cycle. It can be called again and again by using repaint().
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 14/47

Q19. What is advantage of the event delegation model over the earlier event inheritance
model?
Ans. Event delegation is the process to delegate any event to the function means:- events are
handled using different function defined in a listener.
There are numbers of benefits of event delegations model.
1. Different events are categories in different listener Interfaces.
2. By delegating the events to the listener interfaces now we can use these events to
window programming classes. Without delegation it is very difficult to extend
multiple classes.
3. By delegating events any member of listener can receive that event.
4. But any event is only passed to the listener that has registered to receive it.
5. We can also restrict the programmers to use all type of methods in a listener.
Q20. Design a java applet that tries to delete a file on the local file system. This program
demonstrates that when the applet tries to delete a file on the local system, it throws on
security exception.
Ans. import java. Applet.*;
import java.awt.*;
import java. awt.event. *;
public class Delfile extends Applet implements Action Listener
{
TextField t;
Button b;
File d; Label l;
public void init ()
{
l= new label (“file deleted”);
t = new TextField (ion);
b= new Button (“Delete”);
add (t);
add (b);
add(i);
b.addActionListener (this);
}

public void action performed (Action Event e)


{
f = new File (t.getText());
try
{
Boolean bi;
B1 = f.delete ();
l.getText (l.getText() + b1);
}
catch (Exception e)
{
System.out.printIn (“unable to delete”);
}
}
Q21. How an applet is developed with threads? Explain with example.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 15/47

Ans. Threads are used with applets to develop any animated applet. The following applet will
display the scrolling banner this applet scrolls a message from right to left.
import java.awt.*;
import java.applet.*;
/*<applet code=”SimpleBanner” width=300 height=50>
</applet>*/

public class SimpleBanner extends Applets implements Runnable


{
String msg=” A Simple Moving Banner”;
Thread t=null;
int state;
boolean stopflag;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
}
public void start()
{
t=new Thread(this);
stopflag=false;
t.start();
}

public void run()


{
char ch;
for( ; ; )
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
if(stopflag)
break ;
}
catch(InterruptedException e){}
}
}
public void stop()
{
Stopflag=true;
t=null;
}
public void paint(Graphics g)

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 16/47

{
g.drawString(msg,50,50);
}
}

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 17/47

Section – B 2 Marks Questions [QUESTIONS


1 TO 35] [PAGE 15 TO 18]

(Java I/O Handling, MultiThreading, Socket Programming)


Q1. Define socket?
Ans. Sockets are used to connect the system in the network. These sockets are not similar to the
electrical sockets. Various plugs around the network have a standard way of delivering their
payload. Anything that understands the standard protocol can ‘plug in’ to the socket and
communicate.
Q2. Define client/server architecture?
Ans. The term client/server mentioned in the context of networking. A server is anything that has
some resource that can be shared by client.
A client is simply any other entity that wants to gain access from a particular server.
Q3. What are reserve Sockets?
Ans. Reserve sockets are the sockets those are reserved for specific type of transaction for example
port number 21 is for FTP, 23 is for Telnet, 25 for email, 79 is for finger, 80 is for HTTP, 119
is for Netnews etc. There are 1024 sockets are reserved.
Q4. What do mean by proxy server?
Ans. A proxy server act as the client side of a protocol to another server. This is often required
when clients have certain restrictions on which servers they can connect to .A proxy server
has the additional ability to filter certain request or cache the results of those request.
Q5. What is the cause of a NoRouteToHost exception?
Ans. NoRouteToHost exception appear when client socket is unable to create link with the server
socket. There is another exception raised known as, UnKnownHostException.
Q6. Define PrintWriter class.
Ans. PrintWriter class provided by java.io package which is the sub class of Writer class use to
handle character stream can also used with servlet to create response for clients. The object of
the PrinterWriter class is initialized with the constructor of PrintWriter or getWriter() method
of request object.
Q7. Define TCP/IP socket.
Ans. TCP/IP socket are used to implements reliable, bi-directional, persistent, point to point,
stream-based connection between host on the internet. It can be used to connect Java’s I/O
system to other programs that may reside either on the local machine or any other machine on
the Internet.
Q8. Why an UnknownHostException is generated?
Ans. An UnknowHostException is generated when two client machines are connected with server
using socket and the socket does not locate server machine address or wrong server address is
described in the client program.
Q9. Name the package provides all the classes and interface to interact with sockets.
Ans. The package that provide all the classes and interfaces to interact with sockets and
transact data from one machine to another using socket is java. net.
Q10. Why the ServerSocket is defined? How it is differ from normal socket?
Ans. ServerSocket is created using ServerSocket class to describe a server that can listen either
local or remote client program to connect to them on published ports. It is quite different from
the normal socket because it registers itself with the system as having an interest in the client
connection.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 18/47

Q11. What is difference between TCP/IP and UDP protocol?


Ans. TCP/IP is higher-level protocol that manages to robustly string together then sorting and
retransmitting them as necessary to reliably transmit your data. But User Datagram Protocol
is connectionless fast, unreliable transport of packets.
Q12. What is Secure Socket Layer(SSL)?
Ans. Secure Socket Layer is the layer which implements reliable, bi-directional, persistent, point to
point, stream based connections between hosts. TCP/IP protocol is one of the protocol that
use secure socket layer.
Q13. What is Datagram in Socket programming?
Ans. Datagrams are the packet of information send by the server to the client using UDP
(Unreliable datagram protocol). UDP protocol is not responsible for information send by the
server to client , whether is received by client on not.
Q14. Define URLConnection class.
Ans. URLConnection is a general- purpose class for accessing the attributes of a remote resource.
Once you make a connection to a remote server , you can use URLConnection to inspect the
properties of the remote object before actually transporting it locally. These attributes are
exposed by the HTTP protocol specification.
Q15. How proxy server is helpful to speed up process from client side?
Ans. A proxy server speaks the client side of a protocol to another server. This is often required
when clients have certain restrictions on which servers they can connect to a proxy server has
the additional ability to filter certain request or cache the results of those request.
Q16. Define DNS.
Ans. DNS stands for Domain Naming Service . in network four number in IP address describe a
network hierarchy from left to right , the name provided to that IP address is called Domain
Name. The process to the Domain Name to the IP address is called Domain Naming Services.
Q17. Name the package used to transact data using sockets.
Ans. The package that provide all the classes and interfaces to interact with sockets
and transact data from one machine to another using socket is java. net.
Q18. Why the ServerSocket is define and how it is differ from normal socket?
Ans. ServerSocket is created using ServerSocket class to describe a server that can listen either
local or remote client programs to connect to them on published ports. It is quite different
from the normal socket because it registers itself with the system as having an interest in the
client connection.
Q19. When will you use buffered I/O streams?
Ans. Java programs perform I/O through streams. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the java I/O system. All
streams behave in the same manner, even if the actual physical devices to which they are
linked differ. The same I/O classes and methods can be applied to any type of device. An
input stream can abstract many different kinds of input: from a disk file, a keyboard, or a
network socket. An output stream may refer to the console, a disk file or a network
connection.
Q20. What is the purpose of HTTP tunneling?
Ans. Purpose of HTTP tunneling is to expose the attributes defined under the URL so that the
remote objects are recognized on the remote machines.
Q21. How do we start a thread?
Ans. To start a thread in java there is method start() provided by the java Thread class is used. If
thread is temporarily stop using suspend() can resume again using resume() method or
notify() method.
Q22. What is the use of sleep() in thread programming?

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 19/47

Ans. sleep() is the static method provided by java Thread class. Used to temporarily suspend a
thread for specified period of time after that the thread will resume again.
Q23. Define Serialization.
Ans. Serialization is the process of writing the state of object to a byte stream. This is useful when
you want to save the state of your program to a persistent storage area, such as file. At a later
time, you may restore these objects by using the process of deserialization.

Q24. Define BufferedWriter class.


Ans. A BufferedWriter is a Writer that adds a flush() method that can be used to ensure that data
buffers are physically written to the actual output stream. Using a BufferedWriter can
increase performance by reducing the number of times data is actually physically written to
the output stream.
Q25. What is FileWriter?
Ans. FileWriter creates a Writer that you can use to write a file. Its most commonly used
constructors
FileWriter(String filepath)
FileWriter(String filepath, Boolean append)
FileWriter(File obj)
Q26. Define FileReader.
Ans. The FileReader class creates a Reader that you can use to read the contents of a file. Its two
most commonly used constructors are
FileReader(String filepath)
FileReader(File fobj)
Q27. How data can read or write randomly in the file?
Ans. RandomAccessFile object is used to read or write data randomly in the file. It implements the
interface DataInput and DataOutput , which define the basic I/O methods. It also supports
positioning requests.
RandomAccessFile has the following constructors
RandomAccessFile(File fileobj, String access) throw IOException
RandomAccessFile(File filename, String access) throw IOException
Q28. Define PrintStream class?
Ans. PrintStream class provides all of the formatting capabilities we have been using from the
System file handle, PrintStream class has two constructors
PrintStream(OutputStream outputstream)
PrintStream(OutputStream outputstream, boolean flushonnewline)
Q29. Why the SequenceInputStream is useful?
Ans. The SequenceInputStream class allows you to concatenate multiple InputStreams. The
construction of SequenceInputStream is different from any other InputStream. A
SequenceInputStream constructor uses either a pair of InputStreams or an Enumeration of
InputStream as it arguments.
Q30. What is BufferedInputStream?
Ans. Buffereing I/O is a very common performance optimization . Java ‘s BufferedInputStream
class allows you to “wrap” any InputStream into a buffered stream and achieve this
performance improvement.
BufferedInputStream has two constructors
BufferedInputStream(InputStream inputstream)
BufferedInputStream(InputStream inputstream, int bufsize)
Q31. What do you mean by Thread Priority?
Ans. Thread Priorities are used by the thread scheduler to decide when each thread should be
allowed to run. The higher priority that get more CPU time than lower- priority threads. The
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 20/47

amount of CPU time that a thread gets often depends on several factors. To set the thread
priority the setPriority() method is used. Three types of levels we can specify as a parameter
in this methods. These levels are 1 MIN_PRIORITY 2. MAX_PRIORITY 3.
NORM_PRIORITY.
Q32. What is use of IsAlive() and join() methods in thread?
Ans. The isAlive() method returns true if the thread upon which it is called is still running
otherwise it return false.
Join() method waits until the thread on which it is called terminates. Its name comes from the
concept of the calling thread waiting until the specified thread joins it.
Q33. What is main thread?
Ans. When a java program starts up ,one thread begins running immediately . this is usually called
the main thread of your program , because it is the one that is executed when your program
begins. It is important for two reasons.
1. It is the thread from which other child threads will be spawned
2. It must be the last thread to finish execution. When the main thread stops, your program
terminates.
Q34. What is thread based multi tasking?
Ans. A Thread based multitasking is the process in which the thread is smallest unit of dispatch
able code. This means that a single program can perform two or more tasks simultaneously.
Using the single process space.
Q35. What is an Exception?
Ans. An exception is an abnormal condition that arises in a code sequence at run time. An
exception is a run-time error. To execute the program successfully in computer languages
these exception must be handled.
Q36. Define Swing?
Ans. Swing is a part of java foundation classes library. It is an extension of the Awt
that has been integrated in Java2. It offers much improved functionality over
awt, like tables, traview, better graphics. Event handling dialog box and drag
and drop support.
Q37. Define JFC?
Ans. JFC stands for java foundation classes. These are introduced by the joint
efforts between Sun Microsystems and Netscape to provide better graphics
supports and expanded component features. Java swing is one of the parts of JFC
contain number of other strings than swing.
1. Cut and paste –clipboard support
2. The desktop color features.
3. java 2d-Improved color, image and text support.
Q38. Define height weight component in swing?
Ans. The component those are not dependable on any native system classes are called
lightweight components. In swings the most of the component have their own view
supported by java look and feels classes.
Q39. Differentiate between Swing and AWT?
Ans. There are number of differences between Swing and AWT:
1. Swing components are absolutely implemented with no native code whereas
AWT components may use native code.
2. Swing button and labels can display images but not the AWT components.
3. Swing button can be round or rectangular but AWT button are only rectangular
buttons.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 21/47

Q40. Write down the name of the different swing packages?


Ans. There are number of swing packages and all provide different functionality:
1. javax.swing 2. javax.swing.border 3. javax.swing.event 4. javax.swing.table
5. javax.swing.text etc.
Q41. What do you mean by content pane?
Ans. The content pane was introduced in swing to deal with the complexities, which are
involved, in making lightweight and heavyweight components work together. The
content pane basically manage the interior of a swing frame, which means that the
components need to added to the frame’s content pane, rather than adding directly
to applet or frame itself.

Q42. What is Glass pane?


Ans. The glass pane is the member of the root pane that is used to draw over an area that
already contains some components. A glass pane also be used to catch mouse events
because it sits over the top of the content pane and menu bar.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 22/47

Q43. Define caret listener.


Ans. Caret listener is used to handle caret events. Caret events occur when the caret in a
text component move or when the selection in a text component changes. A caret fires change
event, rather than caret event.
Q44. Define dialogs in swing.
Ans. A dialog is a window that is displayed within the context of another window.
Dialogs are used to manage to input that can’t be handled conveniently, selecting
from a range of options for instance, for enabling data to be entered from the
keyboard. There are two types of dialogs:
1. Modal. 2. Non Model
Q45. Define joption pane in swing.
Ans. Joption pane is the direct subclass of J-component and is stored in package
javax.swing provide different types of methods for designing standard model
dialogs: 1. Confirm Dialog. 2. Input dialog. 3. Message Dialog. 4. Option Dialog.
Q46. What are sliders in swings?
Ans. Sliders are similar to the scrollbar. In swing it is implemented using j-slider class
that enables a number to be set by sliding a control within the range of a minimum
and maximum values. It is often seen in media player to adjust the volume.
Q47. Define progress bar.
Ans. Progress bar are components used when long tasks are performed to show the user
how much time is left before the task is complete.
Progress bar provides three types of constructors:
1. JProgressBar()
2. JProgressBar(int,int)
3. JProgressBar(int,int,int)
Q48. Define jtable class hierarchy.
Ans. A table can display data in rows and columns format in a user interface. A table can
also optionally allow editing swing table represented by that class jtable that extends
the class jcomponent, and jcomponent extends java.awt.container and container
class extends component class extends java.lang.object.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 23/47

Section – B 5 Marks Questions [QUESTIONS 1 TO 24]


[PAGE 19 TO 29]

(Java I/O Handling, Multi Threading, Socket Programming)


Q1. What are the differences between Thread class and Runnable interface ? Give example
also.
Ans. Thread: - In java multithreading programming can be created by extending the Thread class
and creating the object of that class. The extending class must override the run() method
which is the entry point for the new thread. It must also call start() to begin execution of the
new thread.
Runnable: - implementing Runnable interface is the another method to create a
multithreaded program .Runnable abstracts a unit of executable code. To implement
Runnable, a class need only implement a single method called run().
The Thread class defines several methods that can be overridden by a derived class. Of these
methods, the only one that must be overridden is run(). The same method required when
Runnable interface has to be implemented.
Thread class should be extended only when they are being enhanced or modified in some
way. If any of the Threads and other methods are not overridden then Runnable interface is
best.
Example of interface
class mythread implements Runnable
{
Thread t;
mythread()
{
t=new Thread(this, ”Demo thread”);
System.out.println(“child thread”+t);
t.start();
}
public void run()
{
try{
for(int I=5;I>0;I--)
{
System.out.println(“chaild thread :”+I);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(“child interrupted.”);
}
System.out.println(“exiting child thread”);
}
}
class yourthread
{
public static void main(String ap[])
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 24/47

{
new mythread();
try
{
for(int I=5;I>0;I--)
{
System.out.println(“main tthread “+I);
Thread.sleep(1000);
}
}catch(Exception e){}
}
}
Thread class
class mythread extends Thread
{
mythread()
{
super(“demo thread”);
System.out.println(“child thread”+this);
start();
}
public void run()
{
try{for(int I>5;I>0;I--)
{
System.out.println(“child thread”+I);
Thread.sleep(1000);
}
catch(Exception e){}
}
}}
class you
{
public static void main(String ap[])
{new mythread();
try{
for(int I=5;I>0;I--)
{
System.out.prntln(“main Thread”+I);
Thread.sleep(1000);
}
}
catch(Exception e){}
}}
Q2. Distinguish between preemptive and non-preemptive scheduling. Which does Java use?
Ans. Preemptive Scheduling: - In preemptive scheduling of threads a higher priority thread will
run when it wants to be run by suspending the running thread. This feature is also called
preemptive multitasking.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 25/47

Non-preemptive Scheduling: - In non-preemptive scheduling of threads, a running thread


will finish their job and then after a next thread can start running.
Java support preemptive Scheduling. A higher priority thread gets more CPU timing so that it
can interrupt the running thread. But java also provides Synchronization to reduce the
asynchronous behavior of the program by implementing the monitor. This is the process in
which when a thread enters to the monitor all other threads must wait until that thread exits
the monitor.
Q3. What do you mean by scheduling? How thread scheduling takes place?
Ans. Scheduling is the process to specify which thread will work at what time and how much CPU
timing is given to each thread. In operating system there are two types of multitasking:
Pre-emptive
non-preemptive.
In preemptive multi-tasking a thread can be suspended by the higher priority thread. And can
be resumed again after the thread’s job completion.
Non-preemptive multitasking a thread have to wait until the first thread complete its job.
Thread scheduling take place with the help of method define under the thread class name
sleep() that will suspend the current thread and schedule the higher priority thread.
Q4. What is a stream class? How are the stream classes classified?
Ans. A stream in Java is a path along which data flows. It has a source and destination. Both the
source and the destination may be physical devices or programs or other steams in the same
program.
In java stream classes are categorized into two groups based on the data type on which they
operate.
1 ByteStream classes
2. Character Stream classes
Byte Stream classes have been designed to provide functional feature for creating and
manipulating streams and files for reading writing bytes. These streams are uni-directional;
they can transmit bytes in only one direction. There are two kinds of byte stream classes:
Input stream classes an Output stream classes.
Character Stream classes were not a part of the language when it was released. They were
added later when the version 1.1 was announced. Character streams can be used to read and
write 16 bit Unicode characters. There are two kinds of character stream classes, namely,
Reader stream classes and Writer stream classes.
Q5. Write statements to create data streams for writing primitive data to a file.
Ans. import java.io.*;
class my
{
public static void main(String ap[]) throws IOException
{
File prim=new File(“prim.dat”);
FileOutputStream fos=new FileOutputStream(prim);
DataOutputStream d=new DataOutputStream(fos);
d.writeInt(120);
d.,writeDouble(34.56);
d.writeBoolean(false);
d.writeChar(‘x’);
d.close();
fos.close();
}
}
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 26/47

Q6. How I/O is accomplished using input stream OutputStream, Reader and Writer classes?
Ans. InputStream is an abstract class that defines java’s model of steaming byte input. all of
methods in this class will throw an IOException or error conditions. It provides different
methods to handle input
Int available(), void close(), void mark(int numBytes), Boolean markSupported(), int read(),
void reset()
OutputStream: - OutputStream is an abstract class that defines streaming byte output. All of
the methods in the class return void value and throw IOException in the case of error.
Methods of OutputStream.
void close(),void flush(),void write(int b).
Reader: - Reader is an abstract class that defines java ‘s model of streaming character input.
All of the methods in this class will throw an IOException on error condition.
abstract void close(),void mark(int numchars), boolean markSupported()
int read(),void reset()
Writer: - Writer is an abstract class that defines streaming character output. All of the
methods in the class return a void value and throw an IOException in the case of errors.
Q7. Define Thread Priority and Synchronization in java.
Ans. Thread Priority: -Java assigns to each thread a priority that determines how that thread
should be treated with respect to the others. Thread priorities are integers that specify the
relative priority of one thread to another. A higher priority thread doesn’t run any faster than a
lower –priority thread .it is used to decide when to switch from one thread to the next. This
process is called context switching.
Synchronization: - Multithreading programming introduces asynchronous behavior means a
thread can be interrupted by the another thread at any time, but some time It will create some
problems e.g. you must prevent one thread from writing data while another thread is in the
middle of reading it. In this situation there is a need of synchronization, which is provided by
monitor. The monitor is the small box can store single thread at a time when a thread enters in
the monitor no other thread can interrupt it until it exits from the monitor. But java has no
monitor class instead each object has its own implicit monitor that is automatically entered
when one of the object’s synchronized methods called once thread is inside a synchronized
method no other thread can call any other synchronized method code.
Q8. Explain Dead Lock in java.
Ans. A special type of error that you need to avoid that relates specifically to multitasking is
deadlock it occurs when two thread have a circular dependency on a pair of synchronized
objects. E.g suppose one thread enter the monitor on object x and another thread enter the
monitor on object y. if x tries to call any other synchronized method on y, it will block as
expected ,the thread wait for ever, because to access X, it would have to release its own lock
on Y so that the first thread could complete. It is difficult to debug for two reasons.
1. It occurs only rarely, when two threads time-slice in just the right way.
2. It may involve more than two threads and two synchronized objects.
Q9. How can you to write data in text files in java?
Ans. To read /write data into the files java provides two classes FileInputStream and
FileOutputStream. In java files are byte oriented and java provides methods to read and write
bytes from and to a file. Java allows you to wrap a byte-oriented file stream within a
character-based object.
FileOutputStream :- which create byte streams linked to files. To open a file you simply
create an object of one of these classes, specifying the name of the file as an agrument to the
constructor.both classes support additonal ,overriden constructors and throws
FileNotFoundException when an output file is opened any pre existing file by the same name
is destroyed. To close the a file call close() method.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 27/47

FileInputSteam: - to read data from the file you can use read() method which defined under
a version of read() that is defined within FileInputStream
These methods also generate FileNotFoundException.
To read and write data of specific type in the file there is a need of two more classes
DataOutputStream and DataInputStream ,they create Stream objects to write and read data in
specific type . DataOutputStream provides method for writing like writeInt(),
WriteFloat(),writeDouble etc.
DataInputStream class provides method to read data from the file like
readInt(),readFloat(),readDouble() etc.
Q10. Describe the major features of Java exception handling. How is exception handling
carried out in java? What are the major statements that are employed in java
exeception handling and what do they do?
Ans. An exception is a condition that is caused by a run-time error in the program. When the Java
interpreter encounters an error such as dividing an integer by zero, it creates an exception
object and throws it. The purpose of exception handling mechanism is to provide a means:- to
detect and report an “exceptional circumstance” so that appropriate action can be taken.
Features
1. Structured exception handling
2. Provide security from executing illegal instruction those prone to termination of the
program.
3. Use the concept of object oriented approach to handle exceptions
4. User defined exception can also be handled.
Following are the major statements to handle exceptions
1. Try: - Program statements that you want to monitor for exceptions are contained within a
try block.
2. Catch: - If any exception occurs within the try block, it is thrown. These exceptions are
caught in catch block.
3. Finally: - Finally is the last block that will always execute although exception is raised on
not.
4. Throw: - Use to throw exception manually.
5. Throws: - To explicitly throws the exception.
Q11. What is use of Buffered Reader class? Explain with Example.
Ans. BufferedReader class is one of the class define under the java.io package.
Because System not define any method to take input from the keyboard. Buffered Reader
class provide to read and readLine method read data from the keyword also generate
exception called IOException. read() is used to read a character from keyboard and readLine()
method is used to read a line of character from the keyboard. It can be explain by the
following example.
class my
{
public static void main(Strring ap[]) thrws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b,c;
System.out.print(“Enter 1st no”);
a=Integer.parseInt(br.readLine());
System.out.print(“enter 2nd no”);
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println(“sum is “+c);
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 28/47

}
}
in this class file br is BufferedReader object which access the readLine() method to get the
value from keyboard.
Q12. Write a short note of Collection Framework.
Ans. The Java collection framework standardizes the way in which groups of objects are handled
by your programs. Java provides ad hoc classes like Dictionary, Vector, Stack and Properties
to store and manipulate groups of objects.. It was designed to meet several goals. First, the
framework had to be high-performance. Another item created by the collections framework is
the Iterator interface. An Iterator gives you a general-purpose, standardized way of accessing
the elements within a collection one at a time. An iterator provides a means:- of enumerating
the contents of a collection .Because each collection implements Iterator, the elements of any
collection class can be accessed through the methods defined by Iterator.
The framework defines several map interfaces and classes. Maps store key/value pairs
although maps are not “collection” they are fully integrated with the collection view of map.
Q13. In the Java I/O libraries, what is the role of the Reader and Writer classes? What is the
difference between the Reader and Writer classes and the Stream classes?
Ans. In java I/O libraries, the Reader and Writer classes are used to handle character stream.
Character stream are not the part of the java when it was released in 1995. They were added
later when the version1.1 was announced. These classes defined separately as
1. Reader Stream Classes: - Reader stream classes are designed to read character from the
files. Reader class is the base class for all other classes. These classes are functionally
very similar to the input stream classes, except input streams use bytes as their
fundamental unit of information, while reader streams use characters.
2. Writer Stream classes: - The writer stream classes are designed to perform all output
operations on files. Only difference is that while output stream classes are designed to
write bytes, the writer stream classes are designed to write characters.
Q14. What are the basic steps that are required to write data out to the stream? What are the
basic steps that are required to read data from a stream? In your answer, provide
pseudo code or java code.
Ans. The following the java code is used to write data into the file.
1. Create the object of FileOutputStream class e.g.
FileOutputStream f=new FileOutputStream(“c:\myfile.txt”);
2. Create the object of DataOutputStream class to store primitive data and link it with file
using following code.
DataOutputStream d=new DataOutputstream(f);
3. Write different type of data using DataoutputStream object.
d.writeInt(10)’;
d.writeUTF(“Aman”);
d.writeDouble(23.45);
4. Close the DataOutputstream object and file object
d.close();
f.close();
The following steps are used to read data from file.
Create object of FileInputStream to read data from file e.g
FileInputStream f=new FileInputStream(“c:\myfile.txt”);
Create object of DataInputStream to read data of different types e.g.
DataInputStream d=new DataInputStream(f);
Read data and store these into the different variables. e.g.
String n; int c; Double s;
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 29/47

while(d.available()>0)
{ n=d.readUTF();
c=d.readInt();
s=d.readDouble();
System.out.println(“Name “+n);
System.out.println(“code “+c);
System.out.println(“salary “+s); }
Close the DatInputStream object and file object e.g
d.close(); f.close();
Q15. Write statement to create a file stream that concatenates two existing files.
Ans. import java.io.*;
class my
{
public static void main(String ap[]) throws IOException
{
FileInputStream file1=null;
FileInputStream fiel2=null;
SequenceInputStream file3=null;
File1=new FileInputStream(“Text1.dat”);
File2=new FileInputStream(“Text2.dat’);
File3=new SequenceInputStream(file1,file2);
BufferedInputStream inBuffer=new BufferedInputStream(file3);
BufferedOutputStream outBuffer=new BufferedOutputStream(System.out);
int ch;
while((ch=inBuffer.read())!=-1)
{
outBuffer.write((char)ch);
}
inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
}
}
Q16. Write a program to count the number of characters in a file.
Ans.
import java.io.*;
class my
{
public static void main(String ap[]) throws IOException
{
int c=0,i;
FileInputStream f=new FileInputStream("first.txt");
do
{
i=f.read();
c++;
}while(i!=-1);
System.out.println("No of character in the file is " + c);
}
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 30/47

}
Q17. What are the basic user interface components? Explain with example.
Ans. User Interface components help the user to interact with application. Java provides different
types of user interfaces. Some of the basic user interface components in the AWT are
followings.
Label: - A Label can be defined as static text string that act as a description for other AWT
components.
e.g
Label l=new Label(“welcome”,Label.CENTER);
add(l);
The specified creates a Label l displaying static text welcome and place it on the container
2. Buttons: - the component most commonly used in windows that trigger some action in the
interface when they are pressed. Button can be created using the following code in java.
Button b=new Button(“click me”);
add(b);
3. CheckBoxes: - These components have two states : on and off (selected and unselected).
They don’t trigger direct actions in the UI , but are used to indicate optional feature of some
other actions. They can be used in two ways.
Non exclusive :- Given the series of checkboxes , any of them can be selected.
Exclusive :- Given a series of check boxes, only one check box from the series can selected at
a time.
4. Radio Buttons: - A Radio button is hollow round. These are also created from the
checkbox class . In the case of Radio Button only one in a series can be selected at a time.
5. TextField: - provide an area where one can enter the text of single at runtime. Generally
used to get text from the user.
6. Choice menu or Choice list: - the popup list of items from which one can select an item.
Can be created using following code.
Choice ch=new Choice();
ch.add(“apples”);
ch.add(“mangos”);
add(ch);
7. TextArea: - TextArea are editable text fields that can handle more than one line of text
input. TextAreas are created from the TextArea class.
8. Scrolling List: - similar to the Choice List with two significant differences.
More than one item can be selected
Multiple items are displayed.
Created using the following codes.
List l=new List(3);
l.add(“ornage”);
l.add(“Mango”);
l.add(“Vanila”);
add(l);
Q18. Describe the class and interface hierarchy supported by the Collections API.
Ans. There are different types of classes and interfaces provides by java for Collection framework.
Collection Framework was designed to meets several goals . Like to achieve high
performance, high degree of interoperability.
The collection framework defines several interfaces these are of followings.
1. Collection :- Enables you to work with groups of objects; It is at the top of the
collections hierarchy.
2. List :- Extends Collection to handle sequences of List of objects
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 31/47

3. Set :- Extends Collection to handle sets, which must contain unique elements
4. SortedSet :- Extends Set to handle sorted sets.
The collection framework defines the following classes.
1. AbstractCollection :_ Implements most of the Collection interface.
2. AbstractLIst :- Extends AbstractCollection and implements most of the List interface.
3. AbstractSequentialList :- Extends AbstractList for use by a collection that uses
sequential rather than random access of its elements.
4. LinkedList :- Implements a linked list by extending AbstractSequentialList.
Q19. How UDP socket is used ? Discuss with an example.
Ans. public class clientTestUDP
{
Datagramsocket datasocket;
DatagramPacket dataPacket;
public static void main (String args [])
ClientTestUDP UDPClient = new ClientTestUDP ();
UDPClient.go ();
}
public void go ()
{
byte B[] = new. Byte [64];
String str;
try
{
datasocket = new Datagram Socket(1313);
dataPacket = new DatagramPacket(B, B.length);
While (true)
{
dataSocket.receive (dataPacket);
str= new String (datapacket.getData ());
System.Out.printIn (“Td signals received
From” + dataPacket.getAddress ()+
“In Time is: “+Str);
}
}
catch (Exception raised”);
}
}
}
Q20. What is Multithreading?
Ans. A thread executes a series of instructions. Every line of code that is executed is done so by a
thread. Some threads can run for the entire life of the applet, while others are alive for only a
few milliseconds.
Multithreading is the ability to have various parts of program perform program steps
seemingly at the same time. Java let programs interleave multiple program steps through the
use of threads. For example,one thread controls an animation, while another does a
computation. In Java, multithreading is not only powerful, it is also easy to implement.
You can implement threads within a java program in two ways – Creating an object that
extends Class Thread or implementing the interface Runnable.
The key difference between the two is that Thread class has a strart() method which your
program simple calls whereas the Runnable class does not have a start method and you must
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 32/47

create a Thread object and pass your thread to its constructor method. You never call run()
method directly; the start method calls it for you.
Example: Extending thread class
class MyProcess extends Thread{
public void run(){
}
public static void main(String args[]){
MyProcess mp = new MyProcess();
mp.start();
} }
Example: using Runnable interface
class MyProcess implements Runnable {
public void run(){ }
public static void main(String args[]){
Thread mp = new Thread(new MyProcess());
mp.start();
} }
Q21. What are DatagramPacket and why it is used in Socket Programming?
Ans. DatagramPackets can be created with one of four constructors. The first constructor specifies
a buffer that will receive data, and the size of a packet. It is used for receiving data over a
DatagramSocket. The second form allows you to specify an offset into the buffer at which
data will be stored. The third form specifies a target address and port, which are used by a
DatagramSocket to determine where the data in the packet will be sent. The fourth form
transmits packets beginning at the specified offset into the data. Think of the first two forms
as building and the second two forms as stuffing and addressing . the constructor used by
DatagramSocket has four constructor.
DatagramPacket(byte data[], int size)
DatagramPacket(byte data[], int offset,int size)
DatagramPacket(byte data[], int size,InetAddres ipAddress, int port)
DatagramPacket(byte data[], int size, int offset , int size, InetAddress ipAddress, int port)

There are several methods for accessing the internal state of a DatagramPackat. They give
complete access to the destination address and port number of a packet as well as the raw data
and its length.
Q22. Define PushbackReader?
Ans. The PushbackReader class allows one or more characters to be returned to the input stream.
This allows you to look ahead in the input stream. The two constructors of this class is
PushbackReader(Reader inputStream)
PushbackReader(Reader inputstream, int bufsize);
The first form creates a buffered stream that allows one character to be pushed back. In the
second , the size of the Pushback buffer is passed in bufSize.
PushbackReader provides unread() method which returns one or more characters to the
invoking inputstream. It has the three forms
Void unread(int ch);
Void unread(char buffer[])
Void unread(char buffer[], int offset, int numchars)
The first form pushes back the character passed in ch. This will be the next character returned
by the a subsequent call to read(). The second form returns the characters in buffer. The third
form pushes back numChars characters beginning at offset from buffer. An IOException will
thrown if there is an attempt to return a character when the pushback buffer is full.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 33/47

Q23. Define Inter thread Communication.


Ans. Inter thread communication process is to access more than one thread in the multithread
environment. With the help of synchronization or by sending the thread into monitor we can
get control on the thread process but to achieve a more subtle level of control through inter
process communication. In the polling system the consumer would waste many CPU cycles
while it waited for the producer to produce. Once the cycles waiting for the consumer to
finish, and so on, this situation is undesirable. To avoid the polling, Java includes an elegant
inter process communication mechanism via wait(), notify() and notifyAll() methods. These
methods are implemented as final methods in Object, so all classes have them. All three
methods can be called only from within synchronized method. The rules of using these
methods are actually quite simple.
wait() tells the calling thread to give up the monitor and go to sleep until some other thread
enters the same monitor and calls notify().
notify() wakes up the first thread that called wait() on the same object.
notifyAll() wakes up all the threads that called wait() on the same object. The highest priority
thread will run first.

Q24. What are synchronized methods and synchronized statements?


Ans. Synchrorinezed is the way to avoid data corruption caused by simultaneous access to the
same data by multiple threads. Because all the thread in a program share the same memory
space . It is possible to access the same variable or run the same method of the same object at
the same time.
To make the process syrichronized in java there are two ways.
1. Synchronized methods
2. Synchronized statements.
Using the synchronized method we can make any under the synchronized method, all other
threads that try to all it on the same instance have to wait, but synchronized method will not
work in all cases for that purpose use synchronized statement.
Synchronized statement: - This is the another way to imagine that you want to synchronized
access to the objects of a class that was not designed for multithreaded access. The class
doesn’t use synchronized method. Also that class was not created by you.
So you can add synchronized statement to the program to solve this problem. We use a
synchronized block called synchronized statement.

Syntax
Synchronized (object)
{
statement to be synchronized.
}
Q25. Write down all user interface component classes provided by swing their uses.
Ans. Swing package provide a great number of prebuilt components classes.
1. Japplet - Use to design applet in swings.
2. Jbutton - To design push button.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 34/47

3. JCheckbox - A checkbox that can be selected or deselected, displaying state visually.


4. JCheck Menu Item – A menu item that can be selected or deselected.
5. Jcombo box- A combo box which is the a combination of a text and
dropdowns list.
6. Jdialog- The base class for creating a dialog window.
7. Jframe- An extended version of java. Awt.frame that adds support root panes and
other panes.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 35/47

Section – C 2 Marks Questions [QUESTIONS 1 TO 30]


[PAGE 30 TO 32]

(JDBC, RMI, JAVA SERVELTS)


Q1. Define RMI.
Ans. Remote Method Invocation allows a java object that executes on the machine to invoke a
method of a java object that executes on another machine. This is an important feature
because it allows you to build distributed applications.
Q2. What is UniCastRemoteObject?
Ans. UnicastRemoteObject is extends by all the remote objects in RMI which provides
functionality that is needed to make objects available from remote machines. This class is
belongs to java.rmi.Server package.
Q3. How many Layer are provided by the RMI architecture
Ans. There are four different Layer in RMI architecture
1. Application Layer
2. Proxy Layer
3. RemoteReference Layer
4. Transport Layer
Q4. What are the different ways to use Registry services in RMI.
Ans. There are two ways to use registry services
1. To maintain a registry server that is running on a well-known predefined port number.
Any application that is exporting objects can register with this registry.
2. second method involves an application running its own registry services. This allows the
application to have total control over the registry but at the same time makes it more
difficult to define a well known port number that client application can use to access
remote objects.
Q5. Define PreparedStatement Interface.
Ans. The interface PreparedStatement extends the Statement Interface. If the application requires
multiple execution of a particular sql statement, it is predefined and stored in a
PreparedStatement object .
Q6. Benefits of servlet over cgi.
Ans. Servlet offer several advantages over CGI.
Performance
Platform independent
Secure
Use java class libraries
Q7. List the packages used to design servlet.
Ans. Javax.servlet , javax.servlet.http
Q8. List the methods used to handle HTTP request on servlet.
Ans. doDelete(),doGet(),doOptions(),doPost(),doTrace()
Q9. Explain Cookies?
Ans. A cookie is stored on a client and contains state information. Cookies are valuable for
tracking user activities. It can save the information like username,address etc.
Q10. Define Driver Manager in JDBC.
Ans. Java’s Driver Manager controls interaction between the UI and the database driver being
used. It can support multiple drivers connecting to different DBMSSystems. The driver
manger loads the requested driver and provides support for managing database connections.
Q11. What we need to execute Servlet.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 36/47

Ans. To Execute Servlet , we need a package known as JSDK (Java Servlet Development Kit).It
provides all the class libraries and interfaces used to create a small servlet. The package used
by all the servlet programs i.e. java% servlet also available in JSDk.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 37/47

Q12. Define servlet interface.


Ans. All servlet must implements the Servlet Interface. It declares the init(), service() and destroy()
method that are called by the Server during the life cycle of a servlet. A method is also
provided that allows a servlet to obtain any initialization parameters.
Q13. Define javax.servlet package.
Ans. The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate. The most significant of these is Servlet.All servlets
must implement this interface or extend a class that implements the interface. The
ServletRequest and ServletResponse interface are also very important.
Q14. Define Connection Interface.
Ans. A Connection object represents a connection with a database. Within this session SQL
statements can be executed, returning resultsets. Some of the widely used methods of the
connections objects are
Close(), CreatreStatement().
Q15. What is ResultSet ?
Ans. The data that is generated by the execution of a SQL statement is stored in, and can be
accessed, from a ResultSet object. The ResultSet object ‘watches’ a single row of data at a
time. This row of data is called its current row.
Q16. What is ResultSetMetaData Interface?
Ans. The ResultSetMetaData object returned by the getMetaData() constructor provides access to
information which indicates the number, type and properties of ResultSet columns. Some of
its important methods are
getColumnCount(), getColumnName(int), getTableName()
Q17. What are JDBC-EXCEPTION classes?
Ans. There are three types of JDBC EXCEPTION clesses.
1. SQLWarning class
2. DataTrancation class
3. SQLException class
Q18. What is stub class?
Ans. The stub is a client-side proxy. Stub defines all of the interfaces that the remote object
implementation supports. The stub is responsible for making a callo to a remote object as well
as for marshalling imformation to and from a reference layer.
Q19. What is skeleton class?
Ans. The skeleton is a server side proxy that interfaces with the server side RRL(Remote
Reference Layer) n. The skeleton receives method invocation request from the client- side
RRL. The cleint side RRL unmarshals any arguments that are sent to a remote method and
makes a call to the actual object implementation on the server side.
Q20. What is Introspection ?
Ans. This is the feature that allows visual programming tools to drag and drop the componentn
onto an application and allows components to publish the operations and properties they
support.
Q21. What is Persistence?
Ans. Visual design tools provide transparent and simple access to the property sheet of a
component to allow the component to be tailored for a specific application , Modified
properties are stored in such manner that they remain with the component from design to
execution. The capability to store changes to a component’s properties is known as
persistence. It allows components to be customized for latter use.
Q22. What is the ServletConfig interface?

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 38/47

Ans. The ServletConfig Interface is implemented by the server. It allows a servlet to obtain
configuration data when it is loaded. The Method declared by the interface are
getServletContext()
getInitParameter(String param), getInitParameterNames().

Q23. Define ServletException class.


Ans. The ServletException class indicates that a servlet problem has occurred. To create any
servlet we must handle that exception. The ServletException class has the following
constructors.
ServletException()
ServletException(String s)
Q24. Define HttpSession Interface.
Ans. The HttpSession interface is implemented by the server. It enables a servlet to read and write
the state information that is associated with HTTP session. It provides numbers of methods to
handles session of different users.
Q25. Define and get and post method.
Ans. Get and post keyword are specified as the value of method attribute of a form to send request
by the client if client send request using get method then information transfer is limited to the
225 characters.
Q26. What is Web Server?
Ans. Web Server is the server that handle request send by the web clients. All web client send there
request using one of the software known as web browser. Web server these request and send
the response or provide services to the client.
Q27. What is Session Tracking?
Ans. Http is stateless protocol, which means that each request is independent of the previous one.
In some application it is necessary to save the state information so that information can be
collected from several interactions between a browser and server. Mechanism to collect
information about the particular session is called session tracking.
Q28. What do mean by MIME?
Ans. The HTTP header are additional information send by the client software to server. These
headers indicates the request method, communication path, server software or client software
etc. the types of content is specified with MIME stands for Multipurpose Internet Mail
Extension. That specifies ordinary ASCII text has a MIME type of text/plain.
Q29. What is SingleThreadModel Interface?
Ans. The Single Thread Model interface is used to indicate that only a single thread should execute
the service() method of a servlet. It defines no constants and declares no methods. If a servlet
implements this interface, the server creates several instances of it. When a client request
arrives, it is sent to an available instance of the servlet.
Q30. Define HttpSession Interface.
Ans. The HttpSession interface is implemented by the server. It enables a servlet to read and write
the state information that is associated with an HTTP session. And provide different types of
methods to handle session.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 39/47

Section – C 5 Marks Questions [QUESTIONS


1 TO 20] [PAGE 32 TO 40]

(JDBC, RMI, JAVA SERVELTS)


Q1. Define the life cycle of java servlet.
Ans. A java servlet has a life cycle that defines how the servlet is loaded and initialized , how it
receives an respoonds to requests, and how it is taken out of service. The servlet lifecycle is
defined by the javax.servlet.Servlet interface.
All java servlets must, either directly or indirectly, implements the javax.servlet.Servlet
interface so that they can run in the servlet engine. The servlet engine is a customized
extension to a web server for processing servlets.
The javax.servlet.Servlet interface defines methods that are called at specific times and in a
specific order during the servlet lifecycle.
1 Servlet loaded :- The servlet engine instantiate and loads a servlet. The instantiation and
loading can occur when the engine starts,when it needs the servlet in order to respond to a
request , or any time in between.
2. Initialization :- after loading the servlet engine must initalize the servlet. Initialization is a
good time for a servlet to read any persistent data it may have stored, and initalize. The init()
method is used the servlet configuration object. The servlet configuration object also gives
the servlet access to a servlet context object of type ServletContext.
3. Servlet Handles Request : After the servlet is initalized it is ready to handle requests
from a client . Each client request that is made to a servlet is done via a servlet object. The
object are passed as parameters to the service() method defined in the Service interface which
the servlet implements.Thse ServletRequest or ServletResponse interface, or both . The
ServletRequest interface gives the servlet access to the request to the request Parameter the
client send. ServletResponse interface allows the servlet to set response headers and status
codes .
4. Servlet Destroyed
After taking all request and response when servlet engine determine the servlet should
destroy it will automatically destroy the servlet using the gargbage collection
Q2. How can HttpServletRequest /response are handled by the servlet?
Ans. The HttpServlet Class is used to handle the HttpServlet request. It is an abstract class so its
extends the GenericServlet base class and provide the frame work to Http protocol. Servlet
writers must subclass it and override at least one method.
The method normally overridden are
doGet()
doPost()
doGet() and doPost() methods are similar methods and receive the request from the client
machine . but doGet() method accept a small request upto 255 character and doPost() can
accept request of unlimited string and hidden information is provided.
Both method have tha following syntax
doGet(HttpServletRequest rq,HttpServletResponse rs)
doPost(HttpServletRequest rq,HttpServletResponse rs)
Q3. Write down the step to connect java program to database?
Ans. Java program can connect to the database using java database connectivity. The following
steps involves to create a connection with database.
1. Create a data source name using open database connectivity specifying the database to
connect.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 40/47

2. Specify jdbc.odbc.JdbcOdbcDriver in the program using class’s class’s for Name method.
3. Initialize the Connection with the help of Driver Manger ‘s getConnection method.in
which u have to specify the jdbc:odbc bridge with dsn reference.
4. Perform all the code in try/catch blocks ,because connection statements generate two type
of exception SQLException,ClassNotFound Exception.
5. After all that compile the program. With javac
Q4. What are the method provides by ResultSetInterface to Handle primitive data.
Ans. ResultSetInterface :- Resultset Interface will store the result of the select SQL query .
it provide different types of methods like
1.next() :- it will return true if any next record is available in the ResultSet.
2.close() :- It is used to close the ResultSet object.
Methods to handle primitive data
1. getInt() :- use to get integer value from the database.
2. getString():- use to get string value from the database.
3. getFloat():- use to get float value form the the database
4. getDouble():- to get Double value from the database.
5. getShort():- to get small int value from the database.
Q5. Define the connectivity model used by the java to connect database.
Ans. The java application is the UI . this in turn communicates with a driver manager using
underlying java code. The Driver Manager is a class that belongs to the java.sql package. The
driver manager communicates with 32bit ODBC driver.and odbc communicates with access
database.
Functionality of java connectivity model

The Java The ODBC The access


DriverManager System DSN Database Table

Create a Connection Object which


Communicates with ODBC driver and in turn spawns a Result Set object
to Database table.

The Result Set Object


This holds the records retrieved from the Access Database, table.
Date from this result set object can be bound to controls on a java Form.

Q6. Advantages of servlets over competing technologies.


Ans. Advantages
1. Servlets are capable of running in the same process space as the web server
2. java servlets are compiled into java byte-code. So java servlets can execute much more
quickly then common scripting languages.
3. Servlets are written in java and executed by a java virtual machine (JVM). The JVM does
not allow Servlet to direct access to memory location, thereby elimination crashes that
result from invalid memory accesses.
4. Because servlets are written completely in java, they enjoy the same cross-platform
support as any java program.
5. Servlets can run virtually on every popular web server in use today.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 41/47

6. Servlets are durable objects. because they remain in main memory until specifically
instructed to be destroyed.
7. Servlets can dynamically loaded either locally or across the network.
8. Servlets also support the multithreaded feature of java.
9. Servlets are protocol independent .

Q7. What is a distributed object System ? How RMI provides distributed object
mechanism.
Ans. The Distributed object system is a technology that combines networking and object-
oriented programming.
A distributed system includes nodes that perform compilations . A node may be a pc,a
mainframe computer. The nodes of a distributed system are scattered. The node in use is the
local node any other node is the remote node. A distributed system can not be established
without a network that connects nodes and allow the exchange of data.
RMI FOR DISTRIBUTED COMPUTING.
RMI is a simple method used for developing and deploying distributed object application in
java environment. In RMI an object oriented application creation is as simple as writing a
stand alone java application. It enables a programmer to create distributed java application, in
which the methods of the remote java object can be called from other java virtual machines
running either on the same host or on the different host scattered across a network..
Remote object call is identical from the local objects with the following exceptions
1. An object passed as a parameter to a remote method or returned from the method
must be serialzable or be another Remote object.
2. method passed by the remote objects are called by value and not by reference
3. a client always refers tp remote object through one of the Remote interface must be
implements.
The java.rmi and java.rmi.server package contain the interfaces and classes that defines the
functionality of java RMI system..
Q8. How does JSP differ from Servlets?
Ans. Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with
dynamically-generated HTML. Servlets, make you generate the entire page via your program,
even though most of it is always the same. JSP lets you create the two parts separately. Java
Server Pages (JSP) is a Sun Microsystems specification for combining Java with HTML to
provide dynamic content for Web pages. When you create dynamic content, JSPs are more
convenient to write than HTTP servlets because they allow you to embed Java code directly
into your HTML pages, in contrast with HTTP servlets, in which you embed HTML inside
Java code. JSP is part of the Java 2 Enterprise Edition (J2EE).
JSP enables you to separate the dynamic content of a Web page from its presentation. It
categories to two different types of developers: HTML developers, who are responsible for
the graphical design of the page, and Java developers, who handle the development of
software to create the dynamic content. Example of JSP

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">


<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors -->
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 42/47

<% out.println(Utils.getUserNameFromCookie(request)); %>


To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for all the rest of the on-line store's Web page.
</BODY>
</HTML>

Q9. What do you mean by Prepared Statement interface?


Ans. The interface Prepared Statement extends the Statement interface. If the application requires
execution of a particular sql statement, it is pre-compiled and stored in a Prepared Statement
object. This object then can be used many times to execute the statement efficiently.
Commonly useable method by this interface are.
1.executeQuery() :- This method is used to execute SQL statements. SQLException exception
is thrown in case of errors.
2. executeUpdate() :- This method executes SQL UPDATE,DELETE, or INSERT statements.
SQL statements that do not return anything such as SQL DDL statement can also be executed.
The error occur when these methods are called SQLException
Q10. Define the life cycle of an Entity Bean.
Ans. After the EJB container creates the instance, it calls the setEntityContext method of the entity
bean class, The setEntityContext method passes the entity context to the bean.
After instantiation, the entity bean moves to a pool of available instances. While in the
pooled stage, the instance is not associated with any particular EJB object identity. All
instances in the pool are identical. The EJB container assigns an identity to an instance when
moving it to the ready stage.
There are two paths from the pooled stage to the ready stage. On the first path, the client
invokes the create method , causing the EJB container to call the ejbCreate and ejbPostCreate
methods. On the second path, the EJB container invokes the ejbActivate method. While in
the ready stage, an entity bean’s business methods may be invoked.
Q11. Define ServletResponse Interface and the methods provided by the interface.
Ans. The ServletResponse interface is implemented by the server. It enables a servlet to formulate
a response for a client. And provide the following methods to solve the whole process.
getCharacterEncoding() :- Resturn the character encoding for the response in String type
getOutputStream() :- Returns a ServerOutputStream that can be used to write binary data to
the response. An IlegalStateException is thrown if getWriter() has already been invoked for
this request.
getWriter() :- Returns a PrintWriter that can be used to write character data to the response.
An IllegaStateException is thrown if getOutputStream() has already been invoked for this
request.
setContentLength(int size) :- Sets the contentLength for the response to size.
setContentType(String Type) :- Set the contentType for the response to type.
Q12. Differentiate between 2 tier and B-tier applications architectures.
Ans. Node & dumb terminals are connected to the server machine using different way.
1. 2 -tier architecture
2. 3-tier architecture.
3.
1. 2-tier Architecture: - Client is directly connected to the main server. Every thing is handle
by main server.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti,Client


Budhlada
1 (Mansa)-
151502
Data base
Server Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


Client 2

Client 3
SUBJECT: ADVANCE JAVA (MCA – 5) 43/47

2. 3-tier Architecture: - In three tier architecture contains three section.

1. Database Sever. 2. Application Server 3. Clients

Database server maintains database after all condition checks or business logics handled by
Application server. And client send request to application server then after all checks it
transfer to the database server.

Application Clients

Application Client

Application

Differences

2-tier 3-tier

1. Database |Business logic handle 1. Database and Business Logic


by the same server. Handled by different servers.
2. Only having data server. 2. That is a database server and
3. Easy Architecture to understand application server.
4. Less fault tolerance 3. Difficult or complex architecture
5. Client can directly connected to 4. Provide more fault tolerance.
the server which create more traffic 5. Database server connected to on the
network using different application server,
so different client can connect to the
database server using different
application server

Q13. What do you mean by servlet? What are advantages of servlet?


Ans. Servlet are the small platform independent java program that can be used to extend the
functionality of a web server in a array for ways. It is a server side software component
written in java that dynamically extends the functionality of a server. It is a framework for
creating applications that implements the request response paradigm.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 44/47

Advantages of servlet
1. Capable of running in the same process space as the Web server.
2. Compiled. Program
3. Cross platform –program created on one platform can used to any platform because
java provide platform independently.
4. Durable
5. Dynamically loadable accross the network
6. Extensible
7. Multi threaded
8. Protocol independent
9. Written java

Q14. Explain with suitable example request and response object.


Ans. Request object is used to handle the request send from the direct machine.
Response object used to transfer response to the client machine from server. The following
example will show you how request are handle and response is transfer to the client.

User.HTML
<HTML>
<BODY>
<Form name + f1 method = Post .8080
action= “http:// Localhost:8080/servlet/user.java”
<center>
<username <Input type = text name = “Un”>
<BR>
Password <input type = Password
Node = “PW”>
<BR>
<Input type = submit value = send >
<BR>
</center>
</BODY>
</HTML>
</FORM>
user. Java
import java.servlet. *;
import java.io. *;
public class user extends servelet {
public void service (Servelet Request rq. ServletResponse throws servelet &Exception,
IOException.
{
rs.setContentType (“Ext / HTML”);
PrintWriter PW = is.getWriter ();
PW.Printer “HTML> <BODY> “);
PW.Printer (“<H2> your email ID is: <I> “)
PW.printer (“<B>” + rq.getprintwriter (“un”) + “< /0>”);
PW.printer (“yahoo.com”);
PW.close ();
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 45/47

}
}
Q15. What are the various server side technologies? Explain.
Ans. There are numbers of server side technologies that helps to create response for the client from
the server. Like Common Gateway Interface(CGI), Active Server Pages(ASP), Servlet, Java
Server Pages(JSP) etc. These technologies are used to create dynamic web pages.
COMMON GATEWAY INTERFACE :- an interface used to create communication with web
server in early days. In this technology a server could dynamically construct a page by
creating a separate process to handle each client request allow the separate process to read
data from HTTP request and write data to the HTTP response. A variety of languages were
used to build CGI programs, including C, C++ and Perl.
ACTIVE SERVER PAGES :- another server side technology introduced by Microsoft to
create server side response for clients. Having very high performance with a draw back i.e.,
can only accessible on Microsoft based platform.
SERVLET :- the server side technology introduced by java to create server side response
with Java security manager provide platform independence by reducing traffic to network
because of handling all the client request on single address space.
JAVA SERVER PAGES :- technology allows web developers and designers to rapidly
develop and easily maintain, information-rich , dynamic web pages that leverage existing
business system. JSP enables rapid development of web based application that platform
independent. Create response for client with servlet.
Q16. Explain RMI Architecture with layer reference.
Ans. RMI architecture consist of four layers
1 Application 2. Stub/skeleton , Remote Reference and Transport Layer
1. Application Layer : - This layer contains the actual implementation of the client and sever
application. It is in this layers that high – level calls are made to access and export remote
objects.
2. The Proxy Layer : - This layer contains the client stub and server skeleton objects. The
application layer communicates with this proxy layer directly. All calls to remote objects
and marshaling of parameters and return objects are done through these proxies.
3. The Remote Reference Layer – The RRL(Remote Reference Layer ) handles packaging
of a method call and its parameters and its return values for transport over the network.
The RRL uses a server side and the client-side component to communicate via the network
layer.
4. Transport Layer :- The transport layer sets up connections, manages existing connections
and handles remote objects residing in its address space.
Q17. How a servlet is Destroyed Explain?
Ans. The servlet engine is not required to keep a servlet loaded for nay period of time or for the life
of the server. Servlet engines are free to use servlets or retire them at any time. Threrefor,
class or instance variables should not be used to store state information.
When the servlet engine determines that a servlet should be destroyed , the engine must allow
the servlet to release any resource it is using. To do this, the engine calls the servlet’s destroy
method.
The servlet engine must allow any calls to the service method either to complete or to end
with a time out before the engine can destroy the servlet. Once the engine destroys a servlet,
the engine coannot route any more requests to the servlet. The engine must release the servlet
and make it eligible for garbase collection.
Q18. Define HttpServletRequest and HttpServletResponseInterface?
Ans. The HttpServletRequest Interface encapsulates information of the request made to a servlet.
This interface gets information form the client to the servlet for use in the service() method .
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 46/47

It allows HTTP protocol specified header information to be accessed form the service()
method.
Following methods are provided by HttpServletRequest
1. getMethod() :- Returns the HTTP method (GET, POST) with which the request was
made.
2. getQueryString() :- Returns anyQuery String that is part of the HTTP REQUEST.
3. getRemoteUser() :- Returns the name of the ser making the HTTP request.
4. getRequested SessionId() :- To returns the Session Id specified with the HTTP request.
5. getSession(Boolean) :- If Boolean is FALSE, It return s the current valid session associated
with the HTTP request. If Boolean is TRUE, it creates a new session.
6.isRequestedSessionIdValid() :- Checks whether the HTTP request is associated with a
sessionthat is valid in the current session context
7. getCookies() : :- Returns the array of cookies found in the HTTP request.
The HttpServletResponse :- encapsulates information of the response sent by a servlet to a
client. This interface allows a servlet’s service() method to maniputlate HTTP protocol
specified header information and return data to its clients.
Methods of HttpServletResponse
addCookie(Cookies): Adds the specified cookie to the response.
encodeUrl(String) :- Encodes the specified URL by adding the sessionId to it. If encoding is
not required , it returnsthe URL unchanged.
sendRedirect(String) :- Sends a temporary redirect response to a client using the specified
redirect location URL.
Q19. What is Object Serialization also explain its criteria?
Ans. Object Serialization is the capability to write a Java object to a stream in such a way that the
definition and current state of object are preserved. When a serialized object is read from a
stream, the object initialized and in exactly the same state it was written to the stream.
Any Java class and its objects can be serialized as long as that class meets the following
criteria.
The class, or one of its superclasses, must implement the java.io.Serializable interface.
The class must participate with the writeObject() method to control data that is being saved or
append new data to existing saved data.
The class must participate with the readObject() method to read the data that has been written
by the corresponding writeObject() method.
If a serializable class has variables that should not be serialized, those variables Fmust be
marked with transient keyword. The serialization process then ignores them.
Q20. Explain all the methods provided by the Cookie class.
Ans. The Cookie class is used for session management with HTTP and HTTPS protocol . Cookies
are used to get Web Browsers to hold small amounts of state data associated with a a user’s
web browsing. Common applications for cookies include storing user preferences, automating
low security user sign on facilities.
Cookie class provide the following methods
1. Cookie(String,String) :- This the constructor of the class. It defines a cookie with an
initial name/ value pair.
2. setDomain(String) :- Specifies the domain, which this cookie belongs to . This cookie
will be visinble only to the specified domain.
3. setMaxAge(int) >- Sets the maximum age of the cookie. The unit of measurement is
seconds. A value of zero will cause the cookie to be deleted.
4. getValue() :- Returns the value of the cookie.
5. getName() :- returns the name of the cookie. The name of the cookie cannot be changed
after it is created.
Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store


SUBJECT: ADVANCE JAVA (MCA – 5) 47/47

6. getMaxAge() :- returns the maximum specified age of the cookie.


7. setValue():- sets the value of the cookie.

Prepared By: Deep Saini’Z; Near Bus Stand, Bhaiana Basti, Budhlada (Mansa)-
151502
Mobile no: 98882-91206, 98157-60019

Opp.Hindustan medical store

S-ar putea să vă placă și