0% found this document useful (0 votes)
30 views50 pages

Ajp CT2 QB

....................................................

Uploaded by

waghsam099
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views50 pages

Ajp CT2 QB

....................................................

Uploaded by

waghsam099
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

CHAPTER 3: Event Handling

Q. QUESTION
1. An event is generated when internal state of event source is________
A. Not change
B. changed
C. Either change or not
D. None of these
Answer: B

2. _______________method can be used to change location of event


A. changePoint()
B. translatePoint()
C. changeCoordinates()
D. translateCoordinates()
Answer: B

3. Identify the correct syntax


A. public void actionPerformed(ActionEvent ae)
B. public void ActionPerformed(ActionEvent ae)
C. public void actionPerformed(Action ae)
D. all are correct
Answer: A

4. Select proper sequence of following classes used for writing menudriven program:
1. Menu 2. MenuBar 3. MenuItem
A. 2,1,3
B. 1,2,3
C. 3,2,1
D. None Of The Above
Answer: A

5. Till now two models have been introduced in java for:


A. Receiving and processing events
B. Deleting and Processing events
C. Receiving and Deleting
D. Modifying and Rceiving
Answer: A

6. To handle all the events related to ScrollBar, the following method of AdjustmentListener needs
to be overriden.
A. public void adjustmentValueChanged(AdjustmentEvent obj)
B. public void adjustmentChanged(AdjustmentEvent obj)
C. public void actionPerformedActionEvent obj)
D. None of the above
Answer: A

7. What is the preferred way to handle an object's events in java?


A. Override the object's handleEvent() method.
B. Add one or more event listener to handle the events
C. Have the object override its processEvent() methods
D. Have the object override its dispatchEvent() methods
Answer: B

8. When a component loses keyboard focus ____________________this method is selected


A. void focusLost(FocusEvent fe)
B. void focusLoss(FocusEvent fe)
C. void lossfocus(FocusEvent fe)
D. non of the above
Answer: A

9. Which Event is /are handdled on List Component


A. ItemEvent
B. ActionEvent
C. Both A and B
D. Any of one depends on single click and double click
Answer: D

10. Which method is invoked when a component is resized


A. void componentResized(ComponentEvent ce)
B. compoResized(ComponentEvent ce)
C. void componentMoved(ComponentEvent ce)
D. void componentsized(ComponentEvent ce)
Answer: A

11. Which of the following are valid return types, for listener methods?
A. Boolean.
B. Void.
C. the type of event handled.
D.Component.
Answer: B

12. Which of the following components generate action events?


A. Buttons
B. Labels
C. Check boxes
D. Windows
Answer: A

13. Which of the following statements about anonymous inner classes is false?
A. They are declared without name
B. They typically appears in method declartion
C. They are declared with annonymous keyword
D. They can access their top level members
Answer: C

14. Which of these are constants defined in WindowEvent class?


A. WINDOW_ACTIVATED
B. WINDOW_CLOSED
C. WINDOW_DEICONIFIED
D. All of the mentioned
Answer: D

15. Which of these methods are used to register a mouse motion listener?
A. addMouseMotion()
B. addMouseListener()
C. addMouseMotionListener()
D. addMotionListener()
Answer: C

16. WindowListener interface belongs to which class?


A. WindowEvent
B. ComponentEvent
C. ContainerEvent
D. ItemEvent
Answer: A

17. You have created a simple Frame and overridden the paint method as follows
public void paint(Graphics g)
{ g.drawString("Dolly",50,10);
}
What will be the result when you attempt to compile and run the program?
A. The string "Dolly" will be displayed at the centre of the frame
B. The string "Dolly" will be shown at the Right of the form.
C. The word "Dolly" will be seen at the top-left of the form.
D. The string "Dolly" will be shown at the bottom of the form.
Answer: C

18. ____ method is called when a window is being closed.


A. windowClosed(WindowEvent we)
B. windowClosing(WindowEvent we)
C. windowDeactivated(WindowEvent we)
D. windowDeiconified(WindowEvent we)
Answer: B

19. _______ method is provided by AdjustmentListener.


A. adjusmentEvent()
B. adjustmentValueChanged()
C. getValue()
D. getAdjustmentValue()
Answer: B

20. _____ method belongs to which event KeyEvent class?


A. getKeyChar( ) and getkeyCode( )
B. readNumber() and readChar()
C. readKey() and readChar()
D. getKey() and getCode()
Answer: A

21. ___________________ generated when component is removed from container?


A. ComponentEvent
B. ContainerEvent
C. ActionEvent
D. ItemEvent
Answer: B
22. _________________defines one method to recognize when the state of the item changes.
A. ActionListener
B. AdjustmentListener
C. ItemListener
D. MouseListener
Answer: C

23. ______________method returns a reference to the component that was added to or removed
from the container.
A. getContainer()
B. getChild()
C. getValue()
D. None of these
Answer: B

24. _____________method returns a Point object that contains both X and Y coordinates.
A. getLocationOnScreen()
B. getXOnScreen()
C. getYOnScreen()
D. None of the above
Answer: A

25. ___________method returns a value that indicates which modifier keys were pressed when the
event was generated.
A. getModifiers()
B. setModifiers()
C. getActionCommand()
D. none of the above
Answer: A

26. An event adapter can be implemented using ______.


A. standard adapter
B. inner class adapter
C. anonymous inner class adapter
D. All of Above
Answer: D

27. Clicking the closing button on the upper-right corner of a frame generates a(n) __________ event.
A. ItemEvent
B. WindowEvent
C. MouseMotionEvent
D. ComponentEvent
Answer: B

28. Component listener can not be applicable to


A. Button, Choice
B. List, Scrollbar
C. Frame, Label
D Textfield, Text Area
Answer: C

29. From given list which is not method of Mouse Listener?


A. mouseClicked()
B. mousePressed()
C. mouseDragged()
D. mouseEntered()
Answer: C

30. KeyEvent is generated in which sequence.


A. Key typed,pressed,released
B. Key released,typed,pressed
C. Key pressed,typed,released.
D. Key pressed,released,typed
Answer: C

31. Pick the correct statement to register a button b for event handling
A. b.addActionListener(this);
B. b.addItemListener(this);
C. b.addMouseListener(this);
D. b.addFocusListener(this);
Answer: A

32. Suppose that you want to have an object 'eh' to handle the TextEvent of a TextArea object.How
should you add eh as the event handler to it.
A. t.addTextListener(eh)
B. eh.addTextListener(t)
C. addTextListener(eh,t)
D. addTextListener(t,eh)
Answer: A

33. The _________ interface handles list event?


A. ContainerListener
B. ItemListener
C. ActionListener
D. FocusListener
Answer: B

34. The following method is not a part of MouseMotionListener interface.


A. public void mouseClicked(MouseEvent obj)
B. public void mouseDragged(MouseEvent obj)
C. public void mouseMoved(MouseEvent obj)
D. None
Answer: A

35. To listen to mouse clicked events, the listener must implement the __________ interface or
extend the _______ adapter.
A. mouselistner / mouseadapter
B. mousemotionlistner / mousemotionadapter
C. WindowListener/WindowAdapter
D. ComponentListener/ComponentAdapter
Answer: A

36. Choose the correct Program for the following output


