Language Translator

Showing posts with label Qusetions AND Answers. Show all posts
Showing posts with label Qusetions AND Answers. Show all posts

Servlet Request & Response Behaviour

A request from a browser or other client consists
of an HTTP command (usually GET or POST), zero or more request headers (one or
more in HTTP 1.1, since Host is required), a blank line, and, only in the case of
POST requests, some query data. A typical request looks like the following.
GET /servlet/SomeName HTTP/1.1
Host: ...
Header2: ...
...
HeaderN:

When a Web server responds to a request, the response typically consists of a status
line, some response headers, a blank line, and the document. A typical response
looks like this:
HTTP/1.1 200 OK
Content-Type: text/html
Header2: ...
...
HeaderN: ...



...

...


The status line consists of the HTTP version (HTTP/1.1 in the preceding example),
a status code (an integer; 200 in the example), and a very short message corresponding
to the status code (OK in the example). In most cases, the headers are
optional except for Content-Type, which specifies the MIME type of the document
that follows. Although most responses contain a document, some don’t. For
example, responses to HEAD requests should never include a document, and various
status codes essentially indicate failure or redirection (and thus either don’t include a
document or include only a short error-message document).

Servlets can perform a variety of important tasks by manipulating the status line
and the response headers. For example, they can forward the user to other sites; indicate
that the attached document is an image, Adobe Acrobat file, or HTML file; tell
the user that a password is required to access the document; and so forth. This chapter
summarizes the most important status codes and describes what can be accomplished
with them; the following chapter discusses the response headers.


Specifying Status Codes

As just described, the HTTP response status line consists of an HTTP version, a status
code, and an associated message. Since the message is directly associated with the status
code and the HTTP version is determined by the server, all a servlet needs to do is
to set the status code. A code of 200 is set automatically, so servlets don’t usually need
to specify a status code at all. When they do want to, they use response.setStatus,
response.sendRedirect, or response.sendError.


Setting Arbitrary Status Codes: setStatus

When you want to set an arbitrary status code, do so with the setStatus method of
HttpServletResponse. If your response includes a special status code and a document,
be sure to call setStatus before actually returning any of the content with
the PrintWriter. The reason is that an HTTP response consists of the status line,
one or more headers, a blank line, and the actual document, in that order. Servlets do
not necessarily buffer the document, so you have to either set the status code before
using the PrintWriter or carefully check that the buffer hasn’t been flushed and
content actually sent to the browser

The setStatus method takes an int (the status code) as an argument, but
instead of using explicit numbers, for readability and to avoid typos, use the constants
defined in HttpServletResponse. The name of each constant is derived
from the standard HTTP 1.1 message for each constant, all upper case with a prefix
of SC (for Status Code) and spaces changed to underscores. Thus, since the message
for 404 is Not Found, the equivalent constant in HttpServletResponse is
SC_NOT_FOUND. There is one minor exception, however: the constant for code 302
is derived from the message defined by HTTP 1.0 (Moved Temporarily), not the
HTTP 1.1 message (Found).

Setting 302 and 404 Status Codes:
sendRedirect and sendError

Although the general method of setting status codes is simply to call
response.setStatus(int), there are two common cases for which a shortcut
method in HttpServletResponse is provided. Just be aware that both of these
methods throw IOException, whereas setStatus does not. Since the doGet and
doPost methods already throw IOException, this difference only matters if you
pass the response object to another method.

public void sendRedirect(String url)
The 302 status code directs the browser to connect to a new location.
The sendRedirect method generates a 302 response along with a
Location header giving the URL of the new document. Either an
absolute or a relative URL is permitted; the system automatically
translates relative URLs into absolute ones before putting them in the
Location header.

public void sendError(int code, String message)
The 404 status code is used when no document is found on the server.
The sendError method sends a status code (usually 404) along with
a short message that is automatically formatted inside an HTML
document and sent to the client.
Setting a status code does not necessarily mean that you omit the document. For
example, although most servers automatically generate a small File Not Found message
for 404 responses, a servlet might want to customize this response. Again,
remember that if you do send output, you have to call setStatus or sendError
first.

HTTP 1.1 Status Codes

In this section we describe the most important status codes available for use in servlets
talking to HTTP 1.1 clients, along with the standard message associated with
each code. A good understanding of these codes can dramatically increase the capabilities
of your servlets, so you should at least skim the descriptions to see what
options are at your disposal. You can come back for details when you are ready to use
the capabilities.

