Ajava Imp Question With Answer

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

UNIT-1
1) Explain Life cycle of APPLET
Ans:
✓ Every java applet inherits a set of default behaviours from the Applet class.so when an
applet is loaded ,it undergoes a series of changes in its state.
✓ The applet states are:
1. Born or Initialization state
2. Running state
3. Idle state
4. Dead or destroyed state

Life cycle of applet

1) Initialization state(Born)
✓ Applet enters the initialization state when it is first loaded.this is achieved by calling the init()
method of Applet class.The applet is born.
✓ Initialization occurs only once in the applet’s life cycle.
✓ To provide any of behaviour mentioned above,we must overrride init() method:
public void init()
{
............(Action)
............
}
2) Running state
✓ Applet enters the running state when the system calls start() method of Applet class.This
occurs automatically after applet is initialized.
✓ Unlike init() method,the start() method may be called more than once.
✓ We may override the start() method to create a thread to control the applet.
public void start( )
{
............(Action)
............
1
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

3) Idle or stopped state


✓ An applet becomes idle when it is stoppped from running.
✓ We can also stop applet by calling the stop() method explicitly.
✓ To do this override stop() method:
public void stop()
{
..................(Action)
..................
}
4) Dead state
✓ An applet is said to be dead when it is removed from memory .this occurs automatically by
invoking the destroy() mehtod when we quit the browser.
public void destroy()
{
...............
................
}
5) Display state
✓ Applets moves to the display state ,whenever it has to perform some output operations on the
screen.
✓ The paint() method is called to complete this task.
✓ Display state is not considered as a part of the applet’s life cycle.
✓ The paint() method is defined in the applet class.it is inherited from the Component class ,a
super class of Applet.
public void paint()
{
.............(Display statements)
.............
}
2) Difference Between Local and Remote APPLET
Ans:
Local Applet Remote Applet
It is stored locally on a standalone It is stored remotely on server
computer. computer.
It does not required an internet It required an internet connection.
connection.
It can be accessed only in a local It can be accessed by all computers
computer. connected with server
3) Explain and list <applet>tag and its attributes.
Ans:
< APPLET
[CODEBASE= codebase_URL]
CODE=AppletfileName.class
[ALT = Alternate_text]
[Name = applet_instance_name]
WIDTH = Pixels
2
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

HEIGHT = Pixels
[ALIGN= Alignment]
[VSPACE = Pixels]
[HSPACE = Pixles]
[<PARAM NAME=name1 VALUE= value1 >]
[<PARAM NAME=name2 VALUE= value2 >]
..............
</APPLET>

NO Attribute Meaning
CODE=AppletfileName.class Specifies the name of the applet class to be
1 (necessary) loaded.
CODEBASE= codebase_URL Specifies URL of the directory in which the
2 (Optional) applet resides.(must used in remote applet)
WIDTH = Pixels Specify width and height of the space on the
3 HEIGHT = Pixels(necessary) HTML page that will be reserved for applet.
Name = applet_instance_name A name for the other applet on the page may
4 (Optional) refer to this applet.
[ ALIGN= Alignment] Alignment of applet on page.
5
(Optional)
[ VSPACE = Pixels ] It specifies amount of vertical blank space the
6
(Optional) browser should leave surrounding the applet.
[ HSPACE = Pixels] It specifies amount of horizontal blank space the
7
(Optional) browser should leave surrounding the applet.
[ALT = Alternate_text ] Non _java browser will display this text where
8
(Optional) the applet would normally go.

4) What is the use of Appletviewer utility in java?


Ans:
✓ Applet can’t be executed directly.
✓ For running an Applet, HTML file must be created which tells the browser what
to load and how to run it. Applet begins execution via loading of a
HTML page “containing it” after that java enabled web browser or “applet
viewer” is required to run an applet.
✓ JDK provides a utility called “appletviewer” for testing applet
✓ Example: >appletviewer SimpleApplet.html

5) Explain <PARAM> tag in applet using example


Ans:
✓ <PARAM ...> tag is used to supply user defined parameters to applet.
✓ Passing parameter to an appplet code using <PARAM> tag is similar to passing
parameters to the main() method using command line argument.
✓ To pass and handles parameter ,do following:
✓ Include appropriate <PARAM...> tag in HTML document.
✓ Parameters are passed to an applet when applet is loaded.
3
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

✓ We can define init() method in applet to get hold of the parametes defined in
<PARAM> tags.
✓ getParameter() method ,takes one string argument representing the name of program.
✓ Each <PARAM...> tag has a name attribue and value attribute .
Syntax:
<APPLET.......>
<PARAMname=color value=“red”>
<PARAMname=text value=“I like java!”>
</APPLET>
Example:
import java.applet.*;
import java.awt.*;

/*
<applet code=ParamTest.class width=500 height=300>
<param Name="Author" value="Balaguru swami">
</applet>
*/

public class ParamTest extends Applet


{
public void paint(Graphics g)
{
String s=getParameter("Author");
g.drawString("Name:="+s,50,50);
}
}
6) Differentiate APPLET and Application.
Ans:
APPLET APPLICATION
An Applet is an application Application is a program that runs on
designed to be transmitted over the your computer under the operating system
Internet and executed by a Java- of that Computer.
compatible Web browser.
Applet is dynamic program which is Application is static program which run
run on browser. using java interpreter.
Applet do not use the main () method
Application uses main () method for
for initiating the execution of the
execution of the code.
code.
Applets cannot be run Application runs independently using
independently. javac compiler.
Applets cannot read or write files on Application can read write files on the
the web user’s disk. web user’s disk.
Applets are restricted from using Application program can use methods of
libraries from other languages such c, c++ libraries.
as c, c++.

4
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

7) Discuss the advantage and disadvantage of Applet.


Ans:
Advantage
✓ Automatically integrated with HTML.
✓ Can be accessed from various platform and various java-enabled web-browsers.
✓ Can provide dynamic, graphics capabilities.
✓ Implemented in JAVA and easy-to-learn object oriented Programming.
✓ Provide safe security.
Disadvantage
✓ An Applet has limited accessto the local and remote file systems.
✓ Applets don’t access client-side resources, like-Files, Operating system
✓ Applet cannot work with native methods.
✓ It requires the Java plug-in.
8) Explain how to pass parameter to Applet: with syntax and suitable example.
Ans: See Question-5
9) What is an Applet ? how does applet differ from Application.
Ans:
✓ An Applet is a special program of JAVA that can be embedded in a web page.
✓ Appletis small programs that are primarily used in internet computing.
✓ Java applet is a java class that you embed in an HTML page and is
downloaded and executed by a web browser.
Applet Application Program
NO
(web applet) (Stand-alone application)
1 An Applet is an application designed Application is a program that
to be transmitted over the Internet runs on your computer under
and executed by a Java-compatible the operating system.
Web browser.
2 Applet is dynamic program which is Application is static program
run on browser. which run using java interpreter.
3 Applet do not use the main () method Application uses main () method
for initiating the execution of the for execution of the code.
code.
4 Applets cannot be run independently. Application runs independently
They must be run under an applet using javac compiler.
viewer or a java compatible web
browser.
5 Applets cannot read or write files on Application can read write files
the web user’s disk. on the web user’s disk.
6 Applet cannot communicate with Application can communicate
other server on the network. with other servers on the
network.
7 Applet cannot run any program from Application program can run
the local computer. from local computer.
8 Applets are restricted from using Application program can use
libraries from other languages such as methods of c, c++ libraries.
c, c++.