A. B.
import java.awt.*; import java.awt.*;
import java.awt.event.*; import java.awt.event.*;
import java.applet.*; import java.applet.*;
public class Fifth5 extends Applet implements public class Fifth5 extends Applet implements
ItemListener ItemListener
{ {
Checkbox cb1,cb2,cb3; Checkbox cb1,cb2,cb3;
CheckboxGroup cbg; CheckboxGroup cbg;
Label l1; Label l1;
public void init() public void init()
{ {
cbg=new CheckboxGroup(); cbg=new CheckboxGroup();
cb1=new Checkbox("C cb1=new Checkbox("C
programming",cbg,false); programming",cbg,false);
cb2=new Checkbox("C++ cb2=new Checkbox("C++
programming",cbg,true); programming",cbg,true);
cb3=new Checkbox("Java cb3=new Checkbox("Java
programming",cbg,false); programming",cbg,false);
l1=new Label("Before ItemSelection"); l1=new Label("Before ItemSelection");
add(cb2); add(cb1);
add(cb3); add(cb2);
add(l1); add(cb3);
}} } }

C. D.
import java.awt.*; import java.awt.*;
import java.awt.event.*; import java.awt.event.*;
import java.applet.*; import java.applet.*;
public class Fifth5 extends Applet implements public class Fifth5 extends Applet implements
ItemListener ItemListener
{ {
Checkbox cb1,cb2,cb3; Checkbox cb1,cb2,cb3;
CheckboxGroup cbg; CheckboxGroup cbg;
Label l1; Label l1;
public void init() public void init()
{ {
cbg=new CheckboxGroup(); cbg=new CheckboxGroup();
cb1=new Checkbox("C cb1=new Checkbox("C
programming",cbg,false); programming",cbg,false);
cb2=new Checkbox("C++ cb2=new Checkbox("C++
programming",cbg,false); programming",cbg,true);
cb3=new Checkbox("Java cb3=new Checkbox("Java
programming",cbg,false); programming",cbg,false);
l1=new Label("Before ItemSelection"); l1=new Label("Before ItemSelection");
add(cb1); add(cb1);
add(cb2); add(cb2);
add(cb3); add(cb3);
add(l1); add(l1);
} } } }

Answer: D

37. Complete the code to display the selected item of the list.
/* <applet code="MyControl11" width=300 height=300> </applet> */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MyControl11 extends Applet implements ItemListener
{
List list;
Label l;
public void init()
{
list=new List();
l=new Label();
list.add("one");
list.add("two");
list.add("three");
setLayout(null);
list.setBounds(20,20,100,20);
l.setBounds(20,150,100,20);
add(list);
add(l);
list.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
________________________
} }
A. List.getSelectedObjects();
B. l.setText(list.getSelectedItem());
C. label.setText(list.getSelectedItem());
D. list.getItem();
Answer: B

38. Consider following output. Find missing statement from following code.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class keyEp extends Applet implements KeyListener
{
String msg=" ";
int x=10, y=20;
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("key pressed");
int kl=k.getKeyCode();
switch(kl)
{
case KeyEvent.VK_LEFT:
msg+="<left arrow>";
break;
case KeyEvent.VK_RIGHT:
msg+="<right arrow>";
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("key up");
}
public void keyTyped(KeyEvent l)
public void paint(Graphics g)
{
g.drawString(msg,x,y);
} }

A. Missing }
B. Missing ;
C. Missing ( )
D. Missing{}
Answer: D

39. Consider the following code.Which constructor of Checkbox class is used.


/* <applet code="CheckDemo.class" width =100 height=200> </applet> */
import java.awt.*;
import java .applet.*;
import java .awt.event.*;
public class CheckDemo extends Applet implements ItemListener
{
Checkbox c1,c2,c3;
public void init()
{
c1=new Checkbox ("C");
c2=new Checkbox("c++");
c3=new Checkbox("Java");
add(c1);
add(c2);
add(c3);
c1.addItemListener(this);
c3.addItemListener(this);
c3.addItemListener(this);
}
public void paint(Graphics g)
{
g.drawString ("Language selected",10,80);
g.drawString ("C :"+c1.getState(),10,100);
g.drawString("C++ :"+c2.getState(),10,120);
g.drawString("Java :"+c3.getState(),10,140);
}
public void itemStateChanged(ItemEvent ie)
{
repaint();
} }
A. Parameterised constructor
B. Default constructor
C. Both i and ii
D. None of the above
Answer: A

40. Consider the following output. Find the missing statement in the program.
import java.awt.Frame;
import java.awt.event.*;
public class HandleMouseListenerInWindowExample extends Frame implements MouseListener{
int x=0, y=0;
String strEvent = "";
HandleMouseListenerInWindowExample(String title){
super(title);
addWindowListener(new MyWindowAdapter(this));
addMouseListener(this);
setSize(300,300);
setVisible(true); }
public void mouseClicked(MouseEvent e) {
strEvent = "MouseClicked";
x = e.getX();
y = getY();
repaint(); }
public void mouseReleased(MouseEvent e) {
strEvent = "MouseReleased";
x = e.getX();
y = getY();
repaint(); }
public void paint(Graphics g){
g.drawString(strEvent + " at " + x + "," + y, 50,50); }
public static void main(String[] args) {
HandleMouseListenerInWindowExample myWindow =
new HandleMouseListenerInWindowExample("Window With Mouse Events Example");
} }
class MyWindowAdapter extends WindowAdapter{
HandleMouseListenerInWindowExample myWindow = null;
MyWindowAdapter(HandleMouseListenerInWindowExample myWindow){
this.myWindow = myWindow;
}
public void windowClosing(WindowEvent we){
myWindow.setVisible(false);
}

A. B.
public void mouseExited(MouseEvent e) { public void mouseEntered(MouseEvent e) {
strEvent = "MouseExited"; strEvent = "MouseEntered";
x = e.getX(); x = e.getX();
y = getY(); y = getY();
repaint(); } repaint(); }

C. D.
public void mousePressed(MouseEvent e) { All of the Above
strEvent = "MousePressed";
x = e.getX();
y = getY();
repaint(); }

Answer: D

41. Consider the following output. Find the missing statement in the program.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/* <applet code="SimpleKey1" width=300 height=100> </applet> */
public class SimpleKey1 extends JApplet implements KeyListener
{
String msg = "";
int X = 10, Y = 20;
public void init()
{
addKeyListener(this);
requestFocus(); }
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down"); }
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up"); }
public void keyTyped(KeyEvent ke)
{
msg += ke.getKeyChar(); }
public void paint(Graphics g)
{
g.drawString(msg, X, Y); }
}
A. paint();
B. paintGraphics()
C. repaint();
D. None of these
Answer: C

42. Consider the following program. What correction should be done in the program to get correct
output?
import java.applet.*;
import java.awt.event.*;
/* <APPLET Code="SimpleKey" Width=200 Height=250> </APPLET> */
public class SimpleKey extends Applet implements KeyListener
{
String msg="";
int X=10,Y=20;
public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
showStatus("Key Down");
}
public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent ke)
{
msg +=ke.getKeyChar();
repaint();
}
public void paint (Graphics g)
{
}
A. Missing {
B. Missing }
C. Missing statement
D. Missing semicolon
Answer: B

43. Consider the following program. Choose the missing statements to get correct output.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
{
List year, branch;
public void init()
{
add(new Label("Select year and branch:"));
year=new List(3);
branch=new List(5);
year.add("First Year");
year.add("Second Year");
year.add("Third Year");
add(year);
branch.add("AE");
branch.add("CO");
branch.add("EE");
branch.add("EJ");
branch.add("IF");
branch.add("ME");
add(branch);
}
public void paint(Graphics g)
{
g.drawString("You selected: "+year.getSelectedItem()+" "+branch.getSelectedItem(),10, 160);
}}

A. B.
public class Sample extends Applet implements public class Sample extends Applet implements
ItemListener ActionListener
year.addItemListener(this); year.addActionListener(this);
branch.addItemListener(this); branch.addActionListener(this);
public void itemStateChanged(ItemEvent ie) public void actionPerformed(ActionEvent ae)
{ {
repaint(); repaint();
} }

