Friday, January 30, 2009

JDBC Questions

1. What is JDBC?
JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a layer of abstraction that allows users to choose between databases. It allows you to change to a different database engine and to write to a single API. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database.
________________________________________
2. What are the two major components of JDBC?
One implementation interface for database manufacturers, the other implementation interface for application and applet writers.
________________________________________
3. What is JDBC Driver interface?
The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.
________________________________________
4. What are the common tasks of JDBC?
o Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
o Register a driver
o Specify a database
o Open a database connection
o Submit a query
o Receive results
________________________________________
5. How to use JDBC to connect Microsoft Access?
Please see this page for detailed information.
________________________________________
6. What are four types of JDBC driver?
1. Type 1 Drivers
Bridge drivers such as the jdbc-odbc bridge. They rely on an intermediary such as ODBC to transfer the SQL calls to the database and also often rely on native code. It is not a serious solution for an application
2. Type 2 Drivers
Use the existing database API to communicate with the database on the client. Faster than Type 1, but need native code and require additional permissions to work in an applet. Good for client-side connection.
3. Type 3 Drivers
JDBC-Net pure Java driver. It translates JDBC calls to a DBMS-independent net protocol, which is then translated to a DBMS protocol by a server. Flexible. Pure Java and no native code.
4. Type 4 Drivers
Native-protocol pure Java driver. It converts JDBC calls directly into the network protocol used by DBMSs. This allows a direct call from the client machine to the DBMS server.
7. Recommended by Sun's tutorial, driver type 1 and 2 are interim solutions where direct pure Java drivers are not yet available. Driver type 3 and 4 are the preferred way to access databases using the JDBC API, because they offer all the advantages of Java technology, including automatic installation. For more info, visit Sun JDBC page
8. ________________________________________
9. What packages are used by JDBC?
There are at least 8 packages:
0. java.sql.Driver
1. Connection
2. Statement
3. PreparedStatement
4. CallableStatement
5. ResultSet
6. ResultSetMetaData
7. DatabaseMetaData
________________________________________
10. There are three basic types of SQL statements, what are they?
0. Statement
1. CallableStatement
2. PreparedStatement
________________________________________
11. What are the flow statements of JDBC?
A URL string -->getConnection-->DriverManager-->Driver-->Connection-->Statement-->executeQuery-->ResultSet.
________________________________________
12. What are the steps involved in establishing a connection?
This involves two steps: (1) loading the driver and (2) making the connection.
________________________________________
13. How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:
Class.forName("jdbc.DriverXYZ");
________________________________________
14. What Class.forName will do while loading driver?
It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with DBMS.
________________________________________
15. How can you make the connection?
When establishing a connection, have the appropriate driver connect to DBMS. The following line of code illustrates the general idea:
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");
________________________________________
16. How can you create JDBC statement?
A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it by supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :
Statement stmt = con.createStatement();
________________________________________
17. How to make a query?
Create a Statement object and call the Statement.executeQuery method to select data from the database. The results of the query are returned in a ResultSet object.
Statement stmt = con.createStatement();
ResultSet results = stmt.executeQuery("SELECT data FROM aDatabase ");
________________________________________
18. How can you retrieve data from the ResultSet?
Use getXXX() methods to retrieve data from returned ResultSet object.
ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
String s = rs.getString("COF_NAME");
The method getString() is invoked on the ResultSet object rs , so getString() will retrieve the value stored in the column COF_NAME in the current row of rs
________________________________________
19. How to navigate the ResultSet?
By default the result set cursor points to the row before the first row of the result set. A call to next() retrieves the first result set row. The cursor can also be moved by calling one of the following ResultSet methods:
o beforeFirst(): Default position. Puts cursor before the first row of the result set.
o first(): Puts cursor on the first row of the result set.
o last(): Puts cursor before the last row of the result set.
o afterLast() Puts cursor beyond last row of the result set. Calls to previous moves backwards through the ResultSet.
o absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row.
o relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward.
________________________________________
20. What are the different types of Statements?
0. Statement (use createStatement method)
1. Prepared Statement (Use prepareStatement method)
2. Callable Statement (Use prepareCall)
________________________________________
21. If you want to use the percent sign (%) as the percent sign and not have it interpreted as the SQL wildcard used in SQL LIKE queries, how to do that?
Use escape keyword. For example:
stmt.executeQuery("select tax from sales where tax like '10\%' {escape '\'}");
________________________________________
22. How to escape ' symbol found in the input line?
You may use a method to do so:
static public String escapeLine(String s) {
String retvalue = s;
if (s.indexOf ("'") != -1 ) {
StringBuffer hold = new StringBuffer();
char c;
for(int i=0; i < s.length(); i++ ) {
if ((c=s.charAt(i)) == '\'' ) {
hold.append ("''");
}else {
hold.append(c);
}
}
retvalue = hold.toString();
}
return retvalue;
}
Note that such method can be extended to escape any other characters that the database driver may interprete another way.
________________________________________
23. How to make an update?
Creates a Statement object and calls the Statement.executeUpdate method.

String updateString = "INSERT INTO aDatabase VALUES (some text)";
int count = stmt.executeUpdate(updateString);
________________________________________
24. How to update a ResultSet?
You can update a value in a result set by calling the ResultSet.update method on the row where the cursor is positioned. The type value here is the same used when retrieving a value from the result set, for example, updateString updates a String value and updateDouble updates a double value in the result set.
rs.first();
updateDouble("balance", rs.getDouble("balance") - 5.00);
The update applies only to the result set until the call to rs.updateRow(), which updates the underlying database.
To delete the current row, use rs.deleteRow().
To insert a new row, use rs.moveToInsertRow().
________________________________________
25. How can you use PreparedStatement?
This special type of statement is derived from the more general class, Statement. If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.
PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
________________________________________
26. How to call a Stored Procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure;
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
________________________________________
27. How to Retrieve Warnings?
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
SQLWarning warning = stmt.getWarnings();
if (warning != null) {

while (warning != null) {
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
________________________________________
28. How to Make Updates to Update ResultSets?
Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.
Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = ("SELECT COF_NAME, PRICE FROM COFFEES");
________________________________________
29. How to set a scroll type?
Both Statements and PreparedStatements have an additional constructor that accepts a scroll type and an update type parameter. The scroll type value can be one of the following values:
o ResultSet.TYPE_FORWARD_ONLY Default behavior in JDBC 1.0, application can only call next() on the result set.
o ResultSet.SCROLL_SENSITIVE ResultSet is fully navigable and updates are reflected in the result set as they occur.
o ResultSet.SCROLL_INSENSITIVE Result set is fully navigable, but updates are only visible after the result set is closed. You need to create a new result set to see the results.
________________________________________
30. How to set update type parameter?
In the constructors of Statements and PreparedStatements, you may use
o ResultSet.CONCUR_READ_ONLY The result set is read only.
o ResultSet.CONCUR_UPDATABLE The result set can be updated.
You may verify that your database supports these types by calling con.getMetaData().supportsResultSetConcurrency(ResultSet.SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
________________________________________
31. How to do a batch job?
By default, every JDBC statement is sent to the database individually. To send multiple statements at one time , use addBatch() method to append statements to the original statement and call executeBatch() method to submit entire statement.
Statement stmt = con.createStatement();
stmt.addBatch("update registration set balance=balance-5.00 where theuser="+theuser);
stmt.addBatch("insert into auctionitems(description, startprice) values("+description+","+startprice+")");
...
int[] results = stmt.executeBatch();
The return result of the addBatch() method is an array of row counts affected for each statement executed in the batch job. If a problem occurred, a java.sql.BatchUpdateException is thrown. An incomplete array of row counts can be obtained from BatchUpdateException by calling its getUpdateCounts() method.
32. How to store and retrieve an image?
To store an image, you may use the code:
int itemnumber=400456;

File file = new File(itemnumber+".jpg");
FileInputStream fis = new FileInputStream(file);
PreparedStatement pstmt = con.prepareStatement("update auctionitems set theimage=? where id= ?");
pstmt.setBinaryStream(1, fis, (int)file.length()):
pstmt.setInt(2, itemnumber);
pstmt.executeUpdate();
pstmt.close();
fis.close();
To retrieve an image:
int itemnumber=400456;
byte[] imageBytes;//hold an image bytes to pass to createImage().

PreparedStatement pstmt = con.prepareStatement("select theimage from auctionitems where id= ?");
pstmt.setInt(1, itemnumber);
ResultSet rs=pstmt.executeQuery();
if(rs.next()) {
imageBytes = rs.getBytes(1);
}
pstmt.close();
rs.close();

Image auctionimage = Toolkit.getDefaultToolkit().createImage(imageBytes);
________________________________________
33. How to store and retrive an object?
A class can be serialized to a binary database field in much the same way as the image. You may use the code above to store and retrive an object.
________________________________________
34. How to use meta data to check a column type?
Use getMetaData().getColumnType() method to check data type. For example to retrieve an Integer, you may check it first:
int count=0;
Connection con=getConnection();
Statement stmt= con.createStatement();
stmt.executeQuery("select counter from aTable");
ResultSet rs = stmt.getResultSet();
if(rs.next()) {
if(rs.getMetaData().getColumnType(1) == Types.INTEGER) {
Integer i=(Integer)rs.getObject(1);
count=i.intValue();
}
}
rs.close();
________________________________________
35. Why cannot java.util.Date match with java.sql.Date?
Because java.util.Date represents both date and time. SQL has three types to represent date and time.
o java.sql.Date -- (00/00/00)
o java.sql.Time -- (00:00:00)
o java.sql.Timestamp -- in nanoseconds
Note that they are subclasses of java.util.Date.
________________________________________
36. How to convert java.util.Date value to java.sql.Date?
Use the code below:
Calendar currenttime=Calendar.getInstance();
java.sql.Date startdate= new java.sql.Date((currenttime.getTime()).getTime());

or

SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date enddate = new java.util.Date("10/31/99");
java.sql.Date sqlDate = java.sql.Date.valueOf(template.format(enddate));

JDBC_quest

1) What are the steps involved in establishing a connection?
Ans : This involves two steps: (1) loading the driver and (2) making the connection.
2) How can you load the drivers?
Ans : Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:
Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:
Eg.
Class.forName("jdbc.DriverXYZ");

3) What Class.forName will do while loading drivers?
Ans : It is used to create an instance of a driver and register it with the DriverManager.
When you have loaded a driver, it is available for making a connection with a DBMS.

