My Profile

Friday, January 14, 2011

Java FAQ's Volume2

52.When is init(),start() called ?
53.When you navigate from one applet to another what are the methods called ?
54.What is the difference between Trusted and Untrusted Applet ?
What is Exception ?
55.What are the ways you can handle exception ?
56.When is try,catch block used ?
57.What is finally method in Exceptions ?
58.What are the types of access modifiers ?
59.What is protected and friendly ?
60.What are the other modifiers ?
61.Is synchronised modifier ?
62.What is meant by polymorphism ?
63.What is inheritance ?
64.What is method Overloading ? What is this in OOPS ?
65.What is method Overriding ? What is it in OOPS ?
66.Does java support multi dimensional arrays ?
67.Is multiple inheritance used in Java ?
68.How do you send a message to the browser in JavaScript ?
69.Does javascript support multidimensional arrays ?
70.Why is XML used mainly?
71.Do use coding for database connectivity in XML?
72.What is DTD ?
73.Is there any tool in java that can create reports ?








Interview Type of Questions




74.What is meant by Java ?
75.What is meant by a class ?
76.What is meant by a method ?
77.What are the OOPS concepts in Java ?
78.What is meant by encapsulation ? Explain with an example
79.What is meant by inheritance ? Explain with an example
80.What is meant by polymorphism ? Explain with an example
81.Is multiple inheritance allowed in Java ? Why ?
82.What is meant by Java interpreter ?
83.What is meant by JVM ?
84.What is a compilation unit ?
85.What is meant by identifiers ?
86.What are the different types of modifiers ?
87.What are the access modifiers in Java ?
88.What are the primitive data types in Java ?
89.What is meant by a wrapper class ?
90.What is meant by static variable and static method ?
91.What is meant by Garbage collection ?
92.What is meant by abstract class
93.What is meant by final class, methods and variables ?
94.What is meant by interface ?
95.What is meant by a resource leak ?
96.What is the difference between interface and abstract class ?
97.What is the difference between public private, protected and static What is meant by method overloading ?
98.What is meant by method overriding ?
99.What is singleton class ?
100.What is the difference between an array and a vector ?
101.What is meant by constructor ?
102.What is meant by casting ?
103.What is the difference between final, finally and finalize ?
104.What is meant by packages ?
105.What are all the packages ?
106.Name 2 calsses you have used ?
107.Name 2 classes that can store arbitrary number of objects ?
108.What is the difference between java.applet.* and java.applet.Applet ?
109.What is a default package ?
110.What is meant by a super class and how can you call a super class ?
111.What is anonymous class ?
112.Name interfaces without a method ?
113.What is the use of an interface ?
114.What is a serializable interface ?
115.How to prevent field from serialization ?
116.What is meant by exception ?
117.How can you avoid the runtime exception ?
118.What is the difference between throw and throws ?
119.What is the use of finally ?
120.Can multiple catch statements be used in exceptions ?
121.Is it possible to write a try within a try statement ?
122.What is the method to find if the object exited or not ?
123.What is meant by a Thread ?
124.What is meant by multi-threading ?
125.What is the 2 way of creating a thread ? Which is the best way and why ?
126.What is the method to find if a thread is active or not ?
127.What are the thread-to-thread communcation ?
128.What is the difference between sleep and suspend ?
129.Can thread become a member of another thread ?
130.What is meant by deadlock ?
131.How can you avoid a deadlock ?
132.What are the three typs of priority ?
133.What is the use of synchronizations ?
134.Garbage collector thread belongs to which priority ?
135.What is meant by time-slicing ?
136.What is the use of ‘this’ ?
137.How can you find the length and capacity of a string buffer ?
138.How to compare two strings ?
139.What are the interfaces defined by Java.lang ?
140.What is the purpose of run-time class and system class
141.What is meant by Stream and Types ?
142.What is the method used to clear the buffer ?
143.What is meant by Stream Tokenizer ?
144.What is serialization and de-serialisation ?
145.What is meant by Applet ?
146.How to find the host from which the Applet has originated ?
147.What is the life cycle of an Applet ?
148.How do you load an HTML page from an Applet ?
149.What is meant by Applet Stub Interface ?
150.What is meant by getCodeBase and getDocumentBase method ?
151.How can you call an applet from a HTML file
152.What is meant by Applet Flickering ?
153.What is the use of parameter tag ?
154.What is audio clip Interface and what are all the methods in it ?
155.What is the difference between getAppletInfo and getParameterInfo ?
156.How to communicate between applet and an applet ?
157.What is meant by event handling ?
158.What are all the listeners in java and explain ?
159.What is meant by an adapter class ?
160.What are the types of mouse event listeners ?
161.What are the types of methods in mouse listeners ?
162.What is the difference between panel and frame ?
163.What is the default layout of the panel and frame ?
164.What is meant by controls and types ?
165.What is the difference between a scroll bar and a scroll panel.
166.What is the difference between list and choice ?
167.How to place a component on Windows ?
168.What are the different types of Layouts ?
169.What is meant by CardLayout ?
170.What is the difference between GridLayout and GridBagLayout
171.What is the difference between menuitem and checkboxmenu item.
172.What is meant by vector class, dictionary class , hash table class,and property class ?
173.Which class has no duplicate elements ?
174.What is resource bundle ?
175.What is an enumeration class ?
176.What is meant by Swing ?
177.What is the difference between AWT and Swing ?
178.What is the difference between an applet and a Japplet
179.What are all the components used in Swing ?
180.What is meant by tab pans ?
181.What is the use of JTree ?
182.How can you add and remove nodes in Jtree.
183.What is the method to expand and collapse nodes in a Jtree ?
184.What is the use of JTable ?
185.What is meant by JFC ?
186.What is the class in Swing to change the appearance of the Frame in Runtime.
187.How to reduce flicking in animation ?
188.What is JDBC ?
189.How do you connect to the database ? What are the steps ?
190.What are the drivers available in JDBC ? Explain
191.How can you load the driver ?
192.What are the different types of statement s ?
193.How can you created JDBC statements ?
194.How will you perform transactions using JDBC ?
195.What are the two drivers for web apllication?
196.What are the different types of 2 tier and 3 tier architecture ?
197.How can you retrieve warning in JDBC ?
198.What is the exception thrown by JDBC ?
199.What is meants by PreparedStatement ?
200.What is difference between PreparedStatement and Statement ?
201.How can you call the stored procedures ?
202.What is meant by a ResultSet ?
203.What is the difference between ExecuteUpdate and ExecuteQuery ?
204.How do you know which driver is connected to a database ?
205.What is DSN and System DSN and differentiate these two ?
206.What is meant by TCP, IP, UDP ?
207.What is the difference between TCP and UDP ?
208.What is a proxy server ?
209.What is meant by URL
210.What is a socket and server sockets ?
211.When MalformedURLException and UnknownHost Exception throws ?
212.What is InetAddress ?
213.What is datagram and datagram packets and datagram sockets ?
214.Write the range of multicast socket IP address ?
215.What is meant by a servlet ?
216.What are the types of servlets ? Explain
217.What is the different between a Servlet and a CGI.
218.What is the difference between 2 types of Servlets ?
219.What is the type of method for sending request from HTTP server ?
220.What are the exceptions thrown by Servlets ? Why ?
221.What is the life cycle of a servlet ?
222.What is meant by cookies ?
223.What is HTTP Session ?
224.What is the difference between GET and POST methods ?
225.How can you run a Servlet Program ?
226.How to commuincate between an applet and a servlet ?
227.What is a Servlet-to-Servlet communcation ?
228.What is Session Tracking ?
229.What are the security issues in Servlets ?
230.What is HTTP Tunneling
231.How do you load an image in a Servlet ?
232.What is Servlet Chaining ?
233.What is URL Rewriting ?
234.What is context switching ?
235.What is meant by RMI ?
236.Explain RMI Architecture ?
237.What is meant by a stub ?
238.What is meant by a skelotn ?
239.What is meant by serialisation and deserialisation ?
240.What is meant by RRL ?
241.What is the use of TL ?
242.What is RMI Registry ?
243.What is rmic ?
244.How will you pass parameter in RMI ?
245.What exceptions are thrown by RMI ?
246.What are the steps involved in RMI ?
247.What is meant by bind(), rebind(), unbind() and lookup() methods
248.What are the advanatages of RMI ?
249.What is JNI ?
250.What is Remote Interface ?
251.What class is used to create Server side object ?
252.What class is used to bind the server object with RMI Registry ?
253.What is the use of getWriter method ?
254.What is meant by Javabeans ?
255.What is JAR file ?
256.What is meant by manifest files ?
257.What is Introspection ?
258.What are the steps involved to create a bean ?
259.Say any two properties in Beans ?
260.What is persistence ?
261.What is the use of beaninfo ?
262.What are the interfaces you used in Beans ?
263.What are the classes you used in Beans ?






