Sie sind auf Seite 1von 46

Java Interview Question & Answer

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

Page: 1/46 Debjit Sanyal

Java Interview Question & Answer

Questions from Core Java


1. What is OOAD and explain its characteristics?
Object Oriented Analysis & Design. There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.

2. What is Inheritance? Explain?


Inheritance is the process by which one object acquires the properties of another object.

3. What are the differences between Composition and Inheritance?


Composition is a process by which something creates from scratch. Inheritance is a process by which one object acquires the properties of another object.

4. What is Polymorphism?
Polymorphism is a feature that allows one interface to be used for a general class of action.

5. Explain the Encapsulation principle?


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.

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.

8. What is the difference between String and StringBuffer?


String objects are immutable whereas StringBuffer objects are not. StringBuffer unlike Strings support growable and modifiable strings.

9. Where and how can you use a private constructor?

Page: 2/46 Debjit Sanyal

Java Interview Question & Answer


Private constructor can be used if you do not want any other class to instantiate the class. This concept is generally used in Singleton Design Pattern. The instantiation of such classes is done from a static public method.

10. How are this() and super() used with constructors?


this() is used to invoke a constructor of the same class. super() is used to invoke a super class constructor.

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.

13. What is the difference between set and list?


A Set stores elements in an unordered way and does not contain duplicate elements, whereas a list stores elements in an ordered way but may contain duplicate elements.

14. Whats the difference between a queue and a stack?


Stack is a data structure that is based on last-in-first-out rule (LIFO), while queues are based on Firstin-first-out (FIFO) rule.

15. What method should the key class of Hashmap override?


The methods to override are equals() and hashCode().

16. What is the difference between Enumeration and Iterator?


The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.

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.

19. How can we prevent a Class variable from serialization?


Variable that are declared as transient are not saved by the serialization facilities. Also static variable are not saved.

Page: 3/46 Debjit Sanyal

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.

21. Why are there separate wait and sleep methods?


The static Thread.sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. The wait method gives up control over thread execution indefinitely so that other threads can run.

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.

24. What is late Binding?


Method declared as final can sometime provide a performance enhancement: The compiler is free to inline calls to them because it knows they will not be overridden by a subclass. When a small final method is called, often the java compiler can copy the bytecode for the subroutine directly inline with compiled code of calling method, thus eliminating the costly overhead associated with a method call. Inline is only an option with final method. Normally, java resolves calls to methods dynamically, at run time. This is call late binding. However, since final methods cannot be overridden, a call to one can be resolved a compile time. This is called early binding.

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.

27. Can you override the static method?


No, because static method has early binding.

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.

29. Explain about synchronization. When it is used?


When two or more thread needs to access to share resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called Synchronization.

Page: 4/46 Debjit Sanyal

Java Interview Question & Answer

30. What are the methods in Serializable Interface?


There is not any method in Serializable Interface. Only an object that implements the Serializable interface can be saved and restored by the serialization facilities.

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.

33. What are the differences between an Interface and a Class?


Interface has only method signature there is not any body of any method. Class has method, which is fully implemented. Except abstract class.

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.

35. What are the differences between Map and HashMap?


Map is interface and HashMap is class, which implement Map interface.

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.

39. What are the contents of the finally block?


Finally block content should be used for closing file handles and freeing up any other resource that might have been allocate at the beginning of a method.

40. What is persistence?


Properties of a bean can be saved and retrieved for latter time in other word, a bean can be persistent. In order to persistent, a JavaBeans needs to implement the java.io.Serializable interface. The

Page: 5/46 Debjit Sanyal

Java Interview Question & Answer


java.io.Serializable interface does not have any methods to implement. It is used to indicate that the class that implements it can be save and retrieved.

41. Accessor and mutator methods?


JavaBeans require properties to have accessor and mutator method. A property is another name for a class-wide variable. Accessors provide a standardized way of accessing the value of a property. Mutators provide a standard way to modify the value of a property. In fact, it is good coding practice to provide and use accessor and mutator methods for properties in all Java classes. To make the accessor and mutator methods for a property, the standard practice is to prepend the name of the property with the word 'get' for the get method name and 'set' for the set method name. In the accessor and mutator methods' names, the property name is capitalized, though the property's name should be declared in the lower case.

42. What is final, finalize method and finally?


final: To disallow a method from being overridden, specify final as a modifier at the start its declaration. Methods declared as final cannot be overridden. finalize: Some time an object will need to perform some action when it is destroyed. For example, if an object holding some non-Java resource such as a file handle or windows character font, that you might want to make sure these resource are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. To add a finalizer to a class, you simply define the finalize() method. The Java run time calls the method whenever it is about to recycle an object of that class. finally: finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown .

43. What is the purpose of finalization?


The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup, before the object gets garbage collected. For example, closing an opened database Connection.

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

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.

46. Explain the user defined Exceptions?


User defined Exceptions are the separate Exception classes defined by the user for specific purposed. A user defined can create 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 }

47. What is the difference between throw and throws keywords?


The throw keyword denotes a statement that causes an exception to be initiated. It takes the Exception object to be thrown as an argument. The exception will be caught by an enclosing try-catch block or