4) How can you make the connection?
Ans : In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:
Eg.
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");

5) How can you create JDBC statements?
Ans : A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate.

Eg.
It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt :
Statement stmt = con.createStatement();

6) How can you retrieve data from the ResultSet?
Ans : Step 1.
JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.
Eg.
ResultSet rs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
Step2.
String s = rs.getString("COF_NAME");
The method getString is invoked on the ResultSet object rs , so getString will retrieve (get) the value stored in the column COF_NAME in the current row of rs
7) What are the different types of Statements?
Ans : 1.Statement (use createStatement method) 2. Prepared Statement (Use prepareStatement method) and 3. Callable Statement (Use prepareCall)

8) How can you use PreparedStatement?
Ans : This special type of statement is derived from the more general class, Statement.If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.
The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.
Eg.
PreparedStatement updateSales = con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
9) What setAutoCommit does?
Ans : When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode
Eg.
con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.
Eg.
con.setAutoCommit(false);
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal = con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);

10) How to call a Strored Procedure from JDBC?
Ans : The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open Connection
object. A CallableStatement object contains a call to a stored procedure;
Eg.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
11) How to Retrieve Warnings?
Ans : SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned.
A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
Eg.
SQLWarning warning = stmt.getWarnings();
if (warning != null) {
System.out.println("\n---Warning---\n");
while (warning != null) {
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
System.out.println("");
warning = warning.getNextWarning();
}
}

12) How can you Move the Cursor in Scrollable Result Sets ?
Ans : One of the new features in the JDBC 2.0 API is the ability to move a result set's cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.
Eg.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE .
The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE . The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order.
Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY

13) What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?
Ans : You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened
Eg.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
srs.afterLast();
while (srs.previous()) {
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}


14) How to Make Updates to Updatable Result Sets?
Ans : Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.
Eg.
Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

JSP & Servlet questions

1. The method getWriter returns an object of type PrintWriter. This class has println methods to generate output. Which of these classes define the getWriter method? Select the one correct answer.

A. HttpServletRequest
B. HttpServletResponse
C. ServletConfig
D. ServletContext
Ans: B. The class HttpServletResponse defines the getWriter method.
2. Name the method defined in the HttpServletResponse class that may be used to set the content type. Do not include parenthesis after the method.

setContentType

3. Which of the following statements is correct. Select the one correct answer.
A. The response from the server to a HEAD request consists of status line, content type and the document.
B. The response from the server to a GET request does not contain a document.
C. The setStatus method defined in the HttpServletRequest class takes an int as an argument and sets the status of Http response
D. The HttpServletResponse defines constants like SC_NOT_FOUND that may be used as a parameter to setStatus method.
D. The response from the server to a HEAD request does not contain the document, whereas the response to GET request does contain a document. So A and B are incorrect. C is incorrect because setStauts is defined in HttpServletResponse.
4. The sendError method defined in the HttpServlet class is equivalent to invoking the setStatus method with the following parameter. Select the one correct answer.
A. SC_OK
B. SC_MOVED_TEMPORARILY
C. SC_NOT_FOUND
D. SC_INTERNAL_SERVER_ERROR
E. ESC_BAD_REQUEST
C. sendError(String URL) is equivalent to sending SC_NOT_FOUND (404) response code.
5. The sendRedirect method defined in the HttpServlet class is equivalent to invoking the setStatus method with the following parameter and a Location header in the URL. Select the one correct answer.
A. SC_OK
B. SC_MOVED_TEMPORARILY
C. SC_NOT_FOUND
D. SC_INTERNAL_SERVER_ERROR
E. ESC_BAD_REQUEST
B. sendRedirect(String URL) is equivalent to sending SC_MOVED_TEMPORARILY (302) response code and a location header in the URL.

6. Which of the following statements are correct about the status of the Http response. Select the one correct answer.
A. A status of 200 to 299 signifies that the request was succesful.
B. A status of 300 to 399 are informational messages.
C. A status of 400 to 499 indicates an error in the server.
D. A status of 500 to 599 indicates an error in the client.
A. The following table specifies the specific the status code of Http response.
Status Code Purpose
100-199 Informational
200-299 Request was succesful
300-399 Request file has moved.
400-499 Client error
500-599 Server error.
7. To send binary outptut in a response, the following method of HttpServletResponse may be used to get the appropriate Writer/Stream object. Select the one correct answer.
A. getStream
B. getOutputStream
C. getBinaryStream
D. getWriter
B. The getOutputStream method is used to get an output stream to send binary data. The getWriter method is used to get a PrintWriter object that can be used to send text data.
8. To send text outptut in a response, the following method of HttpServletResponse may be used to get the appropriate Writer/Stream object. Select the one correct answer.
A. getStream
B. getOutputStream
C. getBinaryStream
D. getWriter
D
9. Is the following statement true or false. URL rewriting may be used when a browser is disabled. In URL encoding the session id is included as part of the URL.
ans :true. The statement about URL encoding is correct.
10. Name the class that includes the getSession method that is used to get the HttpSession object.
A. HttpServletRequest
B. HttpServletResponse
C. SessionContext
D. SessionConfig
A. The class HttpServletRequest defines the getSession method.


11. Which of the following are correct statements. Select the two correct answers.
A. The getRequestDispatcher method of ServletContext class takes the full path of the servlet, whereas the getRequestDispatcher method of HttpServletRequest class takes the path of the servlet relative to the ServletContext.
B. The include method defined in the RequestDispatcher class can be used to access one servlet from another. But it can be invoked only if no output has been sent to the server.
C. The getRequestDispatcher(String URL) is defined in both ServletContext and HttpServletRequest method
D. The getNamedDispatcher(String) defined in HttpServletRequest class takes the name of the servlet and returns an object of RequestDispatcher class
A, C.

12. How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:

<%@ page errorPage="error.jsp" %>

redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.

Within error.jsp, if you indicate that it is an error-processing page, via the directive:

<%@ page isErrorPage="true" %>
the Throwable object describing the exception may be accessed within the error page via the exception implicit object.


Note: You must always use a relative URL as the value for the
errorPage attribute.

13. How do I perform browser redirection from a JSP page?

You can use the response implicit object to redirect the browser to a different resource, as:

response.sendRedirect("http://www.foo.com/path/error.html");

14. Applet Servlet Communication

You can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection to the web server. The server then passes this information to the servlet in the normal way. Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.

15. How do I connect to my Java server with a socket when the client applet/application runs behind a proxy/firewall?

I tried it with an applet, but it throws the "host unreachable" exception, among others.

You cannot connect because the client's proxy/firewall prevents most
socket connections. Most firewalls prevent any kind of communication, except for HTTP. This is done to protect the internal infrastructure; users can still browse the Web, but cannot connect to other networked
applications.
However, there are ways to connect your Java applications to Java servers through HTTP. This is sometimes called firewall tunneling. To do this easily, create servlets on the server side and wrap all client messages in HTTP requests.

On the client side, your code should use the URLConnection to send
data to the server:


//connect
URL url = new URL("http://www.myserver.com/servlets/myservlet");

URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "application/octet-stream");

//Open output stream and send some data.
OutputStream out = conn.getOutputStream();
//I am not going to send anything on "out," but you can fill this in.

out.flush();
out.close();

//Open input stream and read the data back.
InputStream in = conn.getInputStream();

//Here you would read the data back.

in.close()


On the server side, when the client says openConnection(), the servlet's doPost() method will be called. In that method, you can read the data and write back to the client.

16. HTTP Tunneling
HTTP tunneling is a general technique whereby data may be sent via an HTTP connection to and from Java Servlets on a Web server. This is done by serializing the data to be transmitted into a stream of bytes, and sending an HTTP message with content type "application/octet-stream". HTTP tunneling is also referred to as Firewall tunneling.

17. What is inter-servlet communication?
As the name says it, it is communication between servlets. Servlets talking to each other. There are many ways to communicate between servlets, including
Request Dispatching
HTTP Redirect
Servlet Chaining
HTTP request (using sockets or the URLConnection class) Shared session, request, or application objects (beans)

Basically interServlet communication is acheived through servlet chaining. Which is a process in which you pass the output of one servlet as the input to other. These servlets should be running in the same server.

e.g. ServletContext.getRequestDispatcher(HttpRequest,HttpResponse).forward("NextServlet") ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet.

18 what is Servlet Filtering?
A filter is a reusable piece of code that can transform the content of HTTP requests, responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource. Filters can act on dynamic or static content. These dynamic and static contents are referred to asweb resources.

