Adv Java QB&ANS2023
Adv Java QB&ANS2023
V SEMESTER BCA
Advanced java programming
22CAC-13
QUESTION BANK WITH ANSWERS
Module I
Multiple Choice Questions
Questions based on Knowledge
1. Which of these functions is called in a Java program to display the output of an applet?
A. display()
B. paint()
C. displayApplet()
D. appletviewer()
Answer: Option B
2. Which of these methods can be used to output a string in an applet?
A. display()
B. print()
C. drawString()
D. transient()
Answer: Option C
5. Which of these packages contain classes and interfaces used for input & output operations of a program?
A. java.util
B. java.lang
C. java.io
D. All of the mentioned
Answer: Option C
10. DataInput is
A. an abstract class defined in java.io
B. a class we can use to read primitive data types
C. an interface that defines methods to open files
D. an interface that defines methods to read primitives data types
Answer: Option D
11. Which is a special type of program that is embedded in the webpage to generate the dynamic content?
A. Package
B. Applet
C. Browser
D. None Of The Above
Answer: Option B
12. What is used to run an Applet?
A. An Html File
B. An Appletviewer Tool(For Testing Purpose)
C. Both A & B
D. None Of The Above
Answer: Option C
13. Which is the correct order of lifecycle in an applet?
A. Applet Is Started,Initialized,Painted,Destroyed,Stopped
B. Applet Is Painted,Started,Stopped,Initilaized,Destroyed
C. Applet Is Initialized,Started,Painted,Stopped,Destroyed
D. Applet Is Painted,Started, Initilaized, Stopped,Destroyed
Answer: Option C
11. Which method is called only once during the run time of your applet?
A. stop()
B. paint()
C. init()
D. destroy()
Answer: Option C
12. When an applet is terminated which of the following sequence of methods calls take place?
A. stop(),paint(),destroy()
B. destroy(),stop(),paint()
C. destroy(),stop()
D. stop(),destroy()
Answer: Option D
Initialization State
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. At this stage, we may do the following.
Create objects needed by the applet
Set up initial values
Load images or fonts
Set up colors
Running State
Applet enters the running state when the system calls the start() method of Applet class. This occurs
automatically after the applet is initialized.
public voids start()
{ ………
……… }
{…………
……….. }
Dead State
An applet is said to be dead when it is removed from memory. This occurs by invoking the destroy()
method when we quit the browser. Destroying stage occurs only once in the applet‘s life cycle.
. Example:
Import java.awt.*;
Import java.applet.*;
Public class HelloJava extends Applet
{
Public void paint(Graphics g)
{
g.drawString(―Hello Java‖, 10,100);
}
}
System.out.println(file.readInt());
file.seek(file. length());
filewriteBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
Catch(IOException e)
{
System.out.println(e);
}
}
}
{
System.out.println(e);
}
}
}
7. Write a note on reading and writing characters
The two subclasses used for handling characters in files are FileReader(for reading characters)
and FileWriter(for writing characters).
The below program uses these two file stream classes to copy the contents of a file
named ― input.dat‖
into a file called ―output.dat‖.
For using a file, it must be opened first. This is done by creating a file stream and then linking it to
the filename. A file stream can be defined using the classes of Reader/InputStream for reading
data and Writer/OutputStream for writing data.
The java.io package in cludes a class known as the File class that provides support for creating files
anddirectories. The class includes several constructing for instantiating the File objects. This class
also contains several methods for supporting the operations such as
Creating a file
Opening a file
Closing a file
Deleting a file
Getting the name of a file
Getting the size of a file
Checking the existence of a file
Renaming a file
Checking whether the file is writable
Checking whether the file is readable
Reader
Reader class and its subclasses are used to read characters from source. Reader class is a base class
of all the classes that are used to read characters from a file memory or console. Reader is an abstract
class and hence we can't instantiate it but we can use its subclasses for reading characters from the
input stream.
We will discuss subclasses of Reader class with their code, in the next few articles
Methods of Reader classes
These methods are of Reader class
Writer
Writer class and its subclasses are used to write characters to a file, memory or console. Writer is
an abstract class and hence we can't create its object but we can use its subclasses for writing
characters to the output stream. We will discuss subclasses of Writer with their code in the next
few artic les
Methods of writer classes
Methods of Writer class provide support for writing characters to the output stream. As this is an
abstractclass. Hence, some undefined abstract methods are defined in ths subclasses of Output
Stream
Long Answers
// Demonstrate Labels
import java.awt.*;
import java.applet.*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet {
public void init( ) {
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
// add labels to applet window
add(one);
add(two);
add(three);
}
}
The labels are organized in the window by the default layout manager.
The Choice class is used to create a pop-up list of items from which the user may choose. Thus,a
Choice control is a form of menu. When inactive, a Choice component takes up only enough
space to show the currently selected item. When the user clicks on it, the whole list of choices
pops up, and a new selection can be made. Each item in the list is a string that appears as a left-
justified label in the order it is added to the Choice object. Choice only defines the default
constructor, which creates an empty list. To add a selection to the list, call add( ). It has this
general form:
void add(String name)
To determine which item is currently selected, you may call either
getSelectedItem( ) or getSelectedIndex( ). These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item.
getSelectedIndex( ) returns the index of the item. The first item is at index 0. By default, the
first item added to the list is selected.
To obtain the number of items in the list, call getItemCount( ). You can set the currently
selected item using the select( ) method with either a zero-based integer index or a string that
will match a name in the list.
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice
object, which shows only the single selected item in the menu, a List object can be constructed
to show any number of choices in the visible window. It can also be created to allow multiple
selections. List provides these constructors:
List( ) throws HeadlessException
List(int numRows) throws HeadlessException
List(int numRows, boolean multipleSelect) throws HeadlessException
The first version creates a List control that allows only one item to be selected at any one time.
In the second form, the value of numRows specifies the number of entries in the list that will
always be visible (others can be scrolled into view as needed). In the third form, ifmultipleSelect is
true, then the user may select two or more items at a time. If it is false, then
only one item may be selected. To add a selection to the list, call add( ). It has the following
two forms:
void add(String name)
void add(String name, int index)
Here, name is the name of the item added to the list. The first form adds items to the end of
the list. The second form adds the item at the index specified by index. Indexing begins at
zero. You can specify –1 to add the item to the end of the list. For lists that allow only single
selection, you can determine which item is currently selected by calling either
getSelectedItem( ) or getSelectedIndex( ). These methods are shown here:
String getSelectedItem( )
int getSelectedIndex( )
The getSelectedItem( ) method returns a string containing the name of the item. If more than
one item is selected, or if no selection has yet been made, null is returned. getSelectedIndex(
)
returns the index of the item.
int getItemCount( )
void select(int index)
Given an index, you can obtain the name associated with the item at that index by calling
getItem( ), which has this general form:
String getItem(int index)
Here, index specifies the index of the desired item.
To process list events, you will need to implement the ActionListener interface. Each time a
List item is double-clicked, an ActionEvent object is generated. Its getActionCommand( )
method can be used to retrieve the name of the newly selected item. Also, each time an item is
selected or deselected with a single click, an ItemEvent object is generated. Its
getStateChange( )
method can be used to determine whether a selection or deselection triggered this event.
getItemSelectable( ) returns a reference to the object that triggered this event. Here is an
example that converts the Choice controls in the preceding section into List components, one
multiple choice and the other single choice
Scroll bars are used to select continuous values between a specified minimum and maximum.
Scroll bars may be oriented horizontally or vertically. A scroll bar is actually a composite of
several individual parts. Each end has an arrow that you can click to move the current value of
the scroll bar one unit in the direction of the arrow.
Scrollbar( ) throws HeadlessException
Scrollbar(int style) throws HeadlessException
Scrollbar(int style, int initialValue, int thumbSize, int min, int max)
throws HeadlessException
The first form creates a vertical scroll bar. The second and third forms allow you to specify the
orientation of the scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll bar is created.
If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal. In the third form of the
constructor, the initial value of the scroll bar is passed in initialValue. The number of units
represented by the height of the thumb is passed in thumbSize. The minimum and maximum
values for the scroll bar are specified by min and max.
If you construct a scroll bar by using one of the first two constructors, then you need to set its
parameters by using setValues( ), shown here, before it can be used:
void setValues(int initialValue, int thumbSize, int min, int max)
The parameters have the same meaning as they have in the third constructor just described. To
obtain the current value of the scroll bar, call getValue( ). It returns the current setting. To set
the current value, call setValue( ). These methods are as follows:
int getValue( )
void setValue(int newValue)
Here, newValue specifies the new value for the scroll bar. When you set a value, the slider box
inside the scroll bar will be positioned to reflect the new value. You can also retrieve the
minimum and maximum values via getMinimum( ) and getMaximum( ), shown here:
int getMinimum( )
int getMaximum( )
They return the requested quantity. By default, 1 is the increment added to or subtracted from
the scroll bar each time it is scrolled up or down one line. You can change this increment by
calling setUnitIncrement( ).
6. Explain about Layout Managers.
Layout manager automatically arranges controls within a window by using some type of
algorithm. If you have programmed for other GUI environments, such as Windows, then you
are accustomed to laying out your controls by hand. While it is possible to lay out Java controls
by hand, too,you generally won‘t want to, for two main reasons. First, it is very tedious to
manually layout a large number of components. Second, sometimes the width and height
information is not yet available when you need to arrange some control, because the native
toolkit components haven‘t been realized.
Each Container object has a layout manager associated with it. A layout manager is an instance
of any class that implements the LayoutManager interface. The layout manager is set by the
setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used.
Whenever a container is resized (or sized for the first time), the layout manager is used to
position each of the components within it. The setLayout( ) method has the following general
form:
void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager. If you wish to disable the layout
manager and position components manually, pass null for layoutObj. If you do this, you will
need to determine the shape and position of each component manually, using the setBounds(
) method defined by Component. Normally, you will want to use a layout manager.
FlowLayout is the default layout manager. FlowLayout implements a simple layout style,
which is similar to how words flow in a text editor. The direction of the layout is governed by
the container‘s component orientation property, which, by default, is left to right, top to bottom.
Therefore, by default, components are laid out line-by-line beginning at the upper- left corner.
In all cases, when a line is filled, layout advances to the next line. A small space is left between
each component, above and below, as well as left and right. Here are the constructors for
FlowLayout:
FlowLayout( )
FlowLayout(int how)
FlowLayout(int how, int horz, int vert)
The first form creates the default layout, which centers components and leaves five pixels of
space between each component. The second form lets you specify how each line is aligned.
Valid values for how are as follows:
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout.LEADINGFlowLayout.TRAILING
These values specify left, center, right, leading edge, and trailing edge alignment, respectively.
The third constructor allows you to specify the horizontal and vertical space left between
components in horz and vert, respectively. Here is a version of the CheckboxDemo applet
shown earlier in this chapter, modified so that it uses left-aligned flow layout:
// Use left-aligned flow layout.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="FlowLayoutDemo" width=250 height=200>
</applet>
*/
public class FlowLayoutDemo extends Applet
implements ItemListener {
String msg = "";
Checkbox winXP, winVista, solaris, mac;
public void init( ) {
// set left-aligned flow layout
setLayout(new FlowLayout(FlowLayout.LEFT));
winXP = new Checkbox("Windows XP", null, true);
winVista = new Checkbox("Windows Vista");
solaris = new Checkbox("Solaris");
mac = new Checkbox("Mac OS");
add(winXP);
add(winVista);
add(solaris);
add(mac);
// register to receive item events
winXP.addItemListener(this);
winVista.addItemListener(this);
solaris.addItemListener(this);
mac.addItemListener(this);
}
// Repaint when status of a check box changes.
public void itemStateChanged(ItemEvent ie) {
repaint();
}
// Display current state of the check boxes.
public void paint(Graphics g) {
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows XP: " + winXP.getState();
g.drawString(msg, 6, 100);
msg = " Windows Vista: " + winVista.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " Mac: " + mac.getState();g.drawString(msg, 6, 160);
}
}
BorderLayout()
BorderLayout(int horz, int vert)
The first form creates a default border layout. The second allows you to specify the horizontal
and vertical space left between components in horz and vert, respectively. BorderLayout
defines constants that specify the regions as BorderLayout.CENTER, BorderLayout.SOUTH,
BorderLayout.EAST, BorderLayout.WEST, BorderLayout.NORTH.
When adding components, you will use these constants with the following form of add( ),
which is defined by Container:
void add(Component compObj, Object region)
Here, compObj is the component to be added, and region specifies where the component will
be added. Here is an example of a BorderLayout with a component in each layout area:
// Demonstrate BorderLayout.
import java.awt.*;
import java.applet.*;
import java.util.*;
/*
<applet code="BorderLayoutDemo" width=400 height=200>
</applet>
*/
public class BorderLayoutDemo extends Applet {
public void init( ) {
setLayout(new BorderLayout());
add(new Button("This is across the top."),
BorderLayout.NORTH);
add(new Label("The footer message might go here."),
BorderLayout.SOUTH);
add(new Button("Right"), BorderLayout.EAST);
add(new Button("Left"), BorderLayout.WEST);
String msg = "The reasonable man adapts " + "himself to the world;\n" +
"the unreasonable one persists in " +
"trying to adapt the world to himself.\n" +
"Therefore all progress depends " +
"on the unreasonable man.\n\n" + " - George Bernard Shaw\n\n";
add(new TextArea(msg), BorderLayout.CENTER);
}
}
9. What is the purpose of layout managers? With an example explain the use
of Grid Layout.
Layout manager automatically arranges controls within a window by using some type of
algorithm. If you have programmed for other GUI environments, such as Windows, then you
are accustomed to laying out your controls by hand. While it is possible to lay out Java controls
by hand, too,you generally won‘t want to, for two main reasons. First, it is very tedious to
manually layout a large number of components. Second, sometimes the width and height
information is not yet available when you need to arrange some control, because the native
toolkit components haven‘t been realized.
Each Container object has a layout manager associated with it. A layout manager is an instance
of any class that implements the LayoutManager interface. The layout manager is set by the
setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used.
Whenever a container is resized (or sized for the first time), the layout manager is used to
position each of the components within it. The setLayout( ) method has the following general
form:
void setLayout(LayoutManager layoutObj)
GridLayout
GridLayout lays out components in a two-dimensional grid. When you instantiate a
GridLayout, you define the number of rows and columns. The constructors supported by
GridLayout are shown here:
GridLayout( )
GridLayout(int numRows, int numColumns)
GridLayout(int numRows, int numColumns, int horz, int vert)
The first form creates a single-column grid layout. The second form creates a grid layout with
the specified number of rows and columns. The third form allows you to specify the horizontal
and vertical space left between components in horz and vert, respectively. Either numRows or
numColumns can be zero. Specifying numRows as zero allows for unlimited- length columns.
Specifying numColumns as zero allows for unlimited-length rows. Here is a sample program
that creates a 4×4 grid and fills it in with 15 buttons, each labeled with its index:
// Demonstrate GridLayout
import java.awt.*;
import java.applet.*;
/*
<applet code="GridLayoutDemo" width=300 height=200>
</applet>
*/
public class GridLayoutDemo extends Applet {
static final int n = 4;
public void init( ) {
setLayout(new GridLayout(n, n));
setFont(new Font("SansSerif", Font.BOLD, 24));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}
}
10. Name the controls required for creating a menu. With an example explain the
creation of a menu.
=>A top-level window can have a menu bar associated with it. A menu bar displays a list of top-
level menu choices. Each choice is associated with a drop-down menu. This concept is
implemented in the AWT by the following classes:MenuBar,Menu, andMenuItem. In general,
a menu bar contains one or more Menu objects. EachMenu object contains a list of MenuItem
objects. Each MenuItem object represents something that can be selected by the user.
SinceMenu is a subclass ofMenuItem, a hierarchy of nested submenus can be created. It is also
possible to include checkable menu items. These are menu options of type CheckboxMenuItem
and will have a check mark next to them when they are selected. To create a menu bar, first
create an instance ofMenuBar. This class only defines the defaultconstructor. Next, create instances
ofMenu that will define the selections displayed on the
bar. Following are the constructors for Menu:
Menu( ) throws HeadlessException
Menu(String optionName) throws HeadlessException
Menu(String optionName, boolean removable) throws HeadlessException
Here, optionName specifies the name of the menu selection. If removable is true, the menu can
be removed and allowed to float free. Otherwise, it will remain attached to the menu bar.
(Removable menus are implementation-dependent.) The first form creates an empty menu.
Individual menu items are of typeMenuItem. It defines these constructors:
MenuItem( ) throws HeadlessException
MenuItem(String itemName) throws HeadlessException
MenuItem(String itemName, MenuShortcut keyAccel) throws HeadlessException
Here, itemName is the name shown in the menu, and keyAccel is the menu shortcut for this
item. You can disable or enable a menu item by using the setEnabled( ) method.
11. List and explain different methods associated with check boxes.
Here, newName becomes the new name of the invoking menu item. getLabel( ) returns the
current name. You can create a checkable menu item by using a subclass of MenuItem called
CheckboxMenuItem. It has these constructors:
CheckboxMenuItem( ) throws HeadlessException
CheckboxMenuItem(String itemName) throws HeadlessException
CheckboxMenuItem(String itemName, boolean on) throws HeadlessException
Here, itemName is the name shown in the menu. Checkable items operate as toggles. Each
time one is selected, its state changes. In the first two forms, the checkable entry is unchecked.
In the third form, if on is true, the checkable entry is initially checked. Otherwise, it is cleared.
You can obtain the status of a checkable item by calling getState( ). You can set it to a known
state by using setState( ). These methods are shown here:
boolean getState( )
void setState(boolean checked)
12. What is the purpose of TextField class? Explain any three methods of
TextField class with syntax and example.
=>The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste
keys, and mouse selections. TextField is a subclass of TextComponent. TextField defines the
following constructors:TextField( ) throws HeadlessException
TextField(int numChars) throws HeadlessException
TextField(String str) throws HeadlessException
TextField(String str, int numChars) throws HeadlessException
The first version creates a default text field. The second form creates a text field that is
numChars characters wide. The third form initializes the text field with the string contained in
str. The fourth form initializes a text field and sets its width.
TextField (and its superclass TextComponent) provides several methods that allow you to
utilize a text field. To obtain the string currently contained in the text field, call getText( ). To
set the text, call setText( ). These methods are as follows:
String getText( )
void setText(String str)
Here, str is the new string. The user can select a portion of the text in a text field. Also, you
can select a portion of text under program control by using select( ). Your program can obtain
the currently selected text by calling getSelectedText( ). These methods are shown here:
String getSelectedText( )
void select(int startIndex, int endIndex)
getSelectedText( ) returns the selected text. The select( ) method selects the characters
beginning at startIndex and ending at endIndex–1.
You can control whether the contents of a text field may be modified by the user by calling
setEditable( ). You can determine editability by calling isEditable( ). These methods are shown
here:
boolean isEditable( )
void setEditable(boolean canEdit)
isEditable( ) returns true if the text may be changed and false if not. In setEditable( ), if canEdit
is true, the text may be changed. If it is false, the text cannot be altered. There may be times
when you will want the user to enter text that is not displayed, such as a password. You can
disable the echoing of the characters as they are typed by calling setEchoChar( ). This method
specifies a single character that the TextField will display when characters are entered (thus,
the actual characters typed will not be shown). You can check a text field to see if it is in this
mode with the echoCharIsSet( ) method. You can retrieve the echo character by calling the
getEchoChar( ) method. These methods are as follows:
void setEchoChar(char ch)
boolean echoCharIsSet( )
char getEchoChar( )
Here, ch specifies the character to be echoed. Since text fields perform their own editing
functions, your program generally will not respond to individual key events that occur within
a text field. However, you may want to respond when the user presses ENTER. When this
occurs, an action event is generated. Here is an example that creates the classic user name and
password screen:
Long Answers
5. Explain the use of JTextField and any methods associate with it.
Ans.
JTextField is the simplest Swing text component. It is also probably its most widely used text
component. JTextField allows you to edit one line of text. It is derived from
JTextComponent, which provides the basic functionality common to Swing text components.
JTextField uses the Document interface for its model.
Three of JTextField‘s constructors are shown here:
JTextField(int cols) JTextField(String str, int cols)
JTextField(String str)
Here, str is the string to be initially presented, and cols is the number of columns in the text
field. If no string is specified, the text field is initially empty. If the number of columns is not
specified, the text field is sized to fit the specified string. JTextField generates events in
response to user interaction. For example, an ActionEvent is fired when the user presses
ENTER. ACaretEvent is fired each time the caret (i.e., the cursor) changes position.
(CaretEvent is packaged in javax.swing.event.) Other events are also possible. In many cases,
your program will not need to handle these events. Instead, you will simply obtain the string
currently in the text field when it is needed. To obtain the text currently in the text field, call
getText( ).
6. Explain the use of JList and any methods associated with it.
Ans.
In Swing, the basic list class is called JList. It supports the selection of one or more items
from a list. Although the list often consists of strings, it is possible to create a list of just
about any object that can be displayed. JList is so widely used in Java that it is highly
unlikely that you have not seen one before. JList provides several constructors. The one used
here is
JList(Object[ ] items)
This creates a JList that contains the items in the array specified by items. JList is based on
two models. The first is ListModel. This interface defines how access to the list data is
achieved. The second model is the ListSelectionModel interface, which defines methods that
determine what list item or items are selected. Although a JList will work properly by itself,
most of the time you will wrap a JList inside a JScrollPane. This way, long lists will
automatically be scrollable, which simplifies GUI design. It also makes it easy to change the
number of entries in a list without having to change the size of the JList component.
ListSelectionListener. This listener specifies only one method, called valueChanged( ), which
is shown here:
void valueChanged(ListSelectionEvent le)
Here, le is a reference to the object that generated the event. Although ListSelectionEvent
does provide some methods of its own, normally you will interrogate the JList object itself to
determine what has occurred. Both ListSelectionEvent and ListSelectionListener are
packaged in javax.swing.event.
By default, a JList allows the user to select multiple ranges of items within the list, but you
can change this behavior by calling setSelectionMode( ), which is defined by JList. It is
shown here:
void setSelectionMode(int mode)
Here, mode specifies the selection mode. It must be one of these values defined by
ListSelectionModel:
SINGLE_SELECTION SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION.
7. Explain the purpose of JButton and explain any methods associated with it.
Ans.
The JButton class provides the functionality of a push button. JButton allows an icon, a
string, or both to be associated with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str) JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button. When the button is pressed, an
ActionEvent is generated. Using the ActionEvent object passed to the actionPerformed( )
method of the registered ActionListener, you can obtain the action command string
associated with the button. By default, this is the string displayed inside the button. However,
you can set the action command by calling setActionCommand( ) on the button. You can
obtain the action command by calling getActionCommand( ) on the event object. It is
declared like this:
String getActionCommand( )
The action command identifies the button. Thus, when using two or more buttons within the
same application, the action command gives you an easy way to determine which button was
pressed.
8. With an example explain how to create a swing applet.
Ans.
The second type of program that commonly uses Swing is the applet. Swing-based applets
are similar to AWT-based applets, but with an important difference: ASwing applet extends
JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes all of the
functionality found in Applet and adds support for Swing. JApplet is a top-level Swing
container, which means that it is not derived from JComponent. Because JApplet is a top-
level container, it includes the various panes described earlier. This means that all
components are added to JApplet‘s content pane in the same way that components are added
to JFrame‘s content pane.
Swing applets use the same four lifecycle methods as init( ), start( ), stop( ), and destroy( ).
Of course, you need override only those methods that are needed by your applet. Painting is
accomplished differently in Swing than it is in the AWT, and a Swing applet will not
normally override the paint( ) method. All interaction with components in a Swing applet
must take place on the event dispatching thread, as described in the previous section. This
threading issue applies to all Swing programs.
9. Explain the use of JCheckBox and any methods associated with it.
Ans.
The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton, which provides support for two-state buttons, as just described. JCheckBox
defines several constructors. The one used here is JCheckBox(String str) It creates a check
box that has the text specified by str as a label. Other constructors let you specify the initial
selection state of the button and specify an icon. When the user selects or deselects a check
box, an ItemEvent is generated. You can obtain a reference to the JCheckBox that generated
the event by calling getItem( ) on the ItemEvent passed to the itemStateChanged( ) method
defined by ItemListener. The easiest way to determine the selected state of a check box is to
call isSelected( ) on the JCheckBox instance. In addition to supporting the normal check box
operation, JCheckBox lets you specify the icons that indicate when a check box is selected,
cleared, and rolled-over. We won‘t be using this capability here, but it is available for use in
your own programs.
10. Give one example for swing program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class classname implements ActionListener
{
Declare components;
classname()
{
JFrame jfrm=new JFrame("Frame name");
jfrm.setLayout(null);
jfrm.setSize(300,300);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
create components;
add components to frame;
}
}
Module IV
Multiple Choice Questions
Questions based on Understanding
1. In a JDBC program, a query is compiled when it is
A.Executed
B.Initialized
C.Prepared
D.Invoked
Answer: Option C
2. In order to transfer data between a database and an application written in the Java
programming language, the JDBC API provides which of these methods?
A. Methods on the ResultSet class for retrieving SQL SELECT results as Java types.
B. Methods on the PreparedStatement class for sending Java types as SQL statement
parameters.
C. Methods on the CallableStatement class for retrieving SQL OUT parameters as Java
types.
D. All mentioned above Answer: Option
D
3. The Acronym for the term UDA is
A. Unified Data Access
B. Universal Data Access
C. Universal Digital Access
D. Uniform Data Access
Answer: Option B
4. Which method is used to establish the connection with the specified url in a Driver
Manager class?
A. public static void registerDriver(Driver driver)
B. public static void deregisterDriver(Driver driver)
C. public static Connection getConnection(String url)
D. public static Connection getConnection(String url,String userName,String password)
Answer: Option C
5. Which driver Network connection is indirect that a JDBC client makes to a middleware
process that acts as a bridge to the DBMS server?
A. JDBC-Net
B. JDBC-ODBC bridge
C. Native API as basis
D. Native protocol as basis Answer:
Option A
6. JDBC technology-based drivers generally fit into how many categories?
A. 4
B. 3
C. 2
D. 5
Answer: Option A
7. JDBC stands for
A. Java database connectivity
B. Java database concept
C. Java database communications
D. Java Database convenience
Answer: Option A
8. Which class has traditionally been the backbone of the JDBC architecture?
A. the JDBC driver manager
B. the JDBC driver test suite
C. the JDBC-ODBC bridge
D. All mentioned above Answer: Option
A
9. How many steps are used to connect any java application using JDBC?
A. 5
B. 4
C. 3
D. 6
Answer: Option A
10. Name the class acts as an interface between user and drivers in JDBC
A. DriverClass
B. DriverManager
C. JDBCDriver
D. JDBCAppManager
Answer : Option B
11. In RMI Architecture which layer intercepts method calls made by the client/redirects these
calls to a remote RMI service?
A. Stub & Skeleton Layer
B. Application Layer
C. Remote Reference Layer
D. Transport Layer
Answer: Option A
12. The abbreviation of RMI is
A. Random Method Invocation
B. Remote Memory Interface
C. Remote Method Invocation
D. Random Method Invocation
Answer: Option C
13. RMI Architecture consists of how many layers?
A. 5
B. 3
C. 4
D. 2
Answer: Option C
14. Which program obtains a remote reference to one or more remote objects on a server and
then invokes methods on them in an RMI application?
A. Server
B. Client
C. Both A & B
D. Interface
Answer: Option B
15. Which is an object, acts as a gateway for the client side, all the outgoing requests are routed
through it and it resides at the client side and represents the remote object?
A. Stub
B. Skeleton
C. Both A & B
D. None of the above
Answer: Option A
4. Execute the query: The executeQuery() method of Statement interface is used to execute
queries to the database. This method returns the object of ResultSet that can be used to get
all the records of a table. Syntax of executeQuery() method public ResultSet
executeQuery(String sql)throws SQLException Example to wxwcute query ResultSet
rs=stmt.executeQuery("select * from emp"); while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
5. Close the connection object: By closing connection object statement and ResultSet will
be closed automatically. The close() method of Connection interface is used to close the
connection.
RMI Server The compute engine server accepts tasks from clients, runs the tasks, and returns
any results. The server code consists of an interface and a class. The interface defines the
methods that can be invoked from the client. Essentially, the interface defines the client's
view of the remote object. The class provides the implementation. RMI client. The compute
engine is a relatively simple program: it runs tasks that are handed to it. The clients for the
compute engine are more complex. A client needs to call the compute engine, but it also has
to define the task to be performed by the compute engine
Skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does the
following tasks:
It reads the parameter for the remote method
It invokes the method on the actual remote object, and
It writes and transmits (marshals) the result to the caller.
2. Define a connection in JDBC. Explain any four methods associated with it.
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. Commonly use methods of connection interface
1) public Statement createStatement(): creates a statement object that can be used to execute
SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a
Statement object that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it
is true.
4) public void commit(): saves the changes made since the previous commit/rollback
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
It initiates a connection with remote Virtual Machine (JVM),
It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
It waits for the result It reads (unmarshals) the return value or exception, and
It finally, returns the value to the caller.
a. Persistent cookie
b. Non-persistent cookie
c. All the above
d. None of the above
9. Which packages represent interfaces and classes for servlet API?
a. javax.servlet
b. javax.servlet.http
c. Both A & B
d. java.sevlet
10. What is the lifecycle of a servlet?
a. Servlet class is loaded
b. Servlet instance is created
c. init,Service,destroy method is invoked
d. All mentioned above
11. Which object is created by the web container at time of deploying the project?
a. ServletConfig
b. ServletContext
c. ServletGet
d. ServletPost
12. Which method in session tracking is used in a bit of information that is sent by a web server to
a browser and which can later be read back from that browser?
a. HttpSession
b. URL rewriting
c. Cookies
d. Hidden form fields
13. How many techniques are used in Session Tracking?
a. 4
b. 3
c. 2
d. 5
14. Which one of the following scopes does the attribute in servlet is an object that can be set, get
or removed?
a. session scope
b. request scope
c. application scope
d. All mentioned above
15. In HTTP Request what asks for the loopback of the request message, for testing or for
troubleshooting?
a. PUT
b. OPTIONS
c. DELETE
d. TRACE
16. What is javax.servlet.http.HttpServlet?
A - interface
B - abstract class
C - concreate class
D -Package
17. When service() method of servlet gets called?
A - The service() method is called when the servlet is first created.
B - The service() method is called whenever the servlet is invoked.
C - Both of the above.
D - The service() method is called when the servlet is destroyed
18. Which of the following code is used to get names of the attributes in servlet?
A - response.getAttributeNames()
B - request.getAttributeNames()
C - Header.getAttributeNames()
D – Query.getAttributeNames()
19. Which of the following code retrieves the query string that is contained in the request URL after
the path?
A - Header.getQueryString()
B - response.getQueryString()
C - request.getQueryString()
D – getQueryString()
20. How to create a cookie in servlet?
A - Use new operator.
B - Use request.getCookie() method
C - Use response.getCookie() method
D – Use request.setCookie() method
21. Which of the following code sends a cookie in servlet?
A - response.addCookie(cookie);
B - response.sendCookie(cookie);
C - response.createCookie(cookie);
D – request.createCookie(cookie);
22. HTTP is a protocol
A. Stateful
B. Stateless
C. Persistent
D. Non-persistent
23. Which of the following is/are examples of stateful sessions?
A. SSH
B. Telnet
C. FTP
D. All the above
24. Which of the following is NOT an example of stateful sessions?
A. SSH
B. Telnet
C. FTP
D. HTTP
25. Which of the following method in Java changes the name of the cookie?
A. public void setValue(String value)
B. public void setName(String value)
C. public void getValue(String value)
D. public void getName(String value)
1. Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing the
Servlet by the Servlet container. The Web container or Servlet Container can load the Servlet
at either of the following two stages:
Initializing the context, on configuring the Servlet with a zero or positive integer
value.
If the Servlet is not preceding stage, it may delay the loading process until the Web
container determines that this Servlet is needed to service a request.
The Servlet container performs two operations in this stage :
Loading: Loads the Servlet class.
Instantiation: Creates an instance of the Servlet. To create a new instance of the
Servlet, the container uses the no-argument constructor.
2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container
initializes the instantiated Servlet object. The container initializes the Servlet object by
invoking the Servlet.init(ServletConfig) method which accepts ServletConfig object
reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once, immediately
after the Servlet.init(ServletConfig) object is instantiated successfully. This method is used to
initialize the resources, such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.
3. Handling request: After initialization, the Servlet instance is ready to serve the client requests.
The Servlet container performs the following operations when the Servlet instance is located
to service a request:
a. It creates the ServletRequest and ServletResponse objects. In this case, if this
is a HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which are
subtypes of the ServletRequest and ServletResponse objects respectively.
b. After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the request
and response objects.
The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.
4. Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the
following operations:
It allows all the threads currently running in the service method of the Servlet instance
to complete their jobs and get released.
After currently running threads have completed their jobs, the Servlet container calls
the destroy() method on the Servlet instance.
3. Explain the Java methods used during the life cycle of a Servlet
There are three life cycle methods of a Servlet :
init()
service()
destroy()
1. init() method: The Servlet.init() method is called by the Servlet container to indicate that
this Servlet instance is instantiated successfully and is about to put into service.
Syntax:
//init() method
2. service() method: The service() method of the Servlet is invoked to inform the Servlet about
the client requests.
This method uses ServletRequest object to collect the data requested by the client.
This method uses ServletResponse object to generate the output content.
Syntax:
// service() method
3. destroy() method: The destroy() method runs only once during the lifetime of a Servlet and
signals the end of the Servlet instance.
Syntax:
//destroy() method
public void destroy()
As soon as the destroy() method is activated, the Servlet container releases the Servlet
instance.
Working of Cookies:
By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. Hence, a cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user
as the old user.
5. List and explain the different types of cookies available.
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
6. List any four commonly used methods of the Cookie class in Java
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
User A and User B both are requesting to connect to a server. The servlet container uses the
HttpSession interface to connect to the server by creating a unique id for each request. The unique
id is used to identify a user. The unique id can be stored in a request parameter or in a cookie.
Stateless session
Once the user is authenticated it maintains a token to do the further process, so there is no need
to maintain any channel between client and server, the client needs to re-authenticate if the token is
lost or expired.
Example: http protocol, all web based application.