Java Interview Questions -24

Java Interview Questions -24

1.Explain the usage of the keyword transient?
This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).

2. What's the difference between constructors and other methods?
Constructors must have the same name as the class and can not return a value. They are only called once while regular methods could be called many times.

3.Can you call one constructor from another if a class has multiple constructors
Yes. Use this() syntax.

4.How do you know if an explicit object casting is needed?

If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. For example:
Object a; Customer b; b = (Customer) a;
When you assign a subclass to a variable having a supeclass type, the casting is performed automatically.

5. Why isn't the java.sql.DriverManager class being found?

This problem can be caused by running a JDBC applet in a browser that supports the JDK 1.0.2, such as Netscape Navigator 3.0. The JDK 1.0.2 does not
contain the JDBC API, so the DriverManager class typically isn't found by the Java virtual machine running in the browser.
Here's a solution that doesn't require any additional configuration of your web clients. Remember that classes in the java.* packages cannot be
downloaded by most browsers for security reasons. Because of this, many vendors of all-Java JDBC drivers supply versions of the java.sql.* classes that
have been renamed to jdbc.sql.*, along with a version of their driver that uses these modified classes. If you import jdbc.sql.* in your applet code
instead of java.sql.*, and add the jdbc.sql.* classes provided by your JDBC driver vendor to your applet's codebase, then all of the JDBC classes needed
by the applet can be downloaded by the browser at run time, including the DriverManager class.
This solution will allow your applet to work in any client browser that supports the JDK 1.0.2. Your applet will also work in browsers that support the
JDK 1.1, although you may want to switch to the JDK 1.1 classes for performance reasons. Also, keep in mind that the solution outlined here is just an
example and that other solutions are possible.

6.What's the difference between the methods sleep() and wait()

The code sleep(1000); puts thread aside for exactly one second. The code wait(1000), causes a wait of up to one second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

7.How could Java classes direct program messages to the system console, but error messages, say to a file?

The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:
Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st);

8.What's the difference between an interface and an abstract class?

An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class.

9.What would you use to compare two String variables - the operator == or the method equals()?

I'd use the method equals() to compare the values of the Strings and the == to check if two variables point at the same instance of a String object.

10.Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.

11.Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.

12.Can you write a Java class that could be used both as an applet as well as an application?

Yes. Add a main() method to the applet.

13.Explain the usage of Java packages.

This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

14.How can a subclass call a method or a constructor defined in a superclass?

Use the following syntax: super.myMethod(); To call a constructor of the superclass, just write super(); in the first line of the subclass's constructor

15.What's the difference between a queue and a stack?

Stacks works by last-in-first-out rule (LIFO), while queues use the FIFO rule

16.Can an inner class declared inside of a method access local variables of this method?

It's possible if these variables are final.

17.If a class is located in a package, what do you need to change in the OS environment to be able to use it?

You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Let's say a class Employee belongs to a package com.xyz.hr; and is located in the file c:\dev\com\xyz\hr\Employee.java. In this case, you'd need to add c:\dev to the variable CLASSPATH. If this class contains the method main(), you could test it from a command prompt window as follows:
c:\>java com.xyz.hr.Employee

18.What's the difference between J2SDK 1.5 and J2SDK 5.0?

There's no difference, Sun Microsystems just re-branded this version.

19.What can go wrong if you replace && with & in the following code:

String a=null; if (a!=null && a.length()>10) {...}
A single ampersand here would lead to a NullPointerException.

20.What's the main difference between a Vector and an ArrayList

Java Vector class is internally synchronized and ArrayList is not.

21.When should the method invokeLater()be used?

This method is used to ensure that Swing components are updated through the event-dispatching thread.

22.You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces?

Sometimes. But your class may be a descendent of another class and in this case the interface is your only option.

23. What comes to mind when you hear about a young generation in Java?

Garbage collection.

24.How would you make a copy of an entire Java object with its state?

Have this class implement Cloneable interface and call its method clone().

25.How can you minimize the need of garbage collection and make the memory use more effective?