C. D.
public class Sample extends Applet implements public class Sample extends Applet implements
AdjustmentListener WindowListener
year.addAdjustmentListener(this); year.addWindowListener(this);
branch.addAdjustmentListener(this); branch.addWindowListener(this);
public void itemStateChanged(AdjustmentEvent public void windowActivated(WindowEvent we)
ae) {
{ repaint();
repaint(); }
}

Answer: A

44. Consider the following program. Find which statement contains error.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code = "PasswordAL.java" width = 600 height=600></applet>*/
public class PasswordAL extends Applet implements ActionListener
{
Button b1; String msg;
TextField t1;
public void init()
{
b1 = new Button("Click ME");
b1.addActionListener(this);
add(b1);
msg ="Wait";
t1 = new TextField(10);
t1.setEchoChar('#');
add(t1); }
public void actionPerformed()
{
String t;
t = ae.getActionCommand();
if(t.equals("Click ME") )
{
t = t1.getText();
if(t.equals("java") )
msg = "Correct";
else
msg="Wrong";
repaint();
} }
public void paint(Graphics g)
{
g.drawString(msg,200,200);
} }
A. error in the statement where ActionListener is implemented
B. error in the statement where getActionCommand is called
C. error in the statement where public void actionPerformed() method is called
D. None of the above
Answer: C

45. Correct code of the output window is


A. public class TestDemo extends JApplet B. public class TestDemo extends JApplet
{ {
public void init() public void init()
{ {
JButton b = new JButton("Button"); JButton b = new JButton("Button");
Container c = getContentPane(); Container c = getContentPane();
c.setLayout(new FlowLayout()); c.add(b);
c.add(b); }
} }
}

C. public class TestDemo extends JApplet D public class TestDemo extends JApplet
{ {
public void init() public void init()
{ {
JButton b = new JButton("Button"); JButton b = new JButton("Button");
Container c = getContentPane(); c.setLayout(new FlowLayout());
c.setLayout(new FlowLayout()); c.add(b);
} }
} }

Answer: A

46. Debug following program and find out the error


import java.io.*;
import java.lang.*;
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class ButtonDemoError extends Applet implements ActionListener
{
Button square;
Label num1;
TextField n1;
public void init()
{
square=new Button("square");
num1=new Label("Enter number");
n1=new TextField(15);
add(num1);
add(n1);
add(square);
square.addActionListener(this);
}
public void actionPerformed (ActionEvent ae)
{
String str=ae.getActionCommand();
String no1=n1.getText();
int a=Integer.parseInt(no1);
int result=a*a;
msg="square number-"+result;
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,100,100);
} }
/*<Applet code="ButtonDemo" width=300 height=300> </Applet>*/

A. statement missing semicolon ;


B. Cannot find symbol ‘msg’
C. cannot accessed 'msg'
D undefined symbol num1
Answer: B

47. Debug the following code and find which statement contains error.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class DemoAdjustmentEvent extends Applet
implements AdjustmentListener
{
Scrollbar sbRed,sbGreen,sbBlue;
public void init()
{
sbRed=new Scrollbar(Scrollbar.VERTICAL,20,10,0,255);
sbGreen=new Scrollbar(Scrollbar.VERTICAL,20,10,0,255);
sbBlue=new Scrollbar(Scrollbar.VERTICAL,20,10,0,255);
add(sbRed);add(sbGreen);add(sbBlue);
sbRed.addAdjustmentListener(this);
sbGreen.addAdjustmentListener(this);
sbBlue.addAdjustmentListener(this);
}
public void itemStateChanged(AdjustmentEvent ae)
{
int r=sbRed.getValue();
int g=sbGreen.getValue();
int b=sbBlue.getValue();
Color c=new Color(r,g,b);
setBackground(c);
}}
/*<applet codebase="DemoAdjustmentEvent.class" width=300 height=300></applet>*/
A. Error in statement were itemStateChanged( ) method is defined
B. Error in <applet> tag
C. Error in statement were Scrollbar sbRed is created
D. Both A and B
Answer: A

48. Fill in the blank from the given option


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class CircleListener extends MouseAdapter
{
private int radius = 25;
public void __________________(MouseEvent event)
{
Applet app = (Applet)event.getSource();
Graphics g = app.getGraphics();
g.fillOval(event.getX()-radius,event.getY()-radius,2*radius,2*radius);
} }
A. mousePressed()
B. mouseReleased()
C. mouseDragged()
D. mouseClick()
Answer: A

49. Find out the Error statement


