Beruflich Dokumente
Kultur Dokumente
Questions from Core Java .........................................................................................2 Questions from Servlets..................................................................................................................................12 Questions from JSP........................................................................................................................................16 Questions from JDBC......................................................................................................................................19 Questions from Struts 1.x framework..............................................................................................................20 Questions from JSF.........................................................................................................................................25 Questions from Portal & Portlet.......................................................................................................................28 Questions from EJB........................................................................................................................................30 Bean Managed Persistence .................................................................................................................33 Container Managed Persistence...........................................................................................................33 Questions from Hibernate...............................................................................................................................35 Questions from Web Service..........................................................................................................................40 What are Web Services?................................................................................................................................40 What is SOAP? ..............................................................................................................................................40 What is WSDL?...............................................................................................................................................40 What is UDDI?.................................................................................................................................................40 Can business method of the implementing class be static or final?................................................................40 How many development styles are there in web service?..............................................................................40 What is the difference between JAX--WS and JAX-RPC?..............................................................................41 What is Apache Axis2?...................................................................................................................................41 What is full form of REST?..............................................................................................................................41 Questions from Spring....................................................................................................................................42
4. What is Polymorphism?
Polymorphism is a feature that allows one interface to be used for a general class of action.
6. What is Interface?
Using the keyword interface, you can fully abstract a class interface from its implementation. That is, using interface, you can specify what a class must do, but not how it does it. Interfaces are syntactically similar to class, but they lack instance variable, and their methods are declared without body. Once it is defined, any number of classes can implement an interface. Also one class can implement any number of interfaces.
7. What is Abstract Class? What are the differences between an Abstract Class and an Interface?
Abstract class is a class, which may have one or more abstract method. A method, which has no body only declare part, is mention is called abstract method. Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. Abstract class may have fully defied method in it.
11. Is combination of final and static with abstract class possible? If yes how and if no why?
Though abstract classes are not fully defined so it cannot be final, and static is not a valid modifier of class.
12. What is Vector and ArrayList? What are the differences between them? When to use each.
Vector and ArrayList are class, which are part of Collection Framework. The Collection Framework is a sophisticated hierarchy of interface and classes that managing group of objects. Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the Collection Framework.
17. What are Hash Table and HashMap? What are the differences between them?
Hash Table and Hash Map are part of Collection Framework. Hash Table is synchronized but HashMap not.
18. What are ListIterator and Iterator? What are the differences between them?
ListIterator and Iterator are interface, which are use for looping through Collection object. ListIterator is sub interface of Iterator menace ListIterator extends Iterator.
Java Interview Question & Answer 20. What are the different ways in which Threads can be created?
Javas multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. Since you cant directly refer to the ethereal state of a running thread, you will deal it through its proxy, the Thread instance that spawned it. To create a new thread, your programs will either extend Thread or implement the Runnable interface.
22. Is it necessary that an Abstract class must have at least one abstract method?
No.
23. What are the differences between Properties and Hash Table?
Properties are subclass of Hash Table.
25. What are the differences between Method Overloading and Method Overriding?
In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded. In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its super class, then the method in the subclass is said to override the method in the super class.
26. What are the access modifiers for methods? Explain the default modifier?
Javas access modifiers are public, private & protected. When no access modifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.
28. Can you have a constructor in an Abstract Class? What is the use of having a constructor in an Abstract class?
Yes I abstract class may have constructor but there is no use of that because abstract class is not fully defies so it cannot be instantiated with the new operator.
31. What is the difference between Serializalble and Externalizable interface? How can you control over the serialization process i.e. how can you customize the seralization process?
When you use Serializable interface, your class is serialized automatically by default. But you can override writeObject() and readObject() two methods to control more complex object serailization process. When you use Externalizable interface, you have a complete control over your class's serialization process. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
32. What one should take care of while serializing the object?
One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
34. What are the various classes/interfaces under util/Collection interface (framework)?
There is lot of class and interface under util/collection interface. It has classes that generate pseudorandom number, manage date etc. It has a sub system to manage group of object called Collection Framework.
36. What are the different access modifiers and mention their scope in Java?
Public, Private & Protected. Public: Any other methods & class can use public class & method. Private: Private method can use within same class. Protected: can use same module.
37. The static keyword can be used with which of the followings (class, methods, blocks, variables).
Methods. Variable
38. How can you handle a piece of code for exception handling in Java?
To handle the exception you should keep the block of code between try {}, and catch the proper exception.
45. 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.
49. What is the difference between checked and Unchecked Exceptions in Java?
All predefined exceptions in Java are either a checked exception or an unchecked exception. Checked exceptions must be caught using try .. catch() block or we should throw the exception using throws clause. If you dont, compilation of program will fail.
51. What are different types of nested class? Nested top-level classes, Member classes, Local classes, Anonymous classes
Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. e.g., outer. Inner. Top-level inner classes implicitly have access only to static variables. There can also be inner interfaces. All of these are of the nested top-level variety. Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class act similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class. Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface. Because local classes are not members, the modifiers public, protected, private, and static are not usable Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor
54. What happens if you dont initialize an instance variable of any of the primitive types in Java? Page: 7/46 Debjit Sanyal
57. What will the access specifier of a variable be by default if it is declared in an Interface?
Final.
63. What are daemon thread and which method is used to create the daemon thread?
Daemon threads are threads with low priority and runs in the back ground doing the garbage collection operation for the java runtime system. The setDaemon() method is used to create a daemon thread. These threads run without the intervention of the user. To determine if a thread is a daemon thread, use the accessor method isDaemon() When a standalone application is run then as long as any user threads are active the JVM cannot terminate, otherwise the JVM terminates along with any daemon threads which might be active. Thus a daemon thread is at the mercy of the runtime system. Daemon threads exist only to serve user threads
74. When do you use continue and when do you use break statements?
When continue statement is applied it prematurely completes the iteration of a loop. When break statement is applied it causes the entire loop to be abandoned.
75. If the method to be overridden has access type protected, can subclass have the access type as private?
No, it must have access type as protected or public, since an overriding method must not be less accessible than the method it overrides.
81. What happens when you call Thread.yield() ? Page: 10/46 Debjit Sanyal
84. Does the thread method start executing as soon as the sleep time is over?
No, after the specified time is over the thread enters into ready state and will only execute when the scheduler allows it to do so.
5. What are the differences between response.sendRedirect() and requestDispatcher. forward()? Under which situation each should be used?
Response.sendRedirect is use to send JSP, HTML or other resource to client. A single client request can pass through many servlet and other resource in the web application. It does not require any extra action or information to invoke method of RequestDispatcher.
6. What is SingleThreadModel? Explain the behavior of Server when your Servlet has implemented the Single Thread Model and 1000 requests simultaneously arrive at the Server.
SingleThreadModel is a signature interface that can used to make a servlet Single Threaded. When you implement SingleThreadModel interface in a servlet that servlet always to be accessible through only one thread. When 1000 request simultaneously arrive at the server performance of the application will be very poor.
7. Difference between application server and web sever? Page: 12/46 Debjit Sanyal
10. What are the common mechanisms used for session tracking?
Cookies SSL sessions URL- rewriting
11. What are the differences between ServletOutputStream and PrintWriter? Can we use them together?
ServletOutputStream is mainly use to send non-text data like image to client and PrintWriter is use only to send text data to the client. You cant use them together.
12. What kind of approach has to be taken when a Servlet has to be made Thread Safe still not degrading the performance of the Server?
Try to avoid declaring instance variable. Or keep the share resource within Synchronized block.
14. What is the parameter in the init method of a Servlet? What is the functionality of this parameter?
ServletConfig object is the parameter of Init method of servlet. It saves the servletConfig so that it can return by the getServletConfig method.
15. From which file does a Servlet get information about server?
From web.xml.
17. What is the difference between Difference between doGet() and doPost()?
A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.
7. What are custom tags? What interfaces do you use to build custom tags?
Custom Tag can replace scriplet in JSP, because custom tag does the same as scriplet do. SimpleTag interface will be use to build custom Tags.
8. How do you differentiate between a Normal JSP page and an Error JSP page?
10. What are the differences between directives and action in JSP?
Directives are message to a JSP container. They do not send out put to a client, but are used to define page attributes, which custom tag libraries use and which other pages include. Action provided convenient method of linking dynamic code to simple markup that appears in a JSP. The functionality is identical to the scriplet elements but has the advantage of completely abstraction any code that would normally have to be intermixing with JSP.
13. What are the different scope values for the <jsp:useBean>?
The different scope values for <jsp:useBean> are 1. page 2. request 3.session 4.application
15. What is the difference between variable declared inside a declaration part and variable declared in scriplet part?
Variable declared inside declaration part is treated as a global variable, that means after conversion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable. And the scope is available to complete jsp and to complete in the converted servlet class. Where as if you declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.
16. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More
17. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriplet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions. <% response.setHeader("Cache-Control","no-store"); //HTTP 1.1 response.setHeader("Pragma\","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %>
19. What are the two kinds of comments in JSP and what's the difference between them?
<% JSP Comment %> <! HTML Comment >
20. How many JSP scripting elements and what are they?
There are three scripting language elements: declarations <%! %> scriptlets <% %> expressions <%= %>
3. What are the differences between Callable Statements, Prepared Statements and Statements? How to use each of them?
Callable Statement used for calling store procedure. Prepared Statement is used for execute precompiled SQL statement. Statement is used for execute any SQL statement.
4. What are the different types of JDBC Drivers? Explain the differences between them and also their pros and cons?
Four type of JDBC are there. Type 1 JDBC to ODBC JDBC take help of Microsoft ODBC driver. Type 2 Java/Native code driver, which is Data base specific driver. Type 3 JDBC drivers, which convert SQL queries into JDBC, formatted statement. Type 4 JDBC drivers, which except SQL queries are translated into the format required by the DBMS.
6. What is a transaction?
Transaction: Transaction is a "Logical unit of work". It must performed by "Either all or Nothing.
4. What are the different XML files that are involved during the usage of validation framework?
Validator.xml and validator_ruls.xml
6. What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the Jakarta Struts Framework this class plays the role of controller. All the requests to the server go through the controller. Controller is responsible for handling all the requests.
8. What is ActionForm?
An ActionForm is a java bean 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.
13. 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.
Java Interview Question & Answer 15. 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>
7. What are the differences between a Backing Bean and Managed Bean?
Backing Beans are merely a convention, a subtype of JSF Managed Beans which have a very particular purpose. There is nothing special in a Backing Bean that makes it different from any other managed bean apart from its usage. What makes a Backing Bean is the relationship it has with a JSF page; it acts as a place to put component references and Event code.
Backing Beans Managed Beans
A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) and it automatically created (and optionally initialized) by JSF when it is needed. The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,
The managed beans that are created by JSF can be stored within the request, session, or application scopes
Backing Beans should be defined in the request scope, exist in a one-to-one relationship with a particular page and hold the entire page specific event handling code. In a real-world scenario, several pages may need to share the same backing bean behind the scenes. A backing bean not only contains view data, but also behavior related to that data.
5. Why portals?
The following are the reasons to use portals: Unified way of presenting information from diverse sources. Services like email, news, infotainment, stock prices and other features are offered by portals. Provides consistent look and feel for enterprise. Eg. MSN, Google sites.
8. Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as passed-by-value", that means that its read-only in the EJB. If anything is altered from inside the EJB, it wont be reflected back to the HttpSession of the Servlet Container. The Pass-by-reference can be used between EJBs Remote Interfaces, as they are remote
9. The EJB container implements the EJBHome and EJB Object classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJB Object classes?
The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. While referring the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer.
10. Can the primary key in the entity bean be a Java primitive type such as int?
The primary key can't be a primitive type--use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive)
12. What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other?
Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Managed. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistence storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrieve values, assign them to the objects in the ejbLoad () which will be called by the container when it instantiates a bean object. Similarly in the ejbStore () the container saves the object values back the persistence storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container. But in case of JDBC you have to explicitly do the above features.
14. Brief description about local interfaces? Page: 31/46 Debjit Sanyal
15. What are the special design cares that must be taken when you work with local interfaces?
It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.
17. What is the difference between Message Driven Beans and Stateless Session beans?
i. Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. ii. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. iii. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.
18. How can I call one EJB from inside of another EJB?
EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.
21. What is the difference between Container-Managed Persistent (CMP) bean and Bean-Managed Persistent (BMP)?
Bean Managed Persistence BMP offers a tactical approach The developer takes care of handling persistence BMP uses hard coded queries so we can optimize our queries Container Managed Persistence CMP is more strategic Vendor takes care of everything by using OR or OODB mappings using metadata. A developer cannot optimize performance as the vendor takes care of it
22. What are the callback methods in Entity beans? What are the callback methods in Entity beans?
Callback methods allow the container to notify the bean of events in its life cycle. The callback methods are defined in the javax.ejb.EntityBean interface. setEntityContext(); unsetEntityContext(); ejbLoad(); ejbStore(); ejbActivate(); ejbPassivate(); ejbRemove();
The other two container types are client-side: An application container for standalone GUIs, console, and batch-type programs the familiar Java applications started with the java command. An applet container, meaning a browser, usually with the Java Plug-in.
When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.
Cons
In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway. Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service and UI tiers.
5. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?
Hibernate uses the version property, if there is one. If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys.
6. What is the difference between the session.get() method and the session.load() method?
Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.
7. What is the difference between the session.update() method and the session.lock() method?
Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
8. How would you reattach detached objects to a session when the same object has already been loaded into the session?
You can use the session.merge() method call.
10. What are the general considerations or best practices for defining your Hibernate persistent classes?
Only use the load() method if you are sure that the object exists. load() method will throw an exception if the unique id is not found in the database. load() just returns a proxy by default and database wont be hit until the proxy is first invoked.
If you are not sure that the object exists, then use one of the get() methods. get() method will return null if the unique id is not found in the database. get() will hit the database immediately.
21. How can Hibernate be configured to access an instance variable directly and not through a setter method?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.
Java Interview Question & Answer 22. How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes may not be updated or deleted by the application.
23. What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Criteria are a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there are a variable number of conditions to be placed upon the result set. dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
What is SOAP?
SOAP is an XML-based protocol to let applications exchange information over HTTP. Or simpler: SOAP is a protocol for accessing a Web Service. SOAP stands for Simple Object Access Protocol SOAP is a communication protocol SOAP is a format for sending messages SOAP is designed to communicate via Internet SOAP is platform independent SOAP is language independent SOAP is based on XML SOAP is simple and extensible SOAP allows you to get around firewalls SOAP is a W3C standard
What is WSDL?
WSDL is an XML-based language for locating and describing Web services. WSDL stands for Web Services Description Language WSDL is based on XML WSDL is used to describe Web services WSDL is used to locate Web services WSDL is a W3C standard
What is UDDI?
UDDI is a directory service where companies can register and search for Web services. UDDI stands for Universal Description, Discovery and Integration UDDI is a directory for storing information about web services UDDI is a directory of web service interfaces described by WSDL UDDI communicates via SOAP UDDI is built into the Microsoft .NET platform
Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test.
FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code. ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml");
XmlWebApplicationContext :
11. What is the typical Bean life cycle in Spring Bean Factory Container?
The spring container finds the beans definition from the XML file and instantiates the bean. Using the dependency injection, spring populates all of the properties as specified in the bean definition If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beans ID. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself. If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization() methods will be called. If an init-method is specified for the bean, it will be called. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.