INTERVIEW QUESTIONS
264.What is the diffrence between an Abstract class and Interface ?
265.What is user defined exception ?
266.What do you know about the garbate collector ?
267.What is the difference between C++ & Java ?
268.Explain RMI Architecture?
269.How do you communicate in between Applets & Servlets ?
270.What is the use of Servlets ?
271.What is JDBC? How do you connect to the Database ?
272.In an HTML form I have a Button which makes us to open another page in 15 seconds. How will do you that ?
273.What is the difference between Process and Threads ?
274.What is the difference between RMI & Corba ?
275.What are the services in RMI ?
276.How will you initialize an Applet ?
277.What is the order of method invocation in an Applet ?
278.When is update method called ?
279.How will you pass values from HTML page to the Servlet ?
280.Have you ever used HashTable and Dictionary ?
281.How will you communicate between two Applets ?
282.What are statements in JAVA ?
283.What is JAR file ?
284.What is JNI ?
285.What is the base class for all swing components ?
286.What is JFC ?
287.What is Difference between AWT and Swing ?
288.Considering notepad/IE or any other thing as process, What will happen if you start notepad or IE 3 times? Where 3 processes are started or 3 threads are started ?
289.How does thread synchronization occurs inside a monitor ?
290.How will you call an Applet using a Java Script function ?
291.Is there any tag in HTML to upload and download files ?
292.Why do you Canvas ?
293.How can you push data from an Applet to Servlet ?
294.What are 4 drivers available in JDBC ?
295.How you can know about drivers and database information ?
296.If you are truncated using JDBC, How can you know ..that how much data is truncated ?And What situation , each of the 4 drivers used ?
297.How will you perform transaction using JDBC ?
298.In RMI, server object first loaded into the memory and then the stub reference is sent to the client ? or whether a stub reference is directly sent to the client ?
299.Suppose server object is not loaded into the memory, and the client request for it , what will happen?
300.What is serialization ?
301.Can you load the server object dynamically? If so, what are the major 3 steps involved in it ?
302.What is difference RMI registry and OSAgent ?
303.To a server method, the client wants to send a value 20, with this value exceeds to 20,. a message should be sent to the client ? What will you do for achieving for this ?
304.What are the benefits of Swing over AWT ?
305.Where the CardLayout is used ?
306.What is the Layout for ToolBar ?
307.What is the difference between Grid and GridbagLayout ?
308.How will you add panel to a Frame ?
309.What is the corresponding Layout for Card in Swing ?
310.What is light weight component ?
311.Can you run the product development on all operating systems ?
312.What is the webserver used for running the Servlets ?
313.What is Servlet API used for conneting database ?
314.What is bean ? Where it can be used ?
315.What is difference in between Java Class and Bean ?
316.Can we send object using Sockets ?
317.What is the RMI and Socket ?
318.How to communicate 2 threads each other ?
319.What are the files generated after using IDL to Java Compilet ?
320.What is the protocol used by server and client ?
321.Can I modify an object in CORBA ?
322.What is the functionality stubs and skeletons ?
323.What is the mapping mechanism used by Java to identify IDL language ?
324.Diff between Application and Applet ?
325.What is serializable Interface ?
326.What is the difference between CGI and Servlet ?
327.What is the use of Interface ?
328.Why Java is not fully objective oriented ?
329.Why does not support multiple Inheritance ?
330.What it the root class for all Java classes ?
331.What is polymorphism ?
332.Suppose If we have variable ‘ I ‘ in run method, If I can create one or more thread each thread will occupy a separate copy or same variable will be shared ?
332.In servlets, we are having a web page that is invoking servlets username and password ? which is cheks in the database ? Suppose the second page also If we want to verify the same information whethe it will connect to the database or it will be used previous information?
333.What are virtual functions ?
334.Write down how will you create a binary Tree ?
335.What are the traverses in Binary Tree ?
336.Write a program for recursive Traverse ?
337.What are session variable in Servlets ?
338.What is client server computing ?
339.What is Constructor and Virtual function? Can we call Virtual funciton in a constructor ?
340.Why we use OOPS concepts? What is its advantage ?
341.What is the middleware ? What is the functionality of Webserver ?
342.Why Java is not 100 % pure OOPS ? ( EcomServer )
343.When we will use an Interface and Abstract class ?
344.What is an RMI?
345.How will you pass parameters in RMI ? Why u serialize?
346.What is the exact difference in between Unicast and Multicast object ? Where we will use ?
347.What is the main functionality of the Remote Reference Layer ?
348.How do you download stubs from a Remote place ?
349.What is the difference in between C++ and Java ? can u explain in detail ? I want to store more than 10 objects in a remote server ? Which methodology will follow ?
350.What is the main functionality of the Prepared Statement ?
351.What is meant by static query and dynamic query ?
352.What are the Normalization Rules ? Define the Normalization ?
353.What is meant by Servelet? What are the parameters of the service method ?
354.What is meant by Session ? Tell me something about HTTPSession Class ?
355.How do you invoke a Servelt? What is the difference in between doPost and doGet methods ?
356.What is the difference in between the HTTPServlet and Generic Servlet ? Expalin their methods ? Tell me their parameter names also ?
357.Have you used threads in Servelet ?
358.Write a program on RMI and JDBC using StoredProcedure ?
359.How do you sing an Applet ?
360.In a Container there are 5 components. I want to display the all the components names, how will you do that one ?
361.Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA ?
362.Tell me the latest versions in JAVA related areas ?
363.What is meant by class loader ? How many types are there? When will we use them?
364.How do you load an Image in a Servlet ?
365.What is meant by flickering ?
366.What is meant by distributed Application ? Why we are using that in our applications ?
367.What is the functionality of the stub ?
368.Have you used any version control ?
369.What is the latest version of JDBC ? What are the new features are added in that ?
370.Explain 2 tier and 3 -tier Architecture ?
371.What is the role of the webserver ?
372.How have you done validation of the fileds in your project ?
373.What is the main difficulties that you are faced in your project ?
374.What is meant by cookies ? Explain ?
375.Problem faced in your earlier project
376.How OOPS concept is achieved in Java
377.Features for using Java
378.How does Java 2.0 differ from Java 1.0
379.Public static void main - Explain
380.What are command line arguments
381.Explain about the three-tier model
382.Difference between String & StringBuffer
383.Wrapper class. Is String a Wrapper Class
384.What are the restriction for static method
385.Purpose of the file class
386.Default modifier in Interface
387.Difference between Interface & Abstract class
388.Can abstract be declared as Final
389.Can we declare variables inside a method as Final Variables
390.What is the package concept and use of package
391.How can a dead thread be started
392.Difference between Applet & Application
393.Life cycle of the Applet
394.Can Applet have constructors
395.Differeence between canvas class & graphics class
396.Explain about Superclass & subclass
397.Difference between TCP & UDP
398.What is AppletStub
399.Explain Stream Tokenizer
400.What is the difference between two types of threads
401.Checked & Unchecked exception
402.Use of throws exception
403.What is finally in exception handling
404.Vector class
405.What will happen to the Exception object after exception handling
406.Two types of multi-tasking
407.Two ways to create the thread
408.Synchronization
409.I/O Filter
410.How can you retrieve warnings in JDBC
411.Can applet in different page communicate with each other
412.Four driver Manager
413.Features of JDBC 20
414.Explain about stored procedures
415.Servlet Life cycle
416.Why do you go for servlet rather than CGI
417.How to generate skeleton & Stub classes
418.Explain lazy activation
419.Firewalls in RMI






Database - JDBC (java.sql)
Connecting to a Database
This example uses the JDBC-ODBC bridge to connect to a database called “mydatabase”.
try {
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);




String url = “jdbc:odbc:mydatabase”;
Connection con = DriverManager.getConnection(
url, “login”, “password”);
} catch (ClassNotFoundException e) {
} catch (SQLException e) {


}


Creating a Table
This example creates a table called “mytable” with three columns: COL_A which holds strings, COL_B which holds integers, and COL_C which holds floating point numbers.
try {
Statement stmt = con.createStatement();




stmt.executeUpdate(“CREATE TABLE mytable (
COL_A VARCHAR(100), COL_B INTEGER, COL_C FLOAT)”);
} catch (SQLException e) {


}


Entering a New Row into a Table
This example enters a row containing a string, an integer, and a floating point number into the table called “mytable”.
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(“INSERT INTO mytable
VALUES (‘Patrick Chan’, 123, 1.23)”);
connection.close();
} catch (SQLException e) {


}


Getting All Rows from a Table
This example retrieves all the rows from a table called “mytable”. A row in “mytable” consists of a string, integer, and floating point number.
try {
Statement stmt = connection.createStatement();




// Get data using colunm names.
ResultSet rs = stmt.executeQuery(
“SELECT * FROM mytable”);
while (rs.next()) {
String s = rs.getString(“COL_A”);
int i = rs.getInt(“COL_B”);
float f = rs.getFloat(“COL_C”);
process(s, i, f);


}






// Get data using colunm numbers.
rs = stmt.executeQuery(
“SELECT * FROM mytable”);
while (rs.next()) {
String s = rs.getString(1);
int i = rs.getInt(2);
float f = rs.getFloat(3);
process(s, i, f);


}


} catch (SQLException e) {


}


Getting Particular Rows from a Table
This example retrieves all rows from a table called “mytable” whose column COL_A equals “Patrick Chan”. A row in “mytable” consists of a string, integer, and floating point number.
try {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(
“SELECT * FROM mytable WHERE COL_A = ‘Patrick Chan’”);
rs.next();
String s = rs.getString(“COL_A”);
int i = rs.getInt(“COL_B”);
float f = rs.getFloat(“COL_C”);
process(s, i, f);
} catch (SQLException e) {


}


Updating a Row of Data in a Table
This example updates a row in a table called “mytable”. In particular, for all rows whose column COL_B equals 123, column COL_A is set to “John Doe”.
try {
Statement stmt = connection.createStatement();
int numUpdated = stmt.executeUpdate(
“UPDATE mytable SET COL_A = ‘John Doe’
WHERE COL_B = 123”);
connection.close();
} catch (SQLException e) {


}


Using a Prepared Statement
A prepared statement should be used in cases where a particular SQL statement is used frequently. The prepared statement is more expensive to set up but executes faster than a statement. This example demonstrates a prepared statement for getting all rows from a table called “mytable” whose column COL_A equals “Patrick Chan”. This example also demonstrates a prepared statement for updating data in the table. In particular, for all rows whose column COL_B equals 123, column COL_A is set to “John Doe”.
try {
// Retrieving rows from the database.
PreparedStatement stmt = connection.prepareStatement(
“SELECT * FROM mytable WHERE COL_A = ?”);
int colunm = 1;
stmt.setString(colunm, “Patrick Chan”);
ResultSet rs = stmt.executeQuery();




// Updating the database.
stmt = connection.prepareStatement(
“UPDATE mytable SET COL_A = ? WHERE COL_B = ?”);
colunm = 1;
stmt.setString(colunm, “John Doe”);
colunm = 2;
stmt.setInt(colunm, 123);
int numUpdated = stmt.executeUpdate();
} catch (SQLException e) {


}










Examplets TM provided by permission of the publisher, Addision-Wesley, and
Author Patrick Chan.