Among the types of functionality available to the filter author are
• The accessing of a resource before a request to it is invoked.
• The processing of the request for a resource before it is invoked.
• The modification of request headers and data by wrapping the request in cus-tomized versions of the request object.
• The modification of response headers and response data by providing custom-ized versions of the response object.
• The interception of an invocation of a resource after its call.
• Actions on a servlet, on groups of servlets or static content by zero, one or more filters in a specifiable order.

Examples of Filtering Components
• Authentication filters
• Logging and auditing filters
• Image conversion filters
• Data compression filters
• Encryption filters
• Tokenizing filters
• Filters that trigger resource access events
• XSL/T filters that transform XML content
• MIME-type chain filters
• Caching filters

19. JSP to Servlet communication -Vice Versa

From JSP to Servlet:
When we want to pass a object to Servlet from a JSP page You insert that object you need in the request scope with request.setAttribute()
Then use to the servlet.
In the servlet you use request.getAttribute() to get the object back !

From Servlet to JSP
You insert the object with request.setAttribute(),then use RequestDispatcher ,to forward to the JSP page In the JSP page you use request.getAttribute() to get the object back.
This is the way of communication i do in my projects,Any new :) idea of communication is available than this ?]

20. What is the diffrent between seesion and cookies
session in short lived,and cookies is long lived !
First of all session and cookies should not be compared for differences. To create a session a cookie that stores a session ID is required, so that for every subsequent calls the app server could distinguish between various sessions. Cookies can be used to store additional information, but there primary cause is to store the session ids. Point to note: A server cannot track user sessions if cookies are disabled in the browser. There are other methods like URL Rewritting. But then the true essence of session tracking is lost. All i want to say, is sessions should not be understood as server side cookies or cookies should not be understood as client side sessions. Both were created to facilitate user connection identification. Which means that they should not be compared, since they were made for made to solve different purposes. As far as long lived and short lived is concerned, both have a expiration time which can be set as per will..

21. Whats the difference between using tag and request.sendRedirect

tag is
* Functions only within the single servlet context
* Location/addrs in the borwser doesnt changes when used

1. Using request.sendRedirect u can redirect the browser to diffrent location

2. forwarding is done within the server, and limited in scope to where you can forward. Redirections are done on the client and thus don't have these limitations.

Redirect sends a HTTP redirect code to the user-agent(Browser).Hence it involves a full roundtrip.If we use forward,we can avoid this traffic
22. When a JSP page is compiled, what is it turned into?
A.
Applet
B.
Servlet
C.
Application
D.
Mailet
Answer (B): Compiled JSP pages are turned into Servlets. See JSP Architecture for more information on this translation phase.

23 . Which of the following is not a standard method called as part of the JSP life cycle?
A.
jspInit()
B.
jspService()
C.
_jspService()
D.
jspDestroy()
Answer (B): The standard service method for JSP has an _ in its name
24. If you want to override a JSP file's initialization method, within what type of tags must you declare the method?
A.
<@ @>
B.
<%@ %>
C.
<% %>
D.
<%! %>
Answer (D): Declarations are placed within a set of <%! %> tags.
25. Which of the following can not be used as the scope when using a JavaBean with JSP?
A.
application
B.
session
C.
request
D.
response
E.
page
Answer (D): Response is not a valid object scope for JavaBeans (or anything else).
26. The implicit JSP objects like request, response, and out are only visible in the _jspService() method.
A.
True
B.
False
Answer (D): Response is not a valid object scope for JavaBeans (or anything else).
27. What is the key difference between using a and HttpServletResponse.sendRedirect()?
A.
forward executes on the client while sendRedirect() executes on the server.
B.
forward executes on the server while sendRedirect() executes on the client.
C.
The two methods perform identically.
Answer (B): When you forward a request, the forwarding is done within the server, and limited in scope to where you can forward. Redirections are done on the client and thus don't have these limitations.
28.. Which of the following statements makes your compiled JSP page implement the SingleThreadModel interface?
A. <%@ page isThreadSafe="false" %>
B. <%@ page isThreadSafe="true" %>
Answer (A): If you flag the JSP page as not being thread safe, it will implement the interface.
29. Of the following four valid comment styles that can be used within JSP pages, which can the end user see?
A. <%-- My comments <% out.println("Hello World"); %>
--%>
B.
C. <% // For Loop for (int i=1; i<=4; i++) { %>
<%=i%>>Hello<%=i%>>
<% } %>
D. <% /** yet another comment */ JavaDoc Rules %>
Answer (B): Only the JavaScript comment can be seen from the generated page. The other comments will be buried in the source for the generated servlet.
30 . How can a servlet call a JSP error page?
A.
This capability is not supported.
B.
When the servlet throws the exception, it will automatically be caught by the calling JSP page.
C.
The servlet needs to forward the request to the specific error page URL. The exception is passed along as an attribute named "javax.servlet.jsp.jspException".
D.
The servlet needs to redirect the response to the specific error page, saving the exception off in a cookie.
Answer (C): D will get the browser to display the appropriate page, it just doesn't preserve the state information requiring an unnecessary round trip to the browser. C is the direct approach.
31. When using a JavaBean to get all the parameters from a form, what must the property be set to (??? in the following code) for automatic initialization?



A.
*
B.
all
C.
@
D.
=
Answer (A): The * character is used for this.

32 . IsThreadSafe.. how it works?
By default, the service method of the JSP page implementation class that services the client request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared state is effectively synchronized. There are a couple of different ways to ensure that the service methods are thread-safe. The easy approach is to include the JSP page directive:
<%@ page isThreadSafe="false" %>
This causes the JSP page implementation class to implement the SingleThreadModel interface, resulting in the synchronization of the service method, and having multiple instances of the servlet to be loaded in memory. The concurrent client requests are then distributed evenly amongst these instances for processing in a round-robin fashion, as shown below:

The downside of using this approach is that it is not scalable. If the wait queue grows due to a large number of concurrent requests overwhelming the processing ability of the servlet instances, then the client may suffer a significant delay in obtaining the response.
A better approach is to explicitly synchronize access to shared objects (like those instances with application scope, for example) within the JSP page, using scriptlets:
<% synchronized (application) { SharedObject foo = (SharedObject) application.getAttribute("sharedObject"); foo.update(someValue); application.setAttribute("sharedObject",foo); } %>


33. session.getValue("name") has been deprecated, what method do I call instead?

Use session.getAttribute("name").toString() to accomplish the same thing as the deprecated getValue method.

34. What is the difference between request.getAttribute() and request.getParameter()?

In a request object you can store, on the server side, some object that can be useful during the processing of your pages. This uses request.setAttribute() and request.getAttribute(). Remember that the life of the request object lasts through all the include and forwards, and ends when the page has been sent back to the browser.The getParameter() method, instead, will return you the specific parameter that has been passed to the page through GET or POST.

35. What is a Servlet Context?
A servlet conatiner can have several servlet context Each Servlet context share the common resources

36. Internatilization?
means making it easier for an application to adapt to different regions and languages. The main purpose here is to see that it is not necessary to compile ur programs to make it work with different languages and regions. Things like lables,messages etc need to be separated from ur program code.

37. Can scriptlets contain methods?
the answer is no. Any code included within the scriptlet will finally be part of
_jspService method. Since java does not support nested methods scriptlets cannot contain and methods.
Is JSP Single Threaded?

38. By default JSP Is multi threaded

However u can make it act as single thread as making the isThreadSafe to True


39. Diff in <%@ page isThreadSafe="true" %> or <%@ page isThreadSafe="false" %>

It is required to set the isthreadsafe to false if u want singlethreadmodel.

The default value is true,which means that the JSP container can send multiple, concurrent client requests
to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page.

40. difference between Generic servlets and http servlets.
Consider we are having two servlets A and B. Syntax for calling a method in servlet A from B.

41. when we use only doget()
goGet() method is to rerieve data from server by supplying minimal data inputs.Thats why max data size is 255 chars in doGet().

42. Difference between Container and Server

Web container provides runtime environment for Web components (a Web component is a Servlet or a JSP) and services for these components:
security, oncurrency, life cycle management, transaction, deployment, etc. A Web server is software that provides services to access the nternet; it hosts Web sites. It also performs certain functions for the Web container (such as message handling) and hosting.

43. How many instances wil be created for a servlet if thousand users access a servlet

Only one instance ,since servlet is Multithreaded Arch So only one instance wil be created

44. But the interviewer said not exactly the only one instance It may increase its instance and not limited ONE ,On what criteria the instance will be increaed

For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a
servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize
requests to a particular instance. In the case where a servlet was deployed as part of an application marked in the deployment descriptor as distributable, a container may have only one instance per servlet declaration per virtual machine (VM). However, if the servlet in a distributable application implements the SingleThreadModel interface, the container may instantiate multiple instances of that servlet in each VM of the container.
45. What is the Diff between RequestDispatcher.forward() or HttpServletResponse.sendRedirect()
Two Types of dispatching are available.Forwarding is achieved through the javax.servlet.RequestDispatcher interface.And redirecting is available through the javax.servlet.http.HttpServletResponse interface. When you forward the web container makes a direct call to the target resource without the browsers knowledge.Therefore the url in the browsers window does not change.If users refresh the page to reload , they get the page you forwarded from,not the page you forwarded to.To forward a request you can call the javax.servlet.RequestDispatcher.forward(),passing the request and response objects as parameters.You obtain a reference to RequestDispatcher either from the ServletContext or the HttpServletRequest.ie
ServletContext ctx=this.getServletContext();
RequestDispatcher dispatcher=ctx.getRequestDispatcher("/registerServet");
dispatcher.forward(request,response);
//or....
RequestDispatcher dispatcher=request.getRequestDispatcher("/registerServet");
dispatcher.forward(request,response);
The difference between these two methods is in the ServletContext version the path you provide for the RequestDispatcher must begin with a / and is always relative to Context root.In the HttpServletRequest version,you can omit the leading /,in which case the path is interpretted to be relative to servlet doing forwarding. Redirecting on the otherhand,forces the browser to issue a completely new request to the target page,as if the users had requested it themselves.
response.sendRedirect("/home.html");
46. Choosing Between Forward and Redirect ?