Page: 6/46 Debjit Sanyal

Java Interview Question & Answer


propagated further up the calling hierarchy. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method. An exception can be re-thrown.

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


Throwable.

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.

50. What are pass by reference and pass by value?


Pass by Reference means the passing the address itself rather than passing the value. Pass by Value means passing a copy of the value to be passed

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

52. What are wrapped classes?


Wrapped classes are classes that allow primitive types to be accessed as objects

53. What are the different scopes for Java variables?


The scope of a Java variable is determined by the context in which the variable is declared. Thus a java variable can have one of the three scopes at any given point in time. 1. Instance: - These are typical object level variables, they are initialized to default values at the time of creation of object, and remain accessible as long as the object accessible. 2. Local: - These are the variables that are defined within a method. They remain accessible only during the course of method execution. When the method finishes execution, these variables fall out of scope. 3. Static: - These are the class level variables. They are initialized when the class is loaded in JVM for the first time and remain there as long as the class remains loaded. They are not tied to any particular object instance.

54. What happens if you dont initialize an instance variable of any of the primitive types in Java? Page: 7/46 Debjit Sanyal

Java Interview Question & Answer


Java by default initializes it to the default value for that primitive type. Thus an int will be initialized to 0; a Boolean will be initialized to false.

55. Can main method be declared final?


Yes, the main method can be declared final, in addition to being public static.

56. Can an unreachable object become reachable again?


An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

57. What will the access specifier of a variable be by default if it is declared in an Interface?
Final.

58. What if the main method is declared as private?


The program compiles properly but at runtime it will give "Main method not public." message.

59. In System.out.println(), what is System, out and println?


System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

60. What is the difference between yielding and sleeping?


When a task invokes its yield() method of Object class, it returns to the ready state, either from waiting, running or after its creation. When a task invokes its sleep() method of Thread class, it returns to the waiting state from a running state.

61. What invokes a thread's run() method?


After a thread is started, via its start() method of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

62. What are the states associated in the thread?


A thread is an independent path of execution in a system. The high-level thread states are ready, running, waiting and dead.

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

64. What kind of thread is the Garbage collector thread?


It is a daemon thread.

65. What is the difference between a while statement and a do statement?


A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.

Page: 8/46 Debjit Sanyal

Java Interview Question & Answer

66. How would you implement a thread pool?


public class ThreadPool implements ThreadPoolInt This class is an generic implementation of a thread pool, which takes the following input a) Size of the pool to be constructed b) Name of the class which implements Runnable and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool. This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool.

67. What type of parameter passing does Java support?


In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

68. What is shallow copy and deep copy in Java?


Java provides a mechanism for creating copies of objects called cloning. There are two ways to make a copy of an object called shallow copy and deep copy. Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the references are copied. Thus, if the object you are copying contains references to yet other objects, a shallow copy refers to the same sub objects. Deep copy is a complete duplicate copy of an object. If an object has references to other objects, complete new copies of those objects are also made. A deep copy generates a copy not only of the primitive values of the original object, but copies of all sub objects as well, all the way to the bottom. If you need a true, complete copy of the original object, then you will need to implement a full deep copy for the object. Java supports shallow and deep copy with the Cloneable interface to create copies of objects. To make a clone of a Java object, you declare that an object implements Cloneable, and then provide an override of the clone method of the standard Java Object base class. Implementing Cloneable tells the java compiler that your object is Cloneable. The cloning is actually done by the clone method.

69. Difference between String StringBuffer and StringBuilder?


String is immutable whereas StringBuffer and StringBuilder can change their values. The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.

70. What is reflection API? How are they implemented?


Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields and Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.

71. Can you tell some immutable classes in java?


1. The main immutable class is String. 2. Basic numeric classes like Integer, Long, Float, BigInteger and BigDecimal are immutable classes.

72. What is reflection?


Reflection is the ability of a program to analyze itself & environment.

Page: 9/46 Debjit Sanyal

Java Interview Question & Answer 73. What is Enumeration?


An Enumeration is a list of named constant.

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.

76. What is the difference between = = and equals()?


= = does shallow comparison, It retuns true if the two object points to the same address in the memory, i.e if the same the same reference equals() does deep comparison, it checks if the values of the data in the object are same.

77. What is variable-length argument?


A method takes a variable number of arguments is called a variable-arity method of simply a varargs method.

78. What are short-circuit logical operator?


&& and || is short-circuit logical operator.

79. What is static in java?


Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class. Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a super class can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a no static method. In other words, you can't change a static method into an instance method in a subclass.

80. What is different between Thread.currentThread().getContextClassLoader() and Class.getClassLoader()?


From API document, the Thread.currentThread().getContextClassLoader() returns the context ClassLoader for this Thread. The context ClassLoader is provided by the creator of the thread for use by code running in this thread when loading classes and resources. The default is the ClassLoader context of the parent Thread. The context ClassLoader of the primordial thread is typically set to the class loader used to load the application. The context ClassLoader can be set when a thread is created, and allows the creator of the thread to provide the appropriate class loader to code running in the thread when loading classes and resources. For example, JNDI and JAXP used thread's ClassLoader. You had better to use thread's ClassLoader in your own code when your code need to deployed on J2EE container. The Class.getClassLoader() returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader. For example, Class.getResource() and Class.forName() will use the class loader of trhe current caller's class.