The complete HTTP 1.1 specification is given in RFC 2616. In general, you can
access RFCs online by going to http://www.rfc-editor.org/ and following the links to
the latest RFC archive sites, but since this one came from the World Wide Web Consortium,
you can just go to http://www.w3.org/Protocols/. Codes that are new in
HTTP 1.1 are noted since some browsers support only HTTP 1.0. You should only
send the new codes to clients that support HTTP 1.1, as verified by checking
request.getRequestProtocol.

The rest of this section describes the specific status codes available in HTTP 1.1.
These codes fall into five general categories:
• 100–199
Codes in the 100s are informational, indicating that the client should
respond with some other action.
• 200–299
Values in the 200s signify that the request was successful.
• 300–399
Values in the 300s are used for files that have moved and usually
include a Location header indicating the new address.
• 400–499
Values in the 400s indicate an error by the client.
• 500–599
Codes in the 500s signify an error by the server.

The constants in HttpServletResponse that represent the various codes
are derived from the standard messages associated with the codes. In servlets, you
usually refer to status codes only by means of these constants. For example, you
would use response.setStatus(response.SC_NO_CONTENT) rather than
response.setStatus(204), since the latter is unclear to readers and is prone to
typographical errors. However, you should note that servers are allowed to vary the
messages slightly, and clients pay attention only to the numeric value. So, for example,
you might see a server return a status line of HTTP/1.1 200 Document
Follows instead of HTTP/1.1 200 OK.

100 (Continue)
If the server receives an Expect request header with a value of
100-continue, it means that the client is asking if it can send an attached
document in a follow-up request. In such a case, the server should either
respond with status 100 (SC_CONTINUE) to tell the client to go ahead or use
417 (SC_EXPECTATION_FAILED) to tell the browser it won’t accept the document.
This status code is new in HTTP 1.1.
200 (OK)
A value of 200 (SC_OK) means that everything is fine; the document follows for
GET and POST requests. This status is the default for servlets; if you don’t use
setStatus, you’ll get 200.
202 (Accepted)
A value of 202 (SC_ACCEPTED) tells the client that the request is being acted
upon but processing is not yet complete.
204 (No Content)
A status code of 204 (SC_NO_CONTENT) stipulates that the browser should
continue to display the previous document because no new document is available.
This behavior is useful if the user periodically reloads a page by pressing
the Reload button and you can determine that the previous page is already
up-to-date.
205 (Reset Content)
A value of 205 (SC_RESET_CONTENT) means that there is no new document
but the browser should reset the document view. Thus, this status code is used
to instruct browsers to clear form fields. It is new in HTTP 1.1.
301 (Moved Permanently)
The 301 (SC_MOVED_PERMANENTLY) status indicates that the requested document
is elsewhere; the new URL for the document is given in the Location
response header. Browsers should automatically follow the link to the new
URL.
302 (Found)
This value is similar to 301, except that in principle the URL given by the
Location header should be interpreted as a temporary replacement, not a
permanent one. In practice, most browsers treat 301 and 302 identically. Note:
in HTTP 1.0, the message was Moved Temporarily instead of Found, and
the constant in HttpServletResponse is SC_MOVED_TEMPORARILY, not
the expected SC_FOUND.

JDBC DESCRIPTION

Q. JDBC stands for _______

Ans. Java Database Connectivity.

Q. What is JDBC API?

Ans. JDBC API is a collection of classes and interfaces, which help a Java application to connect to SQL based relational databases by abstracting vendor specific details of the database.

Q. The JDBC classes and interfaces are found in the packages _________ and
________

Ans. java.sql and javax.sql

Q. The latest version of JDBC is __________

Ans. JDBC 3.0

Q. What is a JDBC Driver?

Ans. A JDBC Driver is a middleware that translates the JDBC API calls to database vendor specific API calls. It is an implementation of the classes and interfaces specified in the java.sql and javax.sql packages by the database vendors or third-party vendors.

Q. How does JDBC provide database abstraction to a Java application developer?

Ans. Since the JDBC drivers follow the JDBC specification, the JDBC application developers can replace one driver for their application with another better one without having to rewrite their application. If they had used some proprietary API provided by some RDBMS vendor, they would not have been able to change the driver and/or database without having to rewrite the complete application.

Q. Who develops JDBC Specification?