If you want to pass the control from one page to another, you can either forward to the other page, as described above, or redirect to the new page (using the sendRedirect() method of the implicit response object).

There's an important difference between a forward and a redirect. When you forward, the target page is invoked by the JSP container through an internal method call; the new page continues to process the same request and the browser is not aware of the fact that more than one page is involved. A redirect, on the other hand, means that the first page tells the browser to make a new request to the target page. The URL shown in the browser therefore changes to the URL of the new page when you redirect, but stays unchanged when you use forward. A redirect is slower than a forward because the browser has to make a new request. Another difference is that request scope objects are no longer available after a redirect because it results in a new request. If you need to pass data to the page you redirect to, you have to use a query string and pass them as request parameters (or save the data as session or application scope objects).

So how do you decide if you should use forward or redirect? I look at it like this: Forwarding is always faster, so that's the first choice. But since the URL in the browser refers to the start page even after the forward, I ask myself what happens if the user reloads the page (or just resizes the window; this often reloads the page automatically). If the start page is a page that updates some information, such as adding an item to the shopping cart or inserting information in a database, I don't want it to be invoked again on a reload. To show the result of the processing, I therefore redirect to a page with a confirmation message, instead of using forward.

47. Diff between and <%@ include file="relativeURL" %> ?
adds the content of the page at runtime.
<%@i...> include the page when the jsp file gets compiled.

compiles the files sperately and includes into the JSP page
<%@ include file="relativeURL" %> compiles as part of the current JSP like #include in C

48. why there is no constructors in Servlets?can we have constructor in servlets?if we can how is differed from init() method in servlets?

There is at any time only one instance of a servlet running so you do not need constructors. For passing any values to a servlet on creation you can add parameters to the deployment-descriptor-file. and for performing any tasks on initialising the servlet you can perform them in the servlets init() method. so there is no need for constructors

49. how to view the servlet file that is generated from JSP??? And how find the exact location of the Exception that occured in JSP during runtime.??????
If the appserver that you are using is Websphere please add in a new attribute KeepGenerated with value true in the applications ibm-web-ext.xmi. file .you can find this in the applications deployed directory. this will save the intermediary servlet.java files that are generated
50 if u r using tomcat 3.3.1 we can see the servlet file in the following directory.
In the "tomcat" main directory.
go for "work" directory.
go for " default" directory.
go for the directory were u have placed JSP file like
if u have placed ur jsp file in "webapps/example"
directory then go for "example" directory.
go for "jsp" directory.
here u can see all the servlet files generated for ur JSP files.

51. What is the capacity of parameters that can be sent to servlet thru doGet method?
it depends on the capacity of your environment variable. e.g. for windows it is 2048 characters.

52. How to know in servlet/jsp whether browser accepts cookies or not?
in HttpRequest, there is a method, isRequestedSessionIdFromCookie
which returns true if browser accepts cookie.

53. How to disable back button in browser?
You can disable back button in browser by setting the history to "0".

54. How many cookies(maximum numbers) you can set in a website.
The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.

55. If there are 2 entries for a servlet in web.xml then there will be 2 instances?

56. There is a text box in my JSP page. User is allowed to fill any characters like & % etc. How will you send this information in Query string?

57. I m having 2 forms in my page. If I click submit button on my page what will happen? Both the form s will be submitted or not?


JSP Questions

1. What is JSP technology?
Java Server Page is a standard Java extension that is defined on top of the servlet Extensions. The goal of JSP is the simplified creation and management of dynamic Web pages. JSPs are secure, platform-independent, and best of all, make use of Java as a server-side scripting language.
________________________________________
2. What is JSP page?
A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.
________________________________________
3. What are the implicit objects?
Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:
o request
o response
o pageContext
o session
o application
o out
o config
o page
o exception
________________________________________
4. How many JSP scripting elements and what are they?
There are three scripting language elements:
1. declarations
2. scriptlets
3. expressions
________________________________________
5. Why are JSP pages the preferred API for creating a web-based client program?
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.
________________________________________
6. Is JSP technology extensible?
YES. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
________________________________________
7. What are the two kinds of comments in JSP and what's the difference between them?
<%-- JSP Comment --%>

________________________________________
8. In the Servlet 2.4 specification SingleThreadModel has been deprecates, why?
Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.
________________________________________
9. What is difference between custom JSP tags and beans?
Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components:
0. the tag handler class that defines the tag's behavior
1. the tag library descriptor file that maps the XML element names to the tag implementations
2. the JSP file that uses the tag library
When the first two components are done, you can use the tag by using taglib directive:
<%@ taglib uri="xxx.tld" prefix="..." %>
Then you are ready to use the tags you defined. Let's say the tag prefix is test:
MyJSPTag or
JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags

to declare a bean and use

to set value of the bean class and use
<%=identifier.getclassField() %>
to get value of the bean class.
Custom tags and beans accomplish the same goals -- encapsulating complex behavior into simple and accessible forms. There are several differences:
o Custom tags can manipulate JSP content; beans cannot.
o Complex operations can be reduced to a significantly simpler form with custom tags than with beans.
o Custom tags require quite a bit more work to set up than do beans.
o Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.
o Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
________________________________________

Wednesday, January 21, 2009

Inheritance

1) What is the difference between superclass & subclass?
Ans : A super class is a class that is inherited whereas subclass is a class that does the inheriting.
2) Which keyword is used to inherit a class?
Ans : extends
3) Subclasses methods can access superclass members/ attributes at all times?
True/False
Ans : False
4) When can subclasses not access superclass members?
Ans : When superclass is declared as private.
5) Which class does begin Java class hierarchy?
Ans : Object class
6) Object class is a superclass of all other classes?
True/False
Ans : True
7) Java supports multiple inheritance?
True/False
Ans : False
8) What is inheritance?
Ans : Deriving an object from an existing class. In the other words, Inheritance is the process of inheriting all the features from a class
9) What are the advantages of inheritance?
Ans : Reusability of code and accessibility of variables and methods of the superclass by subclasses.
10) Which method is used to call the constructors of the superclass from the subclass?
Ans : super(argument)
11) Which is used to execute any method of the superclass from the subclass?
Ans : super.method-name(arguments)
12) Which methods are used to destroy the objects created by the constructor methods?
Ans : finalize()
13) What are abstract classes?
Ans : Abstract classes are those for which instances can’t be created.
14) What must a class do to implement an interface?
Ans: It must provide all of the methods in the interface and identify the interface in its implements clause.
15) Which methods in the Object class are declared as final?
Ans : getClass(), notify(), notifyAll(), and wait()
16) Final methods can be overridden.
True/False
Ans : False
17) Declaration of methods as final results in faster execution of the program?
True/False
Ans: True
18) Final variables should be declared in the beginning?
True/False
Ans : True
19) Can we declare variable inside a method as final variables? Why?
Ans : Cannot because, local variable cannot be declared as final variables.


20) Can an abstract class may be final?
Ans : An abstract class may not be declared as final.
21) Does a class inherit the constructors of it's super class?
Ans: A class does not inherit constructors from any of it's super classes.
22) What restrictions are placed on method overloading?
Ans: Two methods may not have the same name and argument list but different return types.
23) What restrictions are placed on method overriding?
Ans : Overridden methods must have the same name , argument list , and return type. The overriding method may not limit the access of the method it overridees.The overriding method may not throw any exceptions that may not be thrown by the overridden method.
24) What modifiers may be used with an inner class that is a member of an outer class?
Ans : a (non-local) inner class may be declared as public, protected, private, static, final or abstract.
25) How this() is used with constructors?
Ans: this() is used to invoke a constructor of the same class
26) How super() used with constructors?
Ans : super() is used to invoke a super class constructor
27) Which of the following statements correctly describes an interface?
a)It's a concrete class
b)It's a superclass
c)It's a type of abstract class
Ans: c
28) An interface contains __ methods
a)Non-abstract
b)Implemented
c)unimplemented
Ans:c

MULTI THREADING

1) What are the two types of multitasking?
Ans : 1.process-based
2.Thread-based
2) What are the two ways to create the thread?
Ans : 1.by implementing Runnable
2.by extending Thread
3) What is the signature of the constructor of a thread class?
Ans : Thread(Runnable threadob,String threadName)
4) What are all the methods available in the Runnable Interface?
Ans : run()
5) What is the data type for the method isAlive() and this method is available in which class?
Ans : boolean, Thread
6) What are all the methods available in the Thread class?
Ans : 1.isAlive()
2.join()
3.resume()
4.suspend()
5.stop()
6.start()
7.sleep()
8.destroy()
7) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?
Ans :1. wait(),notify() & notifyall()
2. Object class
8) What is the mechanisam defind by java for the Resources to be used by only one Thread at a time?
Ans : Synchronisation
9) What is the procedure to own the moniter by many threads?
Ans : not possible
10) What is the unit for 1000 in the below statement?
ob.sleep(1000)
Ans : long milliseconds
11) What is the data type for the parameter of the sleep() method?
Ans : long
12) What are all the values for the following level?
max-priority
min-priority
normal-priority
Ans : 10,1,5
13) What is the method available for setting the priority?
Ans : setPriority()
14) What is the default thread at the time of starting the program?
Ans : main thread
15) The word synchronized can be used with only a method.
True/ False
Ans : False