5
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

10) Explain how to set background color within in applet area.


Ans:

import java.awt.*;
import java.applet.*;
/*<applet code=Hello.class width=400 heigth=400>
</applet>*/
public class Hello extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.pink);
g.drawString( “Hello java” ,10,100);
}
}

11) Describe process to design a webpage with <Applet>tag


Ans:
1. Building an applet code(.java file)
2. Creating an executable applet (.class file)
3. Designing a web page using HTML tags
4. Preparing <APPLET> tag
5. Incorporating <APPLET> tag into the web page
6. Creating HTML file
7. Testing the applet code
Example:

import java.awt.*;
import java.applet.*;
/*<applet code=Hello.class width=400 heigth=400>
</applet>*/
public class Hello extends Applet
{
public void paint(Graphics g)
{
setBackground(Color.pink);
g.drawString( “Hello java” ,10,100);
}
}

12) List any four method of applet class.


Ans:

No Methods Action

6
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

Used to implement each of four life cycles


void init( ), void start() stages of an applet.
1
void stop(), void destroy( ) :

Used to obtain parameter data that is


String getParameter(String
passed to an applet in an HTML
2 paramname): file.returns null if parameters not found.

3 void resize(Dimension dim): Used to resize an applet according to the


dimensions specified by dim.
Used to display a status message in the
4 void showStatus(String str) : status window of the browser or
appletviewer.

7
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

UNIT-2
1) What is Swing? Explain the need of swing.
Ans:
✓ Swing is a part of the java foundation classes.
✓ It is an extension library to AWT.
✓ Swing is a set of classes that provide more powerful and flexible components than
AWT
Need of Swing
✓ The uniform look and feel across platform is an advantage of swing
✓ Swing is light weight components.
✓ Swing is compatible for standalone/GUI applications, Applets and servlets.

2) Which method associates a checkbox with a particular group?


Ans:CheckBoxGroup () method is associates a checkbox with a particular group
3) Layout manager lays out the components from left to right.
Ans:FlowLayout manager lays out the components from left to right.
4) List any five event classes and five listener interfaces in java.
EventClass EventListener
ActionEvent ActionListener
KeyEvent KeyListener
MouseEvent MouseListener
WindowEvent WindowListener
ItemEvent ItemListener
5) How to create frame window within in applet? Give an example.
Ans:
✓ The frame class is used to provide the main window of an application. It may also
include menu bar.
✓ It is a subclass of Window that supports the capabilities to specify the icon, cursor,
Menu bar, and title.
✓ It implements MenuContainer interface so it can work with Menu bar object.
✓ Default layout is Border Layout.
✓ Frame provides basic building block for screen oriented applications.

Example:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=FrameDemo1.class width=250 height=150></applet>*/
public class FrameDemo1 extends Applet
{ Frame f;
Button b1;
public void init()
{ f=new Frame("Frame Window");
b1=new Button("Show Window");
add(b1);
}
8
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

public boolean action(Event evt,Object arg)


{ boolean visible=f.isShowing();
if(visible)
{ f.hide();
b1.setLabel("Show Window");
}
else
{ f.show();
f.resize(200,100);
b1.setLabel ("hide Window");
}return true;
}}
Output

Before

After

6) What is canvas in AWT? List its constructor and method.


Ans:
✓ The canvas component is a section of a window used primarily as a place to draw
graphics or display images.
✓ Canvas is more similar to a container however Canvas component can’t be used as a
place to put components.
✓ Canvas class implements a GUI objects that supports drawing.
✓ Drawing is not implemented on the canvas itself, but on Graphics object provided by
the canvas.
✓ It provides single parameter constructor and paint ( ) method.
Canvas c=new Canvas ();
c.resize (50, 50);
c.setBackground (Color.red);
add(c);
➢ Constructor:

9
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

Canvas();
Canvas(graphics configuration config);
➢ Methods:
GetAccessibleContext();
getBufferStrartegy();
paint(Graphics g);
update(Graphics g);
createBufferStrategy(int num Buffers);
Example:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code=CanvasDemo.class width=250 height=150></applet>*/
public class CanvasDemo extends Applet
{ Canvas c;
public void init()
{
c=new Canvas();
c.setBackground(Color.pink);
c.setSize(50,90);
add(c);}}
Output:

7) Explain event handling in java.


Ans:
✓ Changing the state of an object is known as an Event.
✓ Example: Pressing or clicking the button, entering a character in Textbox.
✓ Any GUI program is Event Driven. In Event-Driven programming a piece of
event handling codes can execute when an event has been fired in reference to
the user input.
✓ Events are supported by a number of Java Packages like: java util, java.awt and
java.awt. event.
How Events are handled?
There are main three components are required to handle Event.
Event Source: It is objects that can generates an event and send it to one or more
listeners registered with the Source.
Events: An Event is any change of state of an object.
10
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

Listeners: It is an object that the listener to the event. Once the event is received by the
listener can the process of event and then returns it.

8) List layouts manager, classes in java. Explain any one with example.
Ans:

Flow Layout (default Layout)


✓ It is default layout for applets and Panels.
✓ It places controls in the order in which they are added, linearly, from left to
rightand from top to bottom in horizontal and vertical rows.
✓ We can align components to left, right or center.
✓ Components are normally centered in applet.
To create flow Layout :
FlowLayout f1=new FlowLayout ();
FlowLayout f2=new FlowLayout (FlowLayout.LEFT);
FlowLayout f3=new
FlowLayout(FlowLayout.LEFT,10,30); setLayout(f1)
Example:
import
java.applet.*;
import java.awt.*;
/* <applet code=Flowtest.class width=150 height=400></applet> */ public class
Flowtest extends Applet
{
11
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

Button bt1=new Button ("ok");


Button bt2=new Button ("cancel");
Button bt3=new Button("1");
Button bt4=new Button("2");
Button bt5=new Button("3");
Button bt6=new Button("4");
FlowLayout f1=new FlowLayout (FlowLayout.LEFT);
FlowLayout f2=new FlowLayout (FlowLayout.RIGHT);
FlowLayout f3=new FlowLayout (FlowLayout.CENTER);
public void init()
{
SetLayout (f3);
add(bt1);
add(bt2);
add(bt3);
add(bt4);
add(bt5);
add(bt6);
}}

9) Describe any one swing components with example.