Ans. SUN Microsystems prepares and maintains the JDBC specification. Since JDBC is just a specification (suggestions for writing and using JDBC drivers), third-party vendors develop JDBC drivers adhering to this specification. JDBC developers then use these drivers to access data sources.

Q. There are _____ types of JDBC drivers.

Ans. 4

Q. What are the four types of JDBC drivers?

Ans. There are four types of JDBC drivers. Here is a brief description of each of them:

1. JDBC Type 1 Driver (JDBC-ODBC Bridge)

The JDBC-ODBC Bridge translates the standard JDBC API calls to corresponding ODBC calls. This configuration requires the client application to have the JDBC-ODBC API implementation (SUN provides the JDBC-ODBC Driver), the ODBC Driver, and the database vendor specific native APIs such as the OCI library for Oracle installed on each client machine. Since each data access call has to go through many layers, this approach is the slowest and the most inefficient for high performance database access requirements. The use of JDBC-ODBC should be considered for experimental purposes only or when no other driver is available (this is because the Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself). However this approach has to be used in some situations for example, a Microsoft Access 2000 database can only be accessed using the JDBC-ODBC Bridge.

2. JDBC Type 2 Driver (Part Java, Part Native Driver)

These type of drivers use a mixture of JDBC API implementation and database vendor specific native APIs for data access. When a database call is made, the JDBC driver translates the request into database vendor specific API call. In this approach, the JDBC Driver along with the database vendor specific native APIs such as the OCI library for Oracle should be installed on each client machine. It doesn't require the presence of ODBC. Type 2 drivers are faster than Type 1 drivers because of the absence of ODBC.

3. JDBC Type 3 Driver (Intermediate Database Access Server)

Type 3 drivers use an intermediate database server (middleware) that has the ability to connect multiple Java clients to multiple databases. The Java client application sends a database call through the JDBC Driver which forwards it to the Intermediate Database Access Server. The intermediate server can use different native protocols to connect to different databases.
One of the benefits of using a Type 3 driver is that it allows the Java application to be flexible, as the Intermediate Database Server can abstract the details of connection to various databases.

4. JDBC Type 4 Driver (Pure Java Driver)

Type 4 Drivers are a pure Java alternative to Type 2 Drivers. When a database call is made, Type 4 drivers connect to the database directly, using database vendor specific network protocols. They do so by making direct socket connections with the database. Type 4 drivers are the simplest to deploy since there are no additional libraries or middleware to install. They are also the most efficient and most widely used JDBC drivers in industry. All major database vendors provide Type 4 JDBC Drivers for their databases and they are also available from third party driver vendors.

Q. Classify the following as a class or an interface:
a) java.sql.Drivermanager
b) java.sql.Connection
c) java.sql.Statement
d) java.sql.ResultSet
e) java.sql.DatabaseMetaData
f) java.sql.ResultSetMetaData
g) java.sql.PreparedStatement
h) java.sql.CallableStatement
i) java.sql.Driver

Ans. a) java.sql.DriverManager is a class.
b) java.sql.Connection is an interface.
c) java.sql.Statement is an interface.
d) java.sql.ResultSet is an interface.
e) java.sql.DatabaseMetaData is an interface.
f) java.sql.ResultSetMetaData is an interface.
g) java.sql.PreparedStatement is an interface which extends the java.sql.Statement interface.
h) java.sql.CallableStatement is an interface which extends the java.sql.Statement interface.
i) Java.sql.Driver is an interface.

Q. The Exception subclass which handles JDBC related exceptions is _________

Ans. java.sql.SQLException







Q. Which interfaces in the java.sql package are implemented by the database vendors/third party driver vendors?

Ans. a) java.sql.Driver
b) java.sql.Connection
c) java.sql.Statement
d) java.sql.PreparedStatement
e) java.sql.CallableStatement

Q. Can we establish more than one connection with a database using a single driver?

Ans. Yes, we can establish more than one connection with a database using a single driver.

Q. What is a URL in JDBC? Why is it used?

Ans. A URL is a method of uniquely identifying a database driver. In a scenario where more than one driver is used for connecting to one or databases, there has to be some way for uniquely identifying each driver.

Q. Each driver needed by a Java application must first be registered with the _________

Ans. java.sql.DriverManager class

Q. What are the two different ways to load a JDBC driver?

Ans. A JDBC driver can be loaded by using any of the following two ways:

a) By using Class.forName() method as:

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