16) Which priority Thread can prompt the lower primary Thread?
Ans : Higher Priority
17) How many threads at a time can access a monitor?
Ans : one
18) What are all the four states associated in the thread?
Ans : 1. new 2. runnable 3. blocked 4. dead
19) The suspend()method is used to teriminate a thread?
True /False
Ans : False
20) The run() method should necessary exists in clases created as subclass of thread?
True /False
Ans : True
21) When two threads are waiting on each other and can't proceed the programe is said to be in a deadlock?
True/False
Ans : True
22) Which method waits for the thread to die ?
Ans : join() method
23) Which of the following is true?
1) wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method
2) Among wait(),notify(),notifyall() the wait() method only throws IOException
3) wait(),notify(),notifyall() & sleep() are methods of object class
Ans : 1 &2
24) Garbage collector thread belongs to which priority?
Ans : low-priority
25) What is meant by timeslicing or time sharing?
Ans : Timeslicing is the method of allocating CPU time to individual threads in a priority schedule.
26) What is meant by daemon thread? In java runtime, what is it's role?
Ans : Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system.

Exception Handling

1) What is the difference between ‘throw’ and ‘throws’ ?And it’s application?
Ans : Exceptions that are thrown by java runtime systems can be handled by Try and catch blocks. With throw exception we can handle the exceptions thrown by the program itself. If a method is capable of causing an exception that it does not
handle, it must specify this behavior so the callers of the method can guard
against that exception.
2) What is the difference between ‘Exception’ and ‘error’ in java?
Ans : Exception and Error are the subclasses of the Throwable class. Exception class is used for exceptional conditions that user program should catch. With exception class we can subclass to create our own custom exception.
Error defines exceptions that are not excepted to be caught by you program. Example is Stack Overflow.
3) What is ‘Resource leak’?
Ans : Freeing up other resources that might have been allocated at the beginning of a method.
4)What is the ‘finally’ block?
Ans : Finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement match the exception. Any time a method is about to return to the caller from inside try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also execute.
5) Can we have catch block with out try block? If so when?
Ans : No. Try/Catch or Try/finally form a unit.
6) What is the difference between the following statements?
Catch (Exception e),
Catch (Error err),
Catch (Throwable t)
Ans :
7) What will happen to the Exception object after exception handling?
Ans : It will go for Garbage Collector. And frees the memory.
8) How many Exceptions we can define in ‘throws’ clause?
Ans : We can define multiple exceptions in throws clause.
Signature is..
type method-name (parameter-list) throws exception-list
9) The finally block is executed when an exception is thrown, even if no catch matches it.
True/False
Ans : True
10) The subclass exception should precede the base class exception when used within the catch clause.
True/False
Ans : True
11) Exceptions can be caught or rethrown to a calling method.
True/False
Ans : True
12) The statements following the throw keyword in a program are not executed.
True/False
Ans : True
13) The toString ( ) method in the user-defined exception class is overridden.
True/False
Ans : True

Packages and interface

1) What are packages ? what is use of packages ?
Ans :The package statement defines a name space in which classes are stored.If you omit the package, the classes are put into the default package.
Signature... package pkg;
Use: * It specifies to which package the classes defined in a file belongs to. * Package is both naming and a visibility control mechanism.
2) What is difference between importing "java.applet.Applet" and "java.applet.*;" ?
Ans :"java.applet.Applet" will import only the class Applet from the package java.applet
Where as "java.applet.*" will import all the classes from java.applet package.

3) What do you understand by package access specifier?
Ans : public: Anything declared as public can be accessed from anywhere
private: Anything declared in the private can’t be seen outside of its class.
default: It is visible to subclasses as well as to other classes in the same package.
4) What is interface? What is use of interface?
Ans : It is similar to class which may contain method’s signature only but not bodies.
Methods declared in interface are abstract methods. We can implement many interfaces on a class which support the multiple inheritance.
5) Is it is necessary to implement all methods in an interface?
Ans : Yes. All the methods have to be implemented.
6) Which is the default access modifier for an interface method?
Ans : public.
7) Can we define a variable in an interface ?and what type it should be ?
Ans : Yes we can define a variable in an interface. They are implicitly final and static.
8) What is difference between interface and an abstract class?
Ans : All the methods declared inside an Interface are abstract. Where as abstract class must have at least one abstract method and others may be concrete or abstract.
In Interface we need not use the keyword abstract for the methods.
9) By default, all program import the java.lang package.
True/False
Ans : True
10) Java compiler stores the .class files in the path specified in CLASSPATH
environmental variable.
True/False
Ans : False
11) User-defined package can also be imported just like the standard packages.
True/False
Ans : True
12) When a program does not want to handle exception, the ______class is used.
Ans : Throws
13) The main subclass of the Exception class is _______ class.
Ans : RuntimeException
14) Only subclasses of ______class may be caught or thrown.
Ans : Throwable
15) Any user-defined exception class is a subclass of the _____ class.
Ans : Exception


16) The catch clause of the user-defined exception class should ______ its
Base class catch clause.
Ans : Exception
17) A _______ is used to separate the hierarchy of the class while declaring an
Import statement.
Ans : Package
18) All standard classes of Java are included within a package called _____.
Ans : java.lang
19) All the classes in a package can be simultaneously imported using ____.
Ans : *
20) Can you define a variable inside an Interface. If no, why? If yes, how?
Ans.: YES. final and static
21) How many concrete classes can you have inside an interface?
Ans.: None
22) Can you extend an interface?
Ans.: Yes
23) Is it necessary to implement all the methods of an interface while implementing the interface?
Ans.: No
24) If you do not implement all the methods of an interface while implementing , what specifier should you use for the class ?
Ans.: abstract
25) How do you achieve multiple inheritance in Java?
Ans: Using interfaces.
26) How to declare an interface example?
Ans : access class classname implements interface.
27) Can you achieve multiple interface through interface?
a)True b) false
Ans : a.
28) Can variables be declared in an interface ? If so, what are the modifiers?
Ans : Yes. final and static are the modifiers can be declared in an interface.
29) What are the possible access modifiers when implementing interface methods?
Ans : public.
30) Can anonymous classes be implemented an interface?
Ans : Yes.
31) Interfaces can’t be extended.
a)True b)False
Ans : b.
32) Name interfaces without a method?
Ans : Serializable, Cloneble & Remote.
33) Is it possible to use few methods of an interface in a class ? If so, how?
Ans : Yes. Declare the class as abstract.

Introduction to Classes and Methods

1) Which is used to get the value of the instance variables?
Ans: Dot notation.
2) The new operator creates a single instance named class and returns a
reference to that object.
a)True b)False
Ans: a.
3) A class is a template for multiple objects with similar features.
a)True b)False
Ans: a.
4) What is mean by garbage collection?
Ans: When an object is no longer referred to by any variable, Java automatically
reclaims memory used by that object. This is known as garbage collection.
5) What are methods and how are they defined?
Ans: Methods are functions that operate on instances of classes in which they are defined.Objects can communicate with each other using methods and can call methods in other classes.
Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method.
A method's signature is a combination of the first three parts mentioned above.
6) What is calling method?
Ans: Calling methods are similar to calling or referring to an instance variable. These methods are accessed using dot notation.
Ex: obj.methodname(param1,param2)
7) Which method is used to determine the class of an object?
Ans: getClass( ) method can be used to find out what class the belongs to. This class is defined in the object class and is available to all objects.