Ans:
JButton
✓ Swing buttons provide features that are not found in the Button class defined by the
AWT.
✓ Swing buttons are subclasses of AbstractButton class which extends JComponent.
✓ AbstractButton is a super class for push buttons, checkboxes and radio buttons. It
contains many methods that allow you to control the behavior of buttons, checkboxes
and radio buttons.
✓ JButton class provides the functionality of a push button. JButton allows an icon, a
stringor both to be associated with the push button.
Methods for Button
public void setText(String s): is used to set specified text on button.
public String getText(): is used to return the text of the button.
public void setIcon(Icon b): is used to set the specified Icon on the button.
public Icon getIcon(): is used to get the Icon of the button.

12
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

public void setMnemonic(int a): is used to set the mnemonic on the button.
public void addActionListener(ActionListener a): is used to add the action
listenerto this object.
Constructor for JButton:
JButton(Icon i)
JButton(String s)
JButton(String s,Icon i) //s and i are the string and icon used for the button.
Example:
import java.awt.*;
import javax.swing.*;
public class JButtonDemo extends JFrame
{
JButtonDemo(String title)
{
super(title);
setLayout(new GridLayout(3,2));
Icon plus= new ImageIcon("plus.png");
JButton b1=new JButton("ADD",plus);
JButton b2=new JButton("OK");
add(b1);
add(b2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[])
{
JButtonDemo t=new JButtonDemo("JButton Demo");
t.setSize(300,100);
t.setVisible(true);
}}

10) Differentiate TextArea and TextField.


Ans:
TextArea TextField
TextArea component can allow user to enter The textfield component can allow user to
more than one line of text. enter single line of text.
Syntax:- Syntax:-
TextArea t=new TextArea(); TextField t= new TextField();
In a TextArea we can insert or replace text by In a textfield we cannot insert or replace the
using Insert text() and replace text() method text.
It is a multiple line textbox with vertical and In a textfield it is a single line textbox.
horizontal scrollbar

11) Differentiate checkbox and RadioButton.


Ans:

Check Box Radio Button


In check box, we can select multiple In radio Button, we can select only one choice at
choices at a time. a time.
We can directly implement checkbox. For radio button implementation we have to use

13
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

CheckboxGroup () method.
Checkbox is use for multiple selection RadioButton is use for single selection.
Syntax:- Syntax:-
Checkbox ch1=new checkbox(“pen”); CheckboxGroup ch=new CheckboxGroup();
Add(ch1); Checkbox ch1=new checkbox(“female”);
Ch1.setcheckboxgroup(ch1);
Ch1.setstate(false);
Add(ch1);

12) Describe MOUSEEVENT and MOUSELISTENER interface with example.


Ans:
A MouseEvent is fired to all its registered listeners. When you press, Release or click a
mouse button at the source object or position of the mouse – pointer at (Enter) and away (Exit)
from the source object.
Methods of MouseEvent class: -

MouseEvent Description
Method
getClickCount() It can return number of times the mouse was clicked.
getPoint() It can return a point of object is an AWT class that can represents
the X and Y co-ordinates.
getX() It can return the X co-ordinates of the point at which the event
can occur.
getY() It can return the Y co-ordinates of the point at which the event
can occur.

A MouseListener interface is associated with MouseEvent class it can defines the


Methods to handle MouseEvents.
Methods of MouseListener: -

MouseListener Method Description


Void mousePressed Invoked when the mouse button is pressed down.
(MouseEvent e)
Void mouseReleased Invoked when the mouse button is released.
(MouseEvent e)
Void mouseEntered Invoked when the mouse enters the component.
(MouseEvent e)
Void mouseClicked Invoked when the mouse button is pressed and the released.

EXAMPLE: -
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code= Mousedemo.class Width=500 Height=500>
</applet>*/
Public class Mousedemo extends Applet implement MouseListener
{
String message;
14
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

int x=0, y=0;


Label lbl Ans;
Public void init()
{
LblAns=new label();
Add(lblAns);
addMouseListener(this);
}
Public void MousePressed(MouseEvent e)
{
Message=”MousePressed at x:”+e.getX()+y:”+e.getY();
lblAns.setText(message);
}
Public void MouseReleased(MouseEvent e)
{
Message=”MouseReleased at x:”+e.getX()+y:”+e.getY();
lblAns.setText(message);
}}

13) Describe KEYEVENT and KEYLISTENER interface with example.


Ans:
The KeyEvent is generated when a key is typed, pressed or released.
In order to handle the KeyEvent, we need to register KeyListener.
The KeyListener interface is associated with KeyEvent class.
It defines three methods to handle KeyEvents.
Methods of KeyListener:

Method Description
Public void KeyTyped Invoked when a key has been typed
(KeyEvent e) (pressed and released).
Public void KeyPressed Invoked when a key has been pressed.
(KeyEvent e)
Public void KeyReleased Invoked when a key has been released.
(KeyEvent e)
EXAMPLE: -
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code= Keydemo.class Width=500 Height=500>
</applet>*/
Public class Keydemo extends Applet implement KeyListener
{
TextArea t1;
Public void init()
{

15
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

addKeyListener(this);
}
Public void KeyPressed(KeyEvent e)
{
showStatus(“Key is pressed”);
}
Public void KeyReleased(KeyEvent e)
{
showStatus(“Key is Released”);
}
Public void KeyTyped(KeyEvent e)
{
showStatus(“Key is Typed”);
}}

14) Draw and explain AWT class hierarchy.


Ans:

1) Component
✓ Component class is derived from object class.
✓ It is the super class for all AWT components class such as Label, TextComponent,
RadioButton, and CheckBox etc.
2) Container
✓ Container class is derived from component class.
✓ The Container is a component in AWT that can contain another component like
buttons, textfields, labels etc. The class that extends Container class is known as
container such as Frame, Dialog and Panel.
3) Windows
✓ Windows class is derived from container class.
✓ The window is the containers that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.
4) Panel

16
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

✓ Panel class is derived from container class.


✓ The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
5) Frame
✓ Frame class is derived from container class.
✓ The Frame is the container that contain title bar and can have menu bars. It can have
other components like button, textfield etc.
15) List out interface of eventListener.
Ans:
EventClass EventListener
ActionEvent ActionListener
KeyEvent KeyListener
MouseEvent MouseListener
WindowEvent WindowListener
ItemEvent ItemListener

16) Explain AWT label control.


Ans:
Label:
✓ Labels are component that are used to display text in a container which can’t be edited by
user.
✓ They are generally used to guide the user to perform correct actions on the user interface,
also used for naming other components in the container.
Syntax:
Label l1=new Label (“name”);
add (l1);
Label constructor:
1) Label (): creates an empty label, with its text aligned to left.
2) Label (String): creates label with given text, aligned left.
3) Label (String, int): creates a label with given text string and given alignment value. (0 is
Label. LEFT, 1 is Label. RIGHT, 2 is Label. CENTER)
Methods:
1. getText (): it returns a string containing this label’s text.
2. setText (String: it set a new text of label
3. GetAlignment ( ): it returns an integer value representing the alignment of label (0 is Label.
LEFT, 1 is Label. RIGHT, 2 is Label. CENTER)
4. SetAlignment (int): changes the alignment of this label to the given integer value (0, 1 or 2)
Example:
import java.awt.*;
import java.applet.*;
/*<applet code="LabelDemo" width=400 height=400></applet>*/
public class LabelDemo extends Applet
{
public void init()

17
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

{
String s = "This is a very long label";
Label l1 = new Label(s, Label. LEFT);
add (l1);
Label l2 = new Label(s, Label. CENTER);
add (l2);
Label l3 = new Label(s, Label. RIGHT);
add (l3);
}}

17) Explain AWT pushbutton control.