81. What happens when you call Thread.yield() ? Page: 10/46 Debjit Sanyal

Java Interview Question & Answer


It caused the currently executing thread to move to the ready state if the scheduler is willing to run any other thread in place of the yielding thread. Yield is a static method of class Thread.

82. What is the advantage of yielding?


It allows a time consuming thread to permit other threads to execute.

83. What happens when you call Thread.sleep ()?


It passes time without doing anything and without using the CPU. A call to sleep method requests the currently executing thread to cease executing for a specified amount of time.

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.

85. What threading related methods are there in object class?


wait(), notify() and notifyAll() are all part of Object class and they have to be called from synchronized code only

86. What are the two ways of synchronizing the code?


Synchronizing an entire method by putting the synchronized modifier in the methods declaration. To execute the method, a thread must acquire the lock of the object that owns the method. Synchronize a subset of a method by surrounding the desired lines of code with curly brackets and inserting the synchronized expression before the opening curly. This allows you to synchronize the block on the lock of any object at all, not necessarily the object that owns the code

87. What happens when the wait() method is called?


The calling thread gives up CPU The calling thread gives up the lock. The calling thread goes into the monitor's waiting pool

88. What happens when the notify() method is called?


One thread gets moved out of monitors waiting pool and into the ready state The thread that was notified us reacquire the monitors lock before it can proceed.

Page: 11/46 Debjit Sanyal

Java Interview Question & Answer

Questions from Servlets.