Use object pooling and weak object references.

26.There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it?

If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface.

27.What comes to mind when someone mentions a shallow copy in Java?

Object cloning.

28.If you're overriding the method equals() of an object, which other method you might also consider?

hashCode()

29.How can you force garbage collection?

You can't force GC, but could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.

30. You are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:
ArrayList or LinkedList?

ArrayList

31.What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it?

You do not need to specify any access level, and Java will use a default package access level.

32.Can we have more than one struts-config.xml file for a single Struts application?

Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml,
/WEB-INF/struts-admin.xml,
/WEB-INF/struts-config-forms.xml
</param-value>
</init-param>
.....
<servlet>

33.What is the difference between session scope and request scope when saving formbean?

when the scope is request,the values of formbean would be available for the current request.
when the scope is session,the values of formbean would be available throughout the session.

34.What are the different kinds of actions in Struts?

The different kinds of actions in Struts are:
 1.ForwardAction
 2.IncludeAction
 3.DispatchAction
 4.LookupDispatchAction
 5.SwitchAction

35.What is DispatchAction?

The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.

36.How to use DispatchAction?

To use the DispatchAction, follow these steps :
 1.Create a class that extends DispatchAction (instead of Action)
 2. In a new class, add a method for every function you need to perform on the service – The method has the same signature as the execute() method of an Action class.
 3.Do not override execute() method – Because DispatchAction class itself provides execute() method.
 4.Add an entry to struts-config.xml

37.Does the JDBC-ODBC Bridge support the new features in the JDBC 3.0 API?

The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.

38.How do I start debugging problems related to the JDBC API?

A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the
system that is related to JDBC operations.If you use the DriverManager facility to establish your database connection, you use the DriverManager.setLogWriter method to enable tracing of JDBCoperations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections,
you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use theXADataSource.setLogWriter method.)

39.What is new in JDBC 2.0?

With the JDBC 2.0 API, you will be able to do the following:
Scroll forward and backward in a result set or move to a specific row (TYPE_SCROLL_SENSITIVE,previous(), last(), absolute(), relative(), etc.)
Make updates to database tables using methods in the Java programming language instead of using SQL commands.(updateRow(), insertRow(), deleteRow(),
etc.)Send multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch())
Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.

40.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.

41.Can the JDBC-ODBC Bridge be used with applets?

Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow
untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent
Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called the Java programming language can't guarantee that a security
violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side
configuration.Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since
appletviewer assumesthat applets are trusted. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as
for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC
driver whenever possible to avoid security problems.

42.What's the JDBC 3.0 API?

The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including scrollable result sets and the SQL:1999 data types.
JDBC (Java Database Connectivity) is the standard for communication between a Java application and a relational database. The JDBC API is released in two
versions; JDBC version 1.22 (released with JDK 1.1.X in package java.sql) and version 2.0 (released with Java platform 2 in packages java.sql and
javax.sql). It is a simple and powerful largely database-independent way of extracting and inserting data to or from any database.

43.How can I use the JDBC API to access a desktop database like Microsoft Access over the network?

Most desktop databases currently require a JDBC solution that uses ODBC underneath. This is because the vendors of these database products haven't
implemented all-Java JDBC drivers.The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use. See the JDBC drivers page for a list of
available JDBC drivers.The JDBC-ODBC bridge from Sun's Java Software does not provide network access to desktop databases by itself.
The JDBC-ODBC bridge loads ODBC as a localDLL, and typical ODBC drivers for desktop databases like Access aren't networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge,
however, to access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is free.

44. 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.

45.Are there any ODBC drivers that do not work with the JDBC-ODBC Bridge?

Most ODBC 2.0 drivers should work with the Bridge. Since there is some variation in functionality between ODBC drivers, the functionality of the bridge
may be affected. The bridge works with popular PC databases, such as Microsoft Access and FoxPro.

46.What causes the "No suitable driver" error?