Ans:
Button
✓ Button component is used to perform events in GUI.
✓ It is rectangular button that can be clicked with a mouse.
✓ Buttons are easy to manage and make the interface presentable.
Button b=new Button (“ok”);
add (b);
Button constructor:
1. Button ()-create an empty Button.
2. Button (String)-create a Button with String.
Example:
import java.awt.*;
import java.applet.*;
/*<applet code="ButtonDemo" width=400 height=400></applet>*/
public class ButtonDemo extends Applet
{
Button b1=new Button (“Button b1”);
Button b2=new Button (“Button b2”);
public void init()
{
add(b1);
add(b2);
}}

18) Explain border layout, flow layout, grid layout with example.
Ans:
Flow Layout (default Layout): see above Question-answer.

Grid Layout:
✓ The Grid layout class puts each component into a place on a grid that is equal in size to all
the other places.
✓ The grid is given specific dimensions when created; Components are added to the grid in
order, starting with upper-left corner to right.
✓ Components are given equal amounts of space in the container.
✓ Grid layout is widely used for arranging components in rows and columns.
18
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

✓ However unlike, Flow Layout, here underlying components are resized to fill the row-
column area. if possible.
✓ Grid Layout can reposition objects after adding or removing components. Whenever area is
resized, components are also resized.
GridLayout b1=new GridLayout (2, 3); // 4 rows and 1 column
SetLayout (b1)

Border Layout
✓ Border layout is the default layout manager for all window, dialog and frame class.
✓ In Border layout, components are added to the edges of the container, the center area is
allotted all the space that’s left over.
✓ Border layout ,provides five areas to hold component:
Four border→ north, south, east, and west
Remaining space: center
✓ When you add a component to the layout you must
Specify which area to place it in.

BorderLayout b1=new BorderLayout ();


setLayout (b1);
add (new Button bt1,BorderLayout.NORTH);
add(new Button bt2,BorderLayout.SOUTH);

19) Event class


Ans:

✓ Java event handling mechanism is represented by event classes.At the root of the java
event class hierarchy is EventObject.
✓ EventObject (Object src)-src are the object that generates event.

19
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

20) Mousereleased method of mouse listener.


Ans: See Mouse Event and MouseListener.

21) Write a short note on AWT windowevent class.


Ans:
✓ The WindowEvent is generated when a window is opened, closed, activated,
deactivated, Iconified, deIconified.
✓ In order to handle the WindowEvent, we need to register windowListener.
✓ The WindowListener interface is associated with WindowEvent class.
✓ It defines Eevent methods to handle WindowEvents.
Methods of WindowListener: -

Method Description
WindowActivated Invoked when a window is activated.
(WindowEvent e)
WindowClosed Invoked when a window has been closed.
(WindowEvent e)
WindowClosing Invoked when a window is in the process of being
(WindowEvent e) closed.
WindowOpened (WindowEvent e) Invoked when a window has been opened.
WindowDeactivated(WindowEvent e) Invoked when a window is deactivated.

EXAMPLE:
import java.awt.*;
import java.awt.event.*;
public class windowprogram extends Frame implements WindowListener
{
TextArea t1;
Public windowprogram()

20
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

{
addWindowListener(this);
setTitle(“Windowed Program”);
setSize(400,400);
setVisible(true);
t1=new TextArea(5,50);
add(t1);
}
public void WindowClosing(WindowEvent e)
{
setVisible(false);
System.exit(0);
}
Public void WindowOpened(WindowEvent e)
{
t1.append Text(“window is opened”);
}
Public void WindowClosed(WindowEvent e)
{
t1.append Text(“window is closed”);
}
Public static void main(String[] args)
{
New windowprogram();
}}

22) Explain JButton, JcomboBox AWT Control in java


Ans: JButton: See above question-answer.
JcomboBox
✓ Swing provides a combo box (a combination of a text field and a drop down list)
through the JComboBox class, which extends JComponent.
✓ A combo box normally displays one entry. However, it can also display a drop-down
list that allows a user to select a different entry.
✓ You can also type your selection into the text field.
✓ Constructor of JComboBox
JComboBox( )
JComboBox(Vector v) //v is vector that initializes the combo box.
✓ Items are added to the list of choices via addItem()method,
void addItem( Object obj) //obj is object to be added to the combo box
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

21
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

class JComboBoxDemo extends JFrame implements ItemListener


{
JComboBox cb;
JLabel jl;
String lang[] = {"JAVA","DOTNET","VB","PHP","C++"};
JComboBoxDemo()
{
super("Combo Box Demo"); setLayout(new FlowLayout());
jl=new JLabel(" ");
add(jl);
cb = new JComboBox(lang);
add(cb);
cb.addItemListener(this);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent ie)
{
jl.setText("you have selected :"+cb.getItemAt(cb.getSelectedIndex()));
}
public static void main(String args[])
{
new JComboBoxDemo();
}}
23) Difference between component and container class in java.
Ans:
Component Container
Components are generally user interface. Containers hold and organize your
Components
Example: Example:
List,Scrollbar,TextArea,TextField,Choice,Button Frame,Window,Dialog,Panel
etc
Every Component have unique container. Containers display components using a
layout manager.
24) What is the main difference between AWT and swing in java?
Ans:
AWT SWING
AWT stands for Abstract windows toolkit. Swing is also called as JFC’s (Java
Foundation classes).
AWT components are called Heavyweight Swings are called light weight component
component.
AWT components require java.awt package. Swing components require javax.swing
package.
AWT components are platform dependent. Swing components are made in purely java
and they are platform independent.
This feature is not supported in AWT. We can have different look and feel in Swing.

22
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