import java.applet.*;
import java.awt.event.*;
/* <applet code="InnerClassDemo" width=200 height=100> </applet> */
public class InnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter());
}
class MyMouseAdapter
{
public void mousePressed(MouseEvent me)
{
showStatus("Mouse Pressed");
} } }
A. public class InnerClassDemo extends Applet
B. addMouseListener(new MyMouseAdapter()); class MyMouseAdapter
C. public void mousePressed(MouseEvent me) {
D. none of the above
Answer: B

50. For the following code select the listener implemented by class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* <applet code="JRadioEvent" width=300 height=100> </applet> */
public class JRadioEvent extends JApplet implements ______________
{
ButtonGroup grp;
JRadioButton red,pioonk,green;
JTextArea ta;
public void init()
{
setLayout(new FlowLayout());
ta=new JTextArea(5,10);
setupButtons();
addListeners();
add(red);
add(pink);
add(green);
add(ta);
}
public void setupButtons()
{
red=new JRadioButton("Red");
pink=new JRadioButton("Pink");
green=new JRadioButton("Green");
grp=new ButtonGroup();
grp.add(red);
grp.add(pink);
grp.add(green);
}
public void addListeners()
{
red.addItemListener(this);
pink.addItemListener(this);
green.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
Object src=ie.getSource();
if(ie.getStateChange()==ItemEvent.SELECTED)
{
if(src==red)
ta.append("We like Redn");
else if(src==pink)
ta.append("We like Pink n");
else
ta.append("We like Green n");
} } }
A. ActionListener
B. ComponentListener
C. ItemListener
D. MouseListener
Answer: A
CHAPTER 4: Networking
Q. QUESTION
1. -------is protocol
A. netnews
B. finger
C. e-mail
D. all of the above
Answer: D

2. ___________method of DatagramPacket is used to find the port number.


A. port()
B. GetPort()
C. getPort()
D. findPort()
Answer: C

3. boolean equals(Object other) will return_______


A. Returns true if object has same internet
address as other.
B. Returns False if object has same internet
address as other.
C. Returns true if object has not same
internet address as other.
D. Returns null if object has same internet
address as other.
Answer: A

4. Connection timed out exception is occurred _________


A. if client socket is not created
B. if serversocket does not accept client
request
C. if port number is not available which is
specified by client socket with host name
D. None of the above
Answer: B

5. ContentHandler , MulticastSocket , URL, SocketImpl are examples of --------


A. package
B. class
C. Interface
D. Method
Answer: B

6. DatagramPacket has ----------- methods


A. int getPort()
B. byte[] getData()
C. int getLength()
D. All of the above
Answer: D

7. getAllByName() method returns an array of_____________ that represents all of the addresses
that specific host name has
A. host names
B. InetAddresses
C. ipaddresses
D. objects
Answer: B

8. getExpiration( ) method present in which class?


A. URL
B. URLDecoder
C. URLConnection
D. none of the above
Answer: C

9. getHostName() of InetAddress class is used to_______


A. Return a string that represents host name
associated with Inetaddress object.
B. Return a string that represents host
address associated with Inetaddress
object.
C. Return an object that represents Ipaddress
associated with host name .
D. Return Ipaddress that is associated with
InetAddress object .
Answer: A

10. How many bits are in a single IP address?


A. 8
B. 16
C. 32
D. 64
Answer: C

11. If server socket is created using serversocket () constructer then which method should we use to
bind the serve socket ?
A. isbind()
B. bind()
C. bind To()
D. bind ( socketAddress host , int backlog)
Answer: D

12. import java.net.ServerSocket; In above statement ServerSocket is -----------


A. package
B. Class
C. Interface
D. method
Answer: B

13. In Uniform Resource Locator (URL), path is pathname of file where information is
A. Stored
B. Located
C. to be transferred
D. Transferred
Answer: A

14. InetAddress also Includes a factory method called____


A. getByAddress()
B. getHostName()
C. getAddress()
D. getIPAddress()
Answer: A

15. Internet Protocol is


A. Low level routing protocol
B. Middle level routing protocol
C. Higher level routing protocol
D. None of above
Answer: A

16. Socket s1= Socket ( localhost, 1346), What does it means ?


A. Client socket is waiting for connection
B. Client socket is created to connect with
specified host name and port number
C. Client socket is name as localhost and Port
number is 1346
D. server socket is connected to local host
with port number 1346
Answer: B

17. TCP,FTP,Telnet,SMTP,POP etc. are examples of ?


A. Socket
B. IP Address
C. Protocol
D. MAC Address
Answer: C

18. TCP/IP style of networking provides ------------------


A. serialized stream of packet data
B. predictable stream of data
C. reliable stream of data
D. All of the above
Answer: D

19. The getByName() method returns an ________________ with host name


A. IP address
B. InetAddress Object
C. port number
D. IPv4
Answer: B

20. Unlike User Datagram Protocol (UDP), Transmission Control Protocol (TCP) has Services which is
A. Connection Oriented
B. Connectionless
C. Connection Available
D. Connection Origin
Answer: A

21. URLConnection class present in which package?


A. url
B. Urlconnection
C. URL
D. .net
Answer: D

22. What does URL stands for?


A. Uniform Resource Locator
B. Uniform Resource Latch
C. Universal Resource Locator
D. Universal Resource Latch
Answer: A

23. What happens if server socket is not able to listen on specified port ?
A. The system exits gracefully with
appropriate message
B. The system will wait till port is free.
C. IOExeption is thrown when opening the
socket
D. PortOccupiedException is thrown.
Answer: C

24. What is the output of following statement?


Socket s1=new Socket("localhost",1234);
System.out.println(s1.getRemoteSocketAddress());
A. IPAddress of client with port number
B. host name, IPAddress and port number of Serversocket
C. host name and IPAddress Serversocket
D. IPAddress of server with port number
Answer: D

25. When you will use this ServerSocket(int port, int que) constructor to create server socket
A. to create ServerSocket with port number
B. to create ServerSocket with port number & Ip address
C. to create ServerSocket with port number and number of incoming client queue
D. B&C
Answer: C

26. If port number is not specified in the URL, getPort() method returns _______
A. -1
B. 8080
C. 80
D. 25
Answer: A

27. If server socket is created using serversocket() constructer then which method should we use to
bind the serve socket?
A. isbind()
B. bind()
C. bindTo()
D. bind(socketAddress host , int backlog)
Answer: D

28. If you use either Telnet or FTP, which is the highest layer you are using to transmit data?
A. Application
B. Presentation
C. Session
D. Transport
Answer: A

29. import java.net.ServerSocket; In above statement ServerSocket is -----------


A. package
B. Class
C. Interface
D. method
Answer: B

30. In Uniform Resource Locator (URL), path is pathname of file where information is
A. Stored
B. Located
C. to be transferred
D. Transferred
Answer: A

31. InetAddress also Includes a factory method called____


A. getByAddress()
B. getHostName()
C. getAddress()
D. getIPAddress()
Answer: A

32. Internet Protocol is


A. Low level routing protocol
B. Middle level routing protocol
C. Higher level routing protocol
D. None of above
Answer: A

33. Is it possible to get the Local host IP?


A. by using InetAddress's getLocalHost() method
B. by using InetAddress's printLocalHost() method
C. by using InetAddress's LocalHost() method
D. none of the above
Answer: A

34. Java.net package consist of interface _______


A. ContentHandlerFactory
B. SocketImplFactory
C. FileNameMap and URLStreamHandlerFactory.
D. All of above
Answer: D

35. java.net.URL provides following methods


A. getProtocol(),getHost()
B. A & C
C. int address
D. none
Answer: A

36. For the following client side code of TCP implementation of sockets, what should be the server
side code in order to establish connection between both the machines?
import java.io.IOException;
import java.net.*;
public class Client
{
public static void main(String[] args) throws UnknownHostException, IOException
{
Socket sock=new Socket("127.0.0.1",2000);
}
}
A. B.
import java.io.IOException; import java.io.IOException;
import java.net.*; import java.net.*;
public class Server public class Server
{ {
public static void main(String[] args) public static void main(String[] args)
throws IOException throws IOException
{ {
ServerSocket ss=new ServerSocket(2000); ServerSocket ss=new ServerSocket();
Socket sock=ss.accept(); Socket sock=new Socket(2000);
System.out.println("Connection System.out.println("Connection
Established"); Established");
} }
} }

C. D.
import java.io.IOException; import java.io.IOException;
import java.net.*; import java.net.*;
public class Server public class Server
{ {
public static void main(String[] args) public static void main(String[] args)
throws IOException throws IOException
{ {
ServerSocket ss=new ServerSocket(2000); ServerSocket ss=new ServerSocket(2000);
System.out.println("Connection Socket sock=ssop.accept();
Established"); System.out.println("Connection
} Established");
} }
}
Answer: A

37. How do I make a connection to URL?


A. B.
URL url; try
URLConnection connection; {
try url = new URL("...");
{ conection = url.openConnection();
url = new URL("..."); }
conection = url.openConnection(); catch (MalFormedURLException e)
} {}
catch (MalFormedURLException e)
{}

C. D.
URL url; None of the above
try
{
url = new URL("...");
conection = url.openConnection();
}
catch (MalFormedURLException e)
{}
Answer: A

38. Identify the factory methods of InetAddress Class:


A. B.
static InetAddress[ ] getAllByName(String static InetAddress getByName(String
hostName) throws UnknownHostException hostName) throws UnknownHostException

C. D.
static InetAddress getLocalHost( ) throws All of the mentioned
UnknownHostException

Answer: D

39. Choose the correct output for the program.


import java.io.*;
import java.net.*;
class demo
{
public static void main(String args[]) throws MalformedURLException
{
URL a=new URL("http://www.msbte.com:/index.html");
System.out.println("port :"+a.getPort());
}
}
A. port : 80
B. 0
C. -1
D. port : -1
Answer: D

40. Choose the correct output for the program.


import java.net.*;
class networking1
{
public static void main(String[] args) throws UnknownHostException
{
InetAddress obj1 = InetAddress.getByName("WWW.google.com");
InetAddress obj2 = InetAddress.getByName("www.google.com");
boolean x = obj1.equals(obj2);
System.out.print(x);
}
}
A. TRUE
B. FALSE
Answer: A

41. In following Java program fill statement showing ***. Select any one option from given options.
class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
******************
System.out.println(""Protocol :""+netAddress.getProtocol());
System.out.println(""Port :""+netAddress.getPort());
System.out.println(""Host :""+netAddress.getHost());
System.out.println(""File :""+netAddress.getFile());
}
}
A. URL netAddress=new URL(http://www.sun.com.8080//index.html);
B. URL netAddress=new URL(http://www.sun.com.//index.html);
C. URL netAddress=new URL(http://www.sun.com//*.html);
D. URL net=new URL(http://www.sun.com.8080//index.html)
Answer: B

42. In following java program fill statement showing *****. Select any one option from given options.
import java.net.*;
public class InetDemo
{
public static void main(String[] args)
{
try
{
InetAddress ip=InetAddress.****************
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
A. getByName();
B. getByName("www.msbte.com");
C. getName( );
D. getName("www.msbte.com");
Answer: B

43. In the following code, what type of protocol is Socket object "skt" uses?
import java.io.*;
import java.net.*;
public class NetClient
{
public static void main(String args[]) throws Exception
{
Socket skt = new Socket("host",88);
}
}
A. Connectionless
B. FTP
C. UDP
D. TCP
Answer: D

44. In the following program choose the correct strings from given options to pass in URL constructor
to get an output without any exception.
import java.net.*;
class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("__________");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
}
}
a) http://www.msbte.com/mainsite/index.php
b) http://www.msbte.com:80/mainsite/index.php
c) www.msbte.com/
d) www.msbte.com/mainsite/index.php

A. Only a
B. Only b
C. Either a or b
D. All
Answer: C

45. Select Correct output


import java.net.*;
class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("https://www.google.com/downloads");
System.out.println("Protocol: "+hp.getProtocol());
System.out.println("Port: "+hp.getPort());
System.out.println("Host: "+hp.getHost());
System.out.println("File: "+hp.getFile());
System.out.println("Ext: "+hp.toExternalForm());
}
}
A. B.
Protocol: https Protocol: https
Port: -1 Port: -1
Host: localhost Host: www.google.com
File: /downloads File: /downloads
Ext: https://www.google.com/downloadsv Ext: https://www.google.com/downloads