b) By using DriverManager class as:

DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());

Q. What are the basic operations that can be performed on any database? How do we handle such operations in JDBC?

Ans. The basic operations that can be performed on any database are:


a) Create a table.
b) Insert a row in the table.
c) Retrieve row(s) from the table.
d) Modify row(s) in the table.
e) Delete row(s) from the table.

Using JDBC, we can perform the aforesaid operations in the following way:

a) Create a table
……
stmt.executeUpdate(“create table Employee (EMPNO (varchar(6), NAME(char(40)”);
……

b) Insert a row into the table
……
stmt.executeUpdate(“insert into Employee values(‘E0001’,’XYZ’”);
……

c) Retrieve row(s) from the table
……
//select ALL the rows from the table.
ResultSet rst=stmt.executeQuery(“select * from Employee”);
while(rst.next())
{
System.out.println(rst.getString(“EMPNO”));
System.out.println(rst.getString(“NAME”));
}
……
//select PARTICULAR rows from the table.
ResultSet rst=stmt.executeQuery(“select * from Employee where
EMPNO=’E0001’”);
while(rst.next())
{
System.out.println(rst.getString(“EMPNO”));
System.out.println(rst.getString(“NAME”));
}

d) Modify row(s) in the table
……
int numUpdated=stmt.executeUpdate(“update Employee set NAME=’ABC’ where EMPNO=’E0001’”);
……

e) Delete row(s) from the table
……
int updated=stmt.executeUpdate(“delete from Employee where EMPNO=’E0001’”);
……
Q. What is the utility of prepared statements?

Ans. Databases are tuned to do statement caches. This cache uses the statement itself as a key and the access plan is stored in the cache with the corresponding statement. This allows the database engine to reuse the plans for statements that have been executed previously. For example, if we sent the database a statement such as "select a, b from t where c = 2", then the computed access plan is cached. If we send the same statement later, the database can reuse the previous access plan, thus saving us CPU power.
Note however, that the entire statement is the key. For example, if we later sent the statement "select a, b from t where c = 3", it would not find an access plan. This is because the "c=3" is different from the cached plan "c=2". So, for example:

for(int i = 0; i < 1000; ++i)
{
PreparedStatement ps = conn.prepareStatement("select a, b
from t where c = " + I);
ResultSet rs = Ps.executeQuery();
rs.close();
ps.close();
}

Here the cache won't be used. Each iteration of the loop sends a different SQL statement to the database. A new access plan is computed for each iteration and we're basically throwing CPU cycles away using this approach. However, look at the next snippet:

PreparedStatement ps = conn.prepareStatement("select a, b from t
where c = ?");
for(int i = 0; i < 1000; ++i)
{
ps.setInt(1, I);
ResultSet rs = ps.executeQuery();
rs.close();
}
ps.close();

Here it will be much more efficient. The statement sent to the database is parameterized using the '?' marker in the SQL. This means every iteration is sending the same statement to the database with different parameters for the "c=?" part. This allows the database to reuse the access plans for the statement and makes the program execute more efficiently inside the database. This basically let's your application run faster or makes more CPU available to users of the database.

Q. What does the method executeUpdate() return?

Ans. It returns the number of rows successfully inserted, updated or deleted. When it is used in conjunction with a select query, it returns a 0 since no rows are updated.

Q. Should we use column names or column index in the getXXX() methods of ResultSet interface?

Ans. Since the column indexes are subject to change due to a change in the database schema, it is advisable to use column names in these methods.

Q. What does the ResultSet.next() method return?

Ans. It returns false when the last record is reached and true otherwise.

Q. How many types of ResultSet objects are provided by JDBC?

Ans. JDBC classifies ResultSet objects on the basis of two characteristics:

a) Scroll Sensitivity
b) Updateability

a) Scroll Sensitivity

A scroll-insensitive resultset represents a static snapshot of the results when the query was made. On the other hand, a scroll-sensitive resultset is sensitive to the changes made to the data after the query has been executed, thus providing a dynamic view of the data as it changes.
The ResultSet class has two static data members; TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE to denote scroll-insensitive and scroll-sensitive resultsets respectively.

c) Updateability

The contents of an updateable resultset can be changed whereas those of a non-updateable resultset cannot be changed. The ResultSet class has two static data members; CONCUR_READ_ONLY and CONCUR_UPDATABLE to denote non-updateable and updateable resultsets.