1. Explain the life cycle methods of a Servlet?
The javax.servlet.Servlet interface defines the three methods known as life-cycle method. public void init(ServletConfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() First the servlet is constructed, then initialized with the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

2. Explain the directory structure of a web application?


The directory structure of a web application consists of two parts. A private directory called WEB-INF a public resource directory which contains public resource folder. WEB-INF folder consists of 1. web.xml 2. classes directory 3. lib directory

3. What is RequestDispatcher? How does it work?


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. RequestDispatcher object can get through getRequestDispatcher method of request object and it has few method like forward, include.

4. How do you send response back to the client from Servlet?


I use sendRedirect method of response object.

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

Java Interview Question & Answer


Web server serves pages for viewing the web browser (i.e. HTML, JSP, ASP etc.) using http protocol. While application server handles business logic, such as transaction processing, messaging, resource pooling, security and messaging etc. Both are accessing via the http request, so from the client view point there no much difference.

8. Difference between single thread and multi thread model servlet?


Typically, a servlet class is instantiated the first time it is invoked. The same instance will be used over several client requests, so all members that are declared in that servlet are shared across clients. That is what is meant by multi threaded model, multiple clients that access the same instance. There are situations where you want to protect your servlet member variables from being modified by different clients. In this case, you can have your servlet implement the marker interface SingleThreadModel. Every time a client makes a request to a servlet that implements this interface, the engine will create a new instance of the servlet. For performance reasons, the engine can also maintain a instance pool, handing out instances as they are needed. Or it could also serialize client requests, executing one after another.

9. What is the difference between servlets and jsp?


In servlet java will be used to generate dynamic HTML pages, but in JSP, java will be reduced and we can use our custom tags to generate HTML pages.

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.

13. Explain ServletContext.


ServletContext interface is a window for a servlet to view its environment. A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

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.

16. What is pre initialization of a servlet? Page: 13/46 Debjit Sanyal

Java Interview Question & Answer


A container doesnt initialize the servlets ass soon as it starts up; it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or pre initializing a servlet.

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.

18. What is the difference between ServletContext and ServletConfig?


ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

19. What's the use of the servlet wrapper classes?


The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behavior is to pass all method calls directly to the underlying objects.

20. What is a deployment descriptor?


A deployment descriptor is an XML document with an .xml extension. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean. The JavaEE server reads the deployment descriptor at run time and acts upon the component accordingly.

21. Should I override the service() method?


We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXxx() method corresponding to the method of the HTTP request. For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXxx() method for the HTTP methods that servlet supports. Because HTTP service method checks the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXxx() method.

22. What is session?


A session refers to all the requests that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.

23. What is Servlet Chaining? Page: 14/46 Debjit Sanyal

Java Interview Question & Answer


Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

24. How are filters?


Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows: Security checks Modifying the request or response Data compression Logging and auditing Response compression Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.

Page: 15/46 Debjit Sanyal

Java Interview Question & Answer

Questions from JSP.


1. What are the advantages of JSP over Servlet?
JSP is a server side technology to make content generation a simple appear. The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.

2. Explain the life-cycle methods in JSP?


The generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. The HttpJspPage interface extends the JspPage interface which in turn extends the Servlet interface of the javax.servlet package. The generated servlet class thus implements all the methods of these three interfaces. The JspPage interface declares only two methods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interface specifically for the JSP pages serving HTTP requests. This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance. The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects. The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called the servlet instance.

3. What JSP lifecycle methods can I override?


You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

4. What are the implicit objects in a JSP?


Implicit object of JSP is request, response, session, page, pageContext, out, application, config, exception etc.

5. How do you handle when 10 requests simultaneously arrive at a Server?


Web container will automatically handle the request.

6. What are JSP directives?


Page, include and taglib are JSP directive.

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?

Page: 16/46 Debjit Sanyal

Java Interview Question & Answer


Normal JSPs page directive should be <%@ page isErrorPage=false %> and Error JSPs page directive should be <% page isErrorPage=true %>.

9. What is action type in JSP?


There is two type of action in JSP. i.e. Standard Action & Custom Action.

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.

11. How do you handle exceptions or errors in JSP?


I create an error page where page directive isErrorPage equal to true. And other normal JSP page directive should be errorPage=error page

12. What is Scope?


Scope is the idea that an object belongs to a certain part of an application. The five main scope of a web application are request, response, page, session, and application. This means that an object may be a part of request, a response, an individual page, a session or an instance of the application. For example, if we said the employee object has session scope, we would mean that the employee object only existed within a certain session.

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

14. What is a thin client?


A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.

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

Page: 17/46 Debjit Sanyal

Java Interview Question & Answer


importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe.

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 %>

18. How is scripting disabled?


Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a sub element of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows: <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group>

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 <%= %>

Page: 18/46 Debjit Sanyal

Java Interview Question & Answer

Questions from JDBC


1. What is the use of Callable Statements and Prepared Statements?
A SQL query can be precompiled and executed by using the Prepared Statement object. The Callable Statement object is used to call a stored procedure from within a J2EE object.

2. How do you call Stored Procedures from Java?


After creating connection create Callable Statement object from connection object. Call execute method of Callable Statement object (call store procedure)

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.

5. What Class.forName will do while loading drivers?


It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

6. What is a transaction?
Transaction: Transaction is a "Logical unit of work". It must performed by "Either all or Nothing.

7. What are the two major components of JDBC?


Two major components of JDBC are Connection Pooling and Data Sources.

Page: 19/46 Debjit Sanyal

Java Interview Question & Answer

Questions from Struts 1.x framework


1. What is Struts?
A web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.

2. How is the MVC design pattern used in Struts framework?


In the MVC design pattern, a central Controller mediates application flow. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model and each handler acts as an adapter between the request and the Model. The Model represents or encapsulates an applications business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans

3. Explain different components of MVC Architechture.


MVC stand for Model View Controller.

4. What are the different XML files that are involved during the usage of validation framework?
Validator.xml and validator_ruls.xml

5. What is the difference between Struts 1.0 and Struts 1.1?


The new features added to Struts 1.1 are 1. RequestProcessor class 2. Method perform() replaced by execute() in Struts base Action Class 3. Changes to web.xml and struts-config.xml 4.Declarative exception handling 5.Dynamic ActionForms 6.Plug-ins 7.Multiple Application Modules 8.Nested Tags 9.The Struts Validator 10.Change to the ORO package 11.Change to Commons logging 12.Removal of Admin actions 13. Deprecation of the GenericDataSource.

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.

Page: 20/46 Debjit Sanyal

Java Interview Question & Answer

7. 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 is done. It is advisable to perform all the database related stuffs in the Action class. The ActionServlet (command) passes the parameterized class to ActionForm 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.

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.

9. What are the important methods of ActionForm?


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

10. 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 FormBean with DynaValidatorForm class.

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


validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Return 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.

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

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.

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


The different kinds of actions in Struts are: ForwardAction IncludeAction DispatchAction LookupDispatchAction SwitchAction

Page: 21/46 Debjit Sanyal

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>

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

17. How to use DispatchAction?


To use the DispatchAction, follow these steps: Create a class that extends DispatchAction (instead of Action) 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. Do not override execute() method Because DispatchAction class itself provides execute() method. Add an entry to struts-config.xml

18. What is the use of ForwardAction?


The ForwardAction class is useful when youre 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 dont have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.

Page: 22/46 Debjit Sanyal

Java Interview Question & Answer 19. 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.

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

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

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

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

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

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

26. How to display validation errors on jsp page?


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

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

28. What are differences between <bean:message> and <bean:write>?


<bean:message>: is used to retrieve keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.

Page: 23/46 Debjit Sanyal

Java Interview Question & Answer


<bean:message key="prompt.customer.firstname"/> <bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body. <bean:write name="customer" property="firstName"/>

29. How the exceptions are handled in struts?


Exceptions in Struts are handled in two ways: Programmatic exception handling: Explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs. Declarative exception handling: You can either define <global-exceptions> handling tags in your struts-config.xml or define the exception handling tags within <action></action> tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions. <global-exceptions> <exception key="some.key" type="java.lang.NullPointerException" path="/WEB-INF/errors/null.jsp"/> </global-exceptions>
OR

<exception key="some.key" type="package.SomeException" path="/WEB-INF/somepage.jsp"/>

30. What is difference between ActionForm and DynaActionForm?


An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger. The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment. ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file. ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter(). DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

31. What is the life cycle of ActionForm?


The lifecycle of ActionForm invoked by the RequestProcessor is as follows: Retrieve or Create Form Bean associated with Action "Store" FormBean in appropriate scope (request or session) Reset the properties of the FormBean Populate the properties of the FormBean Validate the properties of the FormBean Pass FormBean to Action

Page: 24/46 Debjit Sanyal

Java Interview Question & Answer

Questions from JSF


1. What is JSF (or JavaServer Faces)?
A server side user interface component framework for Java technology-based web applications. JavaServer Faces (JSF) is an industry standard and a framework for building component-based user interfaces for web applications. JSF contains an API for representing UI components and managing their state; handling events, serverside validation, and data conversion; defining page navigation; supporting internationalization and accessibility; and providing extensibility for all these features.

2. What are the advantages of JSF?


The major benefits of JavaServer Faces technology are: JavaServer Faces architecture makes it easy for the developers to use. In JavaServer Faces technology, user interfaces can be created easily with its built-in UI component library, which handles most of the complexities of user interface management. Offers a clean separation between behavior and presentation. Provides a rich architecture for managing component state, processing component data, validating user input, and handling events. Robust event handling mechanism. Events easily tied to server-side code. Render kit support for different clients Component-level control over state fullness Highly 'pluggable' - components, view handler, etc JSF also supports internationalization and accessibility Offers multiple, standardized vendor implementations

3. What are differences between struts and JSF?


In a nutshell, Faces has the following advantages over Struts: Eliminated the need for a Form Bean Eliminated the need for a DTO Class Allows the use of the same POJO on all Tiers because of the Backing Bean

4. What are the available implementations of JavaServer Faces?


The main implementations of JavaServer Faces are: Reference Implementation (RI) by Sun Microsystems. Apache MyFaces is an open source JavaServer Faces (JSF) implementation or run-time. ADF Faces is Oracles implementation for the JSF standard.

5. What is Managed Bean?


JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed. It has nothing to do with the bean's functionalities.

Page: 25/46 Debjit Sanyal

Java Interview Question & Answer

6. What is Backing Bean?


Backing beans are JavaBeans components associated with UI components used in a page. Backingbean management separates the definition of UI component objects from objects that perform application-specific processing and hold data. The backing bean defines properties and handling-logics associated with the UI components used on the page. Each backing-bean property is bound to either a component instance or its value. A backing bean also defines a set of methods that perform functions for the component, such as validating the component's data, handling events that the component fires and performing processing associated with navigation when the component activates.

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 backing bean is any bean that is referenced by a form.

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,

Backing Beans should be defined only in the request scope

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.

8. What is view object?


A view object is a model object used specifically in the presentation tier. It contains the data that must display in the view layer and the logic to validate user input, handle events, and interact with the business-logic tier. The backing bean is the view object in a JSF-based application. Backing bean and view object are interchangeable terms.

9. What are the JSF life-cycle phases?


The six phases of the JSF application lifecycle are as follows (note the event processing at each phase):

Page: 26/46 Debjit Sanyal

Java Interview Question & Answer


1. 2. 3. 4. 5. 6. Restore view Apply request values; process events Process validations; process events Update model values; process events Invoke application; process events Render response

10. What does it mean by render kit in JSF?


A render kit defines how component classes map to component tags that are appropriate for a particular client. The JavaServer Faces implementation includes a standard HTML render kit for rendering to an HTML client.

11. Is it possible to have more than one Faces Configuration file?


We can have any number of config files. Just need to register in web.xml. Assume that we want to use faces-config(1,2,and 3),to register more than one faces configuration file in JSF, just declare in the web.xml file

Page: 27/46 Debjit Sanyal

Java Interview Question & Answer

Questions from Portal & Portlet


1. What is a Portlet? Explain its capabilities.
Portlets are UI components that are pluggable and are managed, displayed in a web portal. Markup code fragments are produced by the portlets which are aggregated into a portal page. A portlet resembles an application that is web based and is hosted in a portal. Email, discussion forums, news, blogs, weather reports are some of the examples of portlets.

2. Explain Portal architecture.


The core implementation of the portal is UI, hosted by a Portal server. The HTTP requests, HTML responses, and returning appropriate portal pages are handled by the Portal UI. Enterprise Web application also can be handled by the Portal Server. The portal architecture has the following: Automaton Server: This server performs the management of job scheduling and implementation of a portal. It accesses all remote crawlers and profile services retrieved and stored from a remote database. Image Server: This server hosts images and other web page content used by web services and a portal. With this configuration, large static files are to be sent directly to the browser without portal server impacts. Search Server: This server indexes and searches all the information, applications, communities, documents, web sites through portal. Collaboration Server: Web content publication and management for portals and web applications are supported by this server. Its functionality can be accessed by a remote web services through Enterprise Web Development kit. Content Server: Publication and management of web content for portals and web applications along with form based publishing, branding, templates, content expiration is allowed by this server. Authentication Server: This server handles the portal authentication for users and remote services can be accessed through EDK. Remote Servers: Web services written using the EDK are hosted by remote servers. The servers can be in different countries, on different platforms and domains.

3. What is PortletSession interface?


User identification across many requests and transient information storage about the user is processed by PortletSession interface. One PortletSession is created per portlet application per client. The PortletSession interface provides a way to identify a user across more than one request and to store transient information about that user. The storing of information is defined in two scopes- APPLICATION_SCOPE and PORTLET_SCOPE. APPLICATION_SCOPE: All the objects in the session are available to all portlets, servlets, JSPs of the same portlet application, by using APPLICATION_SCOPE. PORTLET_SCOPE: All the objects in the session are available to the portlet during the requests for the same portlet window. The attributes persisted in the PORTLET_SCOPE are not protected from other web components.

4. What is PortletContext interface? Page: 28/46 Debjit Sanyal

Java Interview Question & Answer


The portlet view of the portlet container is defined by PortletContext. It allows the availability of resources to the portlet. Using this context, the portlet log can be accessed and URL references to resources can be obtained. There is always only one context per portlet application per JVM.

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.

6. Explain the types of portals, Function-based portals and User-based portals


Function-based portals Horizontal Portals: These are the portals are of type general interest. Yahoo!,Lycos,AOL,Freeserve,Sympatico are examples of horizontal portals. Vertical Portals They provide a gateway to the information pertaining to a specific industry such as insurance, banking, finance, automobile, telecom etc. User-Based Portals B2B Portals The enterprises extend to suppliers and partners by using B2B portals. B2C Portals The enterprises extend to customers for ordering, billing, services by using B2C portals. B2E Portals The enterprise knowledge base integration and related applications into user customizable environment is done with B2E portals. This environment is like one stop shop.

Page: 29/46 Debjit Sanyal

Java Interview Question & Answer

Questions from EJB


1. What are the different kinds of enterprise beans?
Different kinds of enterprise beans are Stateless session bean, Stateful session bean, Entity bean, and Message-driven bean.

2. What is Session Bean?


A session bean represents a single client inside the Application Server. To access an application that is deployed on the server, the client invokes the session beans methods. The session bean performs work for its client, shielding the client from complexity by executing business tasks inside the server.

3. What is Entity Bean?


An entity bean represents a business object in a persistent storage mechanism. Some examples of business objects are customers, orders, and products. In the Application Server, the persistent storage mechanism is a relational database. Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table.

4. What is a Message-Driven Bean?


A message-driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it receives messages instead of events. The messages may be sent by any J2EE component--an application client, another enterprise bean, or a Web component--or by a JMS application or system that does not use J2EE technology.

5. What Makes Entity Beans Different from Session Beans?


Entity beans differ from session beans in several ways. Entity beans are persistent, allow shared access, have primary keys, and can participate in relationships with other entity beans.

6. What is bean-managed transaction?


If a developer doesnt want a container to manage transactions, its possible to implement all database operations manually.

7. How EJB invocations happen?


Step 1: Retrieve Home Object reference from Naming Service via JNDI. Step 2: Return Home Object reference to the client. Step 3: Create a new EJB Object through Home Object interface. Step 4: Create EJB Object from the Ejb Object. Step 5: Return EJB Object reference to the client. Step 6: Invoke business method using EJB Object reference. Step 7: Delegate request to Bean (Enterprise Bean).

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

Page: 30/46 Debjit Sanyal

Java Interview Question & Answer


references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice. In terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejbs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it.

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)