C. D.
Protocol: https Protocol: https
Port: -1 Port: -1
Host: www.google.com Host: www.google.com
File: /downloads File: google
Ext: https://www.google.com

Answer: B

46. Select missing statement in following code?


import java.io.*;
import java.net.*;
public class InetDemo
{
public static void main(String[] args)
{
try
{
----------------------------
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
A. InetAddress ip=InetAddress.getByName("www.msbte.com");
B. InetAddress ip=InetAddress.getName("www.msbte.com");
C. InetAddress ip=InetAddress.Name("www.msbte.com");
D. InetAddress =InetAddress.getByName("www.msbte.com");
Answer: A

47. Select proper output for the following program:-


import java.net.*;
class InetAddressTest
{
public static void main(String args[])throws UnknownHostException
{
InetAddress add=InetAddress.getLocalHost();
System.out.println(add);
add=InetAddress.getByName("osborne.com");
System.out.println(add);
InetAddress sw[]=InetAddress.getAllByName("www.google.com");
for(int i=0;i<sw.length;i++)
{
System.out.println(sw[i]);
}
}
}
A.

B.

C.

D.

Answer: C
48. Select the source code to display following output.

A. B.
import java.net.*; import java.net.*;
class NetworkDemo class NetworkDemo
{ {
public static void main(String args[]) public static void main(String args[]) throws
{ UnknownHostException
InetAddress ip[]=InetAddress.getAllByName {
("www.yahoo.com"); InetAddress ip[]=InetAddress.getAllByName
for(int i=0;i<ip.length;i++) ("www.yahoo.com");
{ for(int i=0;i<ip.length;i++)
System.out.println(ip[i].getHostAddress()); {
} System.out.println(ip[i].getHostAddress());
} }
} }
}
C. D.
import java.net.*; import java.net.*;
class NetworkDemo class NetworkDemo
{ {
public static void main(String args[]) throws public static void main(String args[]) throws
UnknownHostException UnknownHostException
{ {
InetAddress ip[]=InetAddress.getByName InetAddress ip=InetAddress.getByName
("www.yahoo.com"); ("www.yahoo.com");
for(int i=0;i<ip.length;i++) System.out.println(ip[i].getHostAddress());
{ }
System.out.println(ip[i].getHostAddress()); }
}
}
}
Answer: B

49. The following Server program _____________________


import java.net.*;
import java.io.*;
public class Server
{
public static void main(String args[]) throws IOException
{
ServerSocket ss = new ServerSocket(2000);
while(true)
{
Socket cs = ss.accept();
PrintWriter pw = new PrintWriter(cs.getOutputStream());
pw.println("welcome");
pw.close();
}
}
}
A. waits for client request at 2000 port number and accepts welcome message from all clients
B. waits for client request at 2000 port number and sends welcome message to all clients
C. All of the mentioned
D. None of the mentioned
Answer: B

50. What correction should be done in the program to get correct output?
import java.net.*;
import java.io.*;
public class URLTest
{
public static void main(String args[]) throws MalformedURLException
{
URL url = new URL("http://www.msbte.com/download");
System.out.println("Protocol:"+ url1.getProtocol());
System.out.println("Port:"+ url1.getPort());
System.out.println("Host:"+ url1.getHost());
System.out.println("File:"+ url1.getFile());
}
}
A. Exception type is wrong.
B. Class should not be public.
C. Creation of object is not correct.
D. Use of created object not correct
Answer: D

CHAPTER 5: Databases
Q. QUESTION
1. Can we retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX
method for each column ?
A. No
B. Yes
C. Statement is incorrect
D. None of the above
Answer: A

2. A programmer uses a Java class known as ___________ to connect to a database


A. JDBC driver
B. Package
C. JDBC Interface
D. none of the Above
Answer: A

3. How can you execute a stored procedure in the database?


A. Call method execute() on a
CallableStatement object
B. Call method executeProcedure() on a
Statement object
C. Call method execute() on a
StoredProcedure object
D. Call method run() on a
ProcedureCommand object
Answer: A

4. How can you retrieve information from a ResultSet?


A. By invoking the method get(“ ”, String
type) on the ResultSet, where type is the
database type
B. By invoking the method get(“ ”, Type type)
on the ResultSet, where Type is an object
which represents a database type
C. By invoking the method getValue(“ ”), and
cast the result to the desired Java type
D. By invoking the special getter methods on
the ResultSet: getString(“ ”), getBoolean (“
”), getClob(“ ”)
Answer: D

5. Identify Correct Syntax for following method of ResultSet ______ absolute (______);
A. boolean, int
B. boolean, void
C. void, int
D. void, void
Answer: A

6. INSERT, DELETE, UPDATE comes under ?


A. Data Modification Language
B. Data Definition Language
C. Data Control Language
D. Data Manipulation Language
Answer: D

7. Methods of ResultSet throws ...... exception.


A. IOException
B. SQLException
C. MethodNotFoundException
D. ResultSetException
Answer: B

8. Native API converts ____________ into the ________________ used by DBMS.


A. JDBC API, network protocol
B. JDBC API, Native API calls
C. JDBC API, User call
D. JDBC API, ODBC API calls
Answer: B

9. PreparedStatement interface extends which interface?


A. Statement
B. CallableStatement
C. None of the above
D. ResultSet
Answer: A

10. The JDBC interface is contained in the......


A. java.sql Package
B. javax.sql Package
C. Both of the Above
D. None of the Above
Answer: C

11. Type of server in two-tier architectures which provides data to client stored on disk pages is called
A. transaction server
B. functional server
C. disk server
D. data server
Answer: D

12. What happens if you call the method close() on a ResultSet object?
A. the method close() does not exist for a
ResultSet. Only Connections can be
closed.
B. the database and JDBC resources are
released
C. you will get a SQLException, because only
Statement objects can close ResultSets
D. the ResultSet, together with the
Statement which created it and the
Connection from which the Statement
was retrieved, will be closed and release
all database and JDBC resources
Answer: B

13. Which are the parameters of setString() method?


A. String value,String paramIndex
B. String paramIndex, String value
C. int paramIndex, int value
D. int paramIndex, String value
Answer: D

14. Which driver is known as Network Protocol, Pure Java Driver?


A. Type 1
B. Type 2
C. Type 3
D. Type 4
Answer: C

15. Which method is used to perform DML statements in JDBC?


A. execute()
B. executeQuery()
C. executeUpdate()
D. executeResult()
Answer: C
16. Which method returns the current result as Resultset object.
A. execute()
B. executeQuery()
C. getResult()
D. getResultSet()
Answer: B

17. Which of the following is FALSE with reference to JDBC Driver


A. All drivers implements the java.sql.Driver
interface.
B. driver classes are not supplied by the
database vendor
C. Driver class return a java.sql.Connection
object.
D. None of the Above
Answer:

18. Which of the Following is NOT a valid Syntax for getConnection() Method
A. public static Connection
getConnection(String url)
B. public static Connection
getConnection (String url, String
userID, String password)
C. public static Connection
getConnection(jdbc:<subprotocol>:
<subname>, String userID, String
password)
D. None of the Above
Answer: C

19. Which of the following query is use for select query?


A. execute()
B. execute(String sql)
C. executeUpdate(String sql)
D. executeQuery(String sql)
Answer: D

20. Which one is the correct syntax for creating a Statement?


A. Statement stmt =
connection.createStatements();
B. Statement stmt =
connection.preparedStatement();
C. Statement stmt =
connection.createStatement();
D. none of these
Answer: C

21. Which type of Driver communicate using a network protocol to a middleware server
A. Type 1 Driver
B. Type 2 Driver
C. Type 3 Driver
D. Type 4 Driver
Answer: C

22. ________ is an open source DBMS product that runs on UNIX, Linux and Windows.
A. MySQL
B. JSP/SQL
C. JDBC/SQL
D. Sun ACCESS
Answer: A

23. _____interface allows storing results of query?


A. Statement
B. Connection
C. ResultSet
D. None of the above
Answer: C

24. Application program interface in two tier architecture database management system is provided
by the
A. close module connectivity
B. open module connectivity
C. close database connectivity
D. open database connectivity
Answer: D

25. The _____________ method executes an SQL statement that may return multiple results.
A. executeUpdate()
B. executeQuery()
C. execute()
D. noexecute()
Answer: C

26. getConnection() method of DriverManager returns __________________________


A. Driver Object
B. ResultSet object
C. Connection Object
D. DataSet Object
Answer: C

27. getResultSet() method belongs to _________.


A. Statement interface
B. Connection interface
C. ResultSet interface
D. DriverManager interface
Answer: A

28. How will JDBC help the programmers to write java applications that manage programming
activities:
A. It helps us to connect to a data source, like a database.
B. It helps us in sending queries and updating statements to the database
C. Retrieving and processing the results received from the database in terms of answering to your
query.
D. All of Above
Answer: D

29. Identify the invalid method of DriverManager-


A. registerDriver()
B. deregisterDriver()
C. getConnection()
D. openConnection()
Answer: D

30. In DriverManager class which method is used to establish the connection with specified url
A. public static void deregisterDriver(Driver driver)
B. public static void registerDriver(Driver driver)
C. public static Connection getConnection(String url)
D. public static Connection getConnection (String url,String userName,String password)
Answer: C

31. In setXXX() methods used for Prepared-Statement the first argument specifies which value?
A. index of column
B. index of row
C. index of Question mark
D. index of Resultset
Answer: C

32. In the following JDBC drivers which is known as partially java driver?
A. JDBC-ODBC bridge driver
B. Native-API driver
C. Network Protocol driver
D. Thin driver
Answer: B

33. In three tier model, middle tier of the services acts as a mediator between _____ and _____.
A. Java applet and DBMS
B. Java application and databases
C. Data source and Application server
D. DBMS and user
Answer: B

34. In the three-tier model, commands are sent to a middle tier of services, which then send SQL
statements to the _______________
A. Client
B. Server
C. Database
D. JDBC
Answer: C

35. JDBC stands for ________.


A. Java Database Connectivity
B. java database components
C. java database controls
D. None of the above
Answer: A
36. The Type 3 architecture is _______________
A. JDBC-Net pure Java
B. JDBC-Native API
C. JDBC-ODBC Bridge Driver
D. All of the above
Answer: A

37. The valid constant to represent ResultSet type is ___________________


A. TYPE_FORWARD_ONLY
B. TYPE_SCROLL_SENSITIVE
C. TYPE_SCROLL_INSENSITIVE
D. All of the mentioned
Answer: D

38. To execute a SELECT statement "select * from Address" on a Statement object stmt, use
A. stmt.execute("select * from Address");
B. stmt.executeQuery("select * from Address");
C. stmt.executeUpdate("select * from Address");
D. stmt.query("select * from Address");
Answer: B

39. To retrieve a Connection object,…………………. Method is used.


A. connection( )
B. establish( )
C. getConnection( )
D. getConnected( )
Answer: C

40. Type 1 driver is also known as


A. JDBC-Native API
B. JDBC-ODBC Bridge Driver
C. JDBC-net pure java
D None of these
Answer: B

41. Using JDBC you can send SQL, PL/SQL statements ___________________
A. to almost any relational database.
B. to MySQL database
C. to MSAccess
D. to Oracle
Answer: A

42. Valid constant to set ResultSet as Scrollable is _____________________


A. ResultSet.TYPE_FORWARD_ONLY
B. ResultSet.TYPE_SCROLL_SENSITIVE
C. ResultSet.TYPE_SCROLL_INSENSITIVE
D. All of above
Answer: D

43. What are types of JDBC driver?


A. JDBC-ODBC bridge
B. JDBC native API
C. pure java JDBC network
D. all the above
Answer: D

44. What contains object specific to database, and used to create Connection object from the
options?
A. Driver Interface / Connect()
B. ResultSet
C. Statement
D. Driver Manager
Answer: A

45. Choose missing statements in following code from given options.


import java.sql.*;
class DemoFetch1
{
public static void main(String args[])
{
Connection con;
PreparedStatement pstmt;
ResultSet rs;
String qry,url;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
url="Jdbc:Odbc:studdsn";
con=DriverManager.getConnection(url,"","");
qry="select * from stud";
pstmt=con.prepareStatement(qry);
rs= ;
System.out.println("Roll NotNametPercentage");
while(rs.next())
{
int rno=rs.getInt("roll");
String nm=rs.getString("sname"); double
per=rs.getDouble("per");
System.out.println(rno+"t"+nm+"t"+per);
}
con.close();
}catch(Exception e){System.out.println(e.toString());}
}
}
A. pstmt.executeUpdate(qry)
B. pstmt.executeUpdate()
C. pstmt.executeQuery(qry)
D. pstmt.executeQuery()
Answer: D
46. Find the error in following code:
Connection con = DriverManager.getConnection ("jdbc:odbc:wombat", "login", "password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next())
{
Integer x = rs.getInt("c");
String s = rs.getString("a");
Float f = rs.getFloat("b");
}
A. Retrieval of the fields is in the wrong order.
B. The password must be encrypted before being sent to the DriverManager.
C. The Driver's URL is in the wrong format.
D. The ResultSet class returns primitive types for integers and floats
Answer: A
47. Consider the following code.What should be the correction done in the code to get correct
output?
import java.sql.*;
class mytable
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = ("jdbc:odbc:mystudtable"); Connection
con=DriverManager.getConnection(url);
System.out.println("ConnectionEstablished");
Statement studste = con.createStatement();
String studqry = "create table student(rno int,name char)";
studste .execute(qry);
}
catch(SQLException e)
{
System.out.println("databse Connection error.....");
}
catch(Exception e)
{
System.out.println("Other error.....");
}
}
A. replace statement studste.execute(qry) with studste.execute(studqry)
B. missing }
C. missing ;
D. Both option i and ii
Answer: D
48. Consider the following program, select the statement that should be added to the program to
get correct output.
import java.sql.*; public
class DBDemo5
{
public static void main(String args[])throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c =DriverManager.getConnection("jdbc:odbc:MyDSN","","");
PreparedStatement s=c.prepareStatement( "update db3 set Name=? where Roll_no=?");
Statement s=c.createStatement( );
s.setString(1,args[0]);
s.setString(2,args[1]);
s.setString(3,args[2]);
ResultSet rs=s.executeQuery("select* from db3");
System.out.println("Name"+"t"+"Roll no"+"t"+"Avg");
while(rs.next())
{
System.out.println(rs.getString(1)+"t"+rs.getInt(2)+"t"+rs.getDouble(3));
}
s.close();
c.close();
}
}
A. s.executeUpdate()
B. c.createStatement( )
C. s.close()
D. c.close()
Answer: A
49. Consider the following code, Find the missing statement to get correct output.
public class DeleteRecords
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:DATA");
String query = "delete from tannis";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.executeUpdate();
pstmt.close();
con.close();
}
catch (Exception e)
{
System.out.println(e);
}

}
}