Q What is the sequence of steps followed by JDBC to communicate with a database?

Ans. JDBC follows the following sequence to talk to a database:

a) Create an instance of a JDBC driver.
b) Register the driver with the DriverManager class.
c) Open a database connection.
d) Submit a query.
e) Receive results.

JAVA EXCEPTIONS DESCRIPTION

Q. The two immediate subclasses of Throwable class are: __________ and _________.

Ans. Exception and Error.

Q. What is an exception?

Ans. An exception is basically a runtime error.

Q. How does an exception arise in a Java code? Illustrate with the help of an example.

Ans. Consider the following code snippet:

public class A
{
public static void main(String args[])
{
int k=4/0;
System.out.println(k);
}
}

The statement int k=4/0; generates an object of the class ArithmeticException via the statement;

ArithmeticException e=new ArithmeticException();

This object starts searching from the line where the exception arose, for a piece of code which can accept it and process accordingly. As a result, all subsequent lines of code are skipped from being executed.

Q. What are the cases in which the finally block is executed?

Ans. The finally block is always executed in the following cases:

1. When no exception arises.
2. When an exception arises and it is handled by one of the catch blocks.
3. When an exception arises and it is not handled by any of the catch blocks.

Q. Is it necessary to write a finally with a try-catch block?

Ans. No, it is not at all mandatory to write a finally block with a try-catch block. This is because a finally block contains code which should execute whether or not the exception arises. However this might not always be required.
Usually, a finally block is used to place code that will release resources acquired in a try block. This strategy is an effective way to avoid resource leaks.

Q. Can a try statement be used in isolation, i.e., without a catch or finally block?

Ans. No, a try statement cannot be used in isolation. It should be followed by either the catch block or the finally block.

Q. What is the output of the following code:

public class A
{
public static void main(String args[])
{
try
{
int num=4/0;
}
catch(Exception e)
{
System.out.println(“Inside Exception”);
}
catch(ArithmeticException e)
{
System.out.println(“Inside ArithmeticException”);
}
}
}

Ans. Output:
Error: exception java.lang.ArithmeticException has already been caught catch(ArithmeticException e)

Reason:
When multiple catch statements are used, it is important to remember that exception subclasses must come before any of their superclasses. This is because, a catch statement that uses a superclasses will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it comes after its superclass. In the above case, Exception is the superclass of all types of exceptions including ArithmeticException.




Q. What is the output of the following code?

public class A
{
public static void main(String args[])
{
try
{
try
{
int num=4/0;
}
catch(NullPointerException e)
{
System.out.println(“Inside NullPointerException”);
}
}
catch(ArithmeticException e)
{
System.out.println(“Inside ArithmeticException”);
}
}
}

Ans. Ouput: Inside ArithmeticException

Reason: In case of nested try-catch statements, if an inner try statement does not have a catch handler for a particular exception, the next try statement’s catch handlers are examined for a match. This continues until one of the catch statements succeeds or until the entire nested try statements are exhausted.

Q. Is it possible to create exceptions of our own?

Ans. Yes, it is possible to create user-defined exceptions. This can be done by extending the Exception class as:

public MyException extends Exception
{
………
………
}




Q. Is it possible that the finally block is not executed?

Ans. Yes, it is possible that the finally block is not executed. This is possible when there is an exception in the finally block itself.

Q. What is the use of throws keyword?

Ans. If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of that method can guard themselves against that exception. This is done by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw.

Q. What is the error in the following code:

void fun() throws NullPointerException, ArithmeticException

……….

public class A
{
public static void main(String args[])
{
try
{
fun();
}
catch(NullPointerException e)
{
}
}
}

Ans. For all the exceptions listed in the throws list of a method, a catch block should be written; otherwise the compiler would report an error. In the above example, the try block should be succeeded by two catch blocks for handling objects of the type NullPointerException and ArithmeticException.

Reason: The Java compiler forces the user to write catch blocks for each of the exceptions mentioned in the throws clause because it is not known till run-time that which exception out of the pre-specified list can be thrown by the method. Therefore, in order to make provision for every possible contingency, the compiler forces the programmer to write a catch block for all exceptions mentioned in the throws exception list.


Q. What is the error in the following code?

public class A
{
public static void main(String args[])
{
float f=2.5f;

switch(f)
{
case 5: System.out.println(“Hello”);
break;

case 2.5: System.out.println(“Bye”);
break;

default: System.out.println(“Not Found”);
}
}
}