UNIT-3
1) Which package is used to perform almost all JDBC operations?
Ans: Java.sql package is used to perform almost all JDBC operations.
2) List JDBC API components. Explain in brief.
Ans:
JDBC has four Components:
1. The JDBC API.
2. The JDBC Driver Manager.
3. The JDBC Test Suite.
4. The JDBC-ODBC Bridge.
1. JDBC API
✓ JDBC API (application programming interface) is a part of the Java platform that
have included in Java Standard Edition (Java SE) and the Java Enterprise Edition
(Java EE) in itself.
✓ The latest version of JDBC 4.0 application programming interface is divided into
two packages
java.sql
javax.sql.
✓ These packages contain all the APIs which provide programmatic access to a
relational database (like oracle, SQL server, MySQL etc.)
✓ Using it, front end java applications can execute query and fetch data.
2 JDBC Driver Managers
✓ This interface manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub
protocol.
✓ The first driver that recognizes a certain sub protocol under JDBC will be used to
establish a database Connection.
✓ Internally, JDBC Driver Manager is a class in JDBC API. The objects of this class
can connect Java applications to a JDBC driver.
✓ Driver Manager is the very important part of the JDBC architecture. The main
responsibility of JDBC Driver Manager is to load all the drivers found in the system
properly.
✓ The Driver Manager also helps to select the most appropriate driver from the
previously loaded drivers when a new open database is connected.
3 JDBC Test Suite
✓ The function of JDBC driver test suite is to make ensure that the JDBC drivers will
run user's program or not.
✓ The test suite of JDBC application program interface is very useful for testing a
driver based on JDBC technology during testing period.
✓ It is used to check compatibility of JDBC driver with (J2EE)Java Platform
Enterprise Edition.
4 JDBC-ODBC Bridge
✓ The JDBC-ODBC Bridge, also known as JDBC type 1 driver is a database driver
that utilizes the ODBC driver to connect the database.
23
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

✓ This driver translates JDBC method calls into ODBC function calls. The Bridge
implements JDBC for any database for which an ODBC driver is available. The
Bridge is always implemented as the sun.jdbc.odbc
✓ Java package and it contains a native library used to access ODBC.
✓ ODBC driver is already installed or come as default driver in windows.

3) List JDBC driver .explain JDBC – TO-ODBC bridge driver (Type-1).


Ans:
Type 1: JDBC ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: All java/Net protocol driver (Middleware)
Type 4: All java/Native protocol driver (Pure)

Type 1: JDBC-ODBC Bridge Driver:


✓ This driver provides a gateway to the ODBC API.
✓ These drivers use a bridging technology to access a database.
✓ The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind
of driver.
✓ When Java first came out, this was a useful driver because most databases only
supported ODBC access but now this type of driver is recommended only for
experimental use or when no other alternative is available.
Advantages:
1. Easy to use
2. Allow easy connectivity to all database supported by the ODBC Driver.
Disadvantages:
1. Slow execution time
2. Dependent on ODBC Driver.

4) List JDBC driver .explain JDBC .NET pure java driver (Type -3).
Ans:

24
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

Type 1: JDBC ODBC Bridge driver (Bridge)


Type 2: Native-API/partly Java driver (Native)
Type 3: All java/Net protocol driver (Middleware)
Type 4: All java/Native protocol driver (Pure)

Type 3: JDBC-Net pure Java


✓ In a Type 3 driver, a three-tier approach is used to accessing databases. The JDBC
clients use standard network sockets to communicate with a middleware application
server.
✓ The socket information is then translated by the middleware application server into
the call format required by the DBMS, and forwarded to the database server.
✓ This kind of driver is extremely flexible, since it requires no code installed on the
client and a single driver can actually provide access to multiple databases.
Advantages:
1. Does not require any native library to be installed.
2. Database independency.
Disadvantages:
1. Slow due to increase number of network call.

5) Whatis a JDBC connection? Explain steps to get database connection using java program.
Ans:
✓ A Connection is the session between java application and database.
✓ The Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData i.e. object of Connection can be used to get the object of
Statement and DatabaseMetaData.
✓ The Connection interface provide many methods for transaction management like
commit(),rollback() etc
Steps to get Database connection
1. Register the driver class
25
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

2. Create the connection object


3. Create the Statement object:
4. Execute the query
5. Close the connection object

6) Give the use of following class: 1.driver managers 2. Connection.


Ans:
1. Driver Managers
The JDBC Driver Manager can connect Java application to a JDBC
driver. Driver Manager is the backbone of the JDBC architecture. It is
quite small and simple.
2. Connection
A Connection is the session between java application and database.
The Connection interface is a factory of Statement, PreparedStatement, and
DatabaseMetaData i.e. object of Connection can be used to get the object of
Statement and DatabaseMetaData.
The Connection interface provide many methods for transaction management
like commit(),rollback() etc

7) Develop a JDBC application that uses any JDBC drivers to display all records.
Ans:
Import java.sql.*;
public class selectdata
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql://localhost:3306/mydb","root", "");
Statement stmt=cn.createStatement ();
System.out.println (“Table data :”);
ResultSet rs=stmt.executeQuery ("select distinct * from stud");
While (rs.next ())
{
System.out.println (rs.getInt ("id") + "\t");
System.out.println (rs.getString ("name") +"\n");
}
}
Catch (Exception e)
{
System.out.println (e);
}
}
}
Output:
26
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

Table data:
1 Sita
8) Develop a JDBC application that uses any JDBC drivers to deletea record.
Ans:
import java.sql.*;
public class del { public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql://localhost:3306/mydb","root","");
Statement stmt=cn.createStatement();
String sql = "delete from stud “+ "where id=2";
stmt.execute(sql);
System.out.println ("Row is deleted");
}
Catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Row is deleted
1 Rita
9) Develop a JDBC application that uses any JDBC drivers to insert a record.
Ans:
import java.sql.*;
public class insert
{
public static void main (Stringargs [])
{
Try
{
Class.forName ("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql: //localhost:3306/mydb","root","");
Statement stmt=cn.createStatement ();
String sql = "INSERT INTO student VALUES (1, 'Rita') ";
stmt.execute (sql);
String sql = "INSERT INTO student VALUES (2, 'Ram') ";
stmt.execute (sql);
System.out.println (“Row is inserted");
ResultSet rs=stmt.executeQuery ("select DISTINCT * from stud ");
While (rs.next ())
{
27
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

System.out.println (rs.getInt ("id") +"\t"); System.out.println (rs.getString("name")+"\n");


}
rs.close () ;
stmt.close ();
cn.close () ;
}
catch (Exception e)
{
System.out.println (e);
}
}
}
10) Write the steps to develop a JDBC application with proper example.
Ans:
Steps to get Database connection
1. Register the driver class
2. Create the connection object
3. Create the Statement object:
4. Execute the query
5. Close the connection object
Example:
import java.sql.*;
public class CreateDB
{
public static void main(String args[])
{
Try
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection ("jdbc: mysql://localhost:3306","root","");
Statement stmt=cn.createStatement();
String sql = "create Database mydb";
stmt.execute(sql);
System.out.println("database created") ;
stmt.close() ;
cn.close() ;
}
Catch(Exception e)
{
System.out.println(e);
}
}
Output: database create
11) List advantages of using JDBC API (disadvantages).

28
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

Ans:
Advantages:
1. Can read any database if proper derivers are installed.
2. Creates XML structure of data from database automatically.
3. No content conversion required.
4. Query and stored procedure supported.
5. Supports modules.

Disadvantages:
1. JDBC is not good if used in large project.
2. It is not at all good in the transaction management.
3. JDBC needs database specific queries.
4. JDBC cannot maintain the database independent SQL statement.
5. When multiple connection are created and closed affects the performance.
6. Exception handling is one of the main drawbacks in JDBC.

12) Explain JDBC prepared statements.