A. Missing import java.sql.Connection;


B. Missing import java.sql.DriverManager;
C. Missing import java.sql.PreparedStatement;
D. All the above
Answer: D
50. Consider the following program, What will be the output of following Code?
import java.sql.*;
public class db15
{
public static void main(String args[])throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection c =DriverManager.getConnection("jdbc:odbc:DSN2","","");
Statement s=c.createStatement( );
int n=s.executeUpdtae("delete from db3"); ResultSet
rs=s.executeQuery("select* from db3");
System.out.println("Name"+"t"+"Roll no"+"t"+"Avg");
while(rs.next())
{
System.out.println(rs.getString(1)+"t"+rs.getInt(2)+"t"+rs.getDouble(3));
}
s.close();
c.close();
}
}
A. Empty Table
B. Table with All Data
C. Error in ResultSet Statement
D. Error in close()
Answer: A

CHAPTER 6: Servlet
Q. QUESTION
1. _____ is the first phase of servlet life cycle
A. service
B. initialization
C. destroy
D. both ii and iii
Answer: B

2. _______ are stored at client side and stores state information.


A. Sessions
B. Cookies
C. Forms
D. None of these
Answer: B

3. _________ class provides functionality that makes it easy to handle requests and responses.
A. ServetRequest
B. ServletResponse
C. GenericServlet
D. None of these
Answer: C