Handling Events with an Anonymous Class
If an event handler is specific to a component (that is, not shared by other components), there is no need to declare a class to handle the event. The event handler can be implemented using an anonymous inner class. This example demonstrates an anonymous inner class to handle key events for a component.




component.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {


}


});






Handling Action Events
Action events are fired by subclasses of AbstractButton and includes buttons, checkboxes, and menus.




AbstractButton button = new JButton(quot;OK”);
button.addActionListener(new MyActionListener());




public class MyActionListener
implements ActionListener {
public void actionPerformed(ActionEvent evt) {
// Determine which abstract
// button fired the event.
AbstractButton button =
(AbstractButton)evt.getSource();


}


}


Handling Key Presses
You can get the key that was pressed either as a key character (which is a Unicode character) or as a key code (a special value representing a particular key on the keyboard).




component.addKeyListener(new MyKeyListener());




public class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
// Check for key characters.
if (evt.getKeyChar() == ‘a’) {
process(evt.getKeyChar());


}






// Check for key codes.
if (evt.getKeyCode() == KeyEvent.VK_HOME) {
process(evt.getKeyCode());


}


}


}


Handling Mouse Clicks
component.addMouseListener(
new MyMouseListener());




public class MyMouseListener
extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
if ((evt.getModifiers() &
InputEvent.BUTTON1_MASK) != 0) {
processLeft(evt.getPoint());


}


if ((evt.getModifiers() &
InputEvent.BUTTON2_MASK) != 0) {
processMiddle(evt.getPoint());


}


if ((evt.getModifiers() &
InputEvent.BUTTON3_MASK) != 0) {
processRight(evt.getPoint());


}


}


}


Handling Mouse Motion
component.addMouseMotionListener(
new MyMouseMotionListener());




public class MyMouseMotionListener
extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
// Process current position of cursor
// while all mouse buttons are up.
process(evt.getPoint());


}


public void mouseDragged(MouseEvent evt) {
// Process current position of cursor
// while mouse button is pressed.
process(evt.getPoint());


}


}


Detecting Double and Triple Clicks
component.addMouseListener(
new MyMouseListener());




public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 3) {
// triple-click
} else if (evt.getClickCount() == 2) {
// double-click


}


}


}


Handling Focus Changes
component.addFocusListener(
new MyFocusListener());




public class MyFocusListener
extends FocusAdapter {
public void focusGained(FocusEvent evt) {
// The component gained the focus.


}


public void focusLost(FocusEvent evt) {
// The component lost the focus.


}


}


Files, Streams, I/O (java.io)




Constructing a Path
On Windows, this example creates the path \blash a\blash b. On Unix, the path would be /a/b.




String path = File.separator +
“a” + File.separator + “b”;




Reading Text from Standard Input
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String str = “”;
while (str != null) {
System.out.print(“> prompt “);
str = in.readLine();
process(str);


}


} catch (IOException e) {


}






Reading Text from a File
try {
BufferedReader in = new BufferedReader(
new FileReader(“infilename”));
String str;
while ((str = in.readLine()) != null) {
process(str);


}


in.close();
} catch (IOException e) {


}






Writing to a File
If the file does not already exist, it is automatically created.
try {
BufferedWriter out = new BufferedWriter(
new FileWriter(“outfilename”));
out.write(“aString”);
out.close();
} catch (IOException e) {


}






Creating a Directory
(new File(“directoryName”)).mkdir();




Appending to a File
try {
BufferedWriter out = new BufferedWriter(
new FileWriter(“filename”, true));
out.write(“aString”);
out.close();
} catch (IOException e) {


}


Deleting a File
(new File(“filename”)).delete();




Deleting a Directory
(new File(“directoryName”)).delete();




Creating a Temporary File
try {
// Create temp file.
File temp = File.createTempFile(
“pattern”, “.suffix”);




// Delete temp file when program exits.
temp.deleteOnExit();




// Write to temp file
BufferedWriter out = new BufferedWriter(
new FileWriter(temp));
out.write(“aString”);
out.close();
} catch (IOException e) {


}






Using a Random Access File
try {
File f = new File(“filename”);
RandomAccessFile raf =
new RandomAccessFile(f, “rw”);




// Read a character.
char ch = raf.readChar();




// Seek to end of file.
raf.seek(f.length());




// Append to the end.
raf.writeChars(“aString”);
raf.close();
} catch (IOException e) {


}


Serializing an Object
The object to be serialized must implement java.io.Serializable.
try {
ObjectOutput out = new ObjectOutputStream(
new FileOutputStream(“filename.ser”));
out.writeObject(object);
out.close();
} catch (IOException e) {


}