8) All the classes in java.lang package are automatically imported when
a program is compiled.
a)True b)False
Ans: a.
9) How can class be imported to a program?
Ans: To import a class, the import keyword should be used as shown.;
import classname;
10) How can class be imported from a package to a program?
Ans: import java . packagename . classname (or) import java.package name.*;
11) What is a constructor?
Ans: A constructor is a special kind of method that determines how an object is
initialized when created.
12) Which keyword is used to create an instance of a class?
Ans: new.
13) Which method is used to garbage collect an object?
Ans: finalize ().
14) Constructors can be overloaded like regular methods.
a)True b)False
Ans: a.
15) What is casting?
Ans: Casting is bused to convert the value of one type to another.
16) Casting between primitive types allows conversion of one primitive type to another.
a)True b)False
Ans: a.
17) Casting occurs commonly between numeric types.
a)True b)False
Ans: a.
18) Boolean values can be cast into any other primitive type.
a)True b)False
Ans: b.
19) Casting does not affect the original object or value.
a)True b)False
Ans: a.
20) Which cast must be used to convert a larger value into a smaller one?
Ans: Explicit cast.
21) Which cast must be used to cast an object to another class?
Ans: Specific cast.
22) Which of the following features are common to both Java & C++?
A.The class declaration
b.The access modifiers
c.The encapsulation of data & methods with in objects
d.The use of pointers
Ans: a,b,c.
23) Which of the following statements accurately describe the use of access modifiers within a class definition?
a.They can be applied to both data & methods
b.They must precede a class's data variables or methods
c.They can follow a class's data variables or methods
d.They can appear in any order
e.They must be applied to data variables first and then to methods
Ans: a,b,d.
24) Suppose a given instance variable has been declared private.
Can this instance variable be manipulated by methods out side its class?
a.yes b.no
Ans: b.
25) Which of the following statements can be used to describe a public method?
a.It is accessible to all other classes in the hierarchy
b.It is accessablde only to subclasses of its parent class
c.It represents the public interface of its class
d.The only way to gain access to this method is by calling one of the public class
methods
Ans: a,c.
26) Which of the following types of class members can be part of the internal part of a class?
a.Public instance variables
b.Private instance variables
c.Public methods
d.Private methods
Ans: b,d.
27) You would use the ____ operator to create a single instance of a named class.
a.new b.dot
Ans: a.
28) Which of the following statements correctly describes the relation between an object and the instance variable it stores?
a.Each new object has its own distinctive set of instance variables
b.Each object has a copy of the instance variables of its class
c.the instance variable of each object are seperate from the variables of other objects
d.The instance variables of each object are stored together with the variables of other objects
Ans: a,b,c.
29) If no input parameters are specified in a method declaration then the declaration will include
a.an empty set of parantheses
b.the term void
Ans: a.
30) What are the functions of the dot(.) operator?
a.It enables you to access instance variables of any objects within a class
b.It enables you to store values in instance variables of an object
c.It is used to call object methods
d.It is to create a new object
Ans: a,b,c.
31) Which of the following can be referenced by this variable?
a.The instance variables of a class only
b.The methods of a class only
c.The instance variables and methods of a class
Ans: c.
32) The this reference is used in conjunction with ___methods.
a.static b.non-static Ans: b.
33) Which of the following operators are used in conjunction with the this and super references?
a.The new operator
b.The instanceof operator
c.The dot operator
Ans: c.
34) A constructor is automatically called when an object is instantiated
a. true b. false
Ans: a.
35) When may a constructor be called without specifying arguments?
a. When the default constructor is not called
b. When the name of the constructor differs from that of the class
c. When there are no constructors for the class
Ans: c.
36) Each class in java can have a finalizer method
a. true b.false
Ans: a.
37) When an object is referenced, does this mean that it has been identified by the finalizer method for garbage collection?
a.yes b.no
Ans: b.
38) Because finalize () belongs to the java.lang.Object class, it is present in all ___.
a.objects b.classes c.methods
Ans: b.
39) Identify the true statements about finalization.
a.A class may have only one finalize method
b.Finalizers are mostly used with simple classes
c.Finalizer overloading is not allowed
Ans: a,c.
40) When you write finalize() method for your class, you are overriding a finalizer
inherited from a super class.
a.true b.false
Ans: a.
41) Java memory management mechanism garbage collects objects which are no longer referenced
a true b.false
Ans: a.
42) are objects referenced by a variable candidates for garbage collection when the variable goes out of scope?
a yes b. no
Ans: a.
43) Java's garbage collector runs as a ___ priority thread waiting for __priority threads to relinquish the processor.
a.high b.low
Ans: a,b.
44) The garbage collector will run immediately when the system is out of memory
a.true b.false
Ans: a.
45) You can explicitly drop a object reference by setting the value of a variable whose data type is a reference type to ___
Ans: null
46) When might your program wish to run the garbage collecter?
a. before it enters a compute-intense section of code
b. before it enters a memory-intense section of code
c. before objects are finalized
d. when it knows there will be some idle time
Ans: a,b,d
47) For externalizable objects the class is solely responsible for the external format of its contents
a.true b.false
Ans: a
48) When an object is stored, are all of the objects that are reachable from that object stored as well?
a.true b.false
Ans: a
49) The default__ of objects protects private and trancient data, and supports the __ of the classes
a.evolution b.encoding
Ans: b,a.
50) Which are keywords in Java?
a) NULL
b) sizeof
c) friend
d) extends
e) synchronized
Ans : d and e
51) When must the main class and the file name coincide?
Ans :When class is declared public.
52) What are different modifiers?
Ans : public, private, protected, default, static, trancient, volatile, final, abstract.
53) What are access modifiers?
Ans : public, private, protected, default.
54) What is meant by "Passing by value" and " Passing by reference"?
Ans : objects – pass by referrence
Methods - pass by value
55) Is a class a subclass of itself?
Ans : A class is a subclass itself.
56) What modifiers may be used with top-level class?
Ans : public, abstract, final.
57) What is an example of polymorphism?
a. Inner class
b. Anonymous classes
c. Method overloading
d. Method overriding
Ans : c

Control Statements

1) What are the programming constructs?
Ans: a) Sequential
b) Selection -- if and switch statements
c) Iteration -- for loop, while loop and do-while loop
2) class conditional {
public static void main(String args[]) {
int i = 20;
int j = 55;
int z = 0;
z = i < j ? i : j; // ternary operator
System.out.println("The value assigned is " + z);
}
}
What is output of the above program?
Ans: The value assigned is 20
3) The switch statement does not require a break.
a)True b)False
Ans: b.
4) The conditional operator is otherwise known as the ternary operator.
a)True b)False
Ans: a.
5) The while loop repeats a set of code while the condition is false.
a)True b)False
Ans: b.
6) The do-while loop repeats a set of code atleast once before the condition is tested.
a)True b)False
Ans: a.
7) What are difference between break and continue?
Ans: The break keyword halts the execution of the current loop and forces control out of the loop.
The continue is similar to break, except that instead of halting the execution of the loop, it starts the next iteration.
8) The for loop repeats a set of statements a certain number of times until a condition is matched.
a)True b)False
Ans: a.
9) Can a for statement loop indefintely?
Ans : Yes.
10) What is the difference between while statement and a do statement/
Ans : 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.

Operators

1) What are operators and what are the various types of operators available in Java?
Ans: Operators are special symbols used in expressions.
The following are the types of operators:
Arithmetic operators,
Assignment operators,
Increment & Decrement operators,
Logical operators,
Biwise operators,
Comparison/Relational operators and
Conditional operators
2) The ++ operator is used for incrementing and the -- operator is used for
decrementing.
a)True b)False
Ans: a.
3) Comparison/Logical operators are used for testing and magnitude.
a)True b)False
Ans: a.
4) Character literals are stored as unicode characters.
a)True b)False
Ans: a.

5) What are the Logical operators?
Ans: OR(|), AND(&), XOR(^) AND NOT(~).
6) What is the % operator?
Ans : % operator is the modulo operator or reminder operator. It returns the reminder of dividing the first operand by second operand.
7) What is the value of 111 % 13?
a. 3
b. 5
c. 7
d. 9
Ans : c.
8) Is &&= a valid operator? Ans : No.
9) Can a double value be cast to a byte?
Ans : Yes
10) Can a byte object be cast to a double value ?
Ans : No. An object cannot be cast to a primitive value.
11) What are order of precedence and associativity?
Ans : Order of precedence the order in which operators are evaluated in expressions.
Associativity determines whether an expression is evaluated left-right or right-left.
12) Which Java operator is right associativity?
Ans : = operator.
13) What is the difference between prefix and postfix of -- and ++ operators?
Ans : The prefix form returns the increment or decrement operation and returns the value of the increment or decrement operation.
The postfix form returns the current value of all of the expression and then
performs the increment or decrement operation on that value.
14) What is the result of expression 5.45 + "3,2"?
a. The double value 8.6
b. The string ""8.6"
c. The long value 8.
d. The String "5.453.2"
Ans : d
15) What are the values of x and y ?
x = 5; y = ++x;
Ans : x = 6; y = 6
16) What are the values of x and z?
x = 5; z = x++;
Ans : x = 6; z = 5

Data types,variables and Arrays

1) What is meant by variable?
Ans: Variables are locations in memory that can hold values. Before assigning any value to a variable, it must be declared.
2) What are the kinds of variables in Java? What are their uses?
Ans: Java has three kinds of variables namely, the instance variable, the local variable and the class variable.
Local variables are used inside blocks as counters or in methods as temporary variables and are used to store information needed by a single method.
Instance variables are used to define attributes or the state of a particular object and are used to store information needed by multiple methods in the objects.
Class variables are global to a class and to all the instances of the class and are useful for communicating between different objects of all the same class or keeping track of global states.
3) How are the variables declared?
Ans: Variables can be declared anywhere in the method definition and can be initialized during their declaration.They are commonly declared before usage at the beginning of the definition.
Variables with the same data type can be declared together. Local variables must be given a value before usage.
4) What are variable types?
Ans: Variable types can be any data type that java supports, which includes the eight primitive data types, the name of a class or interface and an array.
5) How do you assign values to variables?
Ans: Values are assigned to variables using the assignment operator =.
6) What is a literal? How many types of literals are there?
Ans: A literal represents a value of a certain type where the type describes how that value behaves.
There are different types of literals namely number literals, character literals,
boolean literals, string literals,etc.
7) What is an array?
Ans: An array is an object that stores a list of items.
8) How do you declare an array?
Ans: Array variable indicates the type of object that the array holds. Ex: int arr[];
9) Java supports multidimensional arrays.
a)True b)False
Ans: a.
10) An array of arrays can be created.
a)True b)False
Ans: a.
11) What is a string?
Ans: A combination of characters is called as string.
12) Strings are instances of the class String.
a)True b)False
Ans: a.
13) When a string literal is used in the program, Java automatically creates instances of the string class.
a)True b)False
Ans: a.
14) Which operator is to create and concatenate string?
Ans: Addition operator(+).
15) Which of the following declare an array of string objects?
a. String[ ] s;
b. String [ ]s:
c. String[ s]:
d. String s[ ]:
Ans : a, b and d
16) What is the value of a[3] as the result of the following array declaration?
a. 1
b. 2
c. 3
d. 4
Ans : d
17) Which of the following are primitive types?
a. byte
b. String
c. integer
d. Float
Ans : a.
18) What is the range of the char type?
a. 0 to 216
b. 0 to 215
c. 0 to 216-1
d. 0 to 215-1
Ans. D

