0% found this document useful (0 votes)
45 views

AJAVA Question With Answer

The document discusses the life cycle of applets in Java. It explains the four states an applet passes through: initialization, running, idle, and dead. It also covers key methods like init(), start(), stop(), and destroy() that are involved in state transitions. Additionally, it compares local and remote applets, lists the <applet> tag and its attributes, and differentiates applets from standalone applications.

Uploaded by

Mahek Agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

AJAVA Question With Answer

The document discusses the life cycle of applets in Java. It explains the four states an applet passes through: initialization, running, idle, and dead. It also covers key methods like init(), start(), stop(), and destroy() that are involved in state transitions. Additionally, it compares local and remote applets, lists the <applet> tag and its attributes, and differentiates applets from standalone applications.

Uploaded by

Mahek Agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

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)
............
Computer Department, VPMP POLYTECHNIC 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
Computer Department, VPMP POLYTECHNIC 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.
Computer Department, VPMP POLYTECHNIC 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++.

Computer Department, VPMP POLYTECHNIC 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++.

Computer Department, VPMP POLYTECHNIC 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

Computer Department, VPMP POLYTECHNIC 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.

Computer Department, VPMP POLYTECHNIC 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);
}
Computer Department, VPMP POLYTECHNIC 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:

Computer Department, VPMP POLYTECHNIC 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.
Computer Department, VPMP POLYTECHNIC 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
{
Computer Department, VPMP POLYTECHNIC 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.
Computer Department, VPMP POLYTECHNIC 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
Computer Department, VPMP POLYTECHNIC 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;
Computer Department, VPMP POLYTECHNIC 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()
{

Computer Department, VPMP POLYTECHNIC 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

Computer Department, VPMP POLYTECHNIC 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()

Computer Department, VPMP POLYTECHNIC 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.
Computer Department, VPMP POLYTECHNIC 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.

Computer Department, VPMP POLYTECHNIC 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()

Computer Department, VPMP POLYTECHNIC 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.*;

Computer Department, VPMP POLYTECHNIC 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.

Computer Department, VPMP POLYTECHNIC 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.
Computer Department, VPMP POLYTECHNIC 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:

Computer Department, VPMP POLYTECHNIC 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
Computer Department, VPMP POLYTECHNIC 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:
Computer Department, VPMP POLYTECHNIC 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 ())
{
Computer Department, VPMP POLYTECHNIC 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).

Computer Department, VPMP POLYTECHNIC 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.

Computer Department, VPMP POLYTECHNIC 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.

Computer Department, VPMP POLYTECHNIC 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.

Computer Department, VPMP POLYTECHNIC 31

You might also like