11. Can you control when passivation occurs?


The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a strategy to control passivation. The ejbPassivate () method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic.

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.

13. What is EJB QL?


EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence.

14. Brief description about local interfaces? Page: 31/46 Debjit Sanyal

Java Interview Question & Answer


Many developers are using EJBs locally -- that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which colocation is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.

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.

16. What happens if remove ( ) is never invoked on a session bean?


In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The container manages the number of beans in cache. In case of Stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.

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.

19. What is an EJB Context?


EJB Context is an interface that is implemented by the container, and it is also a part of the beancontainer contract. Entity beans use a subclass of EJB Context called Entity Context. Session beans use a subclass called Session Context. These EJB Context objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions.

20. What are the methods of Entity Bean?


An entity bean consists of 4 groups of methods: 1. Create methods 2. finder methods 3. remove methods 4. home methods

Page: 32/46 Debjit Sanyal

Java Interview Question & Answer

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();

23. What is software architecture of EJB?


Session and Entity EJBs consist of 4 and 5 parts respectively: 1. A remote interface (a client interacts with it), 2. A home interface (used for creating objects and for declaring business methods), 3. A bean objects (an object, which actually performs business logic and EJB-specific operations). 4. A deployment descriptor (an XML file containing all information required for maintaining the EJB) or a set of deployment descriptors (if you are using some container-specific features). 5. A Primary Key class - is only Entity bean specific.