Ans:
✓ The PreparedStatement interface is a sub interface of Statement. It is used to
execute parameterized query.
✓ Let's see the example of parameterized query:
✓ String sql="insert into student values (?,?,?)";
✓ We are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.
✓ ? is place holder used in the Prepared statement. It is known as Parameter marker.
✓ Improves performance: The performance of the application will be faster if you
use PreparedStatement interface because query is compiled only once.
✓ The prepareStatement () method of Connection interface is used to return the object
of PreparedStatement.
Syntax:
public PreparedStatement prepareStatement(String query)throws SQLException{}

13) Write a short note on JDBC architecture.


Ans:
✓ The JDBC API supports both two-tier and three-tier processing models for database
access.
General JDBC Architecture
✓ The JDBC API supports both two-tier and three-tier processing models for database
access but in general JDBC Architecture consists of two layers:
1) JDBC API: This provides the application-to-JDBC Manager connection.
2) JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
✓ The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.

29
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

✓ The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple databases.

14) Write a brief note on three tier database design.


Ans:

✓ In the three-tier model, commands are sent to a "middle tier" of services, which then
sends the commands to the data source.
✓ The data source processes the commands and sends the results back to the middle
tier, which then sends them to the user.

30
UNIT WISE GTU PAPER SOLUTION AJAVA (3360701)

✓ MIS (management information system) directors find the three-tier model very
attractive because the middle tier makes it possible to maintain control over access
and the kinds of updates that can be made to corporate data.
✓ Another advantage is that it simplifies the deployment of applications. Finally, in
many cases, the three-tier architecture can provide performance advantages.

31
Gtu paper solution AJAVA(3360701)

UNIT-4
SERVLET
1) What is Servlet? What is difference between Servlet and Applet?
Ans:
✓ Servlet is a technology which is used to create web application.
✓ Servlet technology is used to create web application which resides at server
side and generates dynamic web page.
✓ Servlet technology uses java language to create dynamic web application.
✓ Servlet are designed to work within a request/response processing model.

Servlet Applet
A java servlet executes on the A java Applet executes on the
Web Server in response to Web Browser.
requests from a Web Browser.
Servlet have no GUI. Applets are rich in GUI
Servlet is server side technology.
Applet is client side
technology.
Servlet are more powerful than Java Applets are limited to
Applet. certain operations on the
Browser.
Servlets can be used for server Applets can be used for client
side data validation. side data validation.
2) What is the difference between doGet () method and doPost () method?
Ans:
doGet() doPost()
Data is sent in header to the Data is sent in request body.
server.
Data request can send only Large amount of data can be
limited amount of data. send in Post method.
Get request is not secured Post request is secured
because data is exposed in URL. because data is not exposed in
URL.
Get request is more efficient. Post request is less efficient.
Get request can be bookmarked. Post request is not
bookmarked.

Page 1
Gtu paper solution AJAVA(3360701)

3) Explain the life cycle of Servlet?


Ans:
The life cycle contains the following steps: -

Load servlet class.


Create Instance of servlet.
Call the servlets init () method.
Call the servlets service () method.
Call the servlets destroy () method

1) Load Servlet class.


The servlet class is loaded when the first request for the servlet is
received by the web container.
2) Create Servlet instance.
After the servlet class is loaded, web container creates the instance of
it.The servlet instance is created only once in the servlet life cycle.
3) Call the Servlet init ( ) method.
Once instance of servlet is created, the web container calls the init ( )
method only once after creating the servlet instance.
Syntax:
Public void init (ServletConfig config) throws ServletException
{
//initialize code…
}
4) Call the Servlet Service ( ) method.
The container calls the service () method each time the request for
servlet is received.
Syntax:
Public void service (ServletRequest request, ServletResponce
response) throws ServletException, IOException
{
}
5) Call the Servlet Destroy ( ) method
The web container calls the destroy() method before removing servlet
instance giving a chance for cleanup activity.

Page 2
Gtu paper solution AJAVA(3360701)

4) Write a Servlet to read and display parameters using doGet method.


Ans:

WEB.XML FILE:
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>userName</param-name>
<param-value>Shweta</param-value>
</init-param>
</servlet>
<Servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/DemoServlet</url-pattern>
</servlet-mapping>
</web-app>

SERVLET FILE:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

Page 3
Gtu paper solution AJAVA(3360701)

public class DemoServlet extends HttpServlet


{
String uname;
public void init()
{
ServletConfig config=getServletConfig ();
Uname=config.getInitParameter ("userName");
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter ();
response.setContentType ("text/html");
out.println ("<html><head><title>Simple servlet
Example</title></head>");
out.println ("<body>");
out.println ("Welcome="+uname);
out.println ("</body></html>");
out.close ();}}

5) Create a web form which process servlet and demonstrates use of cookies?
Ans:
Simple example of Servlet Cookies
✓ In this example, we are storing the name of the user in the cookie object and
accessing it in another servlet.
✓ As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the
different value.

index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

Page 4
Gtu paper solution AJAVA(3360701)

FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse resp
onse){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse resp


onse){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();

Page 5
Gtu paper solution AJAVA(3360701)

}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

6) Write a short note on Reading initialization parameters in servlet?


Ans:

Page 6
Gtu paper solution AJAVA(3360701)

✓ You can pass parameters to a servlet from the web.xml file too. They are
called initialization parameters.
✓ The ServletConfig interface is implemented by the server. It can allow servlet
to get the information about the Configuration during its initialization.
✓ There are two types of init parameters available. They are both referred to as
initparameters, although defined in different elements.
Servlet init parameters (defined in <init-param> elements).
o Servlet init parameters are available to only the servlet for which the
<init-param> was configured.
o Servlet init parameters are defined within the <servlet> elements for
each specific servlet.
Context init parameters (defined in <context-param> elements).
o Context init parameters are available to only the servlet or JSP that are
the part of the current web app.
o Context init parameters are defined within the <Web-app> elements.

METHOD DESCRIPTION
String getInitParameter(String Returns a string which can
name) contains the value of the
initialization parameter and name
which can defines names of
initialization parametes.
Enumeration Returns Enumeration of string
getInitParameterNames() objects containing the names of
all initialization parameters.
Public Returns the reference of
ServletContextgetServletContext() ServletContext

7) What is http/servlet Technology?


Ans:
✓ HttpServlet is a technology which is used to create web application.
✓ HttpServlet technology is used to create web application which resides at
server side and generates dynamic web page.
✓ HttpServlet technology uses java language to create dynamic web application.
✓ HttpServlet are designed to work within a request/response processing model.

Page 7
Gtu paper solution AJAVA(3360701)

✓ HttpServlet technology use javax.servlet.http package to build servlet that


works with Http Request and Response.
8) List the Methods of cookie class
Ans:Methods of cookie class: -
1. Cookie c = new cookie(“theme”,”decent”);
2. C.setMaxAge(int);
3. HttpServletResponse.addCookie(c);
4. Cookie c[]=HttpServletResponse.getCookie.
5. C.getName()
9) Explain session tracking with example.
Ans:
✓ Session simply means a particular interval of time.
✓ Session Tracking is a way to maintain state (data) of an user. It is also known
as session management in servlet.
✓ Http protocol is a stateless so we need to maintain state using session tracking
techniques. Each time user requests to the server, server treats the request as
the new request. So we need to maintain the state of a user to recognize to
particular user.
✓ It is shown in the figure given below:

Approaches to session- Tracking: -


1. Using session Tracking API.
2. Cookies
3. Hidden form field
4. Using URL-Rewriting
Example:See abovecookies example for session tracking.

Page 8
Gtu paper solution AJAVA(3360701)

10) Explain advantage of Servlet?


Ans:
1) Better performance: Because it creates a thread for each request not
process (like CGI).
2) Portability: Because it uses java language and java is robust language.
3) Robust: Servlet are managed by JVM so no need to worry about memory
leak, garbage collection etc.
4) Secure: Because it uses java language and java is a secure language.
5) Inexpensive: There are number of free web servers available for personal
use or for commercial purpose.
6) Extensibility: The servlets API is designed in such a way that it can be
easily extensible.
11) Describe HTTPServlet class with its methods with syntax.
Ans:
✓ The javax.servlet. HTTPServlet class is a slightly more advanced base class
than theGenericServlet.
✓ The HttpServlet class has methods you can override for each HTTP method
(GET, POST etc). Here is a list of the methods you can override:
1) doGet (),
2) doPost(),
3) doHead(),
4) doPut(),
5) doDelete(),
6) doOptions()
7) doTrace().
✓ HttpServlet is a easier to work with, and has more convenience methods
thanGerericServlet.
✓ The HttpServlet class reads the HTTP request and determines if the request is
an HTTP GET, POST,PUT,DELETE, HEAD etc and calls one of the
corresponding methods.
✓ Here is an example:

Page 9
Gtu paper solution AJAVA(3360701)

Public class SimpleHttpServlet extends HttpServlet


{
Protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException{
Response.getWriter().write(“<html><body>GET
response</body></html>”);}}

Public class SimpleHttpServlet extends HttpServlet{


Protected void doGet(HttppServletRequest request,
HttpServletResponse response) throws ServletException,
IOException{
doPost(request, response);}
Protected void doPost(HttppServletRequest request,
HttpServletResponse response) throws ServletException,
IOException{
Response.getWriter().write(“GET/POST response”); }}

12) Which package is used for servlet application?


Ans: javax.servlet package is used for servlet application.
13) Explain JAVA servlet development kit.
Ans:
✓ Java Servlet Development Kit(JSDK) is a free program that contents all the
classes and interfaces needed to develop servlets.
✓ The application also contains a web server and servlet engine to run servlet.
✓ The JSDK includes: -
1) The jsdk.jar file which includes the class information necessary to
compile the servlets.
2) The java ServletRunnerprogram. The servlet runner is a program that
runs on your computer, and allows you to run servlets without running a
web server.
3) Several java Servlet Example with .java and .class files for testing
purposes and to help you understand how the java code is implemented.

Page 10
Ajava(3360701)

UNIT-5(JSP)
1) Difference between JSP and Servlet.
Ans:
JSP Servlet
JSP is a file which consists of Servlet is a java class.
HTML tag and scripting code.
Files are saved using .jsp extension Files are saved using .java
extension
It is server side scripting language Servlet is special program of JAVA
which is used to develop dynamic that is already compiled and used to
web pages. create dynamic web contents.
JSP run slower as compared to Servlet runs faster as compared to
Servlet because we need to compile JSP because servlet is already
the code written in JSP to convert it compiled.
in servlet code.
Coding is easy in JSP as compared Coding is difficult in servlet as
to Servlet. compared to Servlet.
JSP are supported to HTTP protocol Servlets are supported to HTTP,
only. FTP and SMTP protocols.

2) Develop JSP code to retrieve data from MySQL database.


Ans:
<html>
<head>
<title>validate</title>
</head>
<body>
<form action="NewRecords.jsp" method="Post">
Name:<input type="text" name="Name"/><br/><br/>
<input type="submit" value="Select"/> </form>
<%@page import="java.sql.*"%>

<% String Uname = request.getParameter("Name");


try
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/vpmp","root","");
Statement stmt = cn.createStatement();
ResultSet rs = stmt.executeQuery("select * from student where
Name='"+Uname+"'");
while(rs.next())
{
out.print("<table border='1'>");
out.print("<tr>");
out.print("<td>"+rs.getString("Id")+"</td>");
out.println("<td>"+rs.getString("Name")+"</td>");
Page 1
Ajava(3360701)

out.print("</tr>"); }
out.print("</table>");
}

catch(Exception e) {
} %>
</body>
</html>

Output:

3) Explain the architecture of JSP with neat diagram.


Ans:

✓ Servlet and JSP are the main technologies to develop the web applications.
✓ Servlet was considered superior to CGI. Servlet technology doesn't create
Process, rather it creates thread to handle request. The advantage of creating
thread over process is that it doesn't allocate separate memory area. Thus
many subsequent requests can be easily handled by servlet.
✓ Problem in Servlet technology Servlet needs to recompile if any designing
code is modified. It doesn't provide separation of concern. Presentation and
Business logic are mixed up.

Page 2
Ajava(3360701)

✓ JSP overcomes almost all the problems of Servlet. It provides better


separation of concern, now presentation and business logic can be easily
separated. You don't need to redeploy the application if JSP page is modified.
✓ JSP provides support to develop web application using JavaBean, custom tags
and JSTL so that we can put the business logic separate from our JSP that will
be easier to test and debug.
4) Explain JSP Expressions
Ans:
✓ A JSP expression element contains a scripting language expression that is
evaluated, converted to a String, and inserted where the expression appears in
the JSP file.
✓ The expression element can contain any expression that is valid according to
the Java Language Specification but you cannot use a semicolon to end an
expression.
Syntax of JSP Expression:
<%= expression %>
You can write XML equivalent of the above syntax as follows: <jsp:
expression>
Expression
</jsp: expression>
Example-4 Write a JSP program to add two variables.

<Html>
<Head>
<title>JSP Hello World</title>
</head><body>
<%! int a=2;int b=3; %>sum of a and b= <%= a+b %>
</body></html>
Output :
sum of a and b=5

5) Explain life cycle of JSP.


Ans:
✓ JSP page looks like a HTML page but is a servlet.
✓ It is not executed directly.
The JSP page follows these phases:
1. Translation of JSP Page
2. Compilation of JSP Page
3. Class loading (class file is loaded by the classloader)
4. Instantiation (Object of the Generated Servlet is created).
5. Initialization (jspInit () method is invoked by the container).
6. Request processing (_jspService () method is invoked by the container).
7. Destroy (jspDestroy () method is invoked by the container).

Page 3
Ajava(3360701)

