Download 1 - Nano Infotech

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 1 of 50
Note:
This question-bank contains three sections.
Section-A contains 1 mark Multiple Choice Objective type questions.
Section-B contains 5 marks subjective questions.
Section-A contains 10 marks subjective questions.
Section – A
[QUESTIONS 1 TO 78]
1 Marks Questions
[PAGE 1 TO 9]
MULTIPLE CHOICE OBJECTIVE TYPE QUESTION
Q1. AppletViewer tool is available in which of the folder of JDK
a) bin
b) lib
c) source
d) class
Q2. Which is the method that starts the applet?
a) main()
b) destroy()
c) init()
d) repaint()
Q3. The sequence of methods invoked automatically when an applet is loaded till it is destroyed is:
a) init(), paint(), start(), stop(), destroy()
b) b) start(), init(), paint(), stop(), destroy()
c) start(), paint(), init(), destroy(), stop()
d) init(), start(), paint(), stop(), destroy()
Q4. What tags are mandatory when creating HTML to display an applet?
a) name, height, width
b) code, name
c) codebase, height, width
d) code, height, width
Q5. Which of the following methods set the frame surface color to pink?
a) setBackground(Color.pink);
b) setColor(PINK);
c) Background(pink);
d) None of the above
Q6. The means by which the browser and the applet communicates is
a) AppletSkeleton interface
b) AppletApplication interface
c) AppletStub interface
d) AppletWindow interface
Q7. Which tag allows the user to pass user-defined parameters to an applet?
a) <applet>
b) <p>
c) <param>
d) <parm>
Q8. How many parameters passed to draw a arc?
a) 4
b) 5
c) 3
d) 6
Q9. Which method is used to paint an applet?
a) draw()
b) repaint()
c) paint()
d) None of these
Q10. Which class is used to draw and fill various shapes?
a) Applet
b) Graphics
c) Paint
d) Color
Q11. Which class is used to get the size, name, style of the text?
a) Color
b) Text
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 2 of 50
c) Font
d) None of these
Q12. The __________ method is used to display a string on an applet.
a) dispString()
b) displayString()
c) drawString()
d) All of these
Q13. The _________ method of the Graphics class is used to draw an image on an applet.
a) dispImage()
b) displayImage()
c) drawImage()
d) None of these
Q14. What is the immediate super class of Applet class?
a) Object
b) Window
c) Panel
d) Component
Q15. The setBackground() method is part of the following class in java.awt package:
a) Component
b) Object
c) Applet
d) Container
e) Graphics
Q16. Which class is at the top of the AWT hierarchy?
a) Container
b) Component
c) Panel
d) Applet
Q17. Which of the following methods can be used to change the size of a java.awt.Component
object?
a) dimension()
b) setSize()
c) area()
d) size()
e) resize()
Q18. What will be the output of line 5
a) Choice c1 = new Choice();
b) c1.add("First");
c) c1.addItem("Second");
d) c1.add("Third");
e) System.out.println(c1.getItemCount());
a) 1
b) 2
c) 3
d) None of the above
Q19. Which one of the following does not extends java.awt.Component
a) CheckBox
b) Canvas
c) CheckbocGroup
d) Label
Q20. How to create TextArea with 80 character-width wide and 10 character-height tall?
a) new TextArea(80, 10)
new TextArea(10, 80)
b) None of these
Q21. Which of the following creates a List with 3 visible items and multiple selection disabled?
a) new List(3, false)
b) new List(true, 3)
c) new List(3, True)
d) new List(false,3)
Q22. Window, Panel and ScrollPane are the subclasses of
a) Container class
b) Component class
C) Frame class
d) None of the above
Q23. Which of the following components allow multiple selections?
a) Non-exclusive Checkboxes
b) Radio buttons
c) Choice
d) Text Boxes
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 3 of 50
Q24. Which layout is used as their default layout by Window, Frame and Dialog classes?
a) CardLayout
b) BorderLayout
c) FlowLayout
d) GridLayout
Q25. Default layout of an applet
a) CardLayout
c) BorderLayout
b) FlowLayout
d) BoxLayout
Q26. In which Layout the components are arranged like a deck of cards?
a) FlowLayout
b) GridLayout
c) Null Layout
d) CardLayout
e) None of these
Q27. The AWT classes and interfaces are contained within
a) javax.awt.* package
b) java.awt.* package
c) java.awt.event.* package
d) None of these
Q28. Which of the following methods is used to set the text of a label?
a) setLabel()
b) setText()
c) setLabelText()
d) setTextLabel()
Q29. Which layout manager is used to organize the components in tabular form?
a) FlowLayout
b) BorderLayout
c) CardLayout
d) GridLayout
Q30. The ActionEvent is generated with the click of a Button?
a) True
b) Flase
Q31. Which of the following statements is false as far as different type of statements is concern in
JDBC?
a) Regular Statement
b) Prepared Statement
c) Callable Statement
d) Interim Statement
Q32. Which of the following methods are needed for loading a database driver in JDBC?
registerDriver() method
a) Class.forName()
b) getConnection()
c) Both A and B
d) None of these
Q33. Which of the following is false as far as type 4 driver is concern?
a) Type 4 driver is “native protocol, pure java” driver
b) Type 4 drivers are 100% Java compatible
c) Type 4 drivers uses Socket class to connect to the database
d) Type 4 drivers can not be used with Netscape
Q34. _____allows you to specify SQL query, in which unknown values are replaced by “?”.
a) Statement
b) PreparedStatement
c) ResultSet
d) None of these
Q35. Which statement is static and synchronized in JDBC API?
a) executeQuery()
b) executeUpdate()
c) getConnection()
d) prepareCall()
Q36. The JDBC-ODBC bridge is
a) Three tiered
c) Best for any platform
b) Multithreaded
d) All of the above
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 4 of 50
Q37. Which method is used to perform DML statements in JDBC?
a) execute()
b) executeQuery()
c) executeUpdate()
d) executeResult()
Q38. The __________ method provides information about the vendor specific errors whose meaning
is defined by the driver vendor only.
a) getNextException()
b) getErrorCode()
c) getSQLState()
d) None of these
Q39. Which method is used to move the ResultSet cursor to the next row of the data?
a) nextLine()
b) next()
b) Line()
d) None of these
Q40. Which class is used to get the metadata for the resultset?
a) ResultSetMetaData
b) DatabaseMetaData
c) Both a and b
d) None of these
Q41. what is the main components of JDBC ?
(a) Driver Manager
(b) Driver
(c) Connection
(d) both a&b
Q42. 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(...),...
Q43. How can you execute DML statements (i.e. insert, delete, update) in the database?
(a) By making use of the InsertStatement, DeleteStatement or UpdateStatement classes
(b) By invoking the execute(...) or executeUpdate(...) method of a normal Statementobject or a subinterface object thereof
(c) By invoking the executeInsert(...), executeDelete(...)
(d) executeUpdate(...)methods of the DataModificationStatement object
(e) By making use of the execute(...) statement of the DataModificationStatement Object
Q44. What is the name of the method used to start a thread execution?
a) init()
b) start()
c) run()
d) resume()
Q45. Which two are valid constructors for Thread?
1. Thread(Runnable r, String name)
2. Thread()
3. Thread(int priority)
4. Thread(Runnable r, ThreadGroup g)
5. Thread(Runnable r, int priority)
A. 1 and 3
B. 2 and 4
C. 1 and 2
D. 2 and 5
Q46. Which of the following line of code is suitable to start a thread ?
a) Thread t = new Thread(X);
b) Thread t = new Thread(X); t.start();
c) X run = new X(); Thread t = new Thread(run); t.start();
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 5 of 50
d) Thread t = new Thread(); x.run();
Q47. Which will contain the body of the thread?
a) run()
b) start()
c) stop()
d) main()
Q48. Which three guarantee that a thread will leave the running state?
1. yield()
5. sleep(1000)
2. wait()
6. aLiveThread.join()
3. notify()
7. Thread.killThread()
4. notifyAll()
A. 1, 2 and 4
B. 2, 5 and 6
C. 3, 4 and 7
D. 4, 5 and 7
Q49. Which method registers a thread in a thread scheduler?
a) run()
b) construct()
c) start()
d) register()
Q50. Assume the following method is properly synchronized and called from a thread A on an object
B:
wait(2000);
After calling this method, when will the thread A become a candidate to get another turn at the CPU?
a) After thread A is notified, or after two seconds.
b) After the lock on B is released, or after two seconds.
c) Two seconds after thread A is notified.
d) Two seconds after lock B is released.
Q51. Which of the following is used in inter-thread communication?
a) wait(), notify(), notifyall()
B) wait(), join()
c) notify(), join(), notifyall()
d) None of these
Q52. Which of the following is the default priority of a thread?
a) 0
b) 5
b) 1
d) 10
Q53. Which of the following statements are true?
a) UTF characters are all 8-bits.
b) UTF characters are all 16-bits.
c) UTF characters are all 24-bits.
d) Unicode characters are all 16-bits.
e) Bytecode characters are all 16-bits.
Q54. Can RMI and Corba based applications interact ?
a) Yes
b) No
Q55. How many types of protocol implementations does RMI have?
a) 2
b) 4
c) 3
d) none
Q56. What's the difference between servlets and applets?
a) Servlets executes on Servers, where as Applets executes on Browser
b) Servlets have GUI, where as an Applet has no GUI
c) Servlets creates static web pages, where as Applets creates dynamic web pages
d) Servlets can handle only a single request, where as Applet can handle multiple
Requests
Q57. The major difference between servlet and CGI is
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 6 of 50
a) Servlets are thread based and CGI is process based
b) Servlets executes slower compared to CGI
c) Servlet has no platform specific API, where as CGI has
d) All of the above
Q58. What is the limit of data to be passed from HTML when doGet() method is used?
a) 4K
b) 8K
c) 2K
d) 1K
Q59. Which method is used to specify before any lines that uses the PintWriter?
a) setPageType()
b) setContextType()
c) setContentType()
d) setResponseType()
Q60. To get the servlet environment information
a) ServletConfig object is used
b) ServletException object is used
c) ServletContext object is used
d) ServletContainer object is used
Q61. The getSession() method with ‘true’ as its parameter [ getSession(true) ] it will return
appropriate session object when
a) the session is completed
b) the session object is passed to another method
c) the session does not exists
d) the session is existing
the
Q62. The values of <servlet-name> and <servlet-class> in web.xml file
a) must be same
b) must not be same
c) may be same
d) None of the above
Q63. A servlet maintain session in
a) Servlet container
c) Servlet request heap
b) Servlet context
d) Servlet response heap
Q64. The life cycle of a servlet is managed by
a) servlet context
b) servlet container
c) the supporting protocol (such as http or https)
d) all of the above
Q65. How many ServletContext objects are available for an entire web application?
a) One each per servlet
b) One each per request
c) One each per response
d) Only one
Q66. ____________ are horizontally or vertically oriented bars which allow the user to select items
between a specified minimum and maximum values .
a) scrollbar
c) ProgressBar
b) Slider
d) None of these
Q67. The __________ is the default layout manager for an applet.
a) GridLayout
c) BorderLayout
b) FlowLayout
d) None of these
Q68. _____________ class is the root element of all Event classes.
a) Obect
b) ObjectEvent
c) EventObject
d) None of these
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 7 of 50
Q69. An ______________is an object which receives notification when an event occurs.
a) event source
b) event listener
b) event class
d) All of these
Q70. How many methods provides the WindowListener interface?
a) 2
b) 4
c) 7
d) 8
Q71. The Delegation Event Model is based on the concept of ______ and _________.
a) event, listener
b) source, event
c) source, listener
d) None of these
Q72. The ________ interface defines methods to handle event related to keys in java.
a) KeyListener
b) KeysHandleListener
c) KeyTypedListener
d) None of these
Q73. The _______ method helps in clearing the contents of the buffer.
a) flush()
b) clear()
c) read()
d) All of these
Q74. Which of the following can you perform using the File class?
a) Change the current directory
b) Return the name of the parent directory
c) Delete a file
d) Find if a file contains text or binary information
Q75. How do you create a Reader object from an InputStream object?
a) Use the static createReader( ) method of InputStream class.
b) Use the static createReader( ) method of Reader class.
c) Create an InputStreamReader object, passing the InputStream object as an argument to the
InputStreamReader constructor.
d)Create an OutputStreamReader object, passing the InputStream object as an argument to the
OutputStreamReader constructor.
Q76. Which of the following are true?
a) The InputStream and OutputStream classes are byte-oriented.
b) The ObjectInputStream and ObjectOutputStream do not support serialized object input and
output.
c) The Reader and Writer classes are character-oriented.
d) The Reader and Writer classes are the preferred solution to serialized object output.
Q77. The File class contains a method that changes the current working directory.
a) True
b) False
Q78. Which of the following are true about the File class?
a) A File object can be used to change the current working directory.
b) A File object can be used to access the files in the current directory.
c) When a File object is created, a corresponding directory or file is created in the local file system.
d) File objects are used to access files and directories on the local file system.
e) File objects can be garbage collected.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 8 of 50
Answer
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
A
C
D
D
A
C
C
D
C
B
C
C
C
C
D
B
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
B
C
C
B
A
A
A
B
B
D
B
B
D
A
D
C
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
D
B
C
B
C
B
B
A
D
D
B
B
C
C
A
B
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
C
A
A
B
D
A
C
A
A
C
C
C
D
C
B
B
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
D
A
B
C
B
C
C
A
A
B,C
C
A,C
B
B,D,E
Section – B
5 Marks Questions
[QUESTIONS 1 TO 33]
[PAGE 10 TO 31]
Q1. What is the difference between a class and an object? What do you mean by the instantiation of
an object? How instantiation is done in implicit and explicit form?
Ans. A class is a blue print or a template that contains methods and variables. Methods are known as
member functions and variables are known as data members.
An object is the instance of a class that represent a class on a specific time and use all the
members of the class.
E.g.
Bike - is class
My bike - instance
Name
Company
Name – City
Company – TVS
Mileage
Mileage - 90 Km/h
Instantiation of an object means provide memory to an object of a class so that the members declare in the
class should be accessible by an object of class. There are two methods to instantiate an object in implicit
form and in explicit form .
IMPLICIT FORM – Implicit means when an object of a class is written by a method.
e.g Integer a = Integer.valueOf (“10 “),
EXPLICIT FORM – Explicit form mean when we create an object of a class by allocating memory explicility.
.e.g. Student s= new Student ( ),
Q2. What are the types of java applets in detail?
Ans. In java we can create application for web page and application for single machine. The application for
Web page is created with the help of applet and application using the Java.awt.Frame. In java we can create
two types of applets.
Local applet means: - Clients and server program both are on the same machine.
Remote applet means: - Applet is available on the different machine (on the server) and client requests for
that applet from different machine. These diagrams show the local and Remote applets.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 9 of 50
Local Computer
To access the local applet, we have to specify the Applet Class file name in CODE attribute of the applet tag
on the client machine.
<applet code = AppletclassName width=300 height=300>
LoadingRemoteApplet
Internet
Client
Remote Applet
applet
Server
To access the remote applet we have to specify the URL address in CODEBASE attribute of the applet tag
on the client machine.
E.g.
<applet Codebase= http://www.netserver.com/applet width=300 height=300>
Q3. How does applets differ from application program? Why do applet class need to be declared as
public? Write the applet tag with arguments.
Ans.
Applet
Application
1.Applet executes on web browser.
1. It executes on Command prompt
2. Every application program no need of main 2. Every application program need to define
function to execute.
main () function in the program
3. No command line argument is passed.
3. We can pass command line arguments in
an application
4. A fast and small program executed on the 4. Programs that does not support web
internet.
browsers.
5.Applet once launch from the server, we 5. Frame are less secure from applet
cannot attach anything with applet so applet is because in frame we can attach database or
more secure program.
any other things after launching from server.
6. Applets are two types remote applet and 6. Frame have single type only.
local applet.
Applet class need to declare public because applets are launched by the <applet> tag and that tag can be
defined within the same program or in different .html file. It is declared public because it can be called
outside the package in which it is declared.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 10 of 50
<applet code=abc.class height=200 width=200>
<param name=”name” value=”raj”>
<param name=”rollno” value=1>
<param name=”class” value=12>
</applet>
Q4. Write a program to draw parallogram.
Ans.
import java.awt. *;
import java.applet. *;
//<applet code=”pr.class” height=”300” width=”200”></applet>
public class pr extends Applet
{
public void paint(Graphics g)
{
int x[] = {40,150,120,10};
int y[] = {10,10,100,100};
g.drawPolygon (x,y,4);
}
}
Q5. Write an applet, which takes the input, and compute the factorial.
Ans.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
//<applet code=fact1 height=200 width=300></applet>
public class fact1 extends Applet implements ActionListener
{
Label l,l1;
TextField t,t1;
Button b;
public void init()
{
l=new Label("enter number for factorial");
l1=new Label("result");
t=new TextField(10);
t1=new TextField(10);
b=new Button("factorial");
add(l);
add(t);
add(l1);
add(t1);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
String s=t.getText();
int n=Integer.parseInt(s);
int f=1;
while(n>=1)
{
f=f*n;
n--;
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 11 of 50
t1.setText(String.valueOf(f));
}
}
Q6. What is Event Handling?
Ans. Almost all programs must respond to commands from the user in order to be useful. Java's AWT
uses event driven programming to achieve processing of user actions. Within the AWT, all user actions
belong to an abstract set of things called events. An event is described as the change in state of an object .
There are three parts to the event model in Java:
Event object - This is an instance of a Java class that contains the characteristics of the event. For
example, if the event is generated from clicking a mouse button, the event object would contain information
such as the coordinates of the mouse cursor, which button was clicked, how many times it was clicked, etc.
Dispatching class/method - This is an object, which detects that an event has occurred and is then
responsible for notifying other objects of the event, passing the appropriate event object to those objects.
These objects are "listeners" for the event. Most AWT components, such as Button, List, TextField, etc. are
examples of dispatching classes.
These methods are conventionally named i.e. addxxListener (to add an object as a listener) or
removexxListener (to remove the object as a listener). Here ‘xx’ is the specific type of event to listen for. In
the case of the Button, this would be "Action" to indicate the action of pushing the button. (So the methods
would be addActionListener and removeActionListener).
Listener Interface - For the dispatching to work properly, the dispatching class must be able to reply on
each of its listeners to contain the method that it executes when the event occurs. This is easily
accomplished in Java through the use of an Interface class. The important point is that a class, which is
going to be a listener, must implement that interface.
Q7. Briefly explain basic user interface components in java AWT?
Ans:- Controls are components, such as buttons, labels and text boxes, that can be added to containers like
Frame, Panel and Applet. The Java.awt package provides an integrated set of classes to manage user
interface components. Components are placed on the user interface by adding them to a container. The
simplest form of Java AWT component is the basic User Interface Component. You can create and add
these to your applet without needing to know anything about creating containers or panels. Because an
applet is a container, you can put other AWT components, such as UI components or other containers, in it.
The basic UI components (controls) like labels, buttons, check boxes, choice menus, and text fields. The
following table gives a list of all the Controls in Java AWT and their respective functions.
In order to add a control to a container, you need to perform the following two steps.
structor.
Controls
Functions
Textbox
Accepts single line alphanumeric entry.
TextArea
Accepts multiple line alphanumeric entry.
Push button
Triggers a sequence of actions.
Label
Displays Text.
Check box
Accepts data that has a yes/no value. More than one checkbox can be selected.
Radio button
Similar to check box except that it allows the user to select a single option from a
group.
Combo box
Displays a drop-down list for single item selection. It allows new value to be entered.
List box
Similar to combo box except that it allows a user to select single or multiple items.
New values cannot be entered.
Q8. List the methods of the applet classes?
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 12 of 50
Ans:- An applet class has several methods that are used to display the text, image, play the audio file and
respond to you at the time of interaction with an applet.
The various methods of an Applet class:Method
Description
void init( )
Begins the execution of an applet when a Web browser or java tool calls
it.
void destroy( )
Terminates an applet when the web browser or java calls this method.
void start( )
Starts the execution of an applet when the web browser or java tool calls
it
void paint()
Execute after start() nothing will draw an applet before when ever we
resize applet window it will also execute again. paint() method can be
called again & again using repaint() method.
void stop( )
Suspends the execution of applet when the web browser or java tools
calls, if this suspended stage is resumed by the start( ) method.
V
oid Changes the size of an applet according to the specified height and
resize(int width, int width.
height)
void play(URL url, Plays the audio clip if it is found at the specified URL.
String clip-name)
Q9. Define Layout manager, what are the types of layouts in java and write a program to implement
one of them. Or create a program using card layout.
Ans. Layout managers display and arrange the various components such as buttons, labels, and text boxes
on the container window. This is used for placing objects in a container for display on screen without
specifying the row, column position.To add a specific layout for a component, an object of the above class is
created.
The AWT package includes classes of the following layout managers
FlowLayout

Grid Layout

BorderLayout

CardLayout
import java.applet.*;
import java.awt.*;
//<applet code=”card.class” height=”300” width=”200”></applet>
public class card extends Applet
{
CardLayout c=new CardLayout();
Label [ ]lb= new Label[5];
public void init()
{
lb[0]= new Label(“Personal details”);
lb[1]= new Label(“Financial details”);
lb[2]= new Label(“Contact details”);
lb[3]= new Label(“dispatch details”);
lb[4]= new Label(“Credit details”);
setLayout(c);
for (int i=0;i<5;i++)
{
add(“Card”+i,lb[i]);
c.show(this,”card”+i);
}
}
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 13 of 50
Q10. Write to a program to handle keyboard events.
Ans:import java.applet.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=”keyhand.class” height=”300” width=”200”></applet>
public class keyhand extends Applet implements KeyListener
{
public void init()
{
TextField t =new TextField();
t.addKeyListener(this);
add(t);
}
public void keyPressed(KeyEvent me)
{
}
public void keyReleased(KeyEvent me)
{
}
public void keyTyped (KeyEvent e)
{
System.out.println(“key typed is”+e.getKeyChar());
}
}
Q11. Explain the different classes to create basic user interface components?
Ans. Java provide all the class to design user interface components in java package. The class hierarchy of
the components we can define as :Component

Text components
Container
Button
Label
Scroll bars
Choice
Check box
Window
List
Panel
Frame
Applet
TextField – TextField class is the sub class of Component class used to take input from clients at run time.
TextField is also known as edit text control. Following constructors and methods are provided by the text
field class.
Constructors:TextField ( )
TextField (String txt)
TextField (String txt, int size)
TextField (int size)
Methods:void setText (String t)
String getText ()
void setEchoChar (Char
Char getEchoChar ( )
void select (int st, int end)
String getSelectedText ( )
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 14 of 50
TextArea – This class is used to input multi-lines. The following syntax and provides the following
constructors.
TextArea (String txt)
TextArea (String txt, int r, int c)
Button –Button is used to initiate an action. Button is used to submit the data from form to database. It
provides the following constructors and methods provide by button class.
Constructors:Button (String lbe)
Button ( )
Methods:getLabel ( )
setLabel (String lbe)
Choice – This class used to design drop down list in java having following constructors and methods:Constructors:Choice ( )
Methods:void select (int index)
String getSelectedItem ( )
int getSelectedIndex ( )
List – This class is used to design list that have the capability of multiple selection. It provides following
methods and constructions.
Constructors:List ( )
List (int size, boolean v)
Methods:String getSelectedItem ( )
String getSelectedItem ( )
int getSelectedIndex ( )
int getSelectedIndexes ( )
Checkbox – This class is used to design checkbox interface so that we can select multiple options at a time.
Constructors:Checkbox (String txt, boolean val, CheckboxGroup kg)
Checkbox (String txt)
Checkbox (String txt, boolean v)
Checkbox (String txt, CheckboxGroup kg, boolean)
Methods:void setState (boolean false)
void setLabel(String lbe)
String getLabel ( )
Q12.Differentiate between the following ;
Ans: Abstract and Concrete class- Abstract class is a class that can not be instantiated, it exists only for
inheritance and it must be inherited, because such classes normally are used as base-classes in inheritance
hierarchies,
we
call
such
classes
abstract
classes.
A class that is neither derived from another class nor is meant to serve as the base for other class is a
concrete class. Concrete classes have no virtual member functions or protected members. String, and
Vector are examples of concrete classes in java.
Final and Finally- The Final keyword can be used with variable declaration as well with methods. The final
modifier with a class specifies that it can have no subclass. The final methods cannot be overridden and
variables cannot be given another value.
Finally is exception handling keyword. It is written after try and catch block. The finally clause is used to
provide the capability to execute code no matter whether or not an exception is thrown or caught.
Overriding and Overloading: Overriding is a method with the same name and arguments as in a parent
class, whereas overloading is the same method name but functions have different argument.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 15 of 50
Abstraction and Encapsulation: Abstraction is removing some distinctions between objects, so as to show
their commonalities.
Encapsulation is hiding the details of the implementation of an object so that there are no external
dependencies on the particular implementation.
Q13. Create an applet, which add two numbers entered through two text boxes and display their sum
in a label?
Ans.
import java. awt.*;
import java.applet.*;
//<applet code=”calc” height=”300” width=”300”></applet>
public class calc extends Applet implements ActionListener
{
TextField t1,t2 ;
Label l1;
Button b1;
public void int ()
{
t1 = new TextField(5);
t2 = new TextField(5);
l1 = new Label();
b1 = new Button(“ADD”);
add (t1);
add (t2) ;
add (l1);
add (b1);
b1.addActionListener (this);
}
public void actionPerformed (ActionEvent e)
{
if (e.getSource()==b1)
{
String s1 = t1.getText();
String s2 = t2.getText ();
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int sum = n1 +n2;
String dis =Integer.toString(sum);
l1.setLabel(dis);
}
}
}
Q14. Explain Deadlock in java.
Ans. A condition that occurs when two processes are each waiting for the other to complete before
proceeding. The result is that both processes will hang. Deadlock occurs most commonly in multitasking
and client/server environments.
A special type of error that you need to avoid that relates specifically to multitasking is deadlock. It occurs
when two thread have a circular dependency on a pair of synchronized objects.
e.g suppose one thread enter the monitor on object x and another thread enter the monitor on object y.
if x tries to call any other synchronized method on y, it will block as expected ,the thread wait forever,
because to access X, it would have to release its own lock on Y so that the first thread could complete.It is a
difficult to debug for two reasons.
1. It occurs only rarely, when two threads time-slice in just the right way.
2. It may involve more than two threads and two synchronized objects..
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 16 of 50
Q15. What is a stream class? How are the stream classes classified?
Ans. A stream in Java is a path along which data flows. It has a source and destination. Both the source
and the destination may be physical devices or programs or other streams in the same program.
In java stream classes are categorized into two groups based on the data type on which they operate.
1. Byte Stream classes
2. Character Stream classes
Streams
Byte Stream
Input
Stream
Output
Stream
Character Stream
Reader
Stream
Writer
Stream
Byte Stream classes have been designed to provide functional feature for creating and manipulating
streams and files for reading/writing bytes. These streams are uni-directional. They can transmit bytes in
only one direction. There are two kinds of byte stream classes:
1. Input stream classes
2. Output stream classes.
Character Stream classes were not a part of the language when it was released. They were added later
when the version 1.1 was announced. Character streams can be used to read and write 16 bit Unicode
characters. There are two kinds of character stream classes, namely,
1. Reader stream classes
2.
Writer stream classes.
Q16. What is use of BufferedReader class? Explain with Example.
Ans. BufferedReader class is one of the class define under the java.io package. Because System does
not define any method to take input from the keyboard. Buffered Reader class provide to read and readLine
method read data from the keyword also generate exception called IOException. read() is used to read a
character from keyboard and readLine() method is used to read a line of character from the keyboard. It can
be explain by the following example.
import java.io.*;
class my
{
public static void main(Strring ap[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b,c;
System.out.print(“Enter 1st no”);
a=Integer.parseInt(br.readLine());
System.out.print(“enter 2nd no”);
b=Integer.parseInt(br.readLine());
c=a+b;
System.out.println(“sum is “+c);
}
}
In this class file br is BufferedReader object which access the readLine() method to get the value from
keyboard.
Q17.
Ans.
Write a program to count the number of characters in a file.
import java.io.*;
class my
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 17 of 50
{
public static void main(String ap[]) throws IOException
{
int c=0,i;
FileInputStream f=new FileInputStream("first.txt");
do
{
i=f.read();
c++;
}while(i!=-1);
System.out.println("No of character in the file is " + c);
}
}
Q18. What is thread and describe the Life cycle of thread.
Ans:- A thread is a single independent path of execution within a program. A thread starts executing the
initial code and subsequent thread methods such as start(), stop() or suspend(), when the program runs.
The time period between the creation and the destruction of the thread object is called the life cycle of a
thread. The five states in thread life cycle are:a. Newborn State:- A new thread that is just created is called the newborn thread and the state is known
as the newborn state. The newborn thread either calls the start () method to run the thread or calls the stop(
) method to destroy the thread.
b. Runnable State:- The Thread that is ready to run, but waiting for the processor availability is called the
Runnable thread and the state is known as the Runnable state. The yield( ) method controls all the
Runnable threads that have the same priorities.
c. Running State:- A thread that is executing is called as the running thread and this state is known as
the running state.
d. Dead State:- A thread has a specific lifespan. A running thread is destroyed automatically, when it has
completed the execution of the run( ) method. It is called natural death.
Q19. What is Multithreading and How many ways to create a Thread ?
Ans. A thread executes a series of instructions. A thread is a single independent path of execution within a
program. Some threads can run for the entire life of the applet, while others are alive for only a few
milliseconds.
Multithreading is the built-in feature of java that runs two or more subprograms simultaneously each
subprogram of such a program is known as a thread and each thread prerforms a separate task. For
example:- one thread controls an animation, while another does a computation. In Java, multithreading is
not only powerful, it is also easy to implement.
You can implement threads within a java program in two ways – Creating an object that extends Class
Thread or implementing the interface Runnable.
The key difference between the two is that Thread class has a strart() method which your program simple
calls whereas the Runnable class does not have a start method and you must create a Thread object and
pass your thread to its constructor method. You never call run() method directly; the start method calls it for
you.
Example: Extending Thread class
class MyProcess extends Thread
{
public void run()
{
}
public static void main(String args[])
{
MyProcess mp = new MyProcess();
mp.start();
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 18 of 50
}
Example: using Runnable interface
class MyProcess implements Runnable
{
public void run()
{
}
public static void main(String args[])
{
Thread mp = new Thread(new MyProcess());
mp.start();
}
}
Q20. What are synchronized methods and synchronized statements with example?
Ans. Synchronized is the way to avoid data corruption caused by simultaneous access to the same data by
multiple threads. Because all the thread in a program share the same memory space. It is possible to access
the same variable or run the same method of the same object at the same time.
To make the process synchronized in java there are two ways.
1. Synchronized methods
2. Synchronized statements.
Using the synchronized method we can make any method as synchronized method, all other threads that
try to access it on the same instance have to wait, but synchronized method will not work in all cases for that
purpose use synchronized statement.
Syntax:- synchronized void disp()
{
}
Synchronized statement: - This is the another way to synchronized access to the objects of a class that
was not designed for multithreaded access. The class doesn’t use synchronized method because that class
was created by some one else and you cannot make any changes in the class source code.
So you can add synchronized statement to the program to solve this problem and that block is defined in the
run method where the object of that class is called. We use a synchronized block called synchronized
statement.
Syntax:synchronized (object)
{
statement to be synchronized.
}
For Example:class A
{
synchronized void disp(String msg)
{
System.out.print(“(“+msg);
try
{
Thread.sleep(2000);
}
catch(Exception e)
{
}
System.out.println(“)”);
}
}
class abc extends Thread
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 19 of 50
{
String s1;
abc obj;
abc(abc obj1,String s)
{
obj=obj1;
s1=new String(s);
}
public void run()
{
obj.disp(s1);
}
public static void main(String arg[])
{
A obj=new A();
abc t=new abc(obj,”This”);
abc t1=new abc(obj,”is”);
abc t2=new abc(obj,”Synchronization”);
t.start();
t1.start();
t2.start();
}
}
Q21. What are DatagramPacket and why it is used in Socket Programming?
Ans. DatagramPackets can be created with one of four constructors. The first constructor specifies a buffer
that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket. The
second form allows you to specify an offset into the buffer at which data will be stored. The third form
specifies a target address and port, which are used by a DatagramSocket to determine where the data in the
packet will be sent. The fourth form transmits packets beginning at the specified offset into the data. Think of
the first two forms as building and the second two forms as stuffing and addressing . DatagramSocket class
has four constructors:1. DatagramPacket(byte data[], int size)
2. DatagramPacket(byte data[], int offset,int size)
3. DatagramPacket(byte data[], int size, InetAddress ipAddress, int port)
4. DatagramPacket(byte data[], int size, int offset , int size, InetAddress ipAddress, int port)
There are several methods for accessing the internal state of a DatagramPackat. They give
complete access to the destination address and port number of a packet as well as the raw data and its
length.
Q22. How UDP socket is used ? Discuss with an example.
Ans.
import java.io.*;
import java.net.*;
public class clientTestUDP
{
DatagramSocket datasocket;
DatagramPacket datapacket;
public static void main (String args [])
{
clientTestUDP UDPClient = new clientTestUDP ();
UDPClient.go ();
}
public void go ()
{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 20 of 50
byte B[ ] = new byte [64];
String str;
try
{
datasocket = new DatagramSocket(1313);
datapacket = new DatagramPacket(B, B.length);
while (true)
{
datasocket.receive (datapacket);
str= new String (datapacket.getData());
System.out.printIn ("Td signals receivedFrom" + datapacket.getAddress ()+"In Time is: "+str);
}
}
catch (Exception raised)
{
}
}
}
Q23. Discuss the Driver Manager Package class functions?
Ans. The JDBC Driver Manager is a very important class that defines objects which connect Java
applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture. It's very
simple and small that is used to provide a means of managing the different types of JDBC database driver
running on an application. The main responsibility of JDBC database driver is to load all the drivers found in
the system properly as well as to select the most appropriate driver from opening a connection to a
database. The Driver Manager also helps to select the most appropriate driver from the previously loaded
drivers when a new open database is connected.
The DriverManager class works between the user and the drivers. The task of the DriverManager class is to
keep track of the drivers that are available and handles, establishing a connection between a database and
the appropriate driver. It even keeps track of the driver login time limits and printing of log and tracing
messages. This class is mainly useful for the simple application, the most frequently used method of this
class is DriverManager.getConnetion(). We can know by the name of the method that this method
establishes a connection to a database.
The DriverManager class maintains the list of the Driver classes. Each driver has to be get registered in the
DriverManager class by calling the method DriverManager.registerDriver().
By calling the Class.forName() method the driver class get automatically loaded. The driver is loaded by
calling the Class.forName() method. JDBC drivers are designed to tell the DriverManager about themselves
automatically when their driver implementation class get loads.
Some of methods are given below:
1. deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the
DriverManager class.
2. registerDriver(Driver driver) : It registers the driver with the DriverManager class.
3. getConnection(String url) : It tries to establish the connection to a given database URL.
4. getConnection(String url, Sting user, String password) : It tries to establish the connection to a given
database URL.
5. getConnection(String url, Properties info) : It tries to establish the connection to a given database
URL.
6. getDriver(String url) : It attempts to locate the driver by the given string.
7. getDrivers() : It retrieves the enumeration of the drivers which has been registered with the
DriverManager class.
Q24. Explain the various JDBC Drivers in detail?
Ans .JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 21 of 50
Type 3: All Java/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)
Type 1 JDBC Driver
JDBC-ODBC Bridge driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a
generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other
alternative is available. The JDBC-ODBC Bridge allows access to almost any database, since the
database's ODBC drivers are already available.
Type 2 JDBC Driver
Native-API/partly Java driver
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into databasespecific calls i.e. this driver is specific to a particular database.
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than
the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type1 and also it uses
Native API which is Database specific.
Type 3 JDBC Driver
All Java/Net-protocol driver
Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then
translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4
drivers. This driver is server-based, so there is no need for any vendor database library to be present on
client machines.. This driver is fully written in Java and hence Portable. It is suitable for the web. The type 3
driver typically provides support for features such as caching (connections, query results, and so on), load
balancing, and advanced system administration such as logging and auditing. This driver is very flexible
allows access to multiple databases using one driver. They are the most efficient amongst all driver types.
Type 4 JDBC Driver
Native-protocol/all-Java driver
The Type 4 uses java networking libraries to communicate directly with the database server The major
benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform
independence and eliminate deployment administration issues. It is most suitable for the web. . Number of
translation layers is very less i.e. type 4 JDBC drivers don't have to translate database requests to ODBC or
a native connectivity interface or to pass the request on to another server, performance is typically quite
good. You don’t need to install special software on the client or server. Further, these drivers can be
downloaded dynamically.
Q25. What is JDBC/ODBC bridge?What are its Advantages?
Ans. The JDBC-ODBC Bridge allows applications written in the Java programming language to use the
JDBC API with many existing ODBC drivers. The Bridge is itself a driver based on JDBC technology ("JDBC
driver") that is defined in the class sun.jdbc.odbc.JdbcOdbcDriver. The Bridge defines the JDBC sub
protocol odbc.
The JDBC-ODBC Bridge offers several advantages
The JDBC-ODBC Bridge makes it unnecessary for programmers using the Java programming
language to deal with non-Java language concepts.

The JDBC-ODBC Bridge allows the programmer to rely on the JDBC API, which is relatively simple and
easy to learn.

JDBC-ODBC Bridge lets a program deal with ODBC through a standardized JDBC interface. That
helps a program avoid being tied to ODBC when a better solution comes along.
Q26. What are the methods provides by ResultSet Interface to Handle primitive data with suitable
example?
Ans. ResultSet Interface :- Resultset Interface store the result of the returned select SQL query . It
provide different types of methods like
1. next() :- it will return true if any next record is available in the ResultSet.
2. close() :- It is used to close the ResultSet object.
Methods to handle primitive data
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 22 of 50
1. getInt() :- use to get integer value from the database.
2. getString():- use to get string value from the database.
3. getFloat():- use to get float value form the the database
4. getDouble():- to get Double value from the database.
5. getShort():- to get small int value from the database.
For example
import java.sql.*;
class abc
{
public static void main(String arg[])
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“jdbc:odbc:ss”);
Statement st=con.createSatatement();
ResultSet rs=st.executeQuery();
ResultSetMetaData rs1=rs.getMetaData();
int num=rs1.getColumnCount();
System.out.print(“Number of columns in table=”+rs1);
System.out.println(rs1.getColumnName(1)+” “+rs1.getColumnName(2)+“ “+rs1.getColumnName(3));
}
catch(Exception e)
{
}
}
}
Q27. Advantages of servlets over competing technologies.
Ans. Advantages
1. Servlets are capable of running in the same process space as the web server
2. java servlets are compiled into java byte-code. So java servlets can execute much more quickly then
common scripting languages.
3. Servlets are written in java and executed by a java virtual machine(JVM). The JVM does not allow
Servlets to direct access to memory location, thereby elimination crashes that result from invalid memory
accesses.
4. Because servlets are written completely in java, the enjoy the same cross-platform support as any java
program.
5. Servlets can run or virtually every popular web server in use today.
6. Servlets are durable objects. because they remain in main memory until specifically instructed to be
destroyed.
7. Servlets can dynamically loaded either locally or across the network.
8. Servlets also support the multithreaded feature of java.
9. Servlets are protocol independent .
Q28. Define the life cycle of java servlet.
Ans. A java servlet has a life cycle that defines how the servlet is loaded and initialized, how it receives an
responds to requests and how it is taken out of service. The servlet lifecycle is defined by the
javax.servlet.Servlet interface.
The javax.servlet.Servlet interface defines methods that are called at specific times and in a specific order
during the servlets lifecycle. A java servlet invokes the init( ),service( ),and destroy( ) methods during its life
cycle. The various steps in a servlet life cycle are:1. create a servlet instance.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 23 of 50
2. The web server invokes the init(ServletConfig config) method of the java servlet. The argument, config
in the init(ServletConfig config) method is an instance of the ServletConfig class. It stores servlet parameters
and a reference to the servlet.
3. init( ):- the init( ) method is initializes the servlet and is invoked only once in the servlet life cycle.
4. service( ):- method is invoked to handle the requests made by the Web browser to the Java servlet.
You can override the service() method of the java servlet.
5. destroy( ):- The destroy( ) method is invoked to destroy a java servlet and free all the resource that a
java servlet occupies. The destroy( ) method is also invoked only once in a servlet lifecycle.
Q29. Differentiate between 2 tier and B-tier applications architectures.
Ans. Node & dumb terminate are connected to the server machine using different way.
1. 2 -tier architecture
2. 3-tier architecture.
1. 2-tier Architecture: - Client is directly connected to the main server. Every thing is handle by main
server.
Client 1
Data base
Server
Client 2
Client 3
2. 3-tier Architecture: - In three tier architecture contains three section.
1. Database Server.
2.
Application Server
3.
Clients
Database server maintains database after all condition check or business logics handled by Application
server. Client send request to application server then after all checks it transfer to the database server.
Application
Clients
Application
Client
Application
Difference between 2-tier and 3-tier
2-tier
1. Database |Business logic handle by
the same server.
2. Only having data server.
3. Easy Architecture to understand.
4. Less fault tolerance.
5. Client can directly connected to the
server which create more traffic
connected to server,
3-tier
1. Database and Business Logic Handled by
different servers.
2. That is a database server and application server.
3. Difficult or complex architecture.
4. Provide more fault tolerance
5. Database server the network different application
so different client can connect to the database
server using different application server
Q30. Explain all the methods provided by the Cookie class.
Ans. The Cookie class is used for session management with HTTP and HTTPS protocol . Cookies are used
to get Web Browsers to hold small amount of state data associated with a user’s web browsing. Common
applications for cookies include storing user preferences, automating low security user sign on facilities.
Cookie class provide the following methods
1. Cookie(String,String) :- This constructor of the class. It defines a cookie with an initial name/ value
pair.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 24 of 50
2. setDomain(String) :- Specifies the domain, which this cookie belongs to . This cookie will be visiable
only to the specified domain.
3. setMaxAge(int) :- Sets the maximum age of the cookie. The unit of measurement is seconds. A value of
zero will cause the cookie to be deleted.
4.
getValue() :- Returns the value of the cookie.
5. getName() :- returns the name of the cookie. The name of the cookie cannot be changed after it is
created.
6. getMaxAge() :- returns the maximum specified age of the cookie.
7. setValue():- sets the value of the cookie.
Q31. How can HttpServlet request /response are handled by the servlets with example?
Ans. The HTTPServlet Class is used to handle the HTTPServlet request. It is an abstract class so its
extends the GenericServlets base class and provide the frame work to Http protocol. Servlets writers must
subclass it and override at least one method.
The method normally overridden are
doGet()
doPost()
doGet() and doPost() methods are similar methods and receive the request from the client machine. but
there is a difference is that doGet() method accept a small request upto 255 character and doPost() can
accept request of unlimited string and hidden information is provided.
Both method have tha following syntax
doGet(HttpServletRequest rq,HttpServletResponse rs)
doPost(HttpServletRequest rq,HttpServletResponse rs)
Example:import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FCookie extends HttpServlet
{
public void doGet ( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
PrintWriter out;
response.setContentType("text/html");
out = response.getWriter();
Cookie c1 = new Cookie("CName1","Cookie Value1");
Cookie c2 = new Cookie("CName2","Cookie Value2");
response.addCookie(c1);
response.addCookie(c2);
out.println("<HTML><HEAD><TITLE>");
out.println(" This output is generated from a Servlet");
out.println("</TITLE></HEAD><BODY>");
out.println(" This has set 2 Cookies");
out.println("</BODY></HTML>");
out.close();
}
}
Q32. What are the functions you can perform servlets? Give methods for the purpose?
Ans. Servlets are the server side technology introduced by java that handles all clients request from the
single address spare. In the life cycle of a servlet, there are different type of methods used those represents
the lifecycle
Those methods are as under:1) init ( )
2) start ( )
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 25 of 50
3) service ( )
4) destrory ( )
1. init ( ) - Methods of the servlet is used to initialize the servlet so that it can handle the
requests of
different clients. Init happens once in the life cycle of servlet.
2. start ( ) - Working process of the servlet will start after the exention of start method and start method
execute as many time as the servlet stop.
3. service ( ) – Service method taken two argunins as servlet request and servlet response. Request to
take request of different clients where as response object is to provide response after taking request.
4. stop ( ) –Stop ( ) method exentes when the servlet stop working and can be restarted by start method.
5. destroy ( ) – Destroy method executes when we remove servlet from memory.
Q33. Create a servlet which uses Cookies.
Ans:- Cookies are small bits of textual information that a Web server sends to a browser and that the
browser returns unchanged when visiting the same Web site or domain later. By having the server read
information it sent the client previously, the site can provide visitors with a number of conveniences like
Identifying a user during an e-commerce session, avoiding username and password, customizing a site etc.
This example demonstrates use of cookie in a servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FCookie extends HttpServlet
{
public void doGet ( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
PrintWriter out;
response.setContentType("text/html");
out = response.getWriter();
Cookie c1 = new Cookie("CName1","Cookie Value1");
Cookie c2 = new Cookie("CName2","Cookie Value2");
response.addCookie(c1);
response.addCookie(c2);
out.println("<HTML><HEAD><TITLE>");
out.println(" This output is generated from a Servlet");
out.println("</TITLE></HEAD><BODY>");
out.println(" This has set 2 Cookies");
out.println("</BODY></HTML>");
out.close();
}
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 26 of 50
Section – A
[QUESTIONS 1 TO 30]
10 Marks Questions
[PAGE 32 TO 62]
Q1. List some of the drawing graphics method in the applet?
Ans:- The various methods of an Graphics class:Methods
Description
drawRect(int x,int y,int width, int height)
Helps you to draw a rectangle
fillRect(int x,int y,int width, int height)
Helps you to draw a fill rectangle
clearRect(int x,int y,int width, int height)
Allows you to erase a rectangle are on the
canvas.
drawLine(int x,int y,int x1, int y1)
Helps you to draw a line
drawstring(“msg”,int x,int y)
Displays a text string
drawPolygon(int x[ ],int y[ ],int num)
Helps you draw a hollow polygon.
getColor( )
Helps you retrieve the current drawing color
getFont ()
Helps you retrieve the currently used font
setColor(Color. red)
Use to set specified color.
setFont(Font obj)
Use to set font style,size,family.
drawArc()
Draws a hollow arc.
copyArea()
Copies a rectangular area on the canvas
drawOval(int x,int y,int width, int height)
Helps you to draw a hollow oval.
drawRoundRect(int x,int y,int width, int Helps you draw a hollow rectangle with
height,int angle1,int angle2)
rounded corners.
Q2. How is it possible to include your own Exceptions in a Java program? Write Suitable code for
the purpose.
Ans User–defined Exceptions can be created by extending inbuilt Exception class and then throwing the
exception.
import java.io.*;
class MyException extends Exception
{
MyException()
{
}
public String toString()
{
return “User created Exception occurred “;
}
}
public class UserExceptionDemo
{
public static void main(String[] args)
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println(“Enter number”);
int a = Integer.parseInt(br.readLine());
System.out.println(“Enter number”);
int b = Integer.parseInt(br.readLine());
display(a,b);
}
catch (MyException e)
{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 27 of 50
System.out.println(e);
}
catch (IOException e)
{
System.out.println(e);
}
}
static void display(int x,int y)throws MyException
{
if(x>y)
{
throw new MyException();
}
else
{
System.out.println(“Exception not occured”);
}
}
}
Q3. Write an applet that takes an integer and reverse that egg. 756 to 657.
Ans.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
//<applet code=app1 height=200 width=200></applet>
public class app1 extends Applet implements ActionListener
{
TextField t,t1;
Label l,r;
Button b;
public void init()
{
l=new Label("Enter no");
r=new Label("Result");
t=new TextField(10);
t1=new TextField(10);
b=new Button("click");
add(l);
add(t);
add(r);
add(t1);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent g)
{
String s=t.getText();
int i=Integer.parseInt(s);
int r1=0;
while(i>0)
{
r1=r1*10+i%10;
i/=10;
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 28 of 50
t1.setText(" "+r1);
}
}
Q4. What do you mean by AWT? What components and containers are used by AWT?
Ans. AWT stands for Abstract Widow Toolkit. It is one of the package defined in java which provides the
Graphical User Interface defining different types of containers and components implementing different types
of listeners for event handling. In the AWT class hierarchy, Component class is at the top of all classes ,
Container comes after then Window and Panel classes.
AWT used different types of containers and components.
Containers:
1. Window : - Window is the top level class of Frame that has no border and title. It always work as top
level window just like desktop window.
2. Frame : Frame is the subclass of Window that has title and border also contain navigation buttons like
minimize, maximized and cross button. Frame can also add user interface components.
3. Panel : Panel also having no title and border but we can use panel to group components that can be
hide or unhide. Panel is the super class of Applet.
Components:
1. Label 2. TextField 3. Button 4. Choice 5. MenuItem 6. List 7. TextArea 8. Scrollbar
Label : Label represent static text in java. Label has the following constructors and methods.
Constructors
Label()
Label(String txt)
Label(String txt,int align)
Methods
void setText(String txt);
void setAlign(int align);
String getText();
int getAlign();
TextField : contains text that can by modify or added at runtime having following constructors and methods:.
Constructors
TextField();
TextField(String txt);
TextField(int size);
Methods
void setText(String txt)
void setEchoChar(char c)
String getText();
char getEchoChar();
Choice : It represents dropdown list in java having following constructors and methods:Constructors
Choice();
Methods
add(String txt);
select(int index)
String getSelectedItem()
MenuItem that represent an item of the top horizonal menu that we can use with frame only.
List : List Control can be used for single selection and multiple selections both.
TextArea : A multilane Text Box that can be used for large text representation with multiple lines.
Scrollbar : A component used for horizontal and vertical scrollbar can be used to scroll any thing in vertical
and horizontal form.
Q5.
How an applet is developed with threads? Explain with example.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 29 of 50
Ans. Threads are used with applets to develop any animated applet. The following applet will display the
scrolling banner this applet scrolls a message from right to left.
import java.awt.*;
import java.applet.*;
/*<applet code=”SimpleBanner” width=300 height=50>
</applet>*/
public class SimpleBanner extends Applets implements Runnable
{
String msg=” A Simple Moving Banner”;
Thread t=null;
int state;
boolean stopflag;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
}
public void start()
{
t=new Thread(this);
stopflag=false;
t.start();
}
public void run()
{
char ch;
for( ; ; )
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
if(stopflag)
break;
}
catch(InterruptedException e){}
}
}
public void stop()
{
Stopflag=true;
t=null;
}
public void paint(Graphics g)
{
g.drawString(msg,50,50);
}
}
Q6. Write a program to implement the windowListener?
Ans:Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 30 of 50
import java. awt. *;
import java.awt.event.*;
import java.applet.*;
public class windowList extends Frame implements WindowListener
{
Label l1,l2;
TextField t1, t2;
Button b1;
public windowList()
{
super(“Implementing Window Listener”);
setLayout(new GridLayout(4,2));
l1 = new Label(“Name”);
l2 = new Label(“Password”);
t1 = new TextField(10);
t2 = new TextField(10);
t2.setEchoChar(‘*’);
b1= new Button(“Send”);
add(l1);
add(t1);
add(l2);
add(t2);
addWindowListener(this);
}
public static void main(String arg[])
{
windowList d =new windowLIst();
d.setSize(400,400);
d.setVisible(true);
}
public void windowClosing(WindowEvent we)
{
this .setVisible(false);
System.exit(0);
}
public void windowActivated(WindowEvent we) { }
public void windowDeactivated(WindowEvent we) { }
public void windowOpened(WindowEvent we) { }
public void windowClosed(WindowEvent we) { }
public void windowIconified(WindowEvent we) { }
public void windowDeiconified(WindowEvent we) { }
}
Q7. Explain MouseListener interface?
Ans:- The MouseListener interface is used for handling different operation that are associated
with the mouse by using these five methods : void mouseClicked(MouseEvent me):- invoked when you click a mouse buttons.
 void mouseEntered(MouseEvent me):- invoked when the mouse entered an AWT object to which the
mouse event is associated.
 void mouseExited(MouseEvent me):- invoked when the mouse leaves an AWT object to which the
mouse event is associated.
 void mousePressed(MouseEvent me):- invoked when the mouse key is pressed.
 void mouseReleased(MouseEvent me):- invoked when the mouse key is released.
The addMouseListener() method is used for monitoring an AWT object for the occurrence of a mouse event.
Now we use only one or two methods in exp as below:Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 31 of 50
public class mouslist extends Applet implements MouseListener
{
String msg=” “;
Int mx=0,my=0;
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
mx=me.getX();
my=me.getY();
msg=”Mouse Clicked at Position “ + mx+” : “+ my;
repaint();
}
public void mouseEntered(MouseEvent me)
{
mx=10;
my=10;
msg= “Mouse entered”;
repaint();
}
public void mouseExited(MouseEvent me)
{
}
public void mousePressed(MouseEvent me){ }
public void mouseReleased(MouseEvent me){ }
public void paint(Graphics g)
{
g.drawString(msg,mx,my);
}
}
Q8. Write a program to accept name ,class and medium (English or hindi).Display all details in a
TextArea when a button show is clicked. HINT-(using ctionlistener,itemlistener)
Ans:/*<applet code=”EventExamp” width=200 height=200></applet>*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventExamp extends Applet implements ActionListener, ItemListener
{
Label l1,l2;
Textfield t1,t2;
CheckboxGroup cg;
Checkbox c1,c2;
TextArea t;
Button b ;
public void init()
{
l1=new Label(“Name”);
l2=new Label(“Class”);
t1=new TextField(10);
t2=new TextField(10);
t=new TextArea(20);
cg =new CheckboxGroup();
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 32 of 50
c1=new Checkbox(“English”,cg,true);
c2=new Checkbox(“Hindi”,cg,false);
b = new Button(“show”);
c1.addItemListener(this);
c2.additemListener(this);
add(l1);
add(l2);
add(t1);
add(t2);
add(t);
add(c1);
add(c2);
add(b);
b.addActionListener(this);
}
public void itemStateChanged(ItemEvent e)
{
if(e.getSource()==c1)
String s=c1.getSelectedItem();
else
if(e.getSource()==c2)
String s=c2.getSelectedItem();
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b)
{
String s1=t1.getText();
String s2=t2.getText();
t.appendText(“Hello “+s1+”your subject is”+s2+”and medium is”+s );
}
}
Q9. Explain the applet life Cycle. In particular explain the roles of the init, start, stop, paint and
destroy methods?
Ans:- Every java applet inherits a set of default behaviors from the Applet class. As a result, when an
applet is loaded. It undergoes a series of changes in its state as below:1. Initialization(init () method):- This method is called to initialized an applet The life cycle of an applet is
begin on that time when the applet is first loaded into the browser and called the init() method. The init()
method is called only one time in the life cycle on an applet.
public void init()
{
}
2. Start (Start () method): The start method of an applet is called after the initialization method init(). This
method may be called multiples time when the Applet needs to be started or restarted. For Example if the
user wants to return to the Applet, in this situation the start( ) Method of an Applet will be called again.
Public void start()
{
}
3. Stop( Stop () method): The stop() method can be called multiple times in the life cycle of applet like the
start () method or should be called at least one time. The stop() method is called to put an applet to dead
state.
public void stop()
{
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 33 of 50
4. paint(paint(Graphics g)): Painting is the way an applet actually draws something on the screen, any
drawing object or text can be placed on the screen using draw object painting may occur number of times
during an applets life cycle. It can be called again and again by using repaint method.
5. Destroy( destroy() method): The destroy() method is called only one time in the life cycle of Applet like
init() method. This method is called when the browser needs to shut down. Destroying enables the applet
perform a clean up job just before it is destroyed or the browser exits. This object is to destroy an applet
from the memory.
Q10. Explain listeners and events with reference to java SWING components. Give two example
events, starting how they are generated, and two example listeners, explaining what they are
listening for, the example listeners need not manipulate the example events?
Ans:- Event is described as the change n state of an object.
Listeners are interface in java that defined the method for handling events.
Exp:Import javax.swing.*;
Import javax.swing.JApplet;
Import java.awt.*;
Import java.awt.event.*;
public class TextDemo extends JPanel implements ActionListener
{
JTextField login;
JPasswordField passwd;
JTextArea ta;
JButton enter, cancel;
public TextDemo( )
{
setLayout(new FlowLayout( ));
ta = new JTextArea(5,15);
login = new JTextField(15);
passwd = new JPassword(15);
enter = new JButton(“Enter”);
cancel = new JButton(“Cancel”):
enter.addActionListener(this);
cancel.addActionListener(this);
this.add(new Jlabel(“Enter Name:-“));
this.add(login);
this.add(new JLabel(“Password”));
this.add(passwd);
this.add(enter);
this.add(cancel);
this.add(ta);
}
public void actoinPerformed(ActionEvent ev)
{
if(ev.getSource()==enter)
{
ta.setText(“ “);
ta.append(“Name:- “+login.getText( )+”\n”);
ta.append(“User logged”);
}
else
if(ev.getSource( )== cancel)
{
ta.setText(“ “);
ta.append(“Login Cancel”);
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 34 of 50
}
public static void main(String arg[])
{
TextDemo td = new TextDemo( );
JFrame f =new JFrame (“Login”);
f.setContentPane(td);
f.setSize(300,300);
f.setVisible(true);
WindowListener l =new WindowAdapter( )
{
public void windowClosing(WindowEvent evn)
{
System.exit(0);
}
}
f.addWindowListener( l );
}
}
Q11. What are the differences between Thread class and Runnable interface ? Give example also.
Ans. Thread class: - In java multithreading programming can be created by extending the Thread class and
creating the object of that class. The extending class must override the run() method which is the entry point
for the new thread. It must also call start() to begin execution of the new thread.
Runnable interface: - implementing Runnable interface is the another method to create a multithreaded
program .Runnable abstracts a unit of executable code. To implement Runnable, a class need only
implement a single method called run().
The Thread class defines several methods that can be overridden by a derived class. Of these methods, the
only one that must be overridden is run(). The same method required when Runnable interface has to be
implemented.
Thread class should be extended only when they are being enhanced or modified in some way. If any of the
Threads and other methods are not overridden then Runnable interface is best.
Differences
Thread
Runnable
Thread class contain all the method used for Runnable Interface contains only the
multithreading in java.
declaration of run method.
Thread class is best when you are extending Runnable interface is most useable when you
only Thread
class because
Multiple want to use multithreading capability with
inheritance is not possible with classes in java applet or frame because to design any Applet
we have to extend applet class so we are not
able to extends another class with that class
so only way we have left is runnable interface.
Example of interface
class mythread implements Runnable
{
Thread t;
mythread()
{
t=new Thread(this, ”Demo thread”);
System.out.println(“child thread”+t);
t.start();
}
public void run()
{
try{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 35 of 50
for(int I=5;I>0;I--)
{
System.out.println(“chaild thread :”+I);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
System.out.println(“child interrupted.”);
}
System.out.println(“exiting child thread”);
}
}
class yourthread
{
public static void main(String ap[])
{
new mythread();
try
{
for(int I=5;I>0;I--)
{
System.out.println(“main tthread “+I);
Thread.sleep(1000);
}
}catch(Exception e){}
}
}
Thread class
class mythread extends Thread
{
mythread()
{
super(“demo thread”);
System.out.println(“child thread”+this);
start();
}
public void run()
{
try{ for(int I>5;I>0;I--)
{
System.out.println(“child thread”+I);
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
class you
{
public static void main(String ap[])
{new mythread();
try{
for(int I=5;I>0;I--)
{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 36 of 50
System.out.prntln(“main Thread”+I);
Thread.sleep(1000);
}
}
catch(Exception e){}
}
}
Q12. Define Thread Priority and Synchronization in java and give example of thread priority.
Ans. ThreadPriority: -Java assigns to each thread a priority that determines how that thread should be
treated with respect to the others. Thread priorities are integers that specify the relative priority of one thread
to another. A higher priority thread doesn’t run any faster than a lower –priority thread .it is used to decide
when to switch from one thread to the next. This process is called context switching.
Synchronization: - Multithreading programming introduces asynchronous behavior means a thread can be
interrupted by the another thread at any time, but some time It will create some problems e.g. you must
prevent one thread from writing data while another thread is in the middle of reading it. In this situation there
is a need of synchronization, which provided by monitor. The monitor is the small box can store single thread
at a time when a thread enters in the monitor no other thread can interrupt it until it exits from the monitor.
But java has no monitor class instead each object has its own implicit monitor that is automatically entered
when one of the object’s synchronized methods called once thread is inside a synchronized method no other
thread can call any other synchronized method code.
Q13. Write a program in java that handles multiple threads also ensure that the main thread is the
last thread to terminate?
Ans. Class A extends Thread
{
public A {String t)
{
super (t)
}
public void run ( )
{
int i ,
for ( c=1, c<=5, c++)
{
try
{
Thread.
sleep(1000
),
System out printer (get name ( )+ “:”+c)
}
catch (Exception e)
{}}}
Class b extends Thread
{
public b(String s)
{
super(s),
}
public void run ( )
}
int i ,
for (c=1,c<=5,c++)
{
try
{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 37 of 50
System .out. printer(get name c)+ “: “+c);
Thread.sleep(1000);,
catch (Exception e)
{}
}}}
class my
{
public statie void main (String s, j)
{
a x = new a ( “first” )
b y = new b ( “second “)
a. setPriority (1);
a. setPriority (5);
a.start ( );
b.start ( );
int c ;
for (1=0 ,c<5 ,c++)
{
try
{
Thread.sleep (1000)
System.out.printer(get name ( ) + “ : “ + c),
}
catch ( Exception e )
{}
}}}
Q14. Define the connectivity model used by the java to connect database.
Ans. The java application is the UI,this is in turn communicates with a driver manager using underlying java
code. Java provide numbers of techniques to connect front end application with back end database. The
following diagram show different connectivity methods.
Type I Drivers : This technique use the following.

Use Bridging techonology

Requeries installation/ configuration on client

Not good for web application.
e.g ODBC bridge.
Type II Drivers
Native API drivers.

Requires installation/ configuration on client machines

Used to leverage existing CLI Libraries.

Not a Thread safe technique. E.g oracle drivers , weblogic drivers.
Type III Drivers
Calls middleware server, usually on database host
Very flexible -- allows access to multiple databases using one driver
Only need to download one driver
But it’s another server application to install and maintain
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 38 of 50
e.g Symantec DBAnywhere
Type IV Drivers

100% Pure Java -- the Holy Grail

Use Java networking libraries to talk directly to database engines

Only disadvantage: need to download a new driver for each database engine e.g Oracle, mSQL
Q15. Explain the features and functionalities of java.sql Package.
Ans The java.sql package contains the entire JDBC API that sends SQL (Structured Query Language)
statements to relational databases and retrieves the results of executing those SQL statements. The JDBC
2.0 API supports a variety of new features and is part of the Java 2 platform.It provides the API for accessing
and processing data stored in a data source (usually a relational database) using the Java programming
language. This API includes a framework whereby different drivers can be installed dynamically to access
different data sources. Although the JDBC API is mainly formed to passing SQL statements to a database, it
provides for reading and writing data from any data source with a tabular format.
Main Features

Very fast database engine

Open source

Written in Java

Supports standard SQL, JDBC API

Strong security features

Multi version concurrency
Features( JDBC 2.0 )

The DataSource interface as a means of making a connection. The Java Naming and Directory
Interface (JNDI) is used for registering a DataSource object with a naming service and also for retrieving it.

Pooled connections -- allowing connections to be used and reused

Distributed transactions -- allowing a transaction to span diverse DBMS servers

RowSet technology -- providing a convenient means of handling and passing data
The java.sql package does the following functions Making a connection with a database via the DriverManager facility
o DriverManager class -- makes a connection with a driver
o SQLPermission class -- provides permission when code running within a Security Manager, such as an
applet, attempts to set up a logging stream through the DriverManager
o Driver interface -- provides the API for registering and connecting drivers based on JDBC technology
("JDBC drivers"); generally used only by the DriverManager class
o DriverPropertyInfo class -- provides properties for a JDBC driver; not used by the general user
 Sending SQL statements to a database
o Statement -- used to send basic SQL statements
o PreparedStatement -- used to send prepared statements or basic SQL statements (derived from
Statement)
o CallableStatement -- used to call database stored procedures (derived from PreparedStatement)
o Connection interface -- provides methods for creating statements and managing connections and their
properties
o Savepoint -- provides savepoints in a transaction
 Retrieving and updating the results of a query
o ResultSet interface
 Provides Metadata information
o DatabaseMetaData interface -- provides information about the database
o ResultSetMetaData interface -- provides information about the columns of a ResultSet object
o ParameterMetaData interface -- provides information about the parameters to PreparedStatement
commands
 Can handle Exceptions
o SQLException -- thrown by most methods when there is a problem accessing data and by some methods
for other reasons
o SQLWarning -- thrown to indicate a warning
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 39 of 50
o DataTruncation -- thrown to indicate that data may have been truncated
BatchUpdateException -- thrown to indicate that not all commands in a batch update executed successfully
Q16. Explain the classes and interfaces available in java.sql package to support JDBC?
Ans.This package provides the APIs for accessing and processing data which is stored in the database
especially relational database by using the java programming language. It includes a framework where
different drivers can be installed dynamically to access different databases especially relational databases.
This java.sql package contains API for the following :
1 Making a connection with a database with the help of DriverManager class
a) DriverManager class: It helps to make a connection with the driver.
b) SQLPermission class: It provides a permission when the code is running within a Security Manager, such
as an applet. It attempts to set up a logging stream through the DriverManager class.
c) Driver interface : This interface is mainly used by the DriverManager class for registering and connecting
drivers based on JDBC technology.
d). DriverPropertyInfo class : This class is generally not used by the general user.
2). Sending SQL Parameters to a database :
a). Statement interface: It is used to send basic SQL statements.
b). PreparedStatement interface: It is used to send prepared statements or derived SQL statements from the
Statement object.
c). CallableStatement interface : This interface is used to call database stored procedures.
d). Connection interface : It provides methods for creating statements and managing their connections and
properties.
e). Savepoint : It helps to make the savepoints in a transaction.
3). Updating and retrieving the results of a query:
a). ResultSet interface: This object maintains a cursor pointing to its current row of data. The cursor is
initially positioned before the first row. The next method of the resultset interface moves the cursor to the
next row and it will return false if there are no more rows in the ResultSet object. By default ResultSet object
is not updatable and has a cursor that moves forward only.
4.) Providing Standard mappings for SQL types to classes and interfaces in Java Programming
language.
a). Array interface: It provides the mapping for SQL Array.
b). Blob interface : It provides the mapping for SQL Blob.
c). Clob interface: It provides the mapping for SQL Clob.
d). Date class: It provides the mapping for SQL Date.
e). Ref interface: It provides the mapping for SQL Ref.
f). Struct interface: It provides the mapping for SQL Struct.
g). Time class: It provides the mapping for SQL Time.
h). Timestamp: It provides the mapping for SQL Timestamp.
i). Types: It provides the mapping for SQL types.
Q17. What do you mean by Prepared Statement interface with example?
Ans. The interface Prepared Statement extends the Statement interface. If the application requires execution
of a particular sql statement, it is pre-compiled and stored in a Prepared Statement object. This object then
can used many times to execute the statement efficiently. Commonly useable method by this interface.
1.executeQuery() :- This method is used to execute SQL statements. SQLException exception is thrown in
case of errors.
2. Execute Update() :- This method executes SQL UPDATE,DELETE, or INSERT statements. SQL
statements that do not return anything such as SQL DDL statement can also be executed.
Whenever we call these methods an error raised by the code i.e SQLException. So you must handle this
exception to work with these statements in JDBC.
Example
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class abc extends Frame implements ActionListener
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 40 of 50
{
PreparedStatement p;
Connection con;
Frame f;
Label l1,l2,l3;
Button b1;
abc()
{
f=new Frame();
l1=new Label(“Enter Rollno”);
l2=new Label(“Enter Name”);
l3=new Label(“Enter Marks”);
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
b1=new Button(“Insert”);
f.add(l1);
f.add(t1);
f.add(l2);
f.add(t2);
f.add(l3);
f.add(t3);
f.add(b1);
b1.addActionListener(this);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
try
{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con= DriverManager.getConnection(“jdbc:odbc:ss”);
p=con.prepareStatement(“insert into stu values(?,?,?)”);
p.setString(1,t1.getText());
p.setString(2,t2.getText());
p.setString(3,t3.getText());
p.executeUpdate();
}
catch(Exception e)
{
}
}
}
public static void main(String arg[])
{
abc obj=new abc();
}
}
Q18.Define the File class and describe its methods with example.
Ans:- The file class is used to deal with files and files system in java. The file class helps determine the
properties of a class such as the permissions to access the file, data and time when the file was created
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 41 of 50
and directory path for the file. File class have some method that are used to retrieved file properties such as
file name, path, can write or readable etc. all functions implements in this example:import java.io.File;
class test
{
static void Parameter(String str)
{
System.out.println(str);
}
public static void main(String arg[])
{
File f1 = new File(“/java/readme”);
Parameter(“File Name “+ f1.getName());
Parameter(“Path: “+ f1.getPath());
Parameter(“Abs Path “+f1.getAbsolutePath ());
Parameter(“Parent “+ f1.getParent ());
Parameter(f1.exists( ) ? “Exists “: “Does not exist”);
Parameter(f1.canWrite( ) ? “is Writeable “: “is not Writeable”);
Parameter(f1.canRead( ) ? “is Readable “: “is not Readable”);
Parameter(“is “ + (f1.isDirectory( ) ? “not “: “a Directory”);
Parameter(“File last Modified :” + f1.lastModified( ));
Parameter(“File size: “ +f1.length ( ) + “Bytes “);
}
}
Q19.
Ans.
Write statement to create a file stream that concatenates two existing files.
import java.io.*;
class my
{
public static void main(String ap[]) throws IOException
{
FileInputStream file1=null;
FileInputStream fiel2=null;
SequenceInputStream file3=null;
File1=new FileInputStream(“Text1.dat”);
File2=new FileInputStream(“Text2.dat’);
File3=new SequenceInputStream(file1,file2);
BufferedInputStream inBuffer=new BufferedInputStream(file3);
BufferedOutputStream outBuffer=new BufferedOutputStream(System.out);
int ch;
while((ch=inBuffer.read())!=-1)
{
outBuffer.write((char)ch);
}
inBuffer.close();
outBuffer.close();
file1.close();
file2.close();
}
}
Q20. Explain FileInput Stream and FileOutput Stream.
Ans. To read /write data into the files java provides two classes FileInputStream and FileOutputStream.
In java files are byte oriented and java provides methods to read and write bytes from and to a file. Java
allows you to wrap a byte-oriented file stream within a character-based object.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 42 of 50
FileOutputStream :- which create byte streams linked to files. To open a file you simply create an object of
one of these classes, specifying the name of the file as an agrument to the constructor.both classes support
additonal ,overriden constructors and throws FileNotFoundException when an output file is opened any pre
existing file by the same name is destroyed. To close the file call close() method.
FileInputSteam: - to read data from the file you can use read() method which defined under a version of
read() that is defined within FileInputStream
These methods also generate FileNotFoundException.
To read and write data of specific type in the file there is a need of two more classes
DataOutputStream and DataInputStream ,they create Stream objects to write and read data in specific data
type . DataOutputStream provides method for writing like writeInt(),
WriteFloat(),writeDouble etc.
DataInputStream class provides method to read data from the file like
readInt(),readFloat(),readDouble() etc.
Q21.How will you create and use TCP sockets(client and server)?
Ans:- Client program:import java.lang.*;
import java.io.*;
import java. net.*;
import java.net.InetAddress;
class TCPClient
{
public static void main(String arg[])
{
Socket soc = null;
DataInputStream dstream = null;
PrintStream ps = null;
System.out.println(“Client is connecting to TCPServer….”);
try
{
InetAddress ipass=
InetAddress.getByName(“java.sun.com”);
soc = new Socket(ipass,1050);
ps = new PrintStream(soc.getOutputStream( ));
ps.println(“ Hi! TCPClient hare..”);
dstream= new DataInputSteam(soc.getInputStream());
System.out.println(dstream.readLine());
}
catch(SocketException se)
{
System.out.println(“Error in sockets “ + se);
}
catch(IOException ioe)
{
System.out.println(“Input/Output Errors “ + se);
}
}
}
Server program:import java. Lang.*;
import java.io.*;
import java.net.*;
import java.net.InetAddress;
class TCPServer
{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 43 of 50
public static final int PORT=1050;
public static void main(String arg[])
{
ServerSocket sc=null;
Socket soc = null;
PrintStream ps = null;
DataInputStream ds = null;
System.out.println(“Server is waiting…..”);
try
{
sc = new ServerSocket(PORT);
System.out.println(“TCPServer has been started: “+ sc);
try
{
//creates a socket connection using TCP/IP
soc = sc.accept( );
System.out.println (“TCPclient has been connected: “+sc);
ds= new DataInputStream(soc.getInputStream());
ps = new PrintStream(soc.getOutputStream( ));
ps.println(“ Hello! TCPServer here.”);
ps.close();
soc.close();
}
catch(SocketException se)
{
System.out.println(“Error in server Stating “ +
se);
}
catch(Exception e)
{
System.out.println(“Error in server starting “+ e);
}
System.out.println(“ Connection from : “ + soc.getInetAddress());
}
catch(Exception ie)
{
System.out.println(“Error in TCPServer “ + e.getMessage());
}
}
}
Q22. Discuss UDP protocol.
Or
How do we create UDP sockets in java ?Explain with the help of an example.
Ans. UDP protocol
transfers datagram
packets. Datagram
packets are used to implement a
connectionless packet delivery service supported by the UDP protocol. Each message is transferred from
source machine to destination based on information contained within that packet. That means, each packet
needs to have destination address and each packet might be routed differently, and might arrive in any
order. Packet delivery is not guaranteed.
Java supports datagram communication through the following classes:


The class DatagramPacket contains several constructors that can be used for creating packet
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 44 of 50
object. One of them is:
DatagramPacket(byte[] buf, int length, InetAddress address,int port);
This constructor is used for creating a datagram packet for sending packets of length length to the specified
port number on the specified host. The message to be transmitted is indicated in the first argument.
The key methods of DatagramPacket class are:
byte[] getData()
Returns the data buffer.
int getLength()
Returns the length of the data to be sent or the length of the data received.
void setData(byte[] buf)
Sets the data buffer for this packet.
void setLength(int length)
Sets the length for this packet.
The class DatagramSocket supports various methods that can be used for transmitting or
receiving data a datagram over the network. The two key methods are:
void send(DatagramPacket p)
Sends a datagram packet from this socket.
void receive(DatagramPacket p)
Receives a datagram packet from this socket.
A simple UDP server program that waits for client’s requests and then accepts the message
(datagram) and sends back the same message is given below.
import java.net.*;
import java.io.*;
public class UDPServer
{
public static void main(String args[])
{
DatagramSocket aSocket = null;
if (args.length < 1) {
System.out.println("Usage: java UDPServer <Port Number>");
System.exit(1);
}
try
{
int socket_no = Integer.valueOf(args[0]).intValue();
aSocket = new DatagramSocket(socket_no);
byte[] buffer = new byte[1000];
while(true) {
DatagramPacket request = new DatagramPacket(buffer,
buffer.length);
aSocket.receive(request);
DatagramPacket reply = new DatagramPacket(request.getData(),
request.getLength(),request.getAddress(),
request.getPort());
aSocket.send(reply);
}
}
catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 45 of 50
finally
{
if (aSocket != null)
aSocket.close();
}
}
}
A corresponding client program for creating a datagram and then sending to the above server
import java.net.*;
import java.io.*;
public class UDPClient
{
public static void main(String args[])
{
DatagramSocket aSocket = null;
if (args.length < 3)
{
System.exit(1);
}
try {
aSocket = new DatagramSocket();
byte [] m = args[0].getBytes();
InetAddress aHost = InetAddress.getByName(args[1]);
int serverPort = Integer.valueOf(args[2]).intValue();
DatagramPacket request =
new DatagramPacket(m, args[0].length(), aHost, serverPort);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData()));
}
catch (SocketException e)
{
System.out.println("Socket: " + e.getMessage());
}
catch (IOException e)
{
System.out.println("IO: " + e.getMessage());
}
finally
{
if (aSocket != null)
aSocket.close();
}
}
}
Q23. What is a distributed object System? How RMI provides distributed object
mechanism.
Ans. The Distributed object system is a technology that combines networking and objectoriented programming.
A distributed system includes nodes that perform compilations. A node may be a pc,a mainframe computer.
The nodes of a distributed system are scattered. The node in use is the local node any other node is the
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 46 of 50
remote node. A distributed system can not be established without a network that connects nodes and allow
the exchange of data.
RMI FOR DISTRIBUTED COMPUTING.
RMI is a simple method used for developing and deploying distributed object application in java
environment. In RMI an object oriented application creation is as simple as writing a stand alone java
application. It enables a programmer to create distributed java application, in which the methods of the
remote java object can be called from other java virtual machines running either on the same host or on the
different host scattered across a network..
Remote object call is identical from the local objects with the following exceptions
1. An object passed as a parameter to a remote method or returned from the method must be serial able
or be another Remote object.
2. method passed by the remote objects are called by value and not by reference
3. a client always refers tp remote object through one of the Remote interface must be implements.
The java.rmi and java.rmi.server package contain the interfaces and classes that defines the functionality of
java RMI system.
Q24. Explain RMI Architecture with layer reference.
Ans. RMI architecture consist of four layers
1. Application Layer : - This layer contains the actual implementation of the client and sever application.
It is in this layers that high – level calls are made to access and export remote objects.
2. The Proxy Layer : - This layer contains the client stub and server skeleton objects. The application
layer communicates with this proxy layer directly. All calls to remote objects and marshaling of parameters
and return objects are done through these proxies.
3. The Remote Reference Layer :– The RRL(Remote Reference Layer ) handles packaging of a method
call and its parameters and its return values for transport over the network.
The RRL uses a server side and the client-side component to communicate via the network
layer.
4. Transport Layer :- The transport layer sets up connections, manages existing connections and
handles remote objects residing in its address space.
Q25. Write steps to create RMI?
Ans:- 1.Create a interface.
2. Create a class that implements the interface.
3. Create a client that connects to the server object using Naming.lookup() method.
remote.java
import java.rmi.*;
public interface remote extends Remote
{
public int sum(int a,int b)throws RemoteException;
}
server.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class server extends UnicastRemoteObject implements remote
{
public server()throws RemoteException
{
super();
}
public int sum(int a,int b)throws RemoteException
{
return (a+b);
}
public static void main(String arg[])
{
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 47 of 50
try
{
server obj=new server();
Naming.rebind("helloserver",obj);
System.out.println("Server is Ready");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
client.java
import java.rmi.*;
class client
{
public static void main(String rg[])
{
try
{
remote obj=(remote)Naming.lookup("helloserver");
int c=obj.sum(4,5);
System.out.println("Sum="+c);
}
catch(Exception e)
{
}
}
}
Q26. What are the various server side technologies? Explain.
Ans. There are numbers of server side technology that helps to create response for the client from the
server side. Like Common Gateway Interface(CGI), Active Server Pages(ASP), Servlets, Java Server
Pages(JSP) etc. These technologies are used to create dynamic web pages.
COMMON GATEWAY INTERFACE :- an interface used to create communication with web server in early
days. In this technology a server could dynamically construct a page by creating a separate process to
handle each client request allow the separate process to read data from HTTP request and write data to the
HTTP response. A variety of languages were used to build CGI programs, including C, C++ and Perl.
ACTIVE SERVER PAGES :- another server side technology introduced by Microsoft to create server side
response for clients. Having very high performance with a draw back i.e., can only accessible on Microsoft
based platform.
SERVLETS :- the server side technology introduced by java to create server side response. Java security
manager provide platform independence by reducing traffic to network because of handling all the client
request on single address space.
JAVA SERVER PAGES :- technology allows web developers and designers to rapidly develop and easily
maintain, information-rich , dynamic web pages that leverage existing business system. JSP enables rapid
development of web based application that platform are independent. Create response for client with
servlets.
Q27. What is a meant by java Servlets? What is difference between the HTTPServlets and Generic
Servlets? Explain their methods and the parameters of those methods?
Ans: Java servlets are the java programs that are used to handle server-side operations in client-server
architecture. Java servlets are platform independent, and therefore provide enhanced features for clientserver operations. Java complied java servlets can be invoked multiple times by the web servers without any
need of recompilation.
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 48 of 50
Difference Between the HTTPServlets and Generic Servelets: Generic servlet is superclass for HttpServlet.
 httpservlet class can also have bydefault service() method.it's not necessary that you can only have
doGet() and doPost() method defined.
 Generic servlet is used for small data transfer whereas HttpServlet is used for huge data transfer.
 Generic servlets class of the javax.servlet package is used to cerate servlets which can
work in any protocols(i.e;not only using HTML format).. where as httpservlets are used to
create http servlets.
 Http servlet is the sub class of Generic sevlet so all the life cycle methods available in the
generic servlets are available to the Http servlets. Http servlets provides methods that
supports cookies,sessions etc.while generic servlets are not.
 Http servlet request,Http servlet responce methods extends generic servlet request,generic servlet
responce.
 GenericServlet belongs to javax.servlet package . HttpServlet belongs to javax.servlet.http package.
 GenericServlet is an abstract class which extends Object and implements Servlet, ServletConfig and
java.io.Serializable interfaces. HttpServlet is an abstract class which extends GenericServlet and
implements java.io.Serializable
Q28. Define HttpServletsRequest and HttpServletsResponseInterface?
Ans. The HttpServletsRequest Interface encapsulates information of the request made to a servlets. This
interface gets information form the client to the servlets for use in the service () method. It allows HTTP
protocol specified header information to be accessed from the service () method.
HttpServletsRequest provides following methods
1. getMethod() :- Returns the HTTP method (GET, POST)
with which the request was made.
2. getQueryString() :- Returns any Query String that is part of the HTTP REQUEST.
3. getRemoteUser() :- Returns the name of the ser making the HTTP request.
4. getRequestedSessionId() :- To returns the Session Id specified with the HTTP request.
5. getSession(Boolean) :- If Boolean is FALSE, It return s the current valid session associated with the
HTTP request. If Boolean is TRUE, it creates a new session.
6. isRequestedSessionIdValid() :- Checks whether the HTTP request is associated with a session that is
valid in the current session context
7. getCookies() : :- Returns the array of cookies found in the HTTP request.
The HttpServletsResponse :- encapsulates information of the response sent by a servlets to a client. This
interface allows a servlets’s service() method to manipulate HTTP protocol specified header information and
return data to its clients.
Methods of HttpServletsResponse
addCookie(Cookies): Adds the specified cookie to the response.
encodeUrl(String) :- Encodes the specified URL by adding the session Id to it. If encoding is not required , it
returns the URL unchanged.
sendRedirect(String) :- Sends a temporary redirect response to a client using the specified redirect location
URL.
Q29. How does JSP differ from Servlets?
Ans. Java provide two types of serverside technology for web clients.
1. servlet
2. JSP
Both techonologies provide services to the web clients. But they have some differences.
Servlet
Jsp
Servlets, make you generate the entire page Java Server Pages (JSP) is a technology that
via your program, even though most of it is lets you mix regular, static HTML with
always the same.
dynamically-generated HTML.
In Servlet each and every thing we have to JSP lets you create the two parts separately.
define should be with in the same class file.
Java Server Pages (JSP) is a Sun
Microsystems specification for combining
Java with HTML to provide dynamic content
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 49 of 50
HTTP servlets, in which you embed HTML
inside Java code.
In servlet you have to remember class code.
Because each and every is define for servlet
response is in the servlet class.
Servlet programming is done through only by
the programmer who is doing programming in
it. No separate designer can be assigned for
static pages.
for Web pages
When you create dynamic content, JSPs are
more convenient to write than HTTP servlets
because they allow you to embed Java code
directly into your HTML pages
JSP is part of the Java 2 Enterprise Edition
(J2EE). And users need not remember large
class codes. Because its automatically
generate servlet
It caters to two different types of developers:
HTML developers, who are responsible for the
graphical design of the page, and Java
developers, who handle the development of
software to create the dynamic content.
Example of JSP
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors -->
<% =new java.util.date() %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for all the rest of the on-line store's Web page.
</BODY>
</HTML>
Q30. Explain with suitable example request and response object.
Ans. Request object is used to handle the request send from the direct machine.
Response object used to transfer response to the client machine from server. The following example will
show you how request are handle and response is transfer to the client.
User.HTML
<HTML>
<BODY>
<Form name = f1 method = Post action= “http:// Localhost:8080/servelet/user”>
<center>
<username <Input type = text name = “Un”>
<BR>
Password <input type = Password name = “PW”>
<BR>
<Input type = submit value = send >
<BR>
</center>
</FORM>
</BODY>
</HTML>
user. Java
import java.servlets. *;
import java.io. *;
public class user extends GenericServlet
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100
SUBJECT: ‘Adv. JAVA’ (BSC-(IT) – 6) Page 50 of 50
{
public void service (ServletRequest rq, ServletsResponse res) throws ServletException, IOException
{
rs.setContentType (“Text / HTML”);
PrintWriter PW = res.getWriter ();
PW.Println (“<HTML> <BODY> “);
PW.Println (“<H2> your email ID is: <IH2> “)
PW.println (“<B>” + rq.getPerameter (“Un”) + “< /B>”);
PW.println (“yahoo.com”);
PW.close ();
}
}
Prepared By: - Vaishnoo Maa Computers, SCO 145, Chotti Baradari, Patiala.
Ph. 0175-2205100, 2215100