Ans. The switch expression can take only the following types of values:
1. byte
2. short
3. int
4. char
It cannot take a float or any other type.

Q. What is a null statement in Java?

Ans. A statement that consists of only a semicolon is called a null statement.

Q. What is the output of the following code?

………
for(int i=0;i<4;i++)
System.out.println(“Hello”);

System.out.println(i);
……….

Ans. Output: cannot resolve the symbol: variable i
Reason: The scope of a variable inside a for-loop ends when the for block ends. Outside the for-block, the variable ceases to exist.



Q. What is the error in the following code?

public class A
{
public static void main(String args[])
{
int t=5, x=10, y=2;

switch(t)
{
case(10/2):
System.out.println(“Hello”);
break;

case(x/y): System.out.println(“Bye”);
break;

default: System.out.println(“Not Found”);
}
}
}

Ans. A case value must be a constant and not a variable. It can be an expression involving only constants which evaluates to a constant. An expression involving variables is not allowed.

Q. What is the error in the following code?

public class A
{
public static void main(String args[])
{
int t=9;

switch(t)
{
case(10-1):
System.out.println(“Hello”);
break;

case(3*3):
System.out.println(“Bye”);
break;

default: System.out.println(“Not Found”);
}
}
}

Ans. Duplicate case values are not allowed.

Q. What is the output of the following code?

public class A
{
public static void main(String args[])
{
int t=9;

switch(f)
{
case(10-1):
System.out.println(“Hello”);

case 3:
System.out.println(“Bye”);

case 4:
System.out.println(“Good Day”);
break;

default:
System.out.println(“Not Found”);
}
}
}

Ans. Output: Hello
Bye
Good Day

Reason: If there are no break statements after any case, it would result in the execution of all the case blocks starting from the first case value which matches with the switch expression.












Q. What is the use of the break statement?

Ans. The break statement causes the termination of a loop and the program control resumes at the next statement following the loop. For example,

for(……..)
{
for(……..)
{
for(……..)
{
if(……..)
break;
}
//Control resumes from here.
}
}

Q. What is the result when you compile and run the following code?

int i = 100;
switch (i)
{
case 100:
System.out.println(i);
case 200:
System.out.println(i);
case 300:
System.out.println(i);
}

[a] Nothing is printed
[b] Compile time error
[c] The values 100,100,100 printed
[d] Only 100 is printed

Ans. The values 100, 100, 100 are printed.








Q. How can you change the break statement below so that it breaks out of the inner and middle loops and continues with the next iteration of the outer loop?

outer:
for ( int x =0; x < 3; x++ ) {
middle: for ( int y=0; y < 3; y++ ) {
if ( y == 1)
break;
}
}
}

[a] break inner:
[b] break middle:
[c] break outer:
[d] continue
[e] continue middle

Ans. break middle;
Reason: When this form of break executes, the control is transferred out of the named block of code. The labeled block of code must enclose the break statement, but it does not need to be the immediately enclosing block. This means you can use a labeled break statement to exit from a set of nested blocks. But you cannot use break to transfer control to a block of code that does not enclose the break statement.

Q. Select all correct answers:
public class ExpTest {
public static void main ( String[] args ) {
try {
MyMethod();
} catch ( Exception e) {
}
}
static void MyMethod() {
try {
System.out.println("a");
} catch ( ArithmeticException ae) {
System.out.println("b");
} finally {
System.out.println("c");
}
System.out.println("d");
}
}

[a] a
[b] b
[c] c
[d] d

Ans. a
c
d

Q. What is the result of the following code when you compile and run?

public class ThrowDemo
{
static void demoMethod()
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println("Caught inside demoMethod.");
throw e; // re-throw the exception
}
}
public static void main(String args[])
{
try
{
demoMethod();
}
catch(NullPointerException e)
{
System.out.println("Recaught: " + e);
}
}
}

[a] Compilation error
[b] Runtime error
[c] Compile successfully, nothing is printed.
[d] Caught inside demoMethod. followed by Recaught: java.lang.NullPointerException: demo



Ans. Caught inside demoMethod. followed by Recaught: java.lang.NullPointerException: demo

Reason: NullPointerException is one of Java’s unchecked exceptions. Therefore, there is not need to mention it in the method’s throws list.

Q. Select the correct answer:

public class ThrowsDemo
{
static void throwMethod()
{
System.out.println("Inside throwMethod.");
throw new IllegalAccessException("demo");
}

public static void main(String args[])
{
try
{
throwMethod();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}
}

[a] Compilation error
[b] Runtime error
[c] Compile successfully, nothing is printed.
[d] inside demoMethod. followed by caught: java.lang.IllegalAccessException: demo

Ans. Compilation error.
Reason: IllegalAccessException is one of Java’s checked exceptions. Therefore, it has to be mentioned in the throws list of throwMethod().









Q. What is the output of the following program if you compile and run?
outer: for (int i = 0; i < 2; i++ ) {
for ( int j = 0; j < 3; j++ ) {
if ( i == j ) {
continue outer;
}
System.out.println("The value of i is: " + i );
System.out.println("The value of i is: " + j);
}
}
[a] The value of i is: 0
The value of j is: 0
[b] The value of i is: 0
The value of j is: 1
[c] The value of i is: 0
The value of j is: 2
[d] The value of i is: 1
The value of j is: 0
[e] The value of i is: 1
The value of j is: 1
[f] The value of i is: 1
The value of j is: 2
Ans. The value of i is: 1
The value of j is: 0
Reason: If you are using the continue statement in labeled form then the statement continues at the next iteration of the labeled loop.

Q. What is the result when you compile and run the following code?

int i = 100;
switch (i)
{
case 100:
System.out.println(i);
case 200:
System.out.println(i);
case 300:
System.out.println(i);
}

[a] Nothing is printed
[b] Compile time error
[c] The values 100,100,100 printed
[d] Only 100 is printed

Ans. The values 100, 100, 100 are printed.

Q. What is the base class for Error and Exception?

Ans. Throwable.

Q. Throwable class resides in the package _______ ?

Ans. java.lang

Q. What class of exceptions are generated by the Java run-time system?

Ans. The Java run-time system generates RuntimeException and Error exceptions.

Q. Can a no argument constructor throw exception?

Ans. Yes, see the following code:
public class A
{
public A() throws Exception
{
throw new Exception("No argu constructor can throw
exception too");
}

public static void main(String args[])
{
try
{
new A();
}
catch (Exception e)
{
System.out.println(e);
}
}
}






Q. I have two exceptions thrown in the same try block,
when the first exeption is thrown, the second exception is
ignored. Why?

Ans. When an exception is thrown, the code cannot continue
its normal path. Therefore, he code following the exception line will not
be executed no matter what.

Q. Checked exception must be caught or declared, how about
unchecked ones?

Ans. Checked exceptions must be caught or declared in the method throws
statement. Unchecked Exceptions do not require the same.
However, if you do, it does not cause an error either. Something must be specified does not imply Something else must not be specified.

Event Delegation Model

Q. Explain the Event Delegation Model.

Ans. The Event Delegation Model is Java’s way of handling user/process generated events. In this model, a source generates an event which is sent to one or more listeners registered with it. The listener then processes the event accordingly.



Q. What is an Event?

Ans. An event is an object that describes a state change in an event source.
For example, a button is an event source and pressing of the button is an event.

Q. What is an Event Source?

Ans. An event source is an object that generates an event. For example, a button is an event source.

Q. What is a Listener?

Ans. A listener is an object that is notified when an event occurs. There are two conditions to be fulfilled in order to become a valid listener;
1. The listener must be registered with at least one of the event sources.
2. It must implement methods that receive and process such events.



Q. The methods that receive and process events are defined in a set of interfaces in the _______ package.

Ans. java.awt.event

Q. Is it necessary to register a listener with an event source?

Ans. Yes, it is necessary to register a listener with an event source because an event notification is sent to only those listeners that are registered with the event source. All registered listeners receive a copy of the event object.

Q. How can a listener register itself with an event source?

Ans. The general form of the registration method is:

public void addTypeListener(new TypeListener())

Here, Type is the name of the event and new TypeListener() is an instance of the event listener object.

Some event sources may allow only one listener to be registered. The general form of such a registration method is:

public void addTypeListener(new TypeListener()) throws java.util.TooManyListenersException

Q. What is multicasting and unicasting?

Ans. When an event occurs, all the registered listeners are notified and sent a copy of the event object. This is known as multicasting.
If there is only one registered listener, then this process is called as unicasting.

Q. Name the event objects and their respective listener interfaces and Adapter Classes for the following events:
1. A button is pressed, a list item is double-clicked, or a menu item is selected.
2. A component is hidden, moved, resized or becomes visible.
3. A component is added to or removed from a container.
4. A check box is clicked.
5. A key is pressed.
6. Mouse is moved or clicked.
7. Value of a text area is changed.
8. A window is opened or closed.


Ans. Event Listener Interface Adapter Class

1. ActionEvent ActionListener None
2. ComponentEvent ComponentListener ComponentAdapter
3. ContainerEvent ContainerListener ContainerAdapter
4. ItemEvent ItemListener None
5. KeyEvent KeytListener KeyAdapter
6. MouseEvent MouseListener MouseAdapter
7. TextEvent TextListener None
8. WindowEvent WindowListener WindowAdapter

Q. Why are there no adapter classes for:
1. ActionEvent
2. ItemEvent
3. TextEvent

Ans. All these classes contain only one method. So, there is no need to write an adapter classes for them.

Q. What is an adapter class?

Ans. An adapter class provides an empty implementation of all the methods in an event listener interface. Such a class is useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act as an event listener by extending such an adapter class and implementing only those events in which you are interested.





















Q. What is an inner class? State an example.

Ans. An inner class is a class defined within another class or within an expression. For example,

public class MousePressedDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
}
}