19) What are primitive data types?
Ans : byte, short, int, long
float, double
boolean
char
20) What are default values of different primitive types?
Ans : int - 0
short - 0
byte - 0
long - 0 l
float - 0.0 f
double - 0.0 d
boolean - false
char - null
21) Converting of primitive types to objects can be explicitly.
a)True
b)False
Ans: b.
22) How do we change the values of the elements of the array?
Ans : The array subscript expression can be used to change the values of the elements of the array.
23) What is final varaible?
Ans : If a variable is declared as final variable, then you can not change its value. It becomes constant.
24) What is static variable?
Ans : Static variables are shared by all instances of a class.

Introduction to Java Programming

1) The Java interpreter is used for the execution of the source code.
a) True b) False
Ans: a.
2) On successful compilation a file with the class extension is created.
a) True b) False
Ans: a.
3) The Java source code can be created in a Notepad editor.
a) True b) False
Ans: a.
4) The Java Program is enclosed in a class definition.
a) True b) False
Ans: a.
5) What declarations are required for every Java application?
Ans: A class and the main( ) method declarations.
6) What are the two parts in executing a Java program and their purposes?
Ans: Two parts in executing a Java program are:
Java Compiler and Java Interpreter.
The Java Compiler is used for compilation and the Java Interpreter is used for execution of the application.
7) What are the three OOPs principles and define them?
Ans : Encapsulation, Inheritance and Polymorphism are the three OOPs
Principles.
Encapsulation:
Is the Mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse.
Inheritance:
Is the process by which one object acquires the properties of another object.
Polymorphism:
Is a feature that allows one interface to be used for a general class of actions.
8) What is a compilation unit?
Ans : Java source code file.
9) What output is displayed as the result of executing the following statement?
System.out.println("// Looks like a comment.");
a. // Looks like a comment
b. The statement results in a compilation error
c. Looks like a comment
d. No output is displayed
Ans : a.
10) In order for a source code file, containing the public class Test, to successfully compile, which of the following must be true?
a. It must have a package statement
b. It must be named Test.java
c. It must import java.lang
d. It must declare a public class named Test
Ans : b
11) What are identifiers and what is naming convention?
Ans : Identifiers are used for class names, method names and variable names. An identifier may be any descriptive sequence of upper case & lower case letters,numbers or underscore or dollar sign and must not begin with numbers.
12) What is the return type of program’s main( ) method?
Ans : void
13) What is the argument type of program’s main( ) method?
Ans : string array.
14) Which characters are as first characters of an identifier?
Ans : A – Z, a – z, _ ,$
15) What are different comments?
Ans : 1) // -- single line comment
2) /* --
*/ multiple line comment
3) /** --
*/ documentation
16) What is the difference between constructor method and method?
Ans : Constructor will be automatically invoked when an object is created. Whereas method has to be call explicitly.
17) What is the use of bin and lib in JDK?
Ans : Bin contains all tools such as javac, applet viewer, awt tool etc., whereas Lib
contains all packages and variables.

Java Language Questions

1. What is a platform?
A platform is the hardware or software environment in which a program runs. Most platforms can be described as a combination of the operating system and hardware, like Windows 2000/XP, Linux, Solaris, and MacOS.
________________________________________
2. What is the main difference between Java platform and other platforms?
The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms.
The Java platform has two components:
1. The Java Virtual Machine (Java VM)
2. The Java Application Programming Interface (Java API)
________________________________________
3. What is the Java Virtual Machine?
The Java Virtual Machine is a software that can be ported onto various hardware-based platforms.
________________________________________
4. What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
________________________________________
5. What is the package?
The package is a Java namespace or part of Java libraries. The Java API is grouped into libraries of related classes and interfaces; these libraries are known as packages.
________________________________________
6. What is native code?
The native code is code that after you compile it, the compiled code runs on a specific hardware platform.
________________________________________
7. Is Java code slower than native code?
Not really. As a platform-independent environment, the Java platform can be a bit slower than native code. However, smart compilers, well-tuned interpreters, and just-in-time bytecode compilers can bring performance close to that of native code without threatening portability.
________________________________________
8. Can main() method be overloaded?
Yes. the main() method is a special method for a program entry. You can overload main() method in any ways. But if you change the signature of the main method, the entry point for the program will be gone. For example:
//the following are legal methods for entry point
public static void main(String[] args) {} // standard
static public void main(String[] args) {} // unconventional
private static void main(String[] args) {} // unconventional

//the following are legal overloaded methods
public static int main(String arg) {}
public void main(String str1, string str2) {}
public String main(String arg, int i) {}
....
For a good practice, don't overload main method or use a similar main method in a class which is not served as an entry point for your program.
________________________________________
9. What is the serialization?
The serialization is a kind of mechanism that makes a class or a bean persistence by having its properties or fields and state information saved and restored to and from storage.
________________________________________
10. How to make a class or a bean serializable?
By implementing either the java.io.Serializable interface, or the java.io.Externalizable interface. As long as one class in a class's inheritance hierarchy implements Serializable or Externalizable, that class is serializable.
________________________________________
11. How many methods in the Serializable interface?
There is no method in the Serializable interface. The Serializable interface acts as a marker, telling the object serialization tools that your class is serializable.
________________________________________
12. How many methods in the Externalizable interface?
There are two methods in the Externalizable interface. You have to implement these two methods in order to make your class externalizable. These two methods are readExternal() and writeExternal().
________________________________________
13. What is the difference between Serializalble and Externalizable interface?
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process.
________________________________________
14. What is a transient variable?
A transient variable is a variable that may not be serialized. If you don't want some field to be serialized, you can mark that field transient or static.
________________________________________
15. Which containers use a border layout as their default layout?
The Window, Frame and Dialog classes use a border layout as their default layout.
________________________________________
16. How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
________________________________________
17. What is synchronization and why is it important?
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often causes dirty data and leads to significant errors.
________________________________________
18. What are synchronized methods and synchronized statements?
Synchronized methods are methods that are used to control access to a method or 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. For example:
//a typical synchronized method

public synchronized void deposit(Amount amt) {
....

}

// a typical synchronized statement

synchronized ( objReference ) {

.....
}