4. __________ uses doGet(), doPost(), doHead, doDelete(), doTrace().


A. GenericServlet
B. HttpServlet
C. both a and b
D. None of the above
Answer: B

5. ________ allows session data to be read and written.


A. GenericServlet class
B. HttpSession interface
C. ServletConfig interface
D. None of these
Answer: B

6. ________ method execute at beginning of servlet life cycle.


A. dispose()
B. init()
C. service()
D. destroy()
Answer: B

7. A servlet stays in memory, so it doesn’t have to be reloaded each time.


A. True
B. False
Answer: A

8. A user types the URL http://www.msbte.com/result. php. Which HTTP request gets generated? Select the one
correct answer
A. GET method
B. POST method
C. HEAD method
D. PUT method
Answer: A

9. Advantages of Cookies are ____________


a) It is used to maintain the state information.
b) Cookies are maintained at client side.
c) It will not work if cookie is disabled from browser.
d) Only textual information can be set in cookie object.
A. All are correct.
B. Only a and b are correct.
C. Only a, b and c are correct.
D. Only a and c are correct.
Answer: B

10. An image file representing a company's logo has to be uploaded to the server. Which of the following HTTP methods
can be used in this situation?
A. doGet()
B. doPost()
C. doTrace()
D. doPut()
Answer: D

11. Apache Tomcat is a ________.


A. Servlet
B. Java program
C. API
D. Web server that is capable of running Java programs.
Answer: D

12. By default, Tomcat runs on port ___________.


A. 8080
B. 8050
C. 8000
D. 8888
Answer: A

13. Cookie class consist __________________.


A. name and value
B. name only
C. value only
D. None of these
Answer: A
14. During Initialization of Servlet, a servlet instance can throw ________.
A. An UnavailableException
B. A ServletException
C. Both A and B
D. None of these
Answer: C

15. Find out correct syntax of service() method of servlet class


A. void service(ServletRequest req, ServletResponse res)
B. int service(ServletRequest req, ServletResponse res)
C. float service(ServletRequest req, ServletResponse res)
D. char service(ServletRequest req, ServletResponse res)
Answer: A

16. For a given ServletResponse response, which retrieve an object for writing text data?
A. response.getOutputWriter()
B. response.getWriter()
C. response.getWriter().getOutputStream()
D. response.getWriter(Writer.OUTPUT_TEXT)
Answer: B

17. getSession(true) method will return appropriate session object if……


A. the session is completed
B. session object is passed to another method
C. the session does not exists
D. the session is existing
Answer: D

18. Give the examples of Application Server from the following?


A. JBoss
B. Weblogic
C. Java Application Server
D. All of the above
Answer: D

19. Given an HttpServletRequest request and HttpServletResponse response, which sets a cookie "username" with the
value "joe" in a servlet?
A. request.addCookie(new Cookie("username", "joe"));
B. response.addCookie(new Cookie("username", "joe"));
C. response.addCookie("username", "joe");
D. request.addCookie("username", "joe");
Answer: A

20. HTTP servlet uses methods like__________________.


A. doPost(),doGet()
B. doText(),destroy()
C. service(),init()
D init(),paint()
Answer: A

21. HttpServlet is a subclass of ____________________.


A. Servlet
B. ServletConfig
C. GenericServlet
D. ServletRequest
Answer: C

22. Identify correct syntax of doGet() method of servlet class


A. void doGet(HTTPRequest req, HTTPResponse res)
B. void doGet(HTTPResponse res, HTTPRequest req)
C. void doGet(HTTPServletRequest req, HTTPServletRequest req )
D. void doGet(HttpServletRequest req, HTTPServletResponse res)
Answer: A

23. Identify method used by following url http://localhost:8080/examples/servlet/test.html?uid=xyz?pass=vvpp?


A. get()
B. post()
C. service()
D. None of Above
Answer: A

24. Identify the correct sequence of Steps for creation and execution of java and html file for servlet
A) Create a directory structure under Tomcat for your application. Write the servlet source code. You need to import the
B) Javax.servlet package and the javax.servlet.http package in your source file.
C) Compile your source code.
D) Create a deployment descriptor.
E) Run Tomcat.
F) Call your servlet from a web browser.
A. ABCDEF
B. ACBDEF
C. BCADEF
D. none of the above
Answer: A

25. In Session tracking which method 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 from Fields
Answer: C

26. Which method is used to get HttpSession object and it belongs to which object?
A. getSession method and HttpServletRequest
B. getSession method and HttpServletResponse
C. getHttpSession and HttpServletResponse
D. getHttpSession and HttpServletRequest
Answer: A

27. Which method of the servlet executed first?


A. service()
B. destroy()
C. init()
D. none of the above
Answer: C

28. Which method returns a servletConfig object that contains any initialization parameters?
A. servletConfig getServletConfig()
B. ServiceConfig getServlet()
C. ServiceConfig getServletConfig()
D. ServiceConfig getConfig()
Answer: B

29. Which methods are used to Extract all names and value pairs from the Http request
A. getParameter() and getParameterValues()
B. getParameter() and getParameterNames()
C. getParameterNames() and getParameterValues()
D. getParameterNameValues() and getParameter()
Answer: C
30. Which of following is not true for servlet?
A. it is persitent
B. platform independence
C. high performance
D. it is single threaded
Answer: D

31. Which of the following are class? 1.ServletContext 2.Servlet 3.GenericServlet 4.HttpServlet
A. 1,2,3,4
B. 1,2
C. 3,4
D. 1,4
Answer: C