24. Can Entity Beans have no create() methods?


Yes. In some cases the data is inserted not using Java application, so you may only need to retrieve the information, perform its processing, but not create your own information of this kind.

25. What is bean-managed transaction?


If a developer doesn't want a Container to manage transactions, it's possible to implement all database operations manually by writing the appropriate JDBC code. This often leads to productivity increase, but it makes an Entity Bean incompatible with some databases and it enlarges the amount of code to be written. A developer explicitly performs all transaction management.

26. What are transaction attributes?


1. NotSupported - transaction context is unspecified. 2. Required - bean's method invocation is made within a transactional context. If a client is not associated with a transaction, a new transaction is invoked automatically.

Page: 33/46 Debjit Sanyal

Java Interview Question & Answer


3. Supports - if a transactional context exists, a Container acts like the transaction attribute is Required, else - like NotSupported. 4. RequiresNew - a method is invoked in a new transaction context. 5. Mandatory - if a transactional context exists, a Container acts like the transaction attribute is Required, else it throws a javax.ejb.TransactionRequiredException. 6. Never - a method executes only if no transaction context is specified.

27. What are transaction isolation levels in EJB?


1. Transaction_read_uncommitted- Allows a method to read uncommitted data from a DB (fast but not wise). 2. Transaction_read_committed: - Guarantees that the data you are getting has been committed. 3. Transaction_repeatable_read: - Guarantees that all reads of the database will be the same during the transaction (good for read and update operations). 4. Transaction_Serializable: - All the transactions for resource are performed serial.