Deserializing an Object
This example deserializes a java.awt.Button object.
try {
ObjectInputStream in = new ObjectInputStream(
new FileInputStream(“filename.ser”));
AnObject object = (AnObject) in.readObject();
in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {


}






Traversing a Directory
public static void traverse(File f) {
process(f);
if (f.isDirectory()) {
String[] children = f.list();
for (int i=0; i> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.
21. Which method of the Component class is used to set the position andsize of a component?
setBounds()
22. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
23What is the difference between yielding and sleeping?
When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.
24. Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing.
25. Is sizeof a keyword?
The sizeof operator is not a keyword.
26. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
27. Does garbage collection guarantee that a program will not run out ofmemory?
Garbage collection does not guarantee that a program will not run out ofmemory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
28. What restrictions are placed on the location of a package statement within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments).
29. Can an object’s finalize() method be invoked while it is reachable?
An object’s finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object’s finalize() method may be invoked by other objects.
30. What is the immediate superclass of the Applet class?
Panel
31. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.Under time slicing, a task executes for a predefined slice of time and thenreenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
32. Name three Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
33. What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.
34. What is the immediate superclass of the Dialog class?
Window
35. What is clipping?
Clipping is the process of confining paint operations to a limited area or shape.
36. What is a native method?
A native method is a method that is implemented in a language other than Java.
37. Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;
38. What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated inexpressions. Associatity determines whether an expression is evaluatedleft-to-right or right-to-left
39. When a thread blocks on I/O, what state does it enter?
A thread enters the waiting state when it blocks on I/O.
40. To what value is a variable of the String type automatically initialized?
The default value of an String type is null.
41. What is the catch or declare rule for method declarations?
If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
42. What is the difference between a MenuItem and a CheckboxMenuItem?
The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked.
43. What is a task’s priority and how is it used in scheduling?
A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.
44. What class is the top of the AWT event hierarchy?
The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy.
45. When a thread is created and started, what is its initial state?
A thread is in the ready state after it has been created and started.
46. Can an anonymous class be declared as implementing an interface and extending a class?
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
47. What is the range of the short type?
The range of the short type is -(2^15) to 2^15 - 1.
48. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.
49. In which package are most of the AWT events that support theevent-delegation model defined?
Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package.
50. What is the immediate superclass of Menu?
MenuItem
51. What is the purpose of finalization?
The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
52. Which class is the immediate superclass of the MenuComponent class.
Object
53. What invokes a thread’s run() method?
After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread’s run() method when the thread is initially executed.
54. What is the difference between the Boolean & operator and the && operator?
If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.
55. Name three subclasses of the Component class.
Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List,Scrollbar, or TextComponent
56. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
57. Which Container method is used to cause a container to be laid out and redisplayed?
validate()
58. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
59. How many times may an object’s finalize() method be invoked by the garbage collector?
An object’s finalize() method may only be invoked once by the garbage collector.
60. What is the purpose of the finally clause of a try-catch-finally statement?
The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.
61. What is the argument type of a program’s main() method?
A program’s main() method takes an argument of the String[] type.
62. Which Java operator is right associative?
The = operator is right associative.
63. What is the Locale class?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
64. Can a double value be cast to a byte?
Yes, a double value can be cast to a byte.
65. What is the difference between a break statement and a continue statement?
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement.
66. What must a class do to implement an interface?
It must provide all of the methods in the interface and identify the interface in its implements clause.
67. What method is invoked to cause an object to begin executing as a separate thread?
The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.
68. Name two subclasses of the TextComponent class.
TextField and TextArea
69. What is the advantage of the event-delegation model over the earlier event-inheritance model?
The event-delegation model has two advantages over the event-inheritance model.First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component’s design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model.
70. Which containers may have a MenuBar?
Frame
71. How are commas used in the intialization and iteration parts of a for statement?
Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.
72. What is the purpose of the wait(), notify(), and notifyAll() methods?
The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object’s wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object’s notify() or notifyAll() methods.
73. What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass.
74. How are Java source code files named?
A Java source code file takes the name of a public class or interface that isdefined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file must take on a name that is different than its classes and interfaces. Source code files use the .java extension.

75. What is the relationship between the Canvas class and the Graphics class?
A Canvas object provides access to a Graphics object via its paint() method.
76. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
77. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.
78. Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.
79. What is the difference between a static and a non-static inner class?
A non-static inner class may have object instances that are associated with instances of the class’s outer class. A static inner class does not have any object instances.
80. What is the difference between the String and StringBuffer classes?
String objects are constants. StringBuffer objects are not.
81. If a variable is declared as private, where may the variable be accessed?
A private variable may only be accessed within the class in which it is declared.
82. What is an object’s lock and which object’s have locks?
An object’s lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object’s lock. All objects and classes have locks. A class’s lock is acquired on the class’s Class object.
83. What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs.
84. How are the elements of a BorderLayout organized?
The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.
85. What is the % operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.
86. When can an object reference be cast to an interface reference?
An object reference be cast to an interface reference when the object implements the referenced interface.
87. What is the difference between a Window and a Frame?
The Frame class extends Window to define a main application window that can have a menu bar.
88. Which class is extended by all other classes?
The Object class is extended by all other classes.
89. Can an object be garbage collected while it is still reachable?
A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected..
90. Is the ternary operator written x : y ? z or x ? y : z ?
It is written x ? y : z.
91. What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.
92. How is rounding performed under integer division?
The fractional part of the result is truncated. This is known as rounding toward zero.
93. What happens when a thread cannot acquire a lock on an object?
If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object’s lock, it enters the waiting state until the lock becomes available.
94. What is the difference between the Reader/Writer class hierarchy and the
InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
95. What classes of exceptions may be caught by a catch clause?
A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types.
96. If a class is declared without any access modifiers, where may the class be accessed?
A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
97. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
98. What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
99. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
100. For which statements does it make sense to use a label?
The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.
101. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
102. Which TextComponent method is used to set a TextComponent to the read-only state?
setEditable()
103. How are the elements of a CardLayout organized?
The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.
104. Is &&= a valid Java operator?
No, it is not.
105. Name the eight primitive Java types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.
106. Which class should you use to obtain design information about an object?
The Class class is used to obtain information about an object’s design.
107. What is the relationship between clipping and repainting?
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.
108. Is “abc” a primitive value?
The String literal “abc” is not a primitive value. It is a String object.
109. What is the relationship between an event-listener interface and an event-adapter class?
An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface.
110. What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.
111. What modifiers may be used with an interface declaration?
An interface may be declared as public or abstract.
112. Is a class a subclass of itself?
A class is a subclass of itself.
113. What is the highest-level event class of the event-delegation model?
The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.
114. What event results from the clicking of a button?
The ActionEvent event is generated as the result of the clicking of a button.
115. How can a GUI component handle its own events?
A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener.
116. What is the difference between a while statement and a do statement?
A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
117. How are the elements of a GridBagLayout organized?
The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
118. What advantage do Java’s layout managers provide over traditional windowing systems?
Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.
119. What is the Collection interface?
The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.
120. What modifiers can be used with a local inner class?
A local inner class may be final or abstract.
121. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
122. What is the difference between the paint() and repaint() methods?
The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread.
123. What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.
124. Can an exception be rethrown?
Yes, an exception can be rethrown.
125. Which Math method is used to calculate the absolute value of a number?
The abs() method is used to calculate absolute values.
126. How does multithreading take place on a computer with a single CPU?
The operating system’s task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
127. When does the compiler supply a default constructor for a class?
The compiler supplies a default constructor for a class if no other constructors are provided.
128. When is the finally clause of a try-catch-finally statement executed?
The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause.
129. Which class is the immediate superclass of the Container class?
Component
130. If a method is declared as protected, where may the method be accessed?
A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared.
131. How can the Checkbox class be used to create a radio button?
By associating Checkbox objects with a CheckboxGroup.
132. Which non-Unicode letter characters may be used as the first character of an identifier?
The non-Unicode letter characters $ and _ may appear as the first character of an identifier
133. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
134. What happens when you invoke a thread’s interrupt method while it is sleeping or waiting?
When a task’s interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.
135. What is casting?
There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.
136. What is the return type of a program’s main() method?
A program’s main() method has a void return type.
137. Name four Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
138. What is the difference between a Choice and a List?
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.
139. What class of exceptions are generated by the Java run-time system?
The Java runtime system generates RuntimeException and Error exceptions.
140. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
141. What is the difference between a field variable and a local variable?
A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method.
142. Under what conditions is an object’s finalize() method invoked by the garbage collector?
The garbage collector invokes an object’s finalize() method when it detects that the object has become unreachable.
143. How are this() and super() used with constructors?
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
144. What is the relationship between a method’s throws clause and the exceptions that can be thrown during the method’s execution?
A method’s throws clause must declare any checked exceptions that are not caught within the body of the method.
145. What is the difference between the JDK 1.02 event model and the event-delegation model introduced with JDK 1.1?
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component’s container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried.
In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces.The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events.
146. How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory.
147. Why are the methods of the Math class static?
So they can be invoked as if they are a mathematical code library.
148. What Checkbox method allows you to tell if a Checkbox is checked?
getState()
149. What state is a thread in when it is executing?
An executing thread is in the running state.
150. What are the legal operands of the instanceof operator?
The left operand is an object reference or null value and the right operand is a class, interface, or array type.
151. How are the elements of a GridLayout organized?
The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.
152. What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
153. If an object is garbage collected, can it become reachable again?
Once an object is garbage collected, it ceases to exist. It can no longer become reachable again.
154. What is the Set interface?
The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements.
155. What classes of exceptions may be thrown by a throw statement?
A throw statement may throw any expression that may be assigned to the Throwable type.
156. What are E and PI?
E is the base of the natural logarithm and PI is mathematical value pi.
157. Are true and false keywords?
The values true and false are not keywords.
158. What is a void return type?
A void return type indicates that a method does not return a value.
159. What is the purpose of the enableEvents() method?
The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.
160. What is the difference between the File and RandomAccessFile classes?
The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file.
161. What happens when you add a double value to a String?
The result is a String object.
162. What is your platform’s default character encoding?
If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1..
163. Which package is always imported by default?
The java.lang package is always imported by default.
164. What interface must an object implement before it can be written to a
stream as an object?
An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object.
165. How are this and super used?
this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance.
166. What is the purpose of garbage collection?
The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused.
167. What is a compilation unit?
A compilation unit is a Java source code file.
168. What interface is extended by AWT event listeners?
All AWT event listeners extend the java.util.EventListener interface.
169. What restrictions are placed on method overriding?
Overridden methods must have the same name, argument list, and return type.The overriding method may not limit the access of the method it overrides.The overriding method may not throw any exceptions that may not be thrown by the overridden method.
170. How can a dead thread be restarted?
A dead thread cannot be restarted.
171. What happens if an exception is not caught?
An uncaught exception results in the uncaughtException() method of the thread’s ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown.


172. What is a layout manager?
A layout manager is an object that is used to organize components in a container.


173. Which arithmetic operations can result in the throwing of an ArithmeticException?
Integer / and % can result in the throwing of an ArithmeticException.


174. What are three ways in which a thread can enter the waiting state?
A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object’s lock, or by invoking an object’s wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method.
175. Can an abstract class be final?
An abstract class may not be declared as final.
176. What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
177. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?
The exception propagates up to the next higher level try-catch statement (if any) or results in the program’s termination.
178. What is numeric promotion?
Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
179. What is the difference between a Scrollbar and a ScrollPane?
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.
180. What is the difference between a public and a non-public class?
A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package.
181. To what value is a variable of the boolean type automatically initialized?
The default value of the boolean type is false.
182. Can try statements be nested?
Try statements may be tested.
183. What is the difference between the prefix and postfix forms of the ++operator?
The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value.
184. What is the purpose of a statement block?
A statement block is used to organize a sequence of statements as a single statement group.
185. What is a Java package and how is it used?
A Java package is a naming context for classes and interfaces. A package is used to create a separate name space for groups of classes and interfaces. Packages are also used to organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces.
186. What modifiers may be used with a top-level class?
A top-level class may be public, abstract, or final.
187. What are the Object and Class classes used for?
The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.
188. How does a try statement determine which catch clause should be usedto handle an exception?
When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed.The remaining catch clauses are ignored.
189. Can an unreachable object become reachable again?
An unreachable object may become reachable again. This can happen when the object’s finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.
190. When is an object subject to garbage collection?
An object is subject to garbage collection when it becomes unreachable to the program in which it is used.
191. What method must be implemented by all threads?
All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.
192. What methods are used to get and set the text label displayed by a Buttonobject?
getLabel() and setLabel()
193. Which Component subclass is used for drawing and painting?
Canvas
194. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
195. What are the two basic ways in which classes that can be run as threads may be defined?
A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.
196. What are the problems faced by Java programmers who don’t use layout managers?
Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.
197. What is the difference between an if statement and a switch statement?
The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.
198. What happens when you add a double value to a String?
The result is a String object.
199. What is the List interface?
The List interface provides support for ordered collections of objects.
5
1. What’s the JDBC 2.0 API?
The JDBC 2.0 API is the latest update of the JDBC API. It contains many new features, including scrollable result sets and the new SQL:1999 (formerly SQL 3) data types. There are two parts to the JDBC 2.0 API: the JDBC 2.0 core API (the java.sql package), which is included in the JavaTM 2 SDK, Standard Edition the JDBC 2.0 Optional Package API (the javax.sql package), which is available separately or as part of the Java 2 SDK, Enterprise Edition
2. Does the JDBC-ODBC Bridge support the new features in the JDBC 2.0 API?
No, the JDBC-ODBC Bridge that is included in the Java 2 Platform initial release does not support the new features in the JDBC 2.0 API. However, Sun and Merant are working to produce a new version of the Bridge that does support the new features. Note that we do not recommend using the Bridge except for experimental purposes or when you have no other driver available.
3. Can the JDBC-ODBC Bridge be used with applets?
Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn’t allowed. The JDBC-ODBC bridge doesn’t allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can’t circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called, the Java programming language can’t guarantee that a security violation won’t occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration.
Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since appletviewer assumes that applets are trusted. It is also possible to use the JDBC-ODBC bridge with applets that are run in the HotJavaTM browser (available from Java Software), since HotJava provides an option to turn off applet security. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems.
4. How do I start debugging problems related to the JDBC API?
A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations.
If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)
5. How can I use the JDBC API to access a desktop database like Microsoft Access over the network?
Most desktop databases currently require a JDBC solution that uses ODBC underneath. This is because the vendors of these database products haven’t implemented all-Java JDBC drivers.
The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use. See the JDBC drivers page for a list of available JDBC drivers.
The JDBC-ODBC bridge from Sun’s Java Software does not provide network access to desktop databases by itself. The JDBC-ODBC bridge loads ODBC as a local DLL, and typical ODBC drivers for desktop databases like Access aren’t networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge , however, to access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is free.
6. Does the JDK include the JDBC API and the JDBC-ODBC Bridge?
Yes, the JDK 1.1 and the Java 2 SDK, Standard Edition (formerly known as the JDK 1.2), contain both the JDBC API and the JDBC-ODBC Bridge. The Java 2 SDK, Standard Edition, contains the JDBC 2.0 core API, which is the latest version. It does not include the JDBC 2.0 Optional Package, which is part of the Java 2 SDK, Enterprise Edition, or which you can download separately.
Note that the version of the JDBC API and the JDBC-ODBC Bridge provided for separate download on the JDBC download page are only for use with the JDK 1.0.2.
7. What JDBC technology-enabled drivers are available?
See our web page on JDBC technology-enabled drivers for a current listing.
8. What documentation is available for the JDBC API?
See the JDBC technology home page for links to information about JDBC technology. This page links to information about features and benefits, a list of new features, a section on getting started, online tutorials, a section on driver requirements, and other information in addition to the specifications and javadoc documentation.
9. Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?
Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in functionality between ODBC drivers, the functionality of the bridge may be affected. The bridge works with popular PC databases, such as Microsoft Access and FoxPro.
10. Does the JDBC-ODBC Bridge work with Microsoft J++?
No, J++ does not support the JDBC-ODBC bridge since it doesn’t implement the Java Native Interface (JNI). Any all-Java JDBC driver should work with J++, however.
11. What causes the “No suitable driver” error?
“No suitable driver” is an error that usually occurs during a call to the DriverManager.getConnection method. The cause can be failing to load the appropriate JDBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL—one that isn’t recognized by your JDBC driver. Your best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are specifying is not being recognized by your JDBC driver.
In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the the shared libraries needed by the Bridge cannot be loaded. If you think this is the cause, check your configuration to be sure that the shared libraries are accessible to the Bridge.
12. Why isn’t the java.sql.DriverManager class being found?
This problem can be caused by running a JDBC applet in a browser that supports the JDK 1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not contain the JDBC API, so the DriverManager class typically isn’t found by the Java virtual machine running in the browser.
Here’s a solution that doesn’t require any additional configuration of your web clients. Remember that classes in the java.* packages cannot be downloaded by most browsers for security reasons. Because of this, many vendors of all-Java JDBC drivers supply versions of the java.sql.* classes that have been renamed to jdbc.sql.*, along with a version of their driver that uses these modified classes. If you import jdbc.sql.* in your applet code instead of java.sql.*, and add the jdbc.sql.* classes provided by your JDBC driver vendor to your applet’s codebase, then all of the JDBC classes needed by the applet can be downloaded by the browser at run time, including the DriverManager class.
This solution will allow your applet to work in any client browser that supports the JDK 1.0.2. Your applet will also work in browsers that support the JDK 1.1, although you may want to switch to the JDK 1.1 classes for performance reasons. Also, keep in mind that the solution outlined here is just an example and that other solutions are possible.
13. Why doesn’t calling the method Class.forName load my JDBC driver?
There is a bug in the JDK 1.1.x that can cause the method Class.forName to fail. A workaround is to explicitly call the method DriverManager.registerDriver(new YourDriverClass()). The exact problem in the JDK is a race condition in the class loader that prevents the static section of code in the driver class from executing and registering the driver with the DriverManager.
14. Why do the java.sql and java.math packages fail to download java.* packages? Is there a workaround?
For security reasons, browsers will not download java.* packages. In order to use the JDBC API with browsers that have not been upgraded to JDK1.1 or beyond, we recommend that the java.sql and java.math packages be renamed jdbc.sql and jdbc.math. Most vendors supplying JDBC technology-enabled drivers that are written purely in the Java programming language already provide versions of these renamed packages. When JDK 1.1 support has been added to your browser, you should convert your applets back to the java.* package names.
15. Why is the precision of java.math.BigDecimal limited to 18 digits in the JDK 1.0.2 add-on version of the JDBC API?
In JDK 1.1, java.math.BigInteger is implemented in C. It supports a precision of thousands of digits. The same is true for BigDecigmal.
The version of BigInteger provided with the JDK 1.0.2 add-on version of the JDBC API is a simplified version written in the Java programming language, and it is limited to 18 digits. Because the implementation of BigDecimal is based on BigInteger, it also is limited to this precision.
In the JDBC 2.0 API, you can use a new version of the method ResultSet.getBigDecimal that does not take a scale parameter and returns a BigDecimal with full precision.
16. Can the JDBC API be added to JDK 1.0.2?
Yes. Download the JDBC 1.22 API from the JDBC download page and follow the installation instructions in the release notes.
If you are using any version of the JDK from 1.1 on, the JDBC API is already included, and you should not download the JDBC 1.22 API.
17. How do I retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX method for each column?
The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column of a row. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without at least the cost of a function call in any scenario. We welcome input from developers on this issue.
18. Why does the ODBC driver manager return ‘Data source name not found and no default driver specified Vendor: 0’
This type of error occurs during an attempt to connect to a database with the bridge. First, note that the error is coming from the ODBC driver manager. This indicates that the bridge-which is a normal ODBC client-has successfully called ODBC, so the problem isn’t due to native libraries not being present. In this case, it appears that the error is due to the fact that an ODBC DSN (data source name) needs to be configured on the client machine. Developers often forget to do this, thinking that the bridge will magically find the DSN they configured on their remote server machine
19. Are all the required JDBC drivers to establish connectivity to my database part of the JDK?
No. There aren’t any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to get a driver and install it before they can connect to a database. We are considering bundling JDBC technology- enabled drivers in the future.
20. Is the JDBC-ODBC Bridge multi-threaded?
No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.
21. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
22. Does the JDBC-ODBC Bridge developed by Merant and Sun support result sets that contain Japanese Characters (DBCS)?
Yes, but we haven’t tested this ourselves. The version of the Bridge in the Java 2 SDK, Standard Edition, and Java 2 SDK, Enterprise Edition, also supports a new charSet Connection property for specifying the character encoding used by the underlying DBMS.
23. Why can’t I invoke the ResultSet methods afterLast and beforeFirst when the method next works?
You are probably using a driver implemented for the JDBC 1.0 API. You need to upgrade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has created scrollable result sets and that the DBMS you are using supports them.
24. How can I retrieve a String or other object type without creating a new object each time?
Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new object.
We are studying this issue to see if it is an area in which the JDBC API should be improved. Stay tuned, and please send us any comments you have on this question.
25. There is a method getColumnCount in the JDBC API. Is there a similar method to find the number of rows in a result set?
No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.
26. I would like to download the JDBC-ODBC Bridge for the Java 2 SDK, Standard Edition (formerly JDK 1.2). I’m a beginner with the JDBC API, and I would like to start with the Bridge. How do I do it?
The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately.
27. If I use the JDBC API, do I have to use ODBC underneath?
No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API.
28. Once I have the Java 2 SDK, Standard Edition, from Sun, what else do I need to connect to a database?
You still need to get and install a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variety of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC connectivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn’t require any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other driver available.
16
What is a JDBC Driver?
A JDBC driver is the set of classes that implement the JDBC interfaces for a particular database.
There are four different types of JDBC driver: A Type 1 driver is a JDBC-ODBC bridge driver; this type of driver enables a client to connect to an ODBC database via Java calls and JDBC—neither the database nor middle tier need to be Java compliant.However, ODBC binary code must be installed on each client machine that uses this driver.
A Type 2 driver converts JDBC calls into calls for a specific database. This driver is referred to as a native-API, partly Java driver. As with the Type 1 driver, some binary code may be required on the client machine, which means this type of driver is not suitable for downloading over a network to a client.
A Type 3 driver is a JDBC-Net pure Java driver, which translates JDBC calls into a database -independent net protocol. Vendors of database middleware products can implement this type of driver into their products to provide interoperability with the greatest number of database servers.

Finally, a Type 4 driver, or, native protocol, pure Java driver converts JDBC calls into the network protocol used by the database directly. A Type 4 driver requires no client software, so it’s ideal for deployment to browsers at runtime. Each of these driver types has its own optimal usage scenarios, and will affect the way you deploy a given Java application.

For example, because Type 4 drivers are 100% Java, use Java sockets to connect to the database, and require no client-side data access code, they are ideal for applets or other download situations inside a firewall.

Oracle’s JDBC Drivers

Oracle provides both Type 2 and Type 4 drivers. All Oracle JDBC drivers support the full JDBC specification, but in addition, they support the extended capabilities of the Oracle database. For example, the JDBC specification doesn’t support LOB data, but the Oracle OCI8 JDBC driver does. Oracle’s implementation of the Type 2 JDBC driver is referred to as the Oracle “OCI driver,” and the version of this driver that supports an Oracle 7 database is the OCI7 driver and the OCI8 supports Oracle 8. These drivers are platform specific; for example, the Windows NT and Windows 95 version of the driver (oci805jdbc.dll.) is implemented as a dynamic link library (DLL) in C. As mentioned previously, Type 2 drivers may require client code. In the case of the OCI8 driver, the clients must have Oracle’s Net*8 and all other dependent files loaded.

A common way to implement Oracle OCI drivers is to use Oracle Application Server with the JWeb cartridge on the middle tier and deploy the client presentation logic as an applet; the interaction with the Oracle database is conducted from the middle tier only, with just the results sent to the client applet as pure HTML or Java and HTML. All Oracle drivers are compliant with the Java Development Kit JDK 1.0 and 1.1.x and support the JDBC 1.22 standard. In addition, all Oracle JDBC drivers support data types such as RAW and LONG RAW, ROWID, and RECURSOR, which are supported in Oracle databases but not part of the JDBC standard. Oracle’s drivers also support execution of PL/SQL stored procedures and anonymous blocks (for dynamic execution), and
include capabilities such as row pre-fetching, execution batching, and defining query columns to
reduce the network round trips to Oracle database. In addition, the OCI driver for Oracle8 supports oracle data types CLOB, BLOB, NCLOB, and BFILE. The screenshot shows an example of one of the classes in the Oracle JDBC, as part of the class hierarchy from which it descends, as displayed in Oracle’s JDeveloper integrated development environment. As you can see, the OraclePreparedStatement class inherits from the java.sql.PreparedStatement class, which in turn inherits from the java.sql.Statement.
Oracle also provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.
1.Add JDBC classes to your Java application or applet class by adding the following statement to your Java source code:
import java.sql.*;
To use the extended capabilities of the Oracle database, you must also import the Oracle JDBC driver. The statement in Java source looks like this:
import oracle.JDBC.driver.*
2.Load the JDBC driver by including the following statement in your class.
Class.forName(“oracle.JDBC.driver.OracleDriver”);
You can load the driver from your class-initialization routine.
3.Obtain a connection to an Oracle database by calling the getConnection() method of the JDBC DriverManager class. When you call this method you need to specify the connection information for the database in the form of a URL. The form the URL will take depends on the driver used. For example, to use the pure Java Type 4 Oracle driver (the thin driver) to connect to an Oracle7 database, the URL would read:
jdbc:oracle:thin@database_name:port_no:SID
To connect to an Oracle8 database using the OCI driver, the URL would be more like:
jdbc:oracle:oci8@database_name
To specify the database for use with an OCI driver, you can use either a SQL*Net name- value pair, or, if you’re using an Oracle Name server, you can use the name from the tnsname.ora file. (Both of these strings would conclude with the logon information as well—specifically the user name and password—but we’ve eliminated that from this example.)
The preliminary driver and database-connection issues now taken care of, there are still several other things your Java source code must include in order for the compiled code to submit queries to the database and process results.
4.Create a Statement object by calling the createStatement() method of the Connection object you created in the previous step. The following statement creates a Statement object stmt:
Statement stmt = conn.createStatement ();
5.Once the Statement object exists (in code), the application can then include code to execute a SQL query by calling the executeQuery() method of the Statement object.The executeQuery() method returns the result of the query in the ResultSet object. The following statement executes a query :
ResultSet rset = stmt.executeQuery (SELECT ename from emp where empno = 7900);
6.Finally, call the next() method of a ResultObject to retrieve a row and display it. Use a loop if the query returns more then one row from the database. For example, the following statements get the name of an employee from the ResultSet object and display it in the java.awt text control placed on the GUI.
rset.next();
enameTxtb.setText = ((String)rset.getString(1));

16
JDBC (java database conctivity)

1. What is JDBC ? what are its advantages ?

A. It is an API .The latest version of jdbc api is (3.0).
The JDBC 3.0 API is divided into two packages:
(1) java.sql and (2) javax.sql.
Both packages are included in the J2SE and J2EE platforms.
advantages:
The JDBC API can be used to interact with multiple data sources in a distributed, heterogenous environment.
It can connect to any of the database from java language.
It can switch over to any backend database without changing java code or by minute changes.
2. How many JDBC Drivers are there ? what are they?
A. There are 4 types of JDBC drivers.
a. JDBC-ODBC Bridge Driver(Type-1 driver)
b. Native API Partly Java Driver(Type-2 driver)
c. Net protocol pure Java Driver(Type-3 driver)
d. Native protocol Pure Java Driver(Type-4 driver)

3. Explain about JDBC-ODBC driver(Type-1) ? When this type of driver is used ?
A. In this mechanism the flow of execution will be
Java code(JDBC API)<------>JDBC-ODBC bridge driver<------->ODBC API<------->ODBC Layer<-------->DataBase
This type of JDBC Drivers provides a bridge between JDBC API and ODBC API.
This Bridge(JDBC-ODBC bridge) translates standard JDBC calls to Corresponding ODBC Calls, and
send them to ODBC database via ODBC Libraries.

The JDBC API is based on ODBC API.
ODBC(Open Database Connectivity)is Microsoft’s API for Database drivers.
ODBC is based on X/Open Call Level Interface(CLI)specification for database access.
The URL and class to be loaded for this type of driver are
Class :- sun.jdbc.odbc.JdbcOdbcDriver
URL :- jdbc:odbc:dsnname

4. Explain about Type-2 driver ? When this type of driver is used ?
A. The Drivers which are written in Native code will come into this category
In this mechanism the flow of Execution will be
java code(JDBC API)<------>Type-2 driver(jdbc driver)<------->Native API(vendor specific)<------->DataBase

When database call is made using JDBC,the driver translates the request into vendor-specific API calls.
The database will process the requet and sends the results back through the Native API ,which will
forward them back to the JDBC dirver. The JDBC driver will format the results to conform to the JDBC
standard and return them to the application.

5. Explain about Type-3 driver ? When this type of driver is used ?
A. In this mechanism the flow of Execution will be
java code(JDBC API)<------>JDBC driver<------->JDBC driver server<-------->Native driver<------->DataBase
The Java Client Application sends the calls to the Intermediate data access server(jdbc driver server)
The middle tier then handles the requet using other driver(Type-II or Type-IV drivers) to complete the request.
6. Explain about Type-4 driver ? When this type of driver is used ?
A. This is a pure java driver(alternative to Type-II drivers).
In this mechanism the flow of Execution will be
java code(JDBC API)<------>Type-4 driver(jdbc driver)<------->DataBase
These type of drivers convert the JDBC API calls to direct network calls using
vendor specific networking protocal by making direct socket connection with
database.
examples of this type of drivers are
1.Tabular Data Stream for Sybase
2.Oracle Thin jdbc driver for Oracle


7. What are the Advantages & DisAdvantages of Type-2 ,Type-4 Drivers over JDBC-ODBC bridge driver(Type-1)?
A. Type-2 & Type-4 are given
8. Which Driver is preferable for using JDBC API in Applets?
A. Type-4 Drivers.
9.Write the Syntax of URL to get connection ? Explain?
A.Syntax:- jdbc:
:
jdbc -----> is a protocal .This is only allowed protocal in JDBC.
----> The subprotocal is used to identify a database driver,or the
name of the database connectivity mechanism, choosen by the database driver providers.
-------> The syntax of the subname is driver specific. The driver may choose any syntax appropriate for its implementation
ex: jdbc:odbc:dsn
jdbc:oracle:oci8:@ database name.
jdbc:orale:thin:@ database name:port number:SID

10.How do u Load a driver ?
A. Using Driver Class.forName(java.lang.String driverclass) or registerDriver(Driver driver) .
11.what are the types of resultsets in JDBC3.0 ?How you can retrieve information of resultset?
A. ScrollableResultSet and ResultSet.We can retrieve information of resultset by using java.sql.ResultSetMetaData interface.You can get the instance by calling the method getMetaData() on ResulSet object.
12.write the steps to Connect database?
A. Class.forName(The class name of a spasific driver);
Connection c=DriverManager.getConnection(url of a spasific driver,user name,password);
Statement s=c.createStatement();
(or)
PreparedStatement p=c.prepareStatement();
(or)
CallableStatement cal=c.prpareCall();
Depending upon the requirement.
13.Can java objects be stored in database? how?
A.Yes.We can store java objects, BY using setObject(),setBlob() and setClob() methods in PreparedStatement
14.what do u mean by isolation level?
A. Isolation means that the business logic can proceed without
consideration for the other activities of the system.
15.How do u set the isolation level?
A. By using setTransactionIsolation(int level) in java.sql.Connection interface.
level MEANS:-
static final int TRANSACTION_READ_UNCOMMITTED //cannot prevent any reads.
static final int TRANSACTION_READ_COMMITTED //prevents dirty reads
static final int TRANSACTION_REPEATABLE_READ //prevents dirty reads & non-repeatable read.
static final int TRANSACTION_SERIALIZABLE //prevents dirty reads , non-repeatable read & phantom read.
These are the static final fields in java.sql.Connection interface.
16. what is a dirty read?
A. A Dirty read allows a row changed by one transaction to be
read by another transaction before any change in the row
have been committed.
This problem can be solved by setting the transaction isolation
level to TRANSACTION_READ_COMMITTED
17. what is a non-repeatable read ?
A. A non-repeatable read is where one transaction reads a row, a second
transaction alters or deletes the row, and the first transaction
re-reads the row,getting different values the second time.

This problem can be solved by setting the transaction isolation
level to TRANSACTION_REPEATABLE_READ
18. what is phantom read?
A. A phantom read is where one transaction reads all rows that satisfy a WHERE condition,a second transaction inserts a row that satisfies that WHERE condition,and the first transaction re-reads for the same condition,retrieving the additional ‘phantom’ row in the second read This problem can be solved by setting the transaction isolation level to TRANSACTION_SERIALIZABLE
19.What is the difference between java.sql.Statement &
java.sql.PreparedStatement ?
A. write the appropriate situations to use these statements?

20.How to retrieve the information about the database ?
A.we can retrieve the info about the database by using inerface java.sql.DatabaseMetaData we can get this object by using getMetaData() method in Connection interface.
21.what are the Different types of exceptions in jdbc?
A. BatchUpdateException
DataTruncation
SQLException
SQLWarning

22.How to execute no of queries at one go?
A. By using a batchUpdate’s (ie throw addBAtch() and executeBatch()) in java.sql.Statement interface,or by using procedures.
23. what are the advantages of connection pool.
A. Performance

24. In which interface the methods commit() & rollback() are defined ?
A. java.sql.Connection interface
25. How to store images in database?
A. Using binary streams (ie getBinaryStream() ,setBinaryStream()). But it is not visable in database ,it is stored in form of bytes ,to make it visable we have to use any one frontend tool.
26.How to check null value in JDBC?
A. By using the method wasNull() in ResultSet ,it returns boolean value.
Returns whether the last column read had a value of SQL NULL.
Note that you must first call one of the getXXX methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.
27.Give one Example of static Synchronized method in JDBC API?
A. getConnection() method in DriverManager class.Which is used to get object of Connection interface.
28.What is a Connection?
A. Connection is an interface which is used to make a connection between client and Database (ie opening a session with a particular database).
29.what is the difference between execute() ,executeUpdate() and executeQuery() ? where we will use them?
A. execute() method returns a boolean value (ie if the given query returns a resutset then it returns true else false),so depending upon the return value we can get the ResultSet object (getResultset())or we can know how many rows have bean affected by our query (getUpdateCount()).That is we can use this method for Fetching queries and Non-Fetching queries.Fetching queries are the queries which are used to fetch the records from database (ie which returns resutset) ex: Select * from emp.
Non-Fetching queries are the queries which are used to update,insert,create or delete the records from database
ex: update emp set sal=10000 where empno=7809.
executeUpdate() method is used for nonfetching queries.which returns int value.
executeQuery() method is used for fetching queries which returns ResulSet object ,Which contains methods to fetch the values.
30.How is jndi useful for Database connection?
A.

JNDI (java naming directory interface)
1. what are the uses of jndi?
A. The role of the JNDI API in the J2EE platform is two fold.
a) It provides the means to perform standard operations
to a directory service resource such as LDAP (Lightweight Directory Access Protocal),Novell Directory Sevices, or Netscape Directory Services.
b) A J2EE applicatin utilizes JNDI to look up interfaces used to create,amongst other things,EJBs,and JDBC connection.