32. Which of the following method is used to destroy the session?


A. dead( )
B. invalidate( )
C. Close( )
D. destroy( )
Answer: D

33. Which of the following methods are main methods in life cycle of servlet?
1. init()
2. service()
3. destroy()
4.stop()
5.wait()
A. 1,2,3,4,5
B. 1,2,3
C. 3,4,5
D. 1,4,5
Answer: B

34. Sessions is a part of the session tracking and it is for maintaining the client state at server side?
(a) True
(b) False
ANSWER: A

35. In session tracking which method 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
ANSWER: C

36. Choose missing statement in following code from given options.


import javax.servlet.*;
import javax.servlet.http.*;
public class SessionDemo extends HTTPServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
HttpSession hs=req.getSession(true);
pw.println("Session ID= "+hs.getId());
}
}
A. import java.io.*;
B. import java.net.*;
C. import java.sql.*;
D. import java.util.*;
Answer:

37. Choose missing statements in following code from given options


public class HelloWorld extends HttpServlet
{
private String message;
public void init()
throws ServletException
{
message ="Hello World";
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out= response.getWriter();
out.println("<h1>"+ message +"</h1>");
}}
publicvoid destroy()
{ }

A. import java.io.*; import javax.servlet.*; import javax.servlet.http.*;


B. import java.Vector.* ; import java.Thread.*; import javax.servlet.*;
C. import javax.servlet.http.*; import java.String.*; import java.Vector;
D. import javax.servlet.http.*; import java.Thread.*; import javax.Client.*;
Answer: A

38. Choose missing statements in following code from given options.


public class GetSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(false);
try {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><body>");
if (session == null) {
writer.println("<p>You are not logged in</p>");
} else {
writer.println("Thank you, you are already logged in");
writer.println("Here is the data in your session");
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Object value = session.getAttribute(name);
writer.println("<p>name=" + name + " value=" + value + "</p>");
} }
writer.println("<p><a href="/ServletSession/login.html">Return" +
"</a> to login page</p>");
writer.println("</body></html>");
writer.close();
} catch (Exception e) {
e.printStackTrace();
} }}
A.
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import javax.servlet.*;

B.
import javax.servlet.http.*;
import java.util.*;

C.
import javax.servlet.*;
import java.util.*;

D.
import javax.servlet.http.*;
import java.io.*;

Answer: A

39. Choose missing statements in following code from given options.


import java.io.*;
import javax.servlet.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException
{
// Get cookies from header of HTTP request.

Cookie[] cookies = request.getCookies();


// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +"; value = " + value);
}
pw.close();
} }
A. import javax.servlet.http.*; and ServletException
B. import javax.servlet.ftp.*; and HeaderException
C. import javax.servlet.http.*; and IOException
D. import javax.servlet.http.*; and NullPointerException
Answer: A

40. Choose missing statements in following code from given options.


public class session1 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throwsServletException, IOException
{
HttpSession hs = request.getSession(true);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
} }
A. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;
B. import java.Vector.* ; import java.Thread.*; import javax.servlet.*;
C. import javax.servlet.http.*; import java.String.*; import java.Vector;
D. import javax.servlet.http.*; import java.Thread.*; import javax.Client.*;
Answer: A

41. Choose missing statements in following code from given options.


import java.io.*;
import javax.servlet.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
String data=request.getParameter("txtdata");
Cookie c=new Cookie("MyCookie",data);
response.addCookie(c);
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<B>My cookie has been sent<BR>");
pw.close();
} }
A. Missing } statement
B. response.setCookie(c) instead of response.addCookie(c )
C. import javax.servlet.http.*;
D. None of these
Answer: C

42. Choose missing statements in following code from given options.


import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;
public class session1 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throwsServletException, IOException
{
response.setContentType("text/html");
String p1=req.getParameter("T1");
String p2=req.getParameter("T2");
pw.print(p1);
pw.print(p2);
pw.close();
} }
A. Missing semicolon
B. Missing Object of PrintWriter
C. Missing Header File
D. None of the above
Answer: B

43. Choose missing statements in following code from given options.


import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException
{
res.setContentType("text/html");
pw.println("Hello Servlet");
pw.close();
} }
A. import javax.servlet.http.*;
B. import java.io.*; PrintWriter pw=res.getWriter();
C. import javax.servlet.http.*; import java.util.*;
D. None of these
Answer: B
44. Consider following code.find syntax error in code
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionExample extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
Date created = new Date(session.getCreationTime());
Date accessed = new Date(session.getLastAccessedTime());
out.println("ID " + session.getId());
out.println("Created: " + created);
out.println("Last Accessed: " + accessed);
String dataName = request.getParameter("dataName");
if (dataName != null && dataName.length() > 0)
String dataValue = request.getParameter("dataValue");
session.setAttribute(dataName, dataValue);
}
Enumeration e = session.getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = session.getAttribute(name).toString();
out.println(name + " = " + value);
} } }
A. error in the if statement
B. missing }}
C. missig semicolon
D. All of these
Answer: A

45. Consider the following code.Select the missing statement to get proper output.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CookEx extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String name=req.getParameter("name");
String value=req.getParameter("age");
Cookie c=new Cookie(name,value);
String p1=c.getName();
String p2=c.getValue();
out.println("Name:" +p1);
out.println("Age:"+p2);
out.println(" ");
} }
A. req.addCookie(c);
B. res.addCookie(c);
C. addCookie(c);
D. res.addCookie();
Answer: B

46. Consider the following program


Select the statement that should be added to the program to get correct output.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class CookieServlet extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse
response)
throws ServletException, IOException {
Cookie c1 = new Cookie("userName", "Helen");
Cookie c2 = new Cookie("password", "Keppler");
response.addCookie(c1);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Cookie Test</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("Please click the button to see the cookies sent to you.");
out.println("<BR>");
out.println("<FORM METHOD=POST>");
out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");
out.println("</FORM>");
out.println("</BODY>");
out.println("</HTML>");
}
A. response.addCookie(c2);
B. response.addCookie(c1);
C. addCookie();
D. response.addcookie(c2);
Answer: A

47. Consider the following program


Select the statement that should be added to the program to get correct output.
import javax.servlet.*;
imopr javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponce responce) throwsServletException,IOException
{
String data = request.getParameter("data");
Cookie cookie = new Cookie("MyCookie",data);

responce.setContentType("text/html");
PrintWriter pw = responce.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}
A. responce.cookie(cookie);
B. responce.add(cookie);
C. responce.addCookie(cookie);
D. none of the above
Answer: C

48. Consider the following program and find out the missing statement
import javax.servlet.*;
import java.io.*;
public class image extends GenericServlet
{
public void service(ServletRequest req,ServletResponse res)throws ServletException,IOException
{
res.setContentType("image/jpeg");
pw.println("<html>");
pw.println("<img src='Sunset.jpg' width=600 height=800>");
pw.println("</html>");
}}
A. PrintWriter pw=res.getWriter();
B. Cookie pw=res.getCookies();
C. InputStream pw=res.getInputStream();
D. String pw;
Answer: A

49. In following Java program fill statement showing ***.Select any one option fro given options
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throwsServletException, IOException
{
String data = request.getParameter("data");
Cookie cookie = ***************
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
} }
A. new Cookie("MyCookie", dat;
B. new Cookie("MyCookie", data);
C. new Cookie("MyCookie", data2);
D. new Cookie("MyCookie", database);
Answer: B

50. In following Java program fill statement showing ******.Select any one option from given options.
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
Enumeration e = ******;
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
} }
A. request.getParameterNames();
B. request.getparameterNames();
C. Request.getParameterNames();
D. request.getParameterName();
Answer: A

You might also like