"No suitable driver" is an error that usually occurs during a call to the DriverManager.getConnection method. The cause can be failing to load the
appropriate JDBC drivers before calling the getConnection method, or it can be specifying an invalid JDBC URL--one that isn't recognized by your JDBC
driver. Your best bet is to check the documentation for your JDBC driver or contact your JDBC driver vendor if you suspect that the URL you are
specifying is not being recognized by your JDBC driver.
In addition, when you are using the JDBC-ODBC Bridge, this error can occur if one or more the the shared libraries needed by the Bridge cannot be loaded.
If you think this is the cause, check your configuration to be sure that the shared libraries are accessible to the Bridge.

47.How do I retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX method for each column?

The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column
of a row. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without
at least the cost of a function call in any scenario. We welcome input from developers on this issue.

48.How to insert and delete a row programmatically? (new feature in JDBC 2.0)

Make sure the resultset is updatable.
1. move the cursor to the specific position.
uprs.moveToCurrentRow();
2. set value for each column.
uprs.moveToInsertRow();//to set up for insert
uprs.updateString("col1" "strvalue");
uprs.updateInt("col2", 5);
...
3. call inserRow() method to finish
the row insert process.
uprs.insertRow();
To delete a row: move to the specific
position and call deleteRow() method:
uprs.absolute(5);
uprs.deleteRow();//delete row 5
To see the changes call refreshRow();
uprs.refreshRow();

49.What are the two major components of JDBC?

One implementation interface for database manufacturers, the other implementation interface for application and applet writers.

50.Which type of JDBC driver is the fastest one?

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the jdbc calls into vendor specific protocol calls and it directly interacts
with the database.

51.Are all the required JDBC drivers to establish connectivity to my database part of the JDK?

No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2 Platform releases other than the JDBC-ODBC Bridge. So,
developers need to get a driver and install it before they can connect to a database. We are considering bundling JDBC technology- enabled drivers in the
future.

52.What are the common tasks of JDBC?

Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
Register a driver
Specify a database
Open a database connection
Submit a query
Receive results
Process results

53.Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

54.Why does the ODBC driver manager return 'Data source name not found and no default driver specified Vendor: 0'

This type of error occurs during an attempt to connect to a database with the bridge. First, note that the error is coming from the ODBC driver manager.
This indicates that the bridge-which is a normal ODBC client-has successfully called ODBC, so the problem isn't due to native libraries not being
present. In this case, it appears that the error is due to the fact that an ODBC DSN (data source name) needs to be configured on the client machine.
Developers often forget to do this, thinking that the bridge will magically find the DSN they configured on their remote server machine

55.How to use JDBC to connect Microsoft Access?

There is a specific tutorial at javacamp.org. Check it out.

56.Is the JDBC-ODBC Bridge multi-threaded?

No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of
the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition,
deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in
the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.

57.What is the query used to display all tables names in SQL Server (Query analyzer)?

select * from information_schema.tables

58.What do you mean by fastest type of JDBC driver?

JDBC driver performance or fastness depends on a number of issues: Quality of the driver code, size of the driver code, database server and its load, Network topology, Number of times your request is translated to a different AP

59.What is a ResultSet ?

ResultSet is a Java Object, it contains the results of executing an SQL query. In other words it is a table of data representing a database result set, which is usually generated by executing a statement that queries the database.

60.How to communicate with data base?

To connect to data base we have set of interfaces provided by Java.sql.*; First you need to load JDBC driver and then Make JDBC connection.

61.What is the use of ForwardAction?

The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.

62.What is IncludeAction?

The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.

63.What is the difference between ForwardAction and IncludeAction?

The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.

64. What is LookupDispatchAction?

The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.

65.What is the use of LookupDispatchAction?

LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.

66.What is MVC?

Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.
Model : The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
Controller:The controller reacts to the user input. It creates and sets the model.

67.What is Jakarta Struts Framework?

Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

68.How you will make available any Message Resources Definitions file to the Struts Framework Environment?

Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.

69.What is Struts?

The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm.
Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems.
The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.

70.What is Action Class?

The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

71.What is ActionForm?

An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

72.What is Struts Validator Framework?

Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.
The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