2. How vendor Naming registry supports JNDI?
A.
JMS (JAVA MESSAGING SERVICE)
1. What is JMS ?
A. JMS (JAVA MESSAGING SERVICE) is an API .It is a specification with one
package javax.jms .It is a technology which can pass the information
synchronously or asynchronously .
2. On what technology is JMS based ?
A. JMS is based on Message-Oriented MiddleWare (MOM).
3. What was the technology for messaging services before JMS was released?
A. Before JMS API specification was released by javasoft ,there was
IBM’s MQSeries implementation of MOM (Message-Oriented MiddleWare).
4. What is MOM (Message-Oriented MiddleWare) ?
A. MOM is a software infrastructure that asynchronously connects multiple
system’s through the production and consumption of data message.
5. How many types of data passing does JMS specification allows ?What are they?
A. JMS specification allows two types of data passing.
a)publish/subscribe [pub/sub model]
b)point-to-point [p-t-p model]

6. In real time which type of data passing is used ?
A. Mostly in real time applications we use both types of data passing combinedly.
7. How jndi is used in JMS ?
A. While writing JMS application (pub/sub or p-t-p) we need TopicConnection or
QueueConnection . we use jndi to get this connections .
8. Write the steps to write pub/sub model application ?
A.
steps to write Publisher (sender) application :-
a)We have to get the TopicConnection through jndi.
b)Create TopicSession by invoking a method createTopicSession() .
c)create a Topic object by invoking createTopic() on TopicSession interface.
d)create a TopicPublisher object of a Topic by invoking createPublisher(javax.jms.Topic t)
on TopicSession.(t is a Topic object that specifies the Topic we want to subscribe to).
e)create TextMessage object and set the text to be published .
f)publish the message by using a method publish() in Publisher interface .
steps to write subscriber (receiver) application :-
a)We have to get the TopicConnection through jndi.
b)Create TopicSession by invoking a method createTopicSession() .
c)create a Topic object by invoking createTopic() on TopicSession interface.
d)create a TopicSubscriber object of a Topic by invoking createSubscriber(javax.jms.Topic) or
createDurableSubscriber(javax.jms.Topic t,String name,String messageselector,boolean nolocal) on TopicSession.
t ------> is a Topic object that specifies the Topic we want to subscribe to.
name ---> is a String that indicates the name under which to maintain the Durable Subscribtion to the specified topic.
messageselector --> is a String that defines selection criteria.
nolocal -------> is a boolean if it is true the Subscriber will not recive messages that were published by the client application .
9. What is the diffrence between DurableSubscription and non-DurableSubscription ?
A.
DurableSubscription :-
DurableSubscription indicates that the client wants to recive all the messages published to a topic,
including messages published when the client connection is not active.