class MyMouseAdapter extends MouseAdapter
{
MousePressedDemo mousePressedDemo;
//single argument constructor.
public MyMouseAdapter(MousePressedDemo mpd)
{
this.mousePressedDemo=mpd;
}
public void mousePressed(MouseEvent me)
{
mousePressedDemo.showStatus(“Mouse Clicked”);
}
}

Q. What is an Anonymous Inner Class? State an example.

Ans. An Anonymous Inner Class is one that is not assigned a name. For example,

public class AnonymousInnerClassDemo extends Applet
{
public void init()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
showStatus(“Mouse Clicked”);
}
});
}
}

Java Virtual Machine

Java Virtual Machine (JVM) is a virtual computer, typically implemented in software on top of a "real" hardware platform and operating system that runs compiled Java programs.

All Java programs are compiled for the JVM. Therefore, the JVM must be implemented on a particular platform before compiled Java programs will run on that platform.

The JVM executes Java bytecodes, so Java bytecodes can be thought of as the machine language of the JVM.

Role of JVM in making Java portable, How?

The JVM plays a central role in making Java portable. It provides a layer of abstraction between the compiled Java program and the underlying hardware platform and operating system. The JVM is central to Java's portability because compiled Java programs run on the JVM, independent of whatever may be underneath a particular JVM implementation.

Various parts of a JVM?

The "virtual hardware" of the Java Virtual Machine can be divided into four basic parts:

1. The Registers
2. The Stack
3. The garbage-collected Heap
4. The Method Area.

These parts are abstract, just like the machine they compose, but they must exist in some form in every JVM implementation. The size of an address in the JVM is 32 bits. The JVM can, therefore, address up to 4 gigabytes (2 to the power of 32) of memory, with each memory location containing one byte. Each register in the JVM stores one 32-bit address. The stack, the garbage-collected heap, and the method area reside somewhere within the 4 gigabytes of addressable memory. The exact location of these memory areas is a decision of the implementer of each particular JVM.

Various data types provided by JVM?

A word in the Java Virtual Machine is 32 bits. The JVM has a small number of primitive data types: byte (8 bits), short (16 bits), int (32 bits), long (64 bits), float (32 bits), double (64 bits), and char (16 bits). With the exception of char, which is an unsigned Unicode character, all the numeric types are signed. These types conveniently map to the types available to the Java programmer. One other primitive type is the object handle, which is a 32-bit address that refers to an object on the heap.

Use of the Stack in JVM?

The Java stack is used to store parameters for and results of bytecode instructions, to pass parameters to and return values from methods, and to keep the state of each method invocation. The state of a method invocation is called its stack frame. All the local variables being used by the current method invocation are also stored in the stack.

Use of the Heap in JVM?

The heap is where the objects of a Java program live. Any time you allocate memory with the new operator; that memory comes from the heap. The Java language doesn't allow you to free allocated memory directly. Instead, the runtime environment keeps track of the references to each object on the heap, and automatically frees the memory occupied by objects that are no longer referenced -- a process called garbage collection.

Method Area in JVM?

The method area is where the bytecodes reside.