73.Give the Details of XML files used in Validator Framework?

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

74.How you will display validation fail errors on jsp page?

Following tag displays all the errors:
<html:errors/>

75.What is ActionServlet?

The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

76.How you will enable front-end validation based on the xml in validation.xml?

The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.

77.How to get data from the velocity page in a action class?

We can get the values in the action classes by using data.getParameter("variable name defined in the velocity page");

78.What are the components of Struts?

Struts components can be categorize into Model, View and Controller:
Model: Components like business logic /business processes and data are the part of model.
View: HTML, JSP are the view components.
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

79.What are the core classes of the Struts Framework?

Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.
JavaBeans components for managing application state and behavior.
Event-driven development (via listeners as in traditional GUI development).
Pages that represent MVC-style views; pages reference view roots via the JSF component tree.

80.What is a framework?

A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

81.What is Struts framework?

Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

82.What is role of ActionServlet?

ActionServlet performs the role of Controller:
 Process user requests
 Determine what the user is trying to achieve according to the request
 Pull data from the model (if necessary) to be given to the appropriate view,
 Select the proper view to respond to the user
 Delegates most of this grunt work to Action classes
Is responsible for initialization and clean-up of resources

83.What is the ActionForm?

ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.

84.What are the important methods of ActionForm?

The important methods of ActionForm are : validate() & reset().

85.What design patterns are used in Struts?

Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.
 Service to Worker
 Dispatcher View
 Composite View (Struts Tiles)
 front Controller
 View Helper
 Synchronizer Token

87.Describe validate() and reset() methods?

validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.
reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.


88.How is the Action Mapping specified?

We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from <ActionMapping> configuration element of struts-config.xml file
<action-mappings>
<action path="/submit"
type="submit.SubmitAction"
name="submitForm"
input="/submit.jsp"
scope="request"
validate="true">
<forward name="success" path="/success.jsp"/>
<forward name="failure" path="/error.jsp"/>
</action>
</action-mappings>

89.What is role of Action Class?

An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.

90.What is ActionMapping?

Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.

91.In which method of Action class the business logic is executed?

In the execute() method of Action class the business logic is executed.
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception ;
execute() method of Action class:
1.Perform the processing required to deal with this request
2.Update the server-side objects (Scope variables) that will be used to create the next page of the user interface
3.Return an appropriate ActionForward object

92.What is difference between LookupDispatchAction and DispatchAction?

The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.

93.What is SwitchAction?

The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.

94.What is DynaActionForm?

A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean.

95.how to display validation errors on jsp page?

<html:errors/> tag displays all the errors. <html:errors/> iterates over ActionErrors request attribute.

96.What are the various Struts tag libraries?

The various Struts tag libraries are:
HTML Tags
Bean Tags
Logic Tags
Template Tags
Nested Tags
Tiles Tags.

97.How does an exception permeate through the code?

An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

98.What are the different ways to handle exceptions?

There are two ways to handle exceptions, 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and 2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

99.What is the basic difference between the 2 approaches to exception handling.

 1> try catch block and 2> specifying the candidate exceptions in the throws clause?

100.When should you use which approach?

In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

101.Is it necessary that each try block must be followed by a catch block?

It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

102.If I write return at the end of the try block, will the finally block still execute?

Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

103.If I write System.exit (0); at the end of the try block, will the finally block still execute?

No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.

104.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.

105.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 leads to significant errors.

106.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

107. What environment variables do I need to set on my machine in order to be able to run Java programs?

CLASSPATH and PATH are the two variables.

108.Can an application have multiple classes having main method?

Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

109.Can I have multiple main methods in the same class?

No the program fails to compile. The compiler says that the main method is already defined in the class.

110.Do I need to import java.lang package any time? Why ?

No. It is by default loaded internally by the JVM.

111.Can I import same package/class twice? Will the JVM load the package twice at runtime?

One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.

112.What are Checked and UnChecked Exception?

A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method? Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method? Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.



-------------------------------------
Also Read:






































 

0 comments:

Post a Comment