28. How many type of container in Java?


There are five defined container types in the J2EE specification. Three of these are server-side containers: The server itself, which provides the J2EE runtime environment and the other two containers. An EJB container to manage EJB components. A Web container to manage servlets and JavaServer Pages.

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.

Page: 34/46 Debjit Sanyal

Java Interview Question & Answer

Questions from Hibernate


1. How will you configure Hibernate?
The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files *.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap hibernate) the SessionFactory, which in turn creates the Session instances. Session instances are the primary interface for the persistence service. hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to configure the hibernate service (connection driver class, connection URL, connection username, connection password, dialect etc). If both files are present in the classpath then hibernate.cfg.xml file overrides the settings found in the hibernate.properties file. Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational database. It is the best practice to store each object in an individual mapping file (i.e mapping file per class) because storing large number of persistent classes into one mapping file can be difficult to manage and maintain. The naming convention is to use the same name as the persistent (POJO) class name. For example Account.class will have a mapping file named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your persistent class code instead of the *.hbm.xml files.

2. What is a SessionFactory? Is it a thread-safe object?


Session is a light weight and a non-thread safe object (No, you cannot share it between threads) that represents a single unit-of-work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method. & public class HibernateUtil { & public static final ThreadLocal local = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session session = (Session) local.get(); //open a new session if this thread has no session if(session == null) { session = sessionFactory.openSession(); local.set(session); } return session; } } It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy.

3. What are the benefits of detached objects?


Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session.

Page: 35/46 Debjit Sanyal

Java Interview Question & Answer

4. What are the pros and cons of detached objects?


Pros:

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.

9. What is Hibernate Query Language (HQL)?


Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

10. What are the general considerations or best practices for defining your Hibernate persistent classes?

Page: 36/46 Debjit Sanyal

Java Interview Question & Answer


1. You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e. accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persist able instance variables. 2. You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object. 3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster. 4. The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects. 5. Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

11. What is the general flow of Hibernate communication with RDBMS?


The general flow of Hibernate communication with RDBMS is: Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files Create session factory from configuration object Get one session from this session factory Create HQL Query Execute query to get list containing Java objects

12. What role does the SessionFactory interface play in Hibernate?


The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole applicationcreated during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory();

13. What are the Core interfaces are of Hibernate framework?


The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions. Session interface SessionFactory interface Configuration interface Transaction interface Query and Criteria interfaces

14. What role does the Session interface play in Hibernate?


The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface role: Wraps a JDBC connection Factory for Transaction

Page: 37/46 Debjit Sanyal

Java Interview Question & Answer


Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

15. Whats the difference between load() and get()?


load() get()

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.

16. What is the difference between and merge and update?


Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

17. What are the Collection types in Hibernate?


Bag, Set, List, Array, Map

18. What are the ways to express joins in HQL?


HQL provides four ways of expressing (inner and outer) joins:An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.

19. Define cascade and inverse option in one-many mapping?


cascade - enable operations to cascade to child entities. cascade ="all | none | save-update |delete |all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true | false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

20. What is Hibernate proxy?


The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

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.

Page: 38/46 Debjit Sanyal

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.

24. What do you mean by fetching strategy?


A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

25. What is automatic dirty checking?


Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

26. What is transactional write-behind?


Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.

27. What are Callback interfaces?


Callback interfaces allow the application to receive a notification when something interesting happens to an objectfor example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

28. What are the types of Hibernate instance states?


Three types of instance states: Transient -The instance is not associated with any persistence context Persistent -The instance is associated with a persistence context Detached -The instance was associated with a persistence context which has been closed currently not associated

29. What are the types of inheritance models in Hibernate?


There are three types of inheritance models in Hibernate: Table per class hierarchy Table per subclass Table per concrete class

Page: 39/46 Debjit Sanyal

Java Interview Question & Answer

Questions from Web Service


What are Web Services?
Web services are application components Web services communicate using open protocols Web services are self-contained and self-describing Web services can be discovered using UDDI Web services can be used by other applications XML is the basis for Web services

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

Can business method of the implementing class be static or final?


No

How many development styles are there in web service?


There are two type of development style. Top down development style. (Contract first approach)

Page: 40/46 Debjit Sanyal

Java Interview Question & Answer


Bottom up development style. (Code first approach)

What is the difference between JAX--WS and JAX-RPC?


Java API for XML-Based RPC (JAX-RPC) is a Legacy Web Services Java API, it uses SOAP and HTTP to do RPCs over the network and enables building of Web services and Web applications based on the SOAP 1.1 specification, Java SE 1.4 or lower. JAX-WS 2.0 is the successor to JAXRPC 1.1. JAX-WS still supports SOAP 1.1 over HTTP 1.1, so interoperability will not be affected. However there are lots of differences: AX-WS maps to Java 5.0 and relies on many of the features new in Java 5.0 like Web Service annotations. JAX-RPC has its own data mapping model, JAX-WS's data mapping model is JAXB. JAXB promises mappings for all XML schemas. JAX-WS introduces message-oriented functionality, dynamic asynchronous functionality which is missing in JAX-RPC. JAX-WS also add support, via JAXB, for MTOM, the new attachment specification.

What is Apache Axis2?


Apache Axis2 is a Web Service engine for deploying the web services.

What is full form of REST?


REpresentational State Transfer.

Page: 41/46 Debjit Sanyal

Java Interview Question & Answer

Questions from Spring


1. What is IOC (or Dependency Injection)?
The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

2. What are the different types of IOC (dependency injection)?


Constructor Injection: Dependencies are provided as constructor parameters. Setter Injection (e.g. spring): Dependencies are assigned through JavaBeans properties. Interface Injection (e.g. Avalon): Injection is done through an interface.

3. What are the types of Dependency Injection Spring supports?


Setter Injection: Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. Constructor Injection: Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator.

4. What are the benefits of IOC (Dependency Injection)?


Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration.

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.

Page: 42/46 Debjit Sanyal

Java Interview Question & Answer


Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own. IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

5. What is Bean Factory?


A Bean Factory is like a factory class that contains a collection of beans. The Bean Factory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients. Bean Factory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. Bean Factory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

6. What is Application Context?


A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory. Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides: A means for resolving text messages, including support for internationalization. A generic way to load file resources. Events to beans that are registered as listeners.

7. What is the difference between Bean Factory and Application Context?


On the surface, an application context is same as a bean factory. But application context offers much more. Application contexts provide a means for resolving text messages, including support for i18n of those messages. Application contexts provide a generic way to load file resources, such as images. Application contexts can publish events to beans that are registered as listeners. Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. Resource Loader support: Springs Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a Resource Loader, Hence provides an application with access to deployment-specific Resource instances. Message Source support: The application context implements Message Source, an interface used to obtain localized messages, with the actual implementation being pluggable

8. What are features of spring?


Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible. Inversion of control (IOC):

Page: 43/46 Debjit Sanyal

Java Interview Question & Answer


Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects. Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services. Container: Spring contains and manages the life cycle and configuration of application objects. MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework. Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments. JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBaties: Spring provides best Integration services with Hibernate, JDO and iBaties

9. How many modules are there in spring? What are they?


The core container: The core container provides the essential functionality of the Spring framework. A primary component of the core container is the BeanFactory, an implementation of the Factory pattern. The BeanFactory applies the Inversion of Control (IOC) pattern to separate an application's configuration and dependency specification from the actual application code. Spring context: The Spring context is a configuration file that provides context information to the Spring framework. The Spring context includes enterprise services such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality. Spring AOP: The Spring AOP module integrates aspect-oriented programming functionality directly into the spring framework, through its configuration management feature. As a result you can easily AOPenable any object managed by the spring framework. The Spring AOP module provides

Page: 44/46 Debjit Sanyal

Java Interview Question & Answer


transaction management services for objects in any Spring-based application. With Spring AOP you can incorporate declarative transaction management into your applications without relying on EJB components. Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception hierarchy for managing the exception handling and error messages thrown by different database vendors. The exception hierarchy simplifies error handling and greatly reduces the amount of exception code you need to write, such as opening and closing connections. Spring DAO's JDBC-oriented exceptions comply to its generic DAO exception hierarchy. Spring ORM: The Spring framework plugs into several ORM frameworks to provide its Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these comply to Spring's generic transaction and DAO exception hierarchies. Spring Web module: The Web context module builds on top of the application context module, providing contexts for Web-based applications. As a result, the spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects. Spring MVC framework: The Model-View-Controller (MVC) framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI.

10. What are the common implementations of the Application Context?


ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as class path resources. The application context is loaded from the application's classpath by using the code. ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

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 :

Page: 45/46 Debjit Sanyal

Java Interview Question & Answer


It loads context definition from an XML file contained within a web application.

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.

12. What do you mean by Auto Wiring?


The spring container is able to auto wire relationships between collaborating beans. This means that it is possible to automatically let spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The auto wiring functionality has five modes. no by Name by Type constructor auto direct

13. What are Bean scopes in Spring Framework?


The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). The scopes supported are listed below: Singleton - : Scopes a single bean definition to a single object instance per Spring IoC container. Prototype - : Scopes a single bean definition to any number of object instances. Request - : Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware SpringApplicationContext. Session - : Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware SpringApplicationContext. Global session - : Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Page: 46/46 Debjit Sanyal

Das könnte Ihnen auch gefallen