Sie sind auf Seite 1von 15

JAVA Interview Q&A

Question: What is transient variable? Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

Question: Name the containers which uses Border Layout as their default layout? Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.

Question: What do you understand by Synchronization? Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption. E.g. Synchronizing a function: public synchronized void Method1 () { // Appropriate method-related code. } E.g. Synchronizing a block of code inside a function: public myFunction (){ synchronized (this) { // Synchronized code here. } }

Question: What is Collection API? Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map. Question: Is Iterator a Class or Interface? What is its use? Answer: Iterator is an interface which is used to step through the elements of a Collection.

Question: What is similarities/difference between an Abstract class and Interface?

class and Interface? Answer: Differences are as follows:


Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast.

Similarities:

Neither Abstract classes or Interface can be instantiated.

Question: How to define an Abstract class? Answer: A class containing abstract method is called Abstract class. An Abstract class can't be instantiated. Example of Abstract class: abstract class testAbstractClass { protected String myString; public String getMyString() { return myString; } public abstract string anyAbstractFunction(); }

Question: How to define an Interface? Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface. Emaple of Interface: public interface sampleInterface { public void functionOne(); public long CONSTANT_ONE = 1000; }

Question: Explain the user defined Exceptions? Answer: User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions. Example: class myCustomException extends Exception { // The class simply has to exist to be an exception }

Question: Explain the new Features of JDBC 2.0 Core API? Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities. New Features in JDBC 2.0 Core API:

Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position JDBC 2.0 Core API provides the Batch Updates functionality to the java applications. Java applications can now use the ResultSet.updateXXX methods. New data types - interfaces mapping the SQL3 data types Custom mapping of user-defined types (UTDs) Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values.

Question: Explain garbage collection? Answer: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected.

Question: How you can force the garbage collection? Answer: Garbage collection automatic process and can't be forced.

Question: What is OOPS? Answer: OOP is the common abbreviation for Object-Oriented Programming.

Question: Describe the principles of OOPS. Answer: There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

Question: Explain the Encapsulation principle. Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.

Question: Explain the Inheritance principle. Answer: Inheritance is the process by which one object acquires the properties of another object.

Question: Explain the Polymorphism principle. Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".

Question: Explain the different forms of Polymorphism. Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

Method overloading Method overriding through inheritance Method overriding through the Java interface

Question: What are Access Specifiers available in Java? Answer: Access specifiers are keywords that determines the type of access to the member of a class. These are:

Public Protected Private Defaults

Question: Describe the wrapper classes in Java. Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type. Following table lists the primitive types and the corresponding wrapper classes:

Primitive
boolean byte char double float int long short void

Wrapper
java.lang.Boolean java.lang.Byte java.lang.Character java.lang.Double java.lang.Float java.lang.Integer java.lang.Long java.lang.Short java.lang.Void

Question: Read the following program: public class test { public static void main(String [] args) { int x = 3; int y = 1; if (x = y) System.out.println("Not equal"); else System.out.println("Equal"); } } What is the result? A. The output is Equal B. The output in Not Equal

C. An error at " if (x = y)" causes compilation to fall. D. The program executes but no output is show on console. Answer: C Q: What is ActionServlet? A: 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.

Q: How you will make available any Message Resources Definitions file to the Struts Framework Environment? A: 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. Example: <message-resources parameter="MessageResources" />

Q: What is Action Class? A: The Action is part of the controller. 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. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model. 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.

Q: Write code of any Action Class? A: Here is the code of Action Class that returns the ActionForward object. TestAction.java
package roseindia.net; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import import import import org.apache.struts.action.Action; org.apache.struts.action.ActionForm; org.apache.struts.action.ActionForward; org.apache.struts.action.ActionMapping;

public class TestAction extends Action {

public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ return mapping.findForward("testAction"); } }

Q: What is ActionForm? A: 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.

Q: What is Struts Validator Framework? A: 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.

Q. Give the Details of XML files used in Validator Framework? A: 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. Q. How you will display validation fail errors on jsp page? A: Following tag displays all the errors: <html:errors/>

Q. How you will enable front-end validation based on the xml in validation.xml? A: 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 side validation script.

Question: What is RequestProcessor and RequestDispatcher? Answer: The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client. The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like The ActionServlet Class The RequestProcessor Class The Action Class The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application. The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows. <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> </servlet>

All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/actionName.do The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>/do/*</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://www.my_site_name.com/mycontext/do/action_Name The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed.

Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception; The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesnt already exist. The strut framework will create only a single instance of each Action class in your application. Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request. <action> path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file. <action> path= "/somerequest" type="com.somepackage.someAction" scope="request"

name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> The action forward mappings also can be specified in a global section, independent of any specific action mapping. <global-forwards> <forward name="Success" path="/action/somejsp.jsp" /> <forward name="Failure" path="/someotherjsp.jsp" /> </global-forwards> public interface RequestDispatcher Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource. getRequestDispatcher public RequestDispatcher getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static. The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher. Parameters: path - a String specifying the pathname to the resource Returns: a RequestDispatcher object that acts as a wrapper for the resource at the specified path See Also: RequestDispatcher, getContext(java.lang.String) getNamedDispatcher public RequestDispatcher getNamedDispatcher(java.lang.String name)

Returns a RequestDispatcher object that acts as a wrapper for the named servlet. Servlets (and JSP pages also) may be given names via server administration or via a web application deployment descriptor. A servlet instance can determine its name using ServletConfig.getServletName(). This method returns null if the ServletContext cannot return a RequestDispatcher for any reason. Parameters: name - a String specifying the name of a servlet to wrap Returns: a RequestDispatcher object that acts as a wrapper for the named servlet See Also: RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName()

Question: Why cant we overide create method in StatelessSessionBean? Answer: From the EJB Spec : - A Session bean's home interface defines one or morecreate(...) methods. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method must be the enterprise Bean's remote interface type. The home interface of a stateless session bean must have one create method that takes no arguments.

Question: Is struts threadsafe?Give an example? Answer: Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.

Question: Can we Serialize static variable? Answer: Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are 1. Serialization ignores static fields, because they are not part of any particular object's state. 2. Base class fields are only handled if the base class itself is serializable.

3. Transient fields. There are four basic things you must do when you are making a class serializable. They are: 1. 2. 3. 4. Implement the Serializable interface. Make sure that instance-level, locally defined state is serialized properly. Make sure that superclass state is serialized properly. Override equals( )and hashCode( ). it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process .... (Source: http://www.oreilly.com/catalog/javarmi/chapter/ch10.html)

Question: What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file? Answer: tiles-def.xml is is an xml file used to configure tiles with the struts application. You can define the layout / header / footer / body content for your View. See more at http://www.roseindia.net/struts/using-tiles-defs-xml.shtml. The resourcebundle.properties file is used to configure the message (error/ other messages) for the struts applications. The file validation.xml is used to declare sets of validations that should be applied to Form Beans. Fpr more information please visit http://www.roseindia.net/struts/address_struts_validator.shtml.

Question: What is the difference between perform() and execute() methods? Answer: Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.

Question: What are the various Struts tag libraries? Answer: Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are: * Bean tag library - Tags for accessing JavaBeans and their properties. * HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..

* Logic tag library - Tags for generating conditional output, iteration capabilities and flow management * Tiles or Template tag library - For the application using tiles * Nested tag library - For using the nested beans in the application

Question: What do you understand by DispatchAction? Answer: DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine Struts actions into one class, each with their own method. The org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the different functions in the same Action class. For example: A package might include separate RegCreate, RegSave, and RegDelete Actions, which just perform different operations on the same RegBean object. Since all of these operations are usually handled by the same JSP page, it would be handy to also have them handled by the same Struts Action. A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform. <html:hidden property="dispatch" value="error"/> <SCRIPT>function set(target) {document.forms[0].dispatch.value=target;}</SCRIPT> <html:submit onclick="set('save');">SAVE</html:submit> <html:submit onclick="set('create');">SAVE AS NEW</html:submitl> <html:submit onclick="set('delete);">DELETE</html:submit> Then, in the Action you can setup different methods to handle the different operations, and branch to one or the other depending on which value is passed in the dispatch field. String dispatch = myForm.getDispatch(); if ("create".equals(dispatch)) { ... if ("save".equals(dispatch)) { ... The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same thing, but without messy branching logic. The base perform method will check a dispatch field for you, and invoke the indicated method. The only catch is that the dispatch methods must use the same signature as perform. This is a very modest requirement, since in practice you usually end up doing that anyway. To convert an Action that was switching on a dispatch field to a DispatchAction, you simply need to create methods like this public ActionForward create( ActionMapping mapping,

ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... public ActionForward save( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... Cool. But do you have to use a property named dispatch? No, you don't. The only other step is to specify the name of of the dispatch property as the "parameter" property of the action-mapping. So a mapping for our example might look like this: <action path="/reg/dispatch" type="app.reg.RegDispatch" name="regForm" scope="request" validate="true" parameter="dispatch"/> If you wanted to use the property "o" instead, as in o=create, you would change the mapping to <action path="/reg/dispatch" type="app.reg.RegDispatch" name="regForm" scope="request" validate="true" parameter="o"/> Again, very cool. But why use a JavaScript button in the first place? Why not use several buttons named "dispatch" and use a different value for each? You can, but the value of the button is also its label. This means if the page designers want to label the button something different, they have to coordinate the Action programmer. Localization becomes virtually impossible. (Source: http://husted.com/struts/tips/002.html).

Question: How Struts relates to J2EE? Answer: Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but

it is itself not part of the J2EE standard.

Question: What is Struts actions and action mappings? Answer: A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward. An action can perform tasks such as validating a user name and password. An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action. An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.

Das könnte Ihnen auch gefallen