________________________________________
19. 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.
________________________________________
20. Can a lock be acquired on a class?
Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.
________________________________________
21. What's new with the stop(), suspend() and resume() methods in JDK 1.2?
The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.
________________________________________
22. What is the preferred size of a component?
The preferred size of a component is the minimum component size that will allow the component to display normally.
________________________________________
23. What method is used to specify a container's layout?
The setLayout() method is used to specify a container's layout.
________________________________________
24. Which containers use a FlowLayout as their default layout?
The Panel and Applet classes use the FlowLayout as their default layout.
________________________________________
25. What is thread?
A thread is an independent path of execution in a system.
________________________________________
26. What is multithreading?
Multithreading means various threads that run in a system.
________________________________________
27. 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.
________________________________________
28. How to create multithread in a program?
You have two ways to do so. First, making your class "extends" Thread class. Second, making your class "implements" Runnable interface. Put jobs in a run() method and call start() method to start the thread.
________________________________________
29. Can Java object be locked down for exclusive use by a given thread?
Yes. You can lock an object by putting it in a "synchronized" block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.
________________________________________
30. Can each Java object keep track of all the threads that want to exclusively access to it?
Yes.
________________________________________
31. What state does a thread enter when it terminates its processing?
When a thread terminates its processing, it enters the dead state.
________________________________________
32. What invokes a thread's run() method?
After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
________________________________________
33. 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 communicate each other.
________________________________________
34. What are the high-level thread states?
The high-level thread states are ready, running, waiting, and dead.
________________________________________
35. What is the Collections API?
The Collections API is a set of classes and interfaces that support operations on collections of objects.
________________________________________
36. What is the List interface?
The List interface provides support for ordered collections of objects.
________________________________________
37. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
________________________________________
38. What is the Vector class?
The Vector class provides the capability to implement a growable array of objects
________________________________________
39. What modifiers may be used with an inner class that is a member of an outer class?
A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
________________________________________
40. 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.
________________________________________
41. What is an Iterator interface?
The Iterator interface is used to step through the elements of a Collection.
________________________________________
42. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
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.
________________________________________
43. What 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.
________________________________________
44. Is sizeof a keyword?
The sizeof operator is not a keyword in Java.
________________________________________
45. What are wrapped classes?
Wrapped classes are classes that allow primitive types to be accessed as objects.
________________________________________
46. Does garbage collection guarantee that a program will not run out of memory?
No, it doesn't. 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
________________________________________
47. 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 then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
________________________________________
48. Name Component subclasses that support painting.
The Canvas, Frame, Panel, and Applet classes support painting.
________________________________________
49. What is a native method?
A native method is a method that is implemented in a language other than Java.
________________________________________
50. How can you write a loop indefinitely?
o for(;;)--for loop;
o while(true)--always true, etc.
________________________________________
51. 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.
________________________________________
52. 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.
________________________________________
53. Which class is the superclass for every class.
Object
________________________________________
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.
Operator & has no chance to skip both sides evaluation and && operator does. If asked why, give details as above.
________________________________________
55. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
________________________________________
56. What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
________________________________________
57. Which Container method is used to cause a container to be laid out and redisplayed?
validate()
________________________________________
58. What is the Properties class?
The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used.
________________________________________
59. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.
________________________________________
60. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.
________________________________________
61. 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.
________________________________________
62. 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.
________________________________________
63. 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.
________________________________________
64. What is an abstract method?
An abstract method is a method whose implementation is deferred to a subclass. Or, a method that has no implementation (an interface of a method).
________________________________________
65. What is a static method?
A static method is a method that belongs to the class rather than any object of the class and doesn't apply to an object or even require that any objects of the class have been instantiated.
________________________________________
66. What is a protected method?
A protected method is a method that can be accessed by any method in its package and inherited by any subclass of its class.
________________________________________
67. 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.
________________________________________
68. 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.
________________________________________
69. 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.
________________________________________
70. 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.
________________________________________
71. What do heavy weight components mean?
Heavy weight components like Abstract Window Toolkit (AWT), depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavy weight.
________________________________________
72. Which package has light weight components?
javax.Swing package. All components in Swing, except JApplet, JDialog, JFrame and JWindow are lightweight components.
________________________________________
73. What are peerless components?
The peerless components are called light weight components.
________________________________________
74. 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.
________________________________________
75. 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.
________________________________________
76. 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.
________________________________________
77. 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.
________________________________________
78. What is the difference between throw and throws keywords?
The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as argument. The exception will be caught by an immediately encompassing try-catch construction or propagated further up the calling hierarchy.
The throws keyword is a modifier of a method that designates that exceptions may come out of the mehtod, either by virtue of the method throwing the exception itself or because it fails to catch such exceptions that a method it calls may throw.
________________________________________
79. 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 or friendly access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package.
________________________________________
80. What is the Map interface?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.
________________________________________
81. Does a class inherit the constructors of its superclass?
A class does not inherit constructors from any of its superclasses.
________________________________________
82. Name primitive Java types.
The primitive types are byte, char, short, int, long, float, double, and boolean.
________________________________________
83. 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.
________________________________________
84. 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.
________________________________________
85. 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.
________________________________________
86. 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 accommodate platform-specific differences among windowing systems.
________________________________________
87. 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.
________________________________________
88. 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.
________________________________________
89. 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.
________________________________________
90. 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.
________________________________________
91. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.
________________________________________
92. 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.
________________________________________
93. 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.
________________________________________
94. Name Container classes.
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane
________________________________________
95. What class allows you to read objects directly from a stream?
The ObjectInputStream class supports the reading of objects from input streams.
________________________________________
96. 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.
________________________________________
97. 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.
________________________________________
98. 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.
________________________________________
99. 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.
________________________________________
100. What is the List interface?
The List interface provides support for ordered collections of objects.
________________________________________
101. 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.
________________________________________
102. 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.
________________________________________
103. 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.
________________________________________
104. 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.
________________________________________
105. 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.
________________________________________
106. 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.
________________________________________
107. 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.
________________________________________
108. What is Serialization and deserialization?
Serialization is the process of writing the state of an object to a byte stream.
Deserialization is the process of restoring these objects.
________________________________________
109. what is tunnelling?
Tunnelling is a route to somewhere. For example, RMI tunnelling is a way to make RMI application get through firewall. In CS world, tunnelling means a way to transfer data.
________________________________________
110. Does the code in finally block get executed if there is an exception and a return statement in a catch block?
If an exception occurs and there is a return statement in catch block, the finally block is still executed. The finally block will not be executed when the System.exit(1) statement is executed earlier or the system shut down earlier or the memory is used up earlier before the thread goes to finally block.
________________________________________
111. How you restrict a user to cut and paste from the html page?
Using javaScript to lock keyboard keys. It is one of solutions.
________________________________________
112. Is Java a super set of JavaScript?
No. They are completely different. Some syntax may be similar.
________________________________________
113. What is a Container in a GUI?
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.
________________________________________
114. How the object oriented approach helps us keep complexity of software development under control?
We can discuss such issue from the following aspects:
o Objects allow procedures to be encapsulated with their data to reduce potential interference.
o Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places.
o The well-defined separations of interface and implementation allow constraints to be imposed on inheriting classes while still allowing the flexibility of overriding and overloading.
________________________________________
115. What is polymorphism?
Polymorphism means "having many forms". It allows methods (may be variables) to be written that needn't be concerned about the specifics of the objects they will be applied to. That is, the method can be specified at a higher level of abstraction and can be counted on to work even on objects of un-conceived classes.
________________________________________
116. What is design by contract?
The design by contract specifies the obligations of a method to any other methods that may use its services and also theirs to it. For example, the preconditions specify what the method required to be true when the method is called. Hence making sure that preconditions are. Similarly, postconditions specify what must be true when the method is finished, thus the called method has the responsibility of satisfying the post conditions.
In Java, the exception handling facilities support the use of design by contract, especially in the case of checked exceptions. The assert keyword can be used to make such contracts.
________________________________________
117. What are use cases?
A use case describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance. It is part of the analysis of a program. The collection of use cases should, ideally, anticipate all the standard circumstances and many of the extraordinary circumstances possible so that the program will be robust.
________________________________________
118. What is the difference between interface and abstract class?
o interface contains methods that must be abstract; abstract class may contain concrete methods.
o interface contains variables that must be static and final; abstract class may contain non-final and final variables.
o members in an interface are public by default, abstract class may contain non-public members.
o interface is used to "implements"; whereas abstract class is used to "extends".
o interface can be used to achieve multiple inheritance; abstract class can be used as a single inheritance.
o interface can "extends" another interface, abstract class can "extends" another class and "implements" multiple interfaces.
o interface is absolutely abstract; abstract class can be invoked if a main() exists.
o interface is more flexible than abstract class because one class can only "extends" one super class, but "implements" multiple interfaces.
o If given a choice, use interface instead of abstract class.
________________________________________
119. What is scalability and performance?
Performance is a measure of "how fast can you perform this task." and scalability describes how an application behaves as its workload and available computing resources increase.
________________________________________
120. What is the benefit of subclass?
Generally:
o The sub class inherits all the public methods and the implementation.
o The sub class inherits all the protected methods and their implementation.
o The sub class inherits all the default(non-access modifier) methods and their implementation.
o The sub class also inherits all the public, protected and default member variables from the super class.
o The constructors are not part of this inheritance model.
________________________________________
121. How to add menushortcut to menu item? (donated in April 2005)
If you have a button instance called aboutButton, you may add menu short cut by calling aboutButton.setMnemonic('A'), so the user may be able to use Alt+A to click the button.
________________________________________
122. Where and how can you use a private constuctor.
Private constructor can be used if you do not want any other class to instanstiate it by using new. The instantiation is done from a static public method, which is used when dealing with the factory method pattern.
________________________________________
123. In System.out.println(),what is System,out and println,pls explain?
System is a predefined final class,out is a PrintStream object acting as a field member and println is a built-in overloaded method in the out object.
________________________________________
124. What is meant by "Abstract Interface"?
First, an interface is abstract. That means you cannot have any implementation in an interface. All the methods declared in an interface are abstract methods or signatures of the methods.
________________________________________
125. Can you make an instance of an abstract class? For example - java.util.Calender is an abstract class with a method getInstance() which returns an instance of the Calender class.
No! You cannot make an instance of an abstract class. An abstract class has to be sub-classed. If you have an abstract class and you want to use a method which has been implemented, you may need to subclass that abstract class, instantiate your subclass and then call that method.
________________________________________
126. What is the output of x
When this kind of question has been asked, find the problems you think is necessary to ask back before you give an answer. Ask if variables a and b have been declared or initialized. If the answer is yes. You can say that the syntax is wrong. If the statement is rewritten as: x< y statement return true and variable a is returned.
________________________________________
127. What is the difference between Swing and AWT components?
AWT components are heavy-weight, whereas Swing components are lightweight. Heavy weight components depend on the local windowing toolkit. For example, java.awt.Button is a heavy weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.
________________________________________
128. Why Java does not support pointers?
Because pointers are unsafe. Java uses reference types to hide pointers and programmers feel easier to deal with reference types without pointers. This is why Java and C# shine.
________________________________________
129. Parsers? DOM vs SAX parser
Parsers are fundamental xml components, a bridge between XML documents and applications that process that XML. The parser is responsible for handling xml syntax, checking the contents of the document against constraints established in a DTD or Schema.
DOM SAX
1. Tree of nodes 1. Sequence of events
2. Memory: Occupies more memory, preffered for small XML documents 2. Doesn't use any memory preferred for large documents
3. Slower at runtime 3. Faster at runtime
4. Stored as objects 4. Objects are to be created
5. Programmatically easy, since objects 5. Need to write code for creating objects are to reffered
6. Ease of navigation 6. Backward navigation is not possible as it sequentially processes the document
________________________________________
130. How many methods in Object class?
This question is not asked to test your memory. It tests you how well you know Java. Ten in total.
o clone()
o equals() & hashcode()
o getClass()
o finalize()
o wait() & notify()
o toString()