Non-DurableSubscription :-
Non-DurableSubscription will not recive the messages published when the client connection is not active.
10. Write the steps to write p-to-p model application ?
A.
steps to write Sender application :-
a)We have to get the QueueConnection through jndi.
b)Create QueueSession by invoking a method createQueueSession() .
c)Create a Queue object by invoking createQueue() on QueueSession interface.
d)Create a QueueSender object of a Queue by invoking createSender(javax.jms.Queue q)
on QueueSession.
e)Create TextMessage object and set the text to be send .
f)Send the message by using a method send() .
steps to write Receiver application :-
a)We have to get the QueueConnection through jndi.
b)Create QueueSession by invoking a method createQueueSession() .
c)Create a Queue object by invoking createQueue() on QueueSession interface.
d)Create a QueueReceiver object of a Queue by invoking createReceiver(javax.jms.Queue) on QueueSession.

JTA (JAVA TRANSACTION API)
1. what is JTS?
A. JTS (JAVA TRANSACTION SERVICE) is the java implementation of CORBA’s
OTS (OBJECT TRANSACTION SERVICE).
2. what is JTA ?
A. JTA (JAVA TRANSACTION API) is the API released by javasoft under J2EE.
It was released after the release of JTS .
3. what are the advantages of JTA over JTS?
A. JTA (JAVA TRANSACTION API) is more flexible and simple to use by the
programer .The JTA API is divided into two parts
a)high-level X/Open Call Level Interface(CLI)
b)low-level XA Call Level Interface(CLI)