Translation:
✓ JSP container checks the JSP page code and converts it to generate the servlet
source code.
✓ After JSP page is translated into servlet all the request for that JSP page are
served by its related servlet class.
Compilation of JSP Page
✓ In this Java source code for the related servlet is compiled by the JSP
container. The container converts source code into byte code.
Class loading:
✓ In this servlet class file is loaded by the class loader.
Instantiation:
✓ Object of the Generated Servlet is created.
Initialization:
✓ In this instantiated object is initialized. For this jspInit() method is invoked by
the container.
✓ jspInit( ) method declared in JSP page and it is implemented by JSP
container.This method called once in JSP life cycle to initialize it with config
params configured in deployment descriptor.
Request processing:
✓ In this stage of JSP life cycle only those objects of a JSP equivalent servlet
that initialized successfully are used by the web container to handle client
request.
✓ _jspService () method is invoked by the container for each client request by
passing request and response object.
Destroy:
✓ If a servlet container decides to destroy a servlet instance of a JSP
page,jspDestroy () method is invoked by the container.
✓ It clean up the environment .It is called only once in JSP life cycle.

Page 4
Ajava(3360701)

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
6) Write a JSP program of user login form with static data.
Ans:
Index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<form action="wel.jsp" method="Post">
<table>
<tr> <td>User Name: </td> <td>
<input type="text" name="userName"/>
</td> </tr>
<tr> <td>Password: </td> <td>
<input type="password" name="userPass"/></td> </tr>
<tr><td><input type="submit" value="Login"/></td> </tr>
</table>
</form>
</body>
</html>
Welcome.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<% String uname = request.getParameter("userName");
String pass = request.getParameter("userPass");
if(uname.equals("shweta") && pass.equals("123"))
{
out.println("Successfully Login");
out.println("Welcome "+uname);
}
else
{
out.println("Sorry..!!! Wrong User Name & Password");
} %>
</body>
</html>

Page 5
Ajava(3360701)

Output:

7) Explain relation of applets and servlet with JSP.


Ans:
✓ There are three primary ways to create client interfaces to java programs that
are delivered over the internet: applet , servlets and Java Server Page(JSP)
✓ Applets run within a client browser, while servlets and JSPs run on the web
server machine.
Applets
✓ Applets are small programs that are downloaded into a Java enabled web
browser.
✓ The browser will execute applet on clients machine .The downloaded applet
has very limited access to client’s machine’s file system and network
capabilities.
Servlets
✓ It is a program that runs with a web server. A servlet is executed in response
to an HTTP request from a client browser.
✓ The servlet executes and then returns an HTML page back to browser.
✓ Once it started it remains in memory and can handle multiple HTTP requests.
It provides dynamic content.

Page 6
Ajava(3360701)

JSP
✓ JSP are text document that describe how a server should handle specific
requests.
✓ JSP is run by JSP server, which interprets the JSP and performs the actions the
page describes.
✓ JSP server compiles the JSP into a servlet to enhance performance. The server
would the periodically check the JSP for changes. If JSP changes the server
will recompile it into a servlet.
✓ JSP is extension to servlet.
✓ JSP looks very similar to static HTML pages, expect they contain special tags
are used to identify and define areas that contain java functionality.
8) Explain JSP scripting elements.
Ans:
✓ The scripting elements provides the ability to insert java code inside the JSP
✓ There are mainly three types of scripting elements:
1. Scriptlet tag
2. Expression tag
3. Declaration tag
Note: Explain each tag with Example.
9) Write simple JSP program to print “HELLO”.
Ans:
<html>
<head>
<title>JSP Hello World</title>
</head>
<body>
<% out.println("Hello World<br>"); %>
</body>
</html>
Output:
Hello World
10) How to access database using JSP. Explain with example.
Ans: See Question 2.
11) Explain <scriptlet> tag with syntax.
Ans:
✓ It is used to execute java source code in JSP.
✓ A scriptlet can contain any number of JAVA language statements, variable or
method declarations, or expressions that are valid in the page scripting
language.
✓ Scriptlet evaluated at request processing time, using the values of any
declarations and expressions that are made to them.
✓ It is used to do complex code rather than simple expression scriptlet tag is
used.
Syntax of Scriptlet:
<% code fragment %>
You can write scriptlet tag in XML as follows:
<jsp: scriptlet>

Page 7
Ajava(3360701)

Code fragment
</jsp: scriptlet>
Example-Write a program to print Hello world in JSP

<html>
<head>
<title>JSP Hello World</title>
</head>
<body><% out.println("Hello World<br>"); %></body>
</html>
Output: Hello World
12) Develop a JSP program to display the grade of a student by accepting the marks of
five subjects.
Ans:
index .jsp
<html>
<head>
<title>JSP Program</title>
</head>
<body>
<form action="StudentGrade" method="Post">
<table>
<tr><td>Subject 1: </td>
<td><input type="text" name="sub1"/></td>
</tr>
<tr><td>Subject 2: </td>
<td><input type="text" name="sub2"/></td>
</tr>
<tr><td>Subject 3: </td>
<td><input type="text" name="sub3"/></td></tr>
<tr><td>Subject 4: </td>
<td><input type="text" name="sub4"/></td>
</tr>
<tr><td>Subject 5: </td>
<td><input type="text" name="sub5"/></td></tr>
<tr><td><input type="submit"
value="Submit"/></td></tr></table></form></body></html>

Grade.jsp
<html>
<head>
<title>JSP Grade</title>
</head>
<body><% int sub1 = Integer.parseInt(request.getParameter("sub1"));
int sub2 = Integer.parseInt(request.getParameter("sub2"));
int sub3 = Integer.parseInt(request.getParameter("sub3"));
int sub4 = Integer.parseInt(request.getParameter("sub4"));
Page 8
Ajava(3360701)

int sub5 = Integer.parseInt(request.getParameter("sub5"));


int total = sub1 + sub2 + sub3 + sub4 + sub5;
float per = (total * 100) / 500;
out.println("Total = "+total+"<br />");
out.println("Percentage = "+per+"<br />"); if(per >= 75)
{
out.println("Distinction");
} else if(per <= 74 && per >= 60)
{ out.println("First Class"); }
else if(per <= 59 && per >= 35)
{
out.println("Second Class");
}
else
{ out.println("Fail");
} %>
</body></html>

13) Develop a JSP application to insert record in MySQL database.


Ans:
<html> <head>
<title>validate</title>
</head>
<body>
<form action="NewRecords.jsp" method="Post">
ID:<input type="text" name="Id"/><br/><br/>
Name:<input type="text" name="Name"/><br/><br/>
<input type="submit" value="Insert"/> </form>
<%@page import="java.sql.*"%>

<% String Uid = request.getParameter("Id");


String Uname = request.getParameter("Name");
try
{
Class.forName("com.mysql.jdbc.Driver");

Page 9
Ajava(3360701)

Connection cn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/vpmp","root","");
Statement stmt = cn.createStatement();
int no = stmt.executeUpdate("insert into student
values('"+Uid+"','"+Uname +"')");

if(no>0)
{
out.println("Data inserted successfully");
} }
catch(Exception e) {
} %>
</body>
</html>

Output:

Page 10

You might also like