As a programmer using JTA he has to concentrate on high-level x/open interface .The low-level XA operations are taken care by the server which is giving the implementation to JTA API.The user will never perform XA operations directly.This makes the user more simple to manipulate with transactions.
4. How JTA or JTS is used by client ?
A. client uses UserTransaction interface in both the cases(JTA/JTS).

17
A message-driven bean is an asynchronous message consumer. A message-driven bean is invoked by the container as a result of the arrival of a JMS message. A message-driven bean has neither a home nor a remote interface. A message-driven bean instance is an instance of a message-driven bean class. To a client, a message-driven bean is a JMS message consumer that implements some business logic running on the server. A client accesses a message-driven bean through JMS by sending messages to the JMS Destination (Queue or Topic) for which the message-driven bean class is the MessageListener. Message-driven bean instances have no conversational state. This means that all bean instances are equivalent when they are not involved in servicing a client message.Message-driven beans are anonymous. They have no client-visible identity.A message-driven bean instance is created by the container to handle the processing of the messages for which the message-driven bean is the consumer. Its lifetime is controlled by the container. A message-driven bean instance has no state for a specific client. However, the instance variables of the message-driven bean instance can contain state across the handling of client messages. Examples of such state include an open database connection and an object reference to an EJB object.

Goals The goal of the message-driven bean model is to make developing an enterprise bean that is asynchro-nously invoked to handle the processing of incoming JMS messages as simple as developing the same functionality in any other JMS MessageListener.A further goal of the message-driven bean model is to allow for the concurrent processing of a stream of messages by means of container-provided pooling of message-driven bean instances.
While the EJB 2.0 specification requires support for only JMS-based messaging, a future goal
of the message-driven bean model is to provide support for other types of messaging in addi-tion
to JMS, and to allow for message-driven beans that are written to their APIs.

1.what is ment by Activation Instantinator?
A.it is a responsible for creating instances of “activatable” objects.
2.what are the activation group works?
A.it is responsible for informing its activation monitor, when eitherits objects become active or inactive.
3.what is the responsibilities of Activator?
A.it is responsible for monitoring and detecting when Activation groups fail.
4.what is the job of Activation monitor?
A.It receives information about active and inactive Objects.
5.what is DGC?
A.Distributed Garbage Collection is server side algorithm.It contains two methods those are dirty()and clean().
6.what is the handle?
A.It represents the Remote for a remote object
7.what is the Remote Stub?
A.Remote stub uses a remote references to carry out a remote method invocation to a RemoteObject.
8.What is the Remote Server?
A.The function need to create and export remote objects (to make them remotely available)
9.what is the RMI / IIOP?
A.This is the Naming service(tnameserv).
10.what is the rmi port no?
A.1099.
11.what is meant by portable component?
A.Writing and keep some where,and using from there without changing code.
12.what is the heepStored?
A.
13.what is the proxy pattern?
A. The copy of the Remote object in our Local Machine(it works like mediating to client & Server)
14.why the interface is required to rmi?
A.
15.which type of objects reference will be given to client?
A. Implement type class type of object references
16.what is ment by bootstraping?
A. when the server startup time it will send some information
to client, that is requirement to client .
java -D java.rmi.server.codebase=”http”//servername:8080”

17.why the constructor required in implemented class?
A. The super class is having one public constructor.
18.how many requests having ServerSockets ?
A.its minimum of 50.
19.what is the activation process?
A. When the clients request comes to the registry then only objects will be bound dynamically.
20.what is meant by jrmp?
A. This is standard rmi communication messaging protocol
21.ping:-
A. Tests to see whether a remote virtual is still alive.
22.narrow :-
Checks to ensure that an object of a remote or abstract interface type can be cast to a desired type.
23.Remote Reference Layer ?
A. Checks for Rmi symantics and to identify remote system in the network
transferable stream. This stream is then passed to transport layer
24. How many requests can server fetch at a time?
A. only one.

25.what is the JNDI [java Naming and Directory Interface] ? what its provides?
A. It provides standard java interface-to-naming events
26. what is the use of Object-Factories?
A.Colon-separated Object list of ContextFactory to use during invocation of naming and directory service operation
27.what is the use of State-Factories?
A.Colon separated list of state factory used to get an object’s state given a reference to the object
28.what is the use of colon_pkg_prefixes?
A. prefix to use when loading context factory.

29. DNS-URL
A. URL defining the DNS host to use for Addresses associated with JNDI urls
30.Authoritative
A. Value of true indicates that service access offers the most
authoritative source
31.BatchSize:-
A. Specifies batch size of data returned from service protocol
20
Questions on Servlets.
1) What is servlet?
Ans: Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.
2) What are the classes and interfaces for servlets?
Ans: There are two packages in servlets and they are javax.servlet and javax.servlet.http.
Javax.servlet contains:
Interfaces Classes

Servlet Generic Servlet
ServletRequest ServletInputStream
ServletResponse ServletOutputStream
ServletConfig ServletException
ServletContext UnavailableException
SingleThreadModel
Javax.servlet.http contains:
Interfaces Classes

HttpServletRequest Cookie
HttpServletResponse HttpServlet
HttpSession HttpSessionBindingEvent
HttpSessionContext HttpUtils
HttpSeesionBindingListener
3) What is the difference between an applet and a servlet?
Ans: a) Servlets are to servers what applets are to browsers.
b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.
4)what is the lifecycle of a servlet.
Ans: Each Servlet has the same life cycle:
a)A server loads and initializes the servlet by init () method.
b)The servlet handles zero / more client’s requests through service() method.
c)The server removes the servlet through destroy() method.
5) What is the ServletConfig() and why are using ServletConfig ?
Ans: This interface is implemented by services in order to pass
configuration information to a servlet when it is first loaded.Aservice writer implementing this interface must write methods
for the servlet to use to get its initialization parameters and the context in which it is running.public interface ServletConfig

6) What is meant by the ServletContext() and use of the method ?
Ans: The ServletContext interface gives servlets access to information about their environment ,and allows them to log significant events. Servlet writers decide what data to log. The interface is implemented by services, and used by servlets. Different virtual hosts should have different servlet contexts.
public interface ServletContext

7) What is use of parseQueryString ?
Ans: Parses a query string and builds a hashtable of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST method. (For example, it should have its key-value pairs delimited by ampersands (&) and its keys separated from its values by equal signs (=).)
Note:
public static Hashtable parseQueryString(String s)
8)what are the types of servlets.
Ans: Genereic Servlets,HttpServlets.
9)what are the different methods in HttpServlet.
Ans: doGet(),doPost(),doHead,doDelete(),deTrace()
10)What is the difference between GET and POST.
Ans: a) doGet() method is used to get information, while doPost( ) method is used for posting information.
b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However,doPost( )requests passes all of its data, of unlimited length.
c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.
11) Why do you need both GET and POST method implementations in Servlet?
Ans: A single servlet can be called from differenr HTML pages,so Different method calls can be possible.
12)When init() and Distroy() will be called.
Ans: init() is called whenever the servlet is loaded for the first time into the webserver.destroy() will be called whenever the servlet is removed from the webserver.
13) Who is loading the init() method of servlet?
Ans: Web server
14)If you want to modify the servlet,will the Webserver need to be ShutDown.
Ans:No
15)What is the advantage of Servlets over other serverside technologies.
Ans: PlatForm independent, so once compiled can be used in any webserver.For different processes different threads will execute in-built mutithreaded.
16) What is Server-Side Includes (SSI)?
Ans: Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags.SSINCLUDE
servlet will be invoked whenever a file with an. shtml extension is requested.So HTML files that include server-side includes must be stored with an .shtml extension.
17)What is Single Threaded Model in Servlets and how is it useful give one practical example.
Ans: For every single user a differnt copy of this servlet is executed.Credit card transactions.
18) What is the uses Sessions ?
Ans: Its a part of the SessionTracking and it is for mainting the client state at server side.
19)What are the advantage of using Sessions over Cookies and URLReWriting?
Ans: Sessions are more secure and fast becasue they are stored at serverside. But Sessions has to be used combindly with Cookies or URLReWriting for mainting the client id that is sessionid at client side.Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies which we are mainting may work or not but in sessions cookies are disable we can maintain our sessionid using URLReWriting .In URLReWriting we can’t maintain large data because it leads to network traffic and access may be become slow.Where as in seesions will not maintain the data which we have to maintain instead we will maintain only the session id.
20) What is session tracking and how do you track a user session in servlets?
Ans: Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time.The methods used for session tracking are:
a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password
b) Hidden form fields - fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the fields is submitted, the fields are sent back to the server
c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.
d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.
e) HttpSession - places a limit on the number of sessions that can exist in memory. This limit is set in the session.maxresidents property
21)What is Cookies and what is the use of Cookies ?
Ans: Cookies are used to get user agents (web browsers etc) to hold small amounts of state associated with a user’s web browsing.Later that infromation read by server
22) What are cookies and how will you use them?
Ans: Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user.a) Create a cookie with the Cookie constructor:
public Cookie(String name, String value)
b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of
HttpServletResponse:public void HttpServletResponse.addCookie(Cookie cookie)
c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest:public Cookie[ ] HttpServletRequest.getCookie( ).
23) How many Cookies is supported to the host ?
Ans: User agents excepted to support twenty per host.And its take fourKilobytes each.
24) What is the use of setComment and getComment methods in Cookies ?
Ans: setComment:If a user agent (web browser) presents this cookie to a user, the cookie’s purpose will be described using this comment. This is not supported by version zero cookies.
public void setComment(String use)
{
}

getComment:
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
25)Why we are used setMaxAge() and getMaxAge() in Cookies ?
Ans: setMaxAge
public void setMaxAge(int expiry)
Sets the maximum age of the cookie.The cookie will expire after that many seconds have passed.Negative values indicate the default behaviour:the cookie is not stored persistently, and will be deleted when the user agent exits.A zero value causes the cookie to be deleted
getMaxAge():
public int getMaxAge()
Returns the maximum specified age of the cookie. If none was specified, a negative value is returned, indicating the default behaviour described with setMaxAge.
26)What is the use of setSecure() and getSecure() in Cookies ?
Ans: setSecure
Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie’s originating server used a secure protocol to set the cookie’s value.
public void setSecure(boolean flag)
getSecure:
Returns the value of the ‘secure’ flag.
public boolean getSecure()
27)What is meant by Httpsession and what is the use of sessions ?
Ans: The HttpSession interface is implemented by services to provide an
association between an HTTP client and HTTP server. This session,
persists over multiple connections and/or requests during a given time
period. Sessions are used to maintain state and user identity across
multiple page requests.
HttpSession session = req.getSession(true);

28) What are the methods in HttpSession and use of those methods?
Ans:
a) getCreationTime()
Returns the time at which this session representation was created.
b) getId()
Returns the identifier assigned to this session.
c) getLastAccessedTime()
Returns the last time the client sent a request carrying the identifier assigned to the session.
d) getSessionContext()
Returns the context in which this session is bound.
e) getValue(String)

Returns the object bound to the given name in the session’s
application layer data.
f) getValueNames()

Returns an array of the names of all the application layer data
objects bound into the session.
g) invalidate()
Causes this representation of the session to be invalidated and removed from its context.
h) isNew()
A session is considered to be “new” if it has been created by the server, but the client has not yet acknowledged joining the session.
j) putValue(String, Object)
Binds the specified object into the session’s application layer data with the given name.
k) removeValue(String)
Removes the object bound to the given name in the session’s application layer data.
29) How do you communicate between the servlets.
Ans: a)servlet chaning
b)Servlet context(RequestDespatcher interface)
30)Can you send the mail from a servlet ,if yes tell how?
Ans:yes.using mail API
31)How do you access variables across the sessions.
Ans:Through ServletContext.
32)where the session data will store?
ans: session objects
33)What is Servlet Context?
Ans:This object represents resources shared by a group of servlets like
servlet’s environment,Application attributes shared in the context
level.
34)How do you trap the debug the errors in servlets.
Ans:error log file
35)How do you debug the Servlet?
Ans:through servlet log();
36)How do u implement threads in servlet?
Ans:Intenally implemented
37)How do you handle DataBase access and in which method of the servlet do you like to create connection.
Ans:init()
38)If you want to improve the performance how do you create connections for multiple users?
A.Connection Pooling.
39)what is connection pooling?
Ans:Class which manages no of user requests for connections to improve the
performance.
40) What are the different servers available for developing and deploying Servlets?
Ans: a) JRun2.0--Allaire
b) Apache—jserv
c) jwsdk2.0 --sun
d) servletexec
e) Tomcat webserver—tomcat
f) Weblogic AS—BEA Systems
g) NetDynamics5.0--sun
h) Iplanet—sun&netscape
i) Netscape—netscape
g) IBM websphere—IBM
h) oracle—oracle
i) Proton-Pramati technologies

41) Is it possible to communicate from an applet to servlet and how many ways and how?
Ans: Yes, there are three ways to communicate from an applet to servlet and
they are:
a) HTTP Communication(Text-based and object-based)
b) Socket Communication
c) RMI Communication

(You can say, by using URL object open the connection to server
and get the InputStream from URLConnection object).
Steps involved for applet-servlet communication:
step: 1 Get the server URL.
URL url = new URL();
step: 2 Connect to the host
URLConnection Con = url.openConnection();
step: 3 Initialize the connection
Con.setUseCatches(false):
Con.setDoOutput(true);
Con.setDoInput(true);
step: 4 Data will be written to a byte array buffer so that we can tell the server the length of the data.
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
step: 5 Create the OutputStream to be used to write the data to the buffer.
DataOutputStream out = new DataOutputStream(byteout);

42) Why should we go for interservlet communication?
Ans: Servlets running together in the same server communicate with each
other in several ways.The three major reasons to use interservlet communication are:
a)Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)
b)Servlet reuse - allows the servlet to reuse the public methods of another servlet.
c)Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)
43) Is it possible to call servlet with parameters in the URL?
Ans: Yes. You can call a servlet with parameters in the syntax as
(?Param1 = xxx || m2 = yyy).
44) What is Servlet chaining?
Ans: Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.In servlet chaining, one servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.
45) How do servlets handle multiple simultaneous requests?
Ans: The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.
46) How are Servlets and JSP Pages related?
Ans: JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.Servlets:
47).How do servlets handle multiple simultaneous requests?
Ans: Using Threads
48).How do I automatically reload servlets?
Ans:depends upon the server’s servlet reload properites.
48).My servlet, which ran correctly under the Servlet 2.0 APIs (Java Web Server 1.1.3) is not running under the Servlet 2.1 APIs (Java Web Server 2.0). What’s wrong?
Ans:You might have used servlet to servlet communication by usingservletcontext methods like getServlet(),getServlets() which are depricated and returns null from new release that is from servlet2.1 API.
49) What are the types of ServletEngines?
Standalone ServletEngine: A standalone engine is a server that includes built-in support for servlets.Add-on ServletEngine: Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.Embedded ServletEngine: it is a lightweight servlet deployment platform that can be embedded in another application.that application become true server.
50)what is httptunneling?
ans: it is mechanism of performing both write and read operations using http protocol.it is extending the functionality of htp protocol.
51).How do I use native code in a servlet?
Ans:
49)What’s with the javax.servlet package naming?
Ans:
50. List out Differences between CGI Perl and Servlet?
Servlet CGI

Platform independent Platform dependent.

Language dependent Language independent.

1 comments:

it's really very useful,thanku naresh

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More