Java All Interview Question Prepared by Abhinav
Short Description
Java All Interview Question Prepared by Abhinav...
Description
TABLE OF CONTENT
page
1. class and interface Based Interview Questions
1-11
2. JDBC Interview Questions
12-18
3. SERVLET FAQ 1
19-27
4.SERVLET FAQ 2
28-34
5.SESSION FAQ
34-37
6. JSP FAQ
38-47
7.STRUTS FAQ1
48-63
8.STRUTS FAQ2
64-88
9.SPRING FAQ 10. JAVA FAQ1
89-98
11.JAVA FAQ2
99-110
12.OOP FAQ
111-113
13.SPRING FAQ
114-117
14.EXCEPTION FAQ
118-124
15 COLLECTION FAQ
125-130
16 COLLECTION FAQ2 17 MULTI THREADING FAQ 18 OBJECT BASED FAQ 19 http://java4732.blogspot.in
131-140 141-154
20 GARBAGE COLLCETION FAQ 21 SERIALIZATION FAQ http://www.developersbook.com/
class and interface Based Interview Questions 1. What's the difference between an interface and an abstract class? An abstract class may contain code in method bodies, which is not allowed in an interface. With abstract classes, you have to inherit your class from it and Java does not allow multiple inheritance. On the other hand, you can implement multiple interfaces in your class. 2. Can an inner class declared inside of a method access local variables of this method? Yes, it is possible if the variables are declared as final. 3. You can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. So can you use abstract classes instead of interfaces? Sometimes. But your class may be a descendent of another class and in this case the interface is your only option because Java does not support multiple inheritance. 4. What access level do you need to specify in the class declaration to ensure that only classes from the same directory can access it? You do not need to specify any access level, and Java will use a default package access level. A class with default access will be accessible only to other classes that are declared in the same directory/package. 5. When you declare a method as abstract method ? We declare a method as abstract, When we want child class to implement the behavior of the method.
6. Can I call a abstract method from a non abstract method ? Yes, We can call a abstract method from a Non abstract method in a Java abstract class 7. What is the difference between an Abstract class and Interface in Java ? or can you explain when you use Abstract classes ? Abstract classes let you define some behavior while forcing your subclasses to provide the rest. These abstract classes will provide the basic funcationality of your application, child class which inherit this class will provide the funtionality of the abstract methods in abstract class. Whereas, An Interface can only declare constants and instance methods, but cannot implement any default behavior. If you want your class to extend some other class but at the same time re-use some features outlined in a parent class/interface - Interfaces are your only option because Java does not allow multiple inheritance and once you extend an abstract class, you cannot extend any other class. But, if you implement an interface, you are free to extend any other concrete class as per your wish. Also, Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. Abstract classes are fast. 8. What are different types of inner classes ? Inner classes nest within other classes. A normal class is a direct member of a package. Inner classes are of four types 1. Static member classes 2. Member classes 3. Local classes 4. Anonymous classes 9. What are the field/method access levels (specifiers) and class access levels ?
Each field and method has an access level corresponding to it: private: accessible only in this class package: accessible only in this package protected: accessible only in this package and in all subclasses of this class public: accessible everywhere this class is available Similarly, each class has one of two possible access levels: package: class objects can only be declared and manipulated by code in this package public: class objects can be declared and manipulated by code in any package 10. What modifiers may be used with an inner class that is a member of an outer class? A non-local inner class may be declared as public, protected, private, static, final, or abstract. 11. Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. 12. What must a class do to implement an interface? It must provide implementation to all of the methods in the interface and identify the interface in its implements clause in the class declaration line of code. 13. What is the difference between a static and a non-static inner class? A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances. 14. When can an object reference be cast to an interface reference? An object reference be cast to an interface reference when the object implements the referenced interface.
15. If a class is declared without any access modifiers, where may the class be accessed? A class that is declared without any access modifiers is said to have default or package level access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. 16. Which class should you use to obtain design information about an object? The Class class is used to obtain information about an object's design. 17. What modifiers may be used with an interface declaration? An interface may be declared as public or abstract. 18. Is a class a subclass of itself? Yes, a class is a subclass of itself. 19. What modifiers can be used with a local inner class? A local inner class may be final or abstract. 20. Can an abstract class be final? An abstract class may not be declared as final. Abstract and Final are two keywords that carry totally opposite meanings and they cannot be used together. 21. What is the difference between a public and a non-public class? A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package. 22. What modifiers may be used with a top-level class? A top-level class may be public, abstract, or final. 23. What are the Object and Class classes used for? The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.
24. Can you make an instance of abstract class No you cannot create an instance of abstract class. If you use new keyword to instantiate an abstract class, you will get a compilation error. 25. Describe what happens when an object is created in Java Several things happen in a particular order to ensure the object is created properly: 1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data. 2. The instance variables of the objects are initialized to their default values. 3. The constructor for the most derived class is invoked. The first thing a constructor does is call the consctructor for its superclasses. This process continues until the constrcutor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. 4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last. 26. What is the purpose of System Class The purpose of the system class is to provide the access to the System reources 27. What is instanceOf operator used for It is used to check if an object can be cast into a specific type without throwing Class cast exception
28. Why we should not have instance variable in an interface? Since all data fields and methods in an Interface are public by default, when we implement that interface in our class, we have public members in our class and this class will expose these data members and this is violation of encapsulation as now the data is not secure 29. What is a singleton class A singleton is an object that cannot be instantiated more than once. The restriction on the singleton is that there can be only one instance of a singleton created by the Java Virtual Machine (JVM) - by prevent direct instantiation we can ensure that developers don't create a second copy. We accomplish this by declaring the constructor private and having a public static instance variable of the class's type that can be accessed using a getInstance() method in the class. 30. Can an abstract class have final method Yes, you can have a final method in an Abstract class. 31. Can a final class have an abstract method No, a Final class cannot have an Abstract method. 32. When does the compiler insist that the class must be abstract The compiler insists that your class be made abstract under the following circumstances: 1. If one or more methods of the class are abstract. 2. If class inherits one or more abstract methods from the parent abstract class and no implementation is provided for that method 3. If class implements an interface and provides no implementation for some methods 33. How is abstract class different from final class Abstract class must be subclassed and an implementation has to be provided by the child class whereas final class cannot be subclassed 34. What is an inner class
An inner class is same as any other class, just that, is declared inside some other class 35. How will you reference the inner class To reference an inner class you will have to use the following syntax: OuterClass$InnerClass 36. Can objects that are instances of inner class access the members of the outer class Yes they can access the members of the outer class 37. Can inner classes be static Yes inner classes can be static, but they cannot access the non static data of the outer classes, though they can access the static data. 38. Can an inner class be defined inside a method Yes it can be defined inside a method and it can access data of the enclosing methods or a formal parameter if it is final 39. What is an anonymous class Some classes defined inside a method do not need a name, such classes are called anonymous classes. 40. What are access modifiers These public, protected and private, these can be applied to class, variables, constructors and methods. But if you don't specify an access modifier then it is considered as Friendly. They determine the accessibility or visibility of the entities to which they are applied. 41. Can protected or friendly features be accessed from different packages No when features are friendly or protected they can be accessed from all the classes in that package but not from classes in another package. 42. How can you access protected features from another package
You can access protected features from other classes by subclassing the that class in another package, but this cannot be done for friendly features.
---------------------------------------------------------------------------------------------------------------------------------JDBC Interview Questions 1- What is JDBC? Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database.
Why use JDBC- Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language). 2- What is JDBC Driver? JDBC Driver is a software component that enables java application to interact with the database.There are 4 types of JDBC drivers: JDBC-ODBC bridge driver
Native-API driver (partially java driver) Network Protocol driver (fully java driver) Thin driver (fully java driver) 1) JDBC-ODBC bridge driver The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.
Advantages: easy to use. can be easily connected to any database. Disadvantages: Performance degraded because JDBC method call is converted into the ODBC function calls. The ODBC driver needs to be installed on the client machine. 2) Native-API driver The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage: performance upgraded than JDBC-ODBC bridge driver. Disadvantage: The Native driver needs to be installed on the each client machine. The Vendor client library needs to be installed on client machine. 3) Network Protocol driver The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage: No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.
Disadvantages: Network support is required on client machine. Requires database-specific coding to be done in the middle tier. Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier. 4) Thin driver The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.
Advantage: Better performance than all other drivers. No software is required at client side or server side. Disadvantage: Drivers depends on the Database. 3- What are the steps to connect to the database in java? There are 5 steps to connect any java application with the database in java using JDBC. They are as follows: Register the driver class Creating connection Creating statement
Executing queries Closing connection 4- What are the JDBC API components? The java.sql package contains interfaces and classes for JDBC API. Interfaces: Connection Statement PreparedStatement ResultSet ResultSetMetaData DatabaseMetaData CallableStatement etc. Classes: DriverManager Blob Clob Types SQLException etc. 5- What are the JDBC statements? There are 3 JDBC statements. Statement PreparedStatement CallableStatement 6- What is the difference between Statement and PreparedStatement interface? In case of Statement, query is complied each time whereas in case of PreparedStatement, query is complied only once. So performance of PreparedStatement is better than Statement. 7- How can we execute stored procedures and functions?
By using Callable statement interface, we can execute procedures and functions. 8- What is the role of JDBC DriverManager class? The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection. 9- What does the JDBC Connection interface? The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData. 10- What does the JDBC ResultSet interface? The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database. 11- What does the JDBC ResultSetMetaData interface? The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc. 12- What does the JDBC DatabaseMetaData interface? The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc. 13- Which interface is responsible for transaction management in JDBC? The Connection interface provides methods for transaction management such as commit(), rollback() etc. 14- What is batch processing and how to perform batch processing in JDBC? By using batch processing technique in JDBC, we can execute multiple queries. It makes the performance fast.
15- How can we store and retrieve images from the database? By using PreparedStatement interface, we can store and retrieve images.
----------------------------------------------------------------------------------------------------------------------------------------
Servlet interview Questions - 1 1- How many objects of a servlet is created? Only one object at the time of first request by servlet or web container. 2- What is the life-cycle of a servlet? The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet: Servlet class is loaded. Servlet instance is created. init method is invoked. service method is invoked. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state. 1) Servlet class is loaded The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2) Servlet instance is created The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException 4) service method is invoked The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException 5) destroy method is invoked The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below: public void destroy() 3- What are the life-cycle methods for a servlet? public void init(ServletConfig config) It is invoked only once when first request comes for the servlet. It is used to initialize the servlet. public void service(ServletRequest request,ServletResponse)throws ServletException,IOException It is invoked at each request.The service() method is used to service the request. public void destroy() It is invoked only once when servlet is unloaded.
4- Who is responsible to create the object of servlet? The web container or servlet container. 5- When servlet object is created? At the time of first request. 6- What is difference between Get and Post method? Get 1) Limited amount of data can be sent because data is sent in header. 2) Not Secured because data is exposed in URL bar. 3) Can be bookmarked 4) Idempotent 5) It is more efficient and used than Post Post 1) Large amount of data can be sent because data is sent in body. 2) Secured because data is not exposed in URL bar. 3) Cannot be bookmarked 4) Non-Idempotent 5) It is less efficient and used 7- What is difference between PrintWriter and ServletOutputStream? PrintWriter is a character-stream class where as ServletOutputStream is a bytestream class. The PrintWriter class can be used to write only character-based information whereas ServletOutputStream class can be used to write primitive values as well as character-based information. 8- What is difference between GenericServlet and HttpServlet? The GenericServlet is protocol independent whereas HttpServlet is HTTP protocol specific. HttpServlet provides additional functionalities such as state management etc. 9- What is servlet collaboration? When one servlet communicates to another servlet, it is known as servlet collaboration. There are many ways of servlet collaboration:
RequestDispacher interface sendRedirect() method etc. 10- What is the purpose of RequestDispatcher Interface? The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interceptor can also be used to include the content of antoher resource. 11- Can you call a jsp from the servlet? Yes, one of the way is RequestDispatcher interface for example: RequestDispatcher rd=request.getRequestDispatcher("/login.jsp"); rd.forward(request,response); 12- Difference between forward() method and sendRedirect() method ? forward() method 1) forward() sends the same request to another resource.2) forward() method works at server side. 3) forward() method works within the server only. sendRedirect() method 1) sendRedirect() method sends new request always because it uses the URL bar of the browser. 2) sendRedirect() method works at client side 3) sendRedirect() method works within and outside the server. 13- What is difference between ServletConfig and ServletContext? The container creates object of ServletConfig for each servlet whereas object of ServletContext is created for each web application. 14- What is Session Tracking? Session simply means a particular interval of time. Session Tracking is a way to maintain state of an user.Http protocol is a stateless protocol.Each time user requests to the server, server treats the request as the new request.So we need to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
Why use Session Tracking? To recognize the user It is used to recognize the particular user. Session Tracking Techniques There are four techniques used in Session tracking: Cookies Hidden Form Field URL Rewriting HttpSession 15- What are Cookies? There are 2 types of cookies in servlets. Non-persistent cookie Persistent cookie Non-persistent cookie It is valid for single session only. It is removed each time when user closes the browser. Persistent cookie It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.
Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage of Cookies It will not work if cookie is disabled from the browser. Only textual information can be set in Cookie object. 16- What is difference between Cookies and HttpSession? Cookie works at client side whereas HttpSession works at server side. 17- What is filter? A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc. 18- How can we perform any action at the time of deploying the project? By the help of ServletContextListener interface. 19- What is the disadvantage of cookies? It will not work if cookie is disabled from the browser. 20- How can we upload the file to the server using servlet? One of the way is by MultipartRequest class provided by third party. 21- What is load-on-startup in servlet? The load-on-startup element of servlet in web.xml is used to load the servlet at the time of deploying the project or server start. So it saves time for the response of first request. 22- What if we pass negative value in load-on-startup? It will not affect the container, now servlet will be loaded at first request. 23- What is war file? A war (web archive) file specifies the web elements. A servlet or jsp project can
be converted into a war file. Moving one servlet project from one place to another will be fast as it is combined into a single file. 24- How to create war file? The war file can be created using jar tool found in jdk/bin directory. If you are using Eclipse or Netbeans IDE, you can export your project as a war file. To create war file from console, you can write following code. jar -cvf abc.war * 25- What are the annotations used in Servlet 3? There are mainly 3 annotations used for the servlet. @WebServlet : for servlet class. @WebListener : for listener class. @WebFilter : for filter class. 26- Which event is fired at the time of project deployment and undeployment? ServletContextEvent. 27- Which event is fired at the time of session creation and destroy? HttpSessionEvent. 28- Which event is fired at the time of setting, getting or removing attribute from application scope? ServletContextAttributeEvent. 29- What is the use of welcome-file-list? It is used to specify the welcome file for the project. 30- What is the use of attribute in servlets? Attribute is a map object that can be used to set, get or remove in request, session or application scope. It is mainly used to share information between one servlet to another.
-------------------------------------------------------------------------------------------------------------------------------------Servlet interview Questions - 2 1- What is a Servlet? Java Servlets is a Server side technology(basically specification) that allow the programmer to develop dynamic web resource program or server side web resource program in Java based web application.
Servlet is the software specification given by sun microsystem that provide set of rule and guideline for vendor company to develop software called servlet container. Servlet is single instance multiple threads based java component in Java web application to generate dynamic web application. 2- What are the types of Servlet? There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of
GenericServlet and provides http protocl specific functionality. 3- What are the differences between a Servlet and an Applet? 1) Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser. 2)Applets have GUI interface but there is no GUI interface in case of Servlets. 3)Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety of operations 4)Servlets can perform operations like interacting with other servlets, JSP Pages, connect to databases etc while Applets cannot do all this.
4- What are the different methods present in a HttpServlet? The methods of HttpServlet class are : doGet() - To handle the GET, conditional GET, and HEAD requests doPost() - To handle POST requests doPut() - To handle PUT requests doDelete() - To handle DELETE requests doOptions() - To handle the OPTIONS requests and doTrace() - To handle the TRACE requests Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and destroy the servlet respectively. They are not any operation specific and are available in all Servlets for use during their active life-cycle.
5- What are the advantages of Servlets over CGI programs? Java Servlets have a number of advantages over CGI and other API's. Some are: 1. Platform Independence - Java Servlets are 100% pure Java, so it is platform independent. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server without modification code. Platform independency of servlets provide a great advantages over alternatives of servlets. 2. Performance - Anyone who has used CGI would agree that Servlets are much more powerful and quicker than CGI. Because the underlying technology is Java, it is fast and can handle multiple request simultaneously. Also, a servlet gets initialized only once in its lifetime and then continues to serve requests without having to be re-initialized again, hence the performance is much higher than CGIs. 3. Extensibility - Java Servlets are developed in java which is robust, welldesigned and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions. Also, in terms of Safety & Security Servlets are superior when compared to CGI. 6- What are the type of protocols supported by HttpServlet? It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol. 7- What is ServletContext? ServletContext is an Interface that 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. There is one context per "web application" per Java Virtual Machine.
8- What is meant by Pre-initialization of Servlet? When servlet container is loaded, all the servlets defined in the web.xml file do not get initialized by default. When the container receives a request to hit a particular servlet, it loads that servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called preinitialization of Servlet. In this case, the servlet is loaded when context is loaded. You can specify 1 in between the tag in the Web.xml file in order to pre-initialize your servlet. Example. 1
9- What mechanisms are used by a Servlet Container to maintain session information? Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.
10- What do you understand by servlet mapping? Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url patterns. For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.
11- What interface must be implemented by all Servlets? The Servlet Interface must be implemented by all servlets (either the GenericServlet or the HttpServlet)
12- What are the uses of Servlets? 1) Servlets are used to process the client requests. 2) A Servlet can handle multiple request concurrently and be used to develop high performance system 3) A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.
13- What are the objects that are received when a servlets accepts call from client? The objects are: ServeltRequest and ServletResponse The ServeltRequest encapsulates the communication from the client to the server. While ServletResponse encapsulates the communication from the Servlet back to the client. All the passage of data between the client and server happens by means of these request and response objects. ---------------------------------------Session Based Interview Questions 1. What is a Session? A Session refers to all the request that a single client makes to a server. A session is specific to the user and for each user a new session is created to track all the requests from that particular user. Sessions are not shared among
users and each user of the system will have a seperate session and a unique session Id. In most cases, the default value of time-out* is 20 minutes and it can be changed as per the website requirements. *Time-Out - The Amount of time after which a session becomes invalidated/destroyed if the session has been inactive. 2. What is Session ID? A session ID is an unique identification string usually a long, random and alphanumeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages. 3. What is Session Tracking? HTTP is stateless protocol and it does not maintain the client state. But there exist a mechanism called "Session Tracking" which helps the servers to maintain the state to track the series of requests from the same user across some period of time. 4. What are different types of Session Tracking? Mechanism for Session Tracking are: a) Cookies b) URL rewriting c) Hidden form fields d) SSL Sessions 5. What is HTTPSession Class? HttpSession Class provides a way to identify a user across across multiple request. The servlet container uses HttpSession interface to create a session between an HTTP client and an HTTP server. The session lives only for a specified time period, across more than one connection or page request from the user. 6. Why do we need Session Tracking in a Servlet based Web Application?
In HttpServlet you can use Session Tracking to track the user state. Simply put, it is used to store information like users login credentials, his choices in previous pages (like in a shopping cart website) etc 7. What are the advantage of Cookies over URL rewriting? Sessions tracking using Cookies are more secure and fast. It keeps the website URL clean and concise instead of a long string appended to the URL everytime you click on any link in the website. Also, when we use url rewriting, it requites large data transfer from and to the server. So, it may lead to significant network traffic and access to the websites may be become slow. 8. What is session hijacking? If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user's Web application session while that session is still in progress. 9. What is Session Migration? Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by: a) Persisting the session into database b) Storing the session in-memory on multiple servers. 10. How to track a user session in Servlets? The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet: HttpSession session = req.getSession(true); Using this session object, the servlet can gain access to the details of the session.
11. How can you destroy the session in Servlet? You can call invalidate() method on the session object to destroy the session. e.g. session.invalidate(); --------------------------------------------------------------------------------------------------------------------
JSP Based Interview Questions 1. What is JSP? JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic content to web applications in a portable, secure and welldefined way. The JSP Technology allows us to use HTML, Java, JavaScript and XML in a single file to create high quality and fully functionaly User Interface components for Web Applications. 2. What do you understand by JSP Actions? JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XMLbased) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters. There are six JSP Actions: < jsp : include / > < jsp : forward / > < jsp : plugin / > < jsp : usebean / > < jsp : setProperty / >
< jsp : getProperty / > 3. What is the difference between < jsp : include page = ... > and < % @ include file = ... >? Both the tags include information from one JSP page in another. The differences are: < jsp : include page = ... > This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful while modularizing a web application. If the included file changes then the new content will be included in the output automatically. < % @ include file = ... > In this case the content of the included file is textually embedded in the page that have < % @ include file=".."> directive. In this case when the included file changes, the changed content will not get included automatically in the output. This approach is used when the code from one jsp file required to include in multiple jsp files. 4. What is the difference between < jsp : forward page = ... > and response.sendRedirect(url)? The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file. sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect also kills the session variables.
5. Name one advantage of JSP over Servlets? Can contain HTML, JavaScript, XML and Java Code whereas Servlets can contain only Java Code, making JSPs more flexible and powerful than Servlets. However, Servlets have their own place in a J2EE application and cannot be ignored altogether. They have their strengths too which cannot be overseen. 6. What are implicit Objects available to the JSP Page? Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application. The JSP implicit objects are: application config exception out page pageContext request response and session 7. What are all the different scope values for the < jsp : useBean > tag? < jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag: a) page b) request c) session and d) application 8. What is JSP Output Comments? JSP Output Comments are the comments that can be viewed in the HTML
source file. They are comments that are enclosed within the < ! - - Your Comments Here - - > 9. What is expression in JSP? Expression tag is used to insert Java values directly into the output. Syntax for the Expression tag is: < %= expression % > An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The most commonly used language is regular Java. 10. What types of comments are available in the JSP? There are two types of comments that are allowed in the JSP. They are hidden and output comments. A hidden comment does not appear in the generated HTML output, while output comments appear in the generated output. Example of hidden comment: < % - - This is a hidden comment - - % > Example of output comment: < ! - - This is an output comment - - > 11. What is a JSP Scriptlet? JSP Scriptlets is a term used to refer to pieces of Java code that can be embedded in a JSP PAge. Scriptlets begins with tag. Java code written inside scriptlet executes every time the JSP is invoked. 12. What are the life-cycle methods of JSP? Life-cycle methods of the JSP are:
a) 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. b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden. c) jspDestroy(): The container calls this when its instance is about to destroyed. The jspInit() and jspDestroy() methods can be overridden within a JSP page. 13. What are JSP Custom tags? JSP Custom tags are user defined JSP language elements. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tags to encapsulate both simple and complex behaviors in an easy to use syntax. The use of custom tags greatly enhances the functionality and simplifies the readability of JSP pages. 14. What is the role of JSP in MVC Model? JSP is mostly used to develop the user interface, It plays are role of View in the MVC Model. 15. What do you understand by context initialization parameters? The context-param element contains the declaration of a web application's servlet context initialization parameters. < context - param > < param - name > name < / param - name > < param - value > value < / param value > < / context-param > The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.
16. Can you extend JSP technology? Yes. JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions & tag libraries can be developed to enhance/extend its features. 17. What do you understand by JSP translation? JSP translation is an action that refers to the convertion of the JSP Page into a Java Servlet. This class is essentially a servlet class wrapped with features for JSP functionality. 18. How can you prevent the Browser from Caching data of the Pages you visit? By setting properties that prevent caching in your JSP Page. They are: 19. How will you handle the runtime exception in your jsp page? The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page. You can define the error page to which you want the request forwarded to, in case of an exception, in each JSP Page. Also, there should be another JSP that plays the role of the error page which has the flag isErrorPage set to True. 20. What is JavaServer Pages Standard Tag Library (JSTL) ? A tag library that encapsulates core functionality common to many JSP applications. JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization and locale-specific formatting tags, SQL tags, and functions.
21. What is JSP container ? A container that provides the same services as a servlet container and an engine that interprets and processes JSP pages into a servlet. 22. What is JSP custom action ? A user-defined action described in a portable manner by a tag library descriptor and imported into a JSP page by a taglib directive. Custom actions are used to encapsulate recurring tasks in writing JSP pages. 23. What is JSP custom tag ? A tag that references a JSP custom action. 24. What is JSP declaration ? A JSP scripting element that declares methods, variables, or both in a JSP page. 25. What is JSP directive ? A JSP element that gives an instruction to the JSP container and is interpreted at translation time. 26. What is JSP document ? A JSP page written in XML syntax and subject to the constraints of XML documents. 27. What is JSP element ? A portion of a JSP page that is recognized by a JSP translator. An element can be a directive, an action, or a scripting element. 28. What is JSP expression ? A scripting element that contains a valid scripting language expression that is evaluated, converted to a String, and placed into the implicit out object. 29. What is JSP expression language ?
A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression. 30. What is JSP page ? A text-based document containing static text and JSP elements that describes how to process a request to create a response. A JSP page is translated into and handles requests as a servlet. 31. What is JSP scripting element ? A JSP declaration, scriptlet, or expression whose syntax is defined by the JSP specification and whose content is written according to the scripting language used in the JSP page. The JSP specification describes the syntax and semantics for the case where the language page attribute is "java". 32. What is JSP scriptlet ? A JSP scripting element containing any code fragment that is valid in the scripting language used in the JSP page. The JSP specification describes what is a valid scriptlet for the case where the language page attribute is "java". 33. What is JSP tag file ? A source file containing a reusable fragment of JSP code that is translated into a tag handler when a JSP page is translated into a servlet. 34. What is JSP tag handler ? A Java programming language object that implements the behavior of a custom tag. If you have any questions that you want answer for - please leave a comment on this page and I will answer them. -----------------------------------------------------------------------------------------------------
Struts interview questions (Part-1) 1.What is MVC? Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data. Model: The model contains the core of the application's functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller. View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur. Controller: The controller reacts to the user input. It creates and sets the model. 2.What is a framework? A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement. 3.What is Struts framework? Struts framework is an open-source framework for developing the web applications in JavaEE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. 4.What are the components of Struts? Struts components can be categorize into Model, View and Controller:
Model: Components like business logic /business processes and data are the part of model. View: HTML, JSP are the view components. Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests. 5.What are the core classes of the Struts Framework? Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design. JavaBeans components for managing application state and behavior. Event-driven development (via listeners as in traditional GUI development). Pages that represent MVC-style views; pages reference view roots via the JSF component tree. 6.What is ActionServlet? ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request. 7.What is role of ActionServlet? ActionServlet performs the role of Controller: · Process user requests · Determine what the user is trying to achieve according to the request · Pull data from the model (if necessary) to be given to the appropriate view, · Select the proper view to respond to the user · Delegates most of this grunt work to Action classes · Is responsible for initialization and clean-up of resources 8.What is the ActionForm? ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.
9.What are the important methods of ActionForm? The important methods of ActionForm are : validate() & reset(). 10.Describe validate() and reset() methods ? validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method. public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) 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. public void reset() {} 11.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. 12.How is the Action Mapping specified ? We can specify the action mapping in the configuration file called strutsconfig.xml. Struts framework creates ActionMappingobject from configuration element of struts-config.xml file
13.What is role of Action Class? An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request. 14.In which method of Action class the business logic is executed ? In the execute() method of Action class the business logic is executed. public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception ; execute() method of Action class: · Perform the processing required to deal with this request · Update the server-side objects (Scope variables) that will be used to create the next page of the user interface · Return an appropriate ActionForward object 15.What design patterns are used in Struts? Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns. · Service to Worker · Dispatcher View · Composite View (Struts Tiles) · Front Controller
· View Helper · Synchronizer Token 16.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: action org.apache.struts.action.ActionServlet config /WEB-INF/struts-config.xml, /WEB-INF/struts-admin.xml, /WEB-INF/struts-config-forms.xml ..... 17.What is the directory structure of Struts application? The directory structure of Struts application
18.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. 19.What are the important tags of struts-config.xml ? The five important sections are:
20.What are the different kinds of actions in Struts? The different kinds of actions in Struts are: · ForwardAction · IncludeAction · DispatchAction · LookupDispatchAction · SwitchAction
---------------------------------------------------------------------------------------------------------------------------------Struts interview questions (Part-2)
21.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. 22.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 DispatchAction Example » 23.What is the use of ForwardAction? The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction. 24.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.
25.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. UseForwardAction 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. 26.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. 27.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. 28.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. 29.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. 30.What if element has declaration with same name as global forward? In this case the global forward is not used. Instead the element’s
takes precendence. 31.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. 32.What are the steps need to use DynaActionForm? Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places: · In struts-config.xml: change your to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm 33.How to display validation errors on jsp page? tag displays all the errors. iterates over ActionErrors request attribute. 34.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 35.What is the use of ? repeats the nested body content of this tag over a specified collection. 36.What are differences between and : is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string. : is used to retrieve and print the value of the bean property. has no body. 37.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 handling tags in your struts-config.xml or define the exception handling tags within tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions. or 38.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. 39.How can we make message resources definitions file available to the Struts framework environment? We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to strutsconfig. xml. 40.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
------------------------------------------------------------------------------------------------------------------------------------
Spring Based interview Questions 1. Explain DI or IOC pattern. Dependency injection (DI) is a programming design pattern and architectural model, sometimes also referred to as inversion of control or IOC, although technically speaking, dependency injection specifically refers to an implementation of a particular form of IOC. Dependency Injection describes the situation where one object uses a second object to provide a particular capacity. For example, being passed a database connection as an argument to the constructor method instead of creating one inside the constructor. The term "Dependency injection" is a misnomer, since it is not a dependency that is injected; rather it is a provider of some capability or resource that is injected. There are three common forms of dependency injection: setter, constructor and interfacebased injection. Dependency injection is a way to achieve loose coupling. Inversion of control (IOC) relates to the way in which an object obtains references to its dependencies. This is often done by a lookup method. The advantage of inversion of control is that it decouples objects from specific lookup mechanisms and implementations of the objects it depends on. As a result, more flexibility is obtained for production applications as well as for testing.
2. What are the different IOC containers available? Spring is an IOC container. Other IOC containers are HiveMind, Avalon, PicoContainer. 3. What are the different types of dependency injection? Explain with examples. There are two types of dependency injection: setter injection and constructor injection. Setter Injection: Normally in all the java beans, we will use setter and getter method to set and get the value of property as follows: public class namebean { String name; public void setName(String a) { name = a; } public String getName() { return name; } } We will create an instance of the bean 'namebean' (say bean1) and set property as bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring configuration file as shown below: < bean id="bean1" class="namebean" > < property name="name" > < value > tom < / value > < / property > < / bean > The subelement < value > sets the 'name' property by calling the set method as setName("tom"); This process is called setter injection. To set properties that reference other beans , subelement of is used as shown below,
< bean id="bean1" class="bean1impl" > < property name="game" > < ref bean="bean2" / > < / property > < / bean > < bean id="bean2" class="bean2impl" / > Constructor injection: For constructor injection, we use constructor with parameters as shown below, public class namebean { String name; public namebean(String a) { name = a; } } We will set the property 'name' while creating an instance of the bean 'namebean' as namebean bean1 = new namebean("tom"); Here we use the < constructor-arg > element to set the property by constructor injection as < bean id="bean1" class="namebean" > < constructor-arg > < value > My Bean Value < / value > < / constructor-arg > < / bean > 4. What is spring? What are the various parts of spring framework? What are the different persistence frameworks which could be used with spring? Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be
selective about which of its components you use while also providing a cohesive framework for J2EE application development. The Spring modules are built on top of the core container, which defines how beans are created, configured, and managed. Each of the modules (or components) that comprise the Spring framework can stand on its own or be implemented jointly with one or more of the others. The functionality of each component is as follows: 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 AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Springbased 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 multipart 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. 5. What is AOP? How does it relate with IOC? What are different tools to utilize AOP? Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behaviour that cuts across the typical divisions of responsibility, such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviours affecting multiple classes into reusable modules. AOP and IOC are complementary technologies in that both apply a modular approach to complex problems in enterprise application development. In a typical object-oriented development approach you might implement logging functionality by putting logger statements in all your methods and Java classes. In an AOP approach you would instead modularize the logging services and apply them declaratively to the components that required logging. The advantage, of course, is that the Java class doesn't need to know about the existence of the logging service or concern itself with any related code. As a result, application
code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its capability is AspectJ. However AspectJ works at the byte code level and you need to use AspectJ compiler to get the aop features built into your compiled code. Nevertheless AOP functionality is fully integrated into the Spring context for transaction management, logging, and various other features. In general any AOP framework control aspects in three possible ways: Joinpoints: Points in a program's execution. For example, joinpoints could define calls to specific methods in a class Pointcuts: Program constructs to designate joinpoints and collect specific context at those points Advices: Code that runs upon meeting certain conditions. For example, an advice could log a message before executing a joinpoint 6. What are the advantages of spring framework? Spring has layered architecture. Use what you need and leave you don't need. Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability. Dependency Injection and Inversion of Control Simplifies JDBC Open source and no vendor lock-in. 7. Can you name a tool which could provide the initial ant files and directory structure for a new spring project? Appfuse or equinox. 8. Explain BeanFactory in spring. Bean factory is an implementation of the factory design pattern and its function is to create and dispense beans. As the bean factory knows about many objects within an application, it is able to create association between collaborating objects as they are instantiated. This removes the burden of configuration from the bean and the client. There are several implementation of BeanFactory. The most useful one is "org.springframework.beans.factory.xml.XmlBeanFactory" It loads its
beans based on the definition contained in an XML file. To create an XmlBeanFactory, pass a InputStream to the constructor. The resource will provide the XML to the factory. BeanFactory factory = new XmlBeanFactory(new FileInputStream("myBean.xml")); This line tells the bean factory to read the bean definition from the XML file. The bean definition includes the description of beans and their properties. But the bean factory doesn't instantiate the bean yet. To retrieve a bean from a 'BeanFactory', the getBean() method is called. When getBean() method is called, factory will instantiate the bean and begin setting the bean's properties using dependency injection. myBean bean1 = (myBean)factory.getBean("myBean"); 9. Explain the role of ApplicationContext in spring. While Bean Factory is used for simple applications; the Application Context is spring's more advanced container. Like 'BeanFactory' it can be used to load bean definitions, wire beans together and dispense beans upon request. It also provide 1) A means for resolving text messages, including support for internationalization. 2) A generic way to load file resources. 3) Events to beans that are registered as listeners. Because of additional functionality, 'Application Context' is preferred over a BeanFactory. Only when the resource is scarce like mobile devices, 'BeanFactory' is used. The three commonly used implementation of 'Application Context' are 1. ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application's classpath by using the code
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); 2. 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"); 3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application. 10. How does Spring supports DAO in hibernate? Spring’s HibernateDaoSupport class is a convenient super class for Hibernate DAOs. It has handy methods you can call to get a Hibernate Session, or a SessionFactory. The most convenient method is getHibernateTemplate(), which returns a HibernateTemplate. This template wraps Hibernate checked exceptions with runtime exceptions, allowing your DAO interfaces to be Hibernate exception-free. Example: public class UserDAOHibernate extends HibernateDaoSupport { public User getUser(Long id) { return (User) getHibernateTemplate().get(User.class, id); } public void saveUser(User user) { getHibernateTemplate().saveOrUpdate(user); if (log.isDebugEnabled()) { log.debug(“userId set to: “ + user.getID()); } } public void removeUser(Long id) {
Object user = getHibernateTemplate().load(User.class, id); getHibernateTemplate().delete(user); } } 11. What are the id generator classes in hibernate? increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment. identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int. sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection. seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence. uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32. guid: It uses a database-generated GUID string on MS SQL Server and MySQL. native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database. assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no element is specified.
select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value. foreign: uses the identifier of another associated object. Usually used in conjunction with a primary key association. 12. How is a typical spring implementation look like? For a typical Spring Application we need the following files 1. An interface that defines the functions. 2. An Implementation that contains properties, its setter and getter methods, functions etc., 3. A XML file called Spring configuration file. 4. Client program that uses the function. 13. How do you define hibernate mapping file in spring? Add the hibernate mapping file entry in mapping resource inside Spring’s applicationContext.xml file in the web/WEB-INF directory. < property name="mappingResources" > < list > < value > org/appfuse/model/User.hbm.xml < / value > < / list > < / property > 14. How do you configure spring in a web application? It is very easy to configure any J2EE-based web application to use Spring. At the very least, you can simply add Spring’s ContextLoaderListener to your web.xml file: < listener > < listener-class > org.springframework.web.context.ContextLoaderListener < / listener-class >
< / listener > 15. Can you have xyz.xml file instead of applicationcontext.xml? ContextLoaderListener is a ServletContextListener that initializes when your webapp starts up. By default, it looks for Spring’s configuration file at WEB-INF/applicationContext.xml. You can change this default value by specifying a element named “contextConfigLocation.” Example: < listener > < listener-class > org.springframework.web.context.ContextLoaderListener < context-param > < param-name > contextConfigLocation < / param-name > < param-value > /WEB-INF/xyz.xml< / param-value > < / context-param > < / listener-class > < / listener >
16. How do you configure your database driver in spring? Using datasource "org.springframework.jdbc.datasource.DriverManagerDataSource". Example: < bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > < property name="driverClassName" > < value > org.hsqldb.jdbcDriver < / value > < / property > < property name="url" >
< value > jdbc:hsqldb:db/appfuse < / value > < / property > < property name="username" > < value > sa < / value > < / property > < property name="password" > < value > < / value > < / property > < / bean > 17. How can you configure JNDI instead of datasource in spring applicationcontext.xml? Using "org.springframework.jndi.JndiObjectFactoryBean". Example: < bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" > < property name="jndiName" > < value > java:comp/env/jdbc/appfuse < / value > < / property > < / bean > 18. What are the key benefits of Hibernate? These are the key benifits of Hibernate: Transparent persistence based on POJOs without byte code processing Powerful object-oriented hibernate query language Descriptive O/R Mapping through mapping file. Automatic primary key generation Hibernate cache: Session Level, Query and Second level cache. Performance: Lazy initialization, Outer join fetching, Batch fetching 19. What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file? Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml. // Initialize the Hibernate environment
Configuration cfg = new Configuration().configure(); // Create the session factory SessionFactory factory = cfg.buildSessionFactory(); // Obtain the new session object Session session = factory.openSession(); The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance. An instance of SessionFactory is typically created once and used to create all sessions related to a given context. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states: transient: never persistent, not associated with any Session persistent: associated with a unique Session detached: previously persistent, not associated with any Session A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session: Session session = null; UserInfo user = null; Transaction tx = null; try { session = factory.openSession(); tx = session.beginTransaction(); user = (UserInfo)session.load(UserInfo.class, id); tx.commit(); } catch(Exception e) { if (tx != null) {
try { tx.rollback(); } catch (HibernateException e1) { throw new DAOException(e1.toString()); } } throw new DAOException(e.toString()); } finally { if (session != null) { try { session.close(); } catch (HibernateException e) { } } } 20. What is the difference between hibernate get and load methods? The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial: The following Hibernate code snippet retrieves a User object from the database: User user = (User) session.get(User.class, userID); The get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached. Hibernate also provides a load() method: User user = (User) session.load(User.class, userID); If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method. On the other hand, get() never
returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed. 21. What type of transaction management is supported in hibernate? Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions. Non-managed in web containers: < bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager" > < property name="sessionFactory" > < ref local="sessionFactory" / > < / property > < / bean > Managed in application server using JTA: < bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager." > < property name="sessionFactory" > < ref local="sessionFactory" / > < / property > < / bean >
22. What is lazy loading and how do you achieve that in hibernate? Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actually called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop. Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception. 23. What are the different fetching strategies in Hibernate? Hibernate3 defines the following fetching strategies: Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN. Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association. Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association. Batch fetching - an optimization strategy for select fetching - Hibernate
retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys. 24. What are different types of cache hibernate supports? Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box: EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory and disk-based caching. However, it does not support clustering. OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS. SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next
section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations. JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture. Commercial Tangosol Coherence cache. 25. What are the different caching strategies? The following four caching strategies are available: Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy. Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called. Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified. Transactional: This is a fully transactional cache that may be used only in a JTA environment. 26. How do you configure 2nd level cache in hibernate? To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows: < hibernate-configuration > < session-factory > < property name="hibernate.cache.provider_class" >org.hibernate.cache.EHCacheProvider< / property > < / session-factory > < / hibernate-configuration > By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties. 27. What is the difference between sorted and ordered collection in hibernate? A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause. 28. What are the types of inheritance models and describe how they work like vertical inheritance and horizontal? There are three types of inheritance mapping in hibernate: Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class. 1. Table per concrete class with unions: In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated] 2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker; 3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker
-----------------------------------------------------------------------------------------------------------------------------------------
Top Java Frequently Asked Questions 1. Can you write a Java class that could be used both as an applet as well as an application? Yes. Just, add a main() method to the applet.
2. Explain the usage of Java packages. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes. 3. If a class is located in a package, what do you need to change in the OS environment to be able to use it? You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Once the class is available in the CLASSPATH, any other Java program can use it. 4. What's the difference between J2SDK 1.5 and J2SDK 5.0? There's no difference, Sun Microsystems just re-branded this version. 5. What are the static fields & static Methods ? If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot accecss non-static field or call non-static methods 6. How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. 7. Is null a keyword? No, the null value is not a keyword. 8. Which characters may be used as the second character of an identifier, but not as the first character of an identifier? The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
9. How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. 10. What is the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. 11. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF8 characters? Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns. 12. Is sizeof a keyword? No, the sizeof operator is not a keyword. 13. What restrictions are placed on the location of a package statement within a source code file? A package statement must appear as the first line in a source code file (excluding blank lines and comments). It cannot appear anywhere else in a source code file. 14. What value does readLine() return when it has reached the end of a file? The readLine() method returns null when it has reached the end of a file. 15. What is a native method? A native method is a method that is implemented in a language other than Java. 16. Can a for statement loop indefinitely? Yes, a for statement can loop indefinitely.
Ex: for(;;) ; 17. What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left 18. What is the range of the short type? The range of the short data type is -(2^15) to 2^15 - 1. 19. What is the range of the char type? The range of the char type is 0 to 2^16 - 1. 20. What is the difference between the Boolean & operator and the && operator? && is a short-circuit AND operator - i.e., The second condition will be evaluated only if the first condition is true. If the first condition is true, the system does not waste its time executing the second condition because, the overall output is going to be false because of the one failed condition. & operator is a regular AND operator - i.e., Both conditions will be evaluated always. 21. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. 22. What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system. 23. What is the argument type of a program's main() method?
A program's main() method takes an argument of the String[] type. (A String Array) 24. Which Java operator is right associative? The = operator is right associative. 25. What is the Locale class? This class is used in conjunction with DateFormat and NumberFormat to format dates, numbers and currency for specific locales. With the help of the Locale class you’ll be able to convert a date like “10/10/2005” to “Segunda-feira, 10 de Outubro de 2005” in no time. If you want to manipulate dates without producing formatted output, you can use the Locale class directly with the Calendar class 26. Can a double value be cast to a byte? Yes, a double value can be cast to a byte. But, it will result in loss of precision. 27. What is the difference between a break statement and a continue statement? A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the beginning of the loop. 28. How are commas used in the intialization and iterationparts of a for statement? Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. 29. How are Java source code files named? A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code
file, then the file can take on a name that is different than its classes and interfaces. Source code files use the .java extension. 30. What value does read() return when it has reached the end of a file? The read() method returns -1 when it has reached the end of a file. 31. Can a Byte object be cast to a double value? No, an object cannot be cast to a primitive value. 32. What is the Dictionary class? The Dictionary class provides the capability to store key-value pairs. It is the predecessor to the current day HashMap and Hashtable. 33. What is the % operator? It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. 34. What is the difference between the Font and FontMetrics classes? The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. 35. How is rounding performed under integer division? The fractional part of the result is truncated. This is known as rounding toward zero. 36. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy? The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented. 37. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. You can use it to manipulate dates & times.
38. For which statements does it make sense to use a label? The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement. 39. What is the purpose of the System class? The purpose of the System class is to provide access to system resources. 40. Is &&= a valid Java operator? No, it is not a valid operator. 41. Name the eight primitive Java data types. The eight primitive types are byte, char, short, int, long, float, double, and boolean. 42. What restrictions are placed on the values of each case of a switch statement? During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. 43. What is the difference between a while statement and a do statement? A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement 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 body of a loop at least once. 44. What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances or objects of a class. Non-static variables take on unique values with each object instance. 45. What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system. 46. Which Math method is used to calculate the absolute value of a number? The abs() method is used to calculate absolute values. 47. Which non-Unicode letter characters may be used as the first character of an identifier? The non-Unicode letter characters $ and _ may appear as the first character of an identifier 48. What restrictions are placed on method overloading? Two methods may not have the same name and argument list but different return types. 49. What is the return type of a program's main() method? A program's main() method has a void return type. i.e., the main method does not return anything. 50. What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.
----------------------------------------------------------------------------------------------------------------------------Top Java Frequently Asked Questions- 2 51. Are true and false keywords? The values true and false are not keywords.
52. What is a void return type? A void return type indicates that a method does not return a value after its execution. 53. What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. 54. Which package is always imported by default? The java.lang package is always imported by default in all Java Classes. 55. What restrictions are placed on method overriding? Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides but it can expand it. The overriding method may not throw any exceptions that are not thrown by the overridden method. 56. Which arithmetic operations can result in the throwing of an ArithmeticException? Integer / and % can result in the throwing of an ArithmeticException. 57. What is the ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run. 58. What is numeric promotion? Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
59. To what value is a variable of the boolean type automatically initialized? The default value of the boolean type is false. 60. What is the difference between the prefix and postfix forms of the ++ operator? The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value to the expression and then performs the increment operation on that value. 61. What is the purpose of a statement block? A statement block is used to organize a sequence of statements as a single statement group. 62. What is the difference between an if statement and a switch statement? The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed. A Switch statement with 5 Case blocks can be compared to an if statement with 5 else-if blocks. 63. What do you mean by object oreiented programming In object oreinted programming the emphasis is more on data than on the procedure and the program is divided into objects. Some concepts in OO Programming are: * The data fields are hidden and they cant be accessed by external functions. * The design approach is bottom up. * The Methods operate on data that is tied together in data structure 64. What are 4 pillars of object oreinted programming 1. Abstraction - It means hiding the details and only exposing the essentioal parts
2. Polymorphism - Polymorphism means having many forms. In java you can see polymorphism when you have multiple methods with the same name 3. Inheritance - Inheritance means the child class inherits the non private properties of the parent class 4. Encapsulation - It means data hiding. In java with encapsulate the data by making it private and even we want some other class to work on that data then the setter and getter methods are provided 65. Difference between procedural and object oreinted language In procedural programming the instructions are executed one after another and the data is exposed to the whole program In Object Oriented programming the unit of program is an object which is nothing but combination of data and code and the data is not exposed outside the object 66. What is the difference between parameters and arguments While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments. 67. What is reflection in java Reflection allows Java code to discover information about the fields, methods and constructors of loaded classes and to dynamically invoke them. The Java Reflection API covers the Reflection features. 68. What is a cloneable interface and how many methods does it contain The cloneable interface is used to identify objects that can be cloned using the Object.clone() method. IT is a Tagged or a Marker Interface and hence it does not have any methods. 69. What is the difference between Java Bean and Java Class
Basically a Bean is a java class but it has getter and setter method and it does not have any logic in it, it is used for holding data. On the other hand the Java class can have what a java bean has and also has some logic inside it 70. What are null or Marker interfaces in Java ? The null interfaces or marker interfaces or Tagged Interfaces, do not have method declarations in them. They are empty interfaces, this is to convey the compiler that they have to be treated differently 71. Does java Support multiple inheritance ? Java does not support multiple inheritance directly like C++, because then it is prone to ambiguity, example if a class extends 2 other classes and these 2 parent classes have same method names then there is ambiguity. Hence in Partial Java Multiple inheritance is supported using Interfaces 72. What are virtual function ? In OOP when a derived class inherits from a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class functions overridden by the derived class, a problem then arises when a derived object has been cast as the base class type. When a derived object is referred to as being of the base's type, the desired function call behavior is ambiguous. The distinction between virtual and not virtual is provided to solve this issue. If the function in question is designated "virtual" then the derived class's function would be called (if it exists). If it is not virtual, the base class's function would be called. 73. Does java support virtual functions ? No java does not support virtual functions direclty like in C++, but it supports using Abstract class and interfaces 74. What is JVM ? When we install a java package. It contains 2 things
* The Java Runtime Environment (JRE) * The Java Development Kit (JDK) The JRE provides runtime support for Java applications. The JDK provides the Java compiler and other development tools. The JDK includes the JRE. Both the JRE and the JDK include a Java Virtual Machine (JVM). This is the application that executes a Java program. A Java program requires a JVM to run on a particular platform 75. What is the difference between Authentication and Authorization ? Authentication is a process for verifying that an individual is who they say they are. Authorization is an additional level of security, and it means that a particular user (usually authenticated), may have access to a particular resource say record, file, directory or script. 76. What types of values does boolean variables take ? It only takes values true and false. 77. Which primitive datatypes are signed ? All primitive datatypes are signed except char and Boolean 78. Is char type signed or unsigned ? char type is integral but unsigned. It range is 0 to 2^7-1 79. What forms an integral literal can be ? decimal, octal and hexadecimal, hence example it can be 28, 034 and 0x1c respectively 80. Why is the main method static ? So that it can be invoked without creating an instance of that class 81. What is the difference between class variable, member variable and automatic(local) variable
class variable is a static variable and does not belong to instance of class but rather shared across all the instances of the Class. member variable belongs to a particular instance of class and can be called from any method of the class automatic or local variable is created on entry to a method and is alive only when the method is executed 82. When are static and non static variables of the class initialized ? The static variables are initialized when the class is loaded Non static variables are initialized just before the constructor is called 83. How is an argument passed in java, is it by copy or by reference? If the variable is primitive datatype then it is passed by copy. If the variable is an object then it is passed by reference 84. How does bitwise (~) operator work ? It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g 11110000 gets coverted to 00001111 85. Can shift operators be applied to float types ? No, shift operators can be applied only to integer or long types (whole numbers) 86. What happens to the bits that fall off after shifting ? They are discarded (ignored) 87. What are the rules for overriding ? The rules for Overriding are: Private method can be overridden by private, protected or public methods Friendly method can be overridden by protected or public methods Protected method can be overridden by protected or public methods Public method can be overridden by public method
88. Explain the final Modifier ? Final can be applied to classes, methods and variables and the features cannot be changed. Final class cannot be subclassed, methods cannot be overridden 89. Can you change the reference of the final object ? No the reference cannot be changed, but the data in that object can be changed 90. Can abstract modifier be applied to a variable ? No it can be applied only to class and methods 91. Where can static modifiers be used ? They can be applied to variables, methods and even a block of code, static methods and variables are not associated with any instance of class 92. When are the static variables loaded into the memory During the class load time 93. When are the non static variables loaded into the memory ? They are loaded just before the constructor is called 94. How can you reference static variables ? You can refer to static variables directly using the class name and you dont need any object instance for it. Ex: ClassTest.execMethod(); can be used to access the execMethod() method of the class ClassTest 95. Can static method use non static features of there class ? No they are not allowed to use non static features of the class, they can only call static methods and can use static data 96. What is static initializer code ?
A class can have a block of initializer code that is simply surrounded by curly braces and labeled as static e.g. public class Test{ static int =10; static{ System.out.println("Hiiiiiii"); } } And this code is executed exactly once at the time of class load 97. Where is native modifier used? It can refer only to methods and it indicates that the body of the method is to be found else where and it is usually written in language other than Java. 98. 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. 99. What do you understand by late binding or virtual method Invocation ? When a compiler for a non object oriented language comes across a method invocation, it determines exactly what target code should be called and build machine language to represent that call. In an object oriented language, this is not possible since the proper code to invoke is determined based upon the class if the object being used to make the call, not the type of the variable. Instead code is generated that will allow the decision to be made at run time. This delayed decision making is called as late binding 100. Can Overridden methods have different return types ? No they cannot have different return types
101. 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 102. What are the Final fields & Final Methods ? Fields and methods can also be declared final. A final method cannot be overridden in a subclass. A final field is like a constant: once it has been given a value, it cannot be assigned again.
---------------------------------------------------------------------------------------------------------------------------------
OOPs based interview questions 1- What are different oops concept in java? Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the software development and maintenance by providing some concepts: Object Class Inheritance Polymorphism Abstraction Encapsulation 2- What is polymorphism? Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding. If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java. 1- Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
2- Compile time Polymorohism - If a class have multiple methods by same name but different parameters, it is known as Method Overloading. 3- What is multiple inheritance and does java support? If a child class inherits the property from multiple parent classes is known as multiple inheritance. Java does not allow to extend multiple classes, to overcome this problem it allows to implement multiple Interfaces. 4- What is an abstraction ? Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction. 5- What is Encapsulation? Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. 6- What is Association? It represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner. The name of an association specifies the nature of relationship between objects. This is represented by a solid line.
Let’s take an example of relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.
8- What is Aggregation? It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.
Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.
---------------------------------------------------------------------------------------------------------------String based interview Questions 1. What would you use to compare two String variables - the operator == or the equals() method? I would personally prefer/use the equals() method to compare two Strings if I want to check the value of the Strings and the == operator if I want to check if the two variables point to the same instance of the String object.
2. For concatenation of strings, which class is good, StringBuffer or String ? StringBuffer is faster than String for concatenation. Also, it is less memory/resource intensive when compared to Strings.
3. As a continuation to the previous question - Why would you say StringBuffers are less resource intensive than Strings during Concatenation? As you might already know, Strings are immutable. So, when you concatenate some value to a String, you are actually creating a fresh String object that is going to hold some more data. This way you have created a new object while the old String object is still alive. As you keep concatenating values to the String, newer objects are going to get created which are going to use up the virtual memory. Whereas, if you use a StringBuffer, you are just editing the objects value rather than creating new objects.
4. To what value is a variable of the String type automatically initialized? The default value of String variable is null.
5. What is the difference between the String and StringBuffer classes? String objects are constants or in other words immutable while StringBuffer objects are not.
6. What happens when you add a double value to a String?
The result is a String object. For that matter, if you add anything to a String, you will end up with a String.
7. What will be the result if you compare StringBuffer with String if both have same values? It will return false as you cannot compare String with StringBuffer directly. If you really want to compare the contents of the String & the StringBuffer you would have to invoke the equals method with the String and the toString() output of the StringBuffer.
8. What is difference between String, StringBuffer and StringBuilder? When to use them? For all practical understanding purposes, all these 3 classes are used to handle/manipulate Strings. The main difference between these 3 classes is: * Strings are immutable while StringBuffer & StringBuilder objects are mutable (can be modified) * StringBuffer is synchronized (thread safe) while StringBuilder is not.
9. When to use Strings or StringBuffer or StringBuilder? What will drive this decision? The type of objects you need to create and how they will be used will drive this decision. So, * If the object value is not going to change, use the String class * If the object value will be changed frequently we must choose either the StringBuffer or the StringBuilder. * Here, if your object will be accessed only by a single thread use StringBuilder because it is faster
* If your object may be accessed my multiple threads use the StringBuffer because it is thread safe Note: Thread safety is not free and comes at the expense of performance. So, if your system is not multi-threaded then use the StringBuilder which will be much faster than the StringBuffer.
10. Why String class is final or immutable? The reason "Why" the string class is final is because - The developers of the Java language did not want programmers to mess with the basic functionality of the String Class. Almost all the basic or core functionality related classes in Java are final for the same reason. If String were not final, you could create a subclass and have two strings that look alike when you see the value in the string, but that are actually different. Ex: See the two string objects below, MyString and YourString are two classes that are sub-classes of the "String" class and contain the same value but their equality check might fail which does not look right. Doesnt it? MyString str1 = "Rocky"; YourString str2 = "Rocky"; This is why String class is final. ==================================== Exception Handling based Questions 1. How could Java classes direct messages to a file instead of the Console? The System class has a variable "out" that represents the standard output, and the variable "err" that represents the standard error device. By default, they both
point at the system console. The standard output could be re-directed to a file as follows: Stream st = new Stream(new FileOutputStream("output.txt")); System.setErr(st); System.setOut(st); 2. Does it matter in what order catch statements for FileNotFoundException and IOException are written? Yes, it does. The child exceptions classes must always be caught first and the "Exception" class should be caught last. 3. What is user-defined exception in java ? User-defined expections are the exceptions defined by the application developer which are errors related to specific application. Application Developer can define the user defined exception by inheriting the Exception class. Using this class we can create & throw new exceptions. 4. What is the difference between checked and Unchecked Exceptions in Java ? Checked exceptions must be caught using try-catch() block or thrown using throws clause. If you dont, compilation of program will fail. whereas we need not catch or throw Unchecked exceptions.
5. What is the catch or declare rule for method declarations? If a checked exception may be thrown within the body of a method, the method must either catch that exception or declare it in its throws clause. This is done to ensure that there are no orphan exceptions that are not handled by any method. 6. What is the purpose of the finally clause of a try-catch-finally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. It is usually used in places where we are connecting to a database so that, we can close the connection or perform any cleanup even if the query execution in the try block caused an exception. 7. What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. 8. Can an exception be rethrown? Yes, an exception can be rethrown any number of times. 9. When is the finally clause of a try-catch-finally statement executed? The finally clause of the try-catch-finally statement is always executed after the catch block is executed, unless the thread of execution terminates or an exception occurs within the execution of the finally clause.
10. What classes of exceptions may be thrown by a throw statement? A throw statement may throw any expression that may be assigned to the Throwable type. 11. What happens if an exception is not caught? An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. 12. What happens if a try-catch-finally statement does not have a catch clause to handle an exception that is thrown within the body of the try statement?The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination. 13. Can try statements be nested? Try statements can be tested. It is possible to nest them to any level, but it is preferable to keep the nesting to 2 or 3 levels at max. 14. How does a try statement determine which catch clause should be used to handle an exception? When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception that was thrown, is executed. The remaining catch clauses are ignored. 15. What is difference between error and exception Error occurs at runtime and cannot be recovered, Outofmemory is one such example. Exceptions on the other hand are due conditions which the application encounters, that can be recovered such as FileNotFound exception or IO exceptions 16. What is the base class from which all exceptions are subclasses ? All exceptions are subclasses of a class called java.lang.Throwable 17. How do you intercept and control exceptions ?
We can intercept and control exceptions by using try/catch/finally blocks. You place the normal processing code in try block You put the code to deal with exceptions that might arise in try block in catch block Code that must be executed no matter what happens must be place in finally block 18. When do we say an exception is handled ? When an exception is thrown in a try block and is caught by a matching catch block, the exception is considered to have been handled. Or when an exception thrown by a method is caught by the calling method and handled, an exception can be considered handled. 19. When do we say an exception is not handled? There is no catch block that names either the class of exception that has been thrown or a class of exception that is a parent class of the one that has been thrown, then the exception is considered to be unhandled, in such condition the execution leaves the method directly as if no try has been executed 20. In what sequence does the finally block gets executed ? If you put finally after a try block without a matching catch block then it will be executed after the try block If it is placed after the catch block and there is no exception then also it will be executed after the try block If there is an exception and it is handled by the catch block then it will be executed after the catch block 21. What can prevent the execution of the code in finally block ? Theoretically, the finally block will execute no matter what. But practically, the following scenarios can prevent the execution of the finally block. * The death of thread * Use of system.exit() * Turning off the power to CPU
* An exception arising in the finally block itself 22. What are the rules for catching multiple exceptions? A more specific catch block must precede a more general one in the source, else it gives compilation error about unreachable code blocks. 23. What does throws statement declaration in a method indicate? This indicates that the method throws some exception and the caller method should take care of handling it. If a method invokes another method that throws some exception, the compiler will complain until the method itself throws it or surrounds the method invocation with a try-catch block. 24. What are checked exceptions? Checked exceptions are exceptions that arise in a correct program, typically due to user mistakes like entering wrong data or I/O problems. Checked Exceptions can be caught and handled by the programmer to avoid random error messages on screen. 25. What are runtime exceptions Runtime exceptions are due to programming bugs like out of bound arrays or null pointer exceptions. 26. What is difference between Exception and errors ? Errors are situations that cannot be recovered and the system will just crash or end. Whereas, Exceptions are just unexpected situations that can be handled and the system can recover from it. We usually catch & handle exceptions while we dont handle Errors. 27. How will you handle the checked exceptions? You can provide a try/catch block to handle it or throw the exception from the method and have the calling method handle it. 28. When you extend a class and override a method, can this new method throw exceptions other than those that were declared by the original
method? No it cannot throw, except for the subclasses of the exceptions thrown by the parent class's method. 29. Is it legal for the extending class which overrides a method which throws an exception, not to throw in the overridden class? Yes, it is perfectly legal. ============================================================= ====
Collection Framework Based Questions- 2 1. What's the main difference between a Vector and an ArrayList Java Vector class is internally synchronized and ArrayList is not. Hence, Vectors are thread-safe while ArrayLists are not. On the Contrary, ArrayLists are faster and Vectors are not. ArrayList has no default size while vector has a default size of 10. 2. What's the difference between a queue and a stack? Stacks works by last-in-first-out rule (LIFO), while queues use the first-in-first-out (FIFO) rule 3. what is a collection? Collection is a group of objects. There are two fundamental types of collections they are Collection and Map. Collections just hold a bunch of objects one after the other while Maps hold values in a key-value pair. Collections Ex: ArrayList, Vector etc. Map Ex: HashMap, Hashtable etc
4. What is the Collections API? The Collections API is a set of classes and interfaces that support operation on collections of objects. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming using the collections. The purpose of the Collection API is to: o Reduces programming efforts. - Increases program speed and quality. o Allows interoperability among unrelated APIs. o Reduces effort to learn and to use new APIs. o Reduces effort to design new APIs. o Encourages & Fosters software reuse. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map. 5. What is the List interface? The List interface provides support for ordered collections of objects. Ex: ArrayList 6. What is the Vector class? The Vector class provides the capability to implement a growable array of objects that is synchronzied and thread-safe. 7. What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection one by one. It is an easier way to loop through the contents of a collection when you do not know, how many objects are present in it. Also, it is a cleaner way to access the contents of a collection when compared to using a for loop and accessing entries using get(index) method. Remember that, when using Iterators they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the
collection itself while traversing an Iterator. 8. What is the Map interface? A map is an object that stores associations between keys and values (key/value pairs). Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot. 9. What is the Collection interface? The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates. 10. What is the Set interface? • The Set interface provides methods for accessing the elements of a finite mathematical set • Sets do not allow duplicate elements • Contains no methods other than those inherited from Collection • It adds the restriction that duplicate elements are prohibited • Two Set objects are equal if they contain the same elements 11. What are different types of collections? * A regular collection has no special order and does not reject duplicates * A list is ordered and does not reject duplicates * A set has no special order but rejects duplicates * A map supports storing data as key-value pairs 12. Difference between Hashtable and HashMap? * Hashtable does not store null value, while HashMap does * Hashtable is synchronized, while HashMap is not * Hashtables are slower because of the synchronization overhead while HashMaps are faster
13.What are the main Implementations of the Set interface ? The main implementations of the List interface are as follows: HashSet TreeSet LinkedHashSet EnumSet 14.What is a HashSet ? A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted to access the object. So, the more efficient your hashcode() implementation the better access performance you’ll get. Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it. 14.What is a TreeSet ? TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time. 15.What is an EnumSet ? An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created. 16.Difference between HashSet and TreeSet ? HashSet does not store data in any Order while the TreeSet stores data in order. Also, you can elements of any type to the hash set while you can only add similar types of elements into a tree set. 17.What are the main Implementations of the Map interface ? The main implementations of the List interface are as follows: HashMap HashTable TreeMap
EnumMap 18.What is a TreeMap ? TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure. 19.How do you decide when to use HashMap and when to use TreeMap ? For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. 20. Can I store multiple keys or values that are null in a HashMap? You can store only one key that has a value null. But, as long as your keys are unique, you can store as many nulls as you want in an HashMap.
============================================================= =
Collection Framework Based Questions- 1 1.What is the difference between java.util.Iterator and java.util.ListIterator? Iterator - Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements ListIterator - extends Iterator, and allows bidirectional traversal of list and also
allows the modification of elements. 2. What is the difference between the HashMap and a Map? Map is an Interface which is part of Java collections framework. It stores data as key-value pairs. Hashmap is class that implements that using hashing technique. 3. What does synchronized means in Hashtable context? Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released. This adds an overhead which makes the Hashtable slower when compared to the Hashmap. You must choose a Hashmap when you want faster performance and choose the Hashtable when you want thread safety 4. Can we make a Hashmap thread safe? If so, how? HashMap can be made thread safe by synchronizing it. Example: Map m = Collections.synchronizedMap(hashMap); 5. Why should I always use ArrayList over Vector? You should choose an ArrayList over a Vector because – not all systems are multi-threaded and thread safety is not a mandatory requirement. In such cases, using a Vector is not only overkill but also adds a lot of overhead which might slow down system performance. Even if you are just iterating through a vector to display its contents, the lock on it still needs to be obtained which makes it much slower. So, choose the ArrayList over a Vector unless your system is multithreaded. 6. What is an enumeration? An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
7. 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, whereas using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only. 8. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort()? Which one is faster? Which one to use and when? Actually speaking, the underlying sorting algorithm & mechanism is the same in both cases. The only difference is type of input passed to them. Collections.sort() has a input as List so it does a conversion of the List to an array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have an array available with you and you want to sort it. 9. What is java.util.concurrent BlockingQueue? How it can be used? The BlockingQueue is available since Java 1.5. Blocking Queue interface extends collection interface, which provides you the power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. 10. What is the ArrayBlockingQueue? Ans- ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head
of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic "bounded buffer" (fixed size buffer), in which a fixedsized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked. 11. Why doesn't Map interface extend Collection? Though the Map interface is part of collections framework, it does not extend collection interface. This was done as a design decision by Sun when the Collection framework was created. Think of it this way – A Map contains keyvalue pair data while a general collection contains only a bunch of values. If the map were to extend the collection class, what will we do with the keys and how will we link the values to their corresponding keys? Alternately, if the collection were to extend the Map, then, where will we go to get the key information for all the values that are already in the Collection? Get the idea? For all practically purposes a Map is considered a collection because it contains a bunch of data in key-value pairs but it does not explicitly extend the collection interface. 12. Which implementation of the List interface (ArrayList or LinkedList) provides for the fastest insertion of a new element into the list? LinkedList. If you are surprised about the answer you see above, read the question again “Fastest Insertion of a new element into the list”. The question is about inserts and not reading data. So, the linkedlist is faster. Because, when an element is inserted into the middle of the list in an ArrayList, the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.
13. Which implementation of the List Interface (ArrayList or LinkedList) provides for faster reads during random access of data? ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there's no fast way to access the Nth element of the list. 14. Which implementation of the List Interface (ArrayList or LinkedList) uses more memory space for the same amount (number) of data? Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers. So, the LinkedList uses more memory space when compared to an ArrayList of the same size 15. Where will you use ArrayList and Where will you use LinkedList? If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time (depending on the location of the object being added/removed) in an ArrayList. If the purpose of your collection is to populate it once and read it multiple times from random locations in the list, then the ArrayList would be faster and a better choice because Positional access requires linear-time (depending on the location of the object being accessed) in a LinkedList and constant-time in an ArrayList. In short - If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.
16.Why insertion and deletion in ArrayList is slow compared to LinkedList? ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array. During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node. 17.How do you traverse through a collection using its Iterator? To use an iterator to traverse through the contents of a collection, follow these steps: 1. Obtain an iterator to the start of the collection by calling the collection’s iterator() method. 2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true. 3. Within the loop, obtain each element by calling next(). 18.How do you remove elements during Iteration? Iterator also has a method remove() when remove is called, the current element in the iteration is deleted. 19.What are the main implementations of the List interface? The main implementations of the List interface are as follows : ArrayList : Resizable-array implementation of the List interface. The best allaround implementation of the List interface. Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods." LinkedList : Doubly-linked list implementation of the List interface. May provide
better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques). 20.What are the advantages of ArrayList over arrays? Some of the advantages ArrayList has over arrays are: It can grow dynamically It provides more powerful insertion and search mechanisms than arrays. 21.How to obtain Array from an ArrayList? Array can be obtained from an ArrayList using toArray() method on ArrayList. List arrayList = new ArrayList(); arrayList.add(obj1); arrayList.add(obj2); arrayList.add(obj3); … Object a[] = arrayList.toArray(); 22.Why are Iterators returned by ArrayList called Fail Fast? Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. So, it is considered fail fast. 23.How do you sort an ArrayList (or any list) of user-defined objects? Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator). 24.What is the Comparable interface? The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered. The Comparable interface in the generic form is written as follows:
interface Comparable where T is the name of the type parameter. All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows: int i = object1.compareTo(object2) If object1 < object2: The value of i returned will be negative. If object1 > object2: The value of i returned will be positive. If object1 = object2: The value of i returned will be zero. 25.What are the differences between the Comparable and Comparator interfaces? The Comparable uses the compareTo() method while the Comparator uses the compare() method You need to modify the class whose instance is going to be sorted and add code corresponding to the Comparable implementation. Whereas, for the Comparator, you can have a separate class that has the sort logic/code. In case of Comparable, Only one sort sequence can be created while Comparator can have multiple sort sequences.
============================================================= ========
Multi threading Based Interview Questions 1. Why would you use a synchronized block vs. synchronized method? Synchronized blocks place locks for shorter periods than synchronized methods. 2. What's the difference between the methods sleep() and wait() The code sleep(1000); puts thread to sleep (Or prevent the thread from executing) 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. 3. There are two classes: A and B. The class B need to inform a class A when some important event has happened. What Java technique would you use to implement it? If these classes are threads I'd consider notify() or notifyAll(). For regular classes you can use the Observer interface. 4. What is Runnable interface ? Are there any other ways to make a multithreaded java program? There are two ways to create new threads: - Define a new class that extends the Thread class - Define a new class that implements the Runnable interface, and pass an object of that class to a Thread's constructor. The advantage of the second approach is that the new class can be a subclass of any class, not just of the Thread class.
5. How can I tell what state a thread is in ? Prior to Java 5, isAlive() was commonly used to test a threads state. If isAlive() returned false the thread was either new or terminated but there was simply no way to differentiate between the two. Starting with the release of Java Tiger (Java 5) you can now get what state a thread is in by using the getState() method which returns an Enum of Thread.States. A thread can only be in one of the following states at a given point in time. New, Runnable, Blocked, Waiting, Timed_waiting and Terminated 6. What is the difference between notify and notify All methods ? A call to notify causes at most one thread waiting on the same object to be notified (i.e., the object that calls notify must be the same as the object that called wait). A call to notifyAll causes all threads waiting on the same object to be notified. If more than one thread is waiting on that object, there is no way to control which of them is notified by a call to notifyAll so, sometimes it is better to use notify than notifyAll. 7. What is synchronized keyword? In what situations you will Use it? Synchronization is the act of serializing access to critical sections of code. We will use this keyword when we expect multiple threads to access/modify the same data. It helps prevent dirty read/write and helps keep thread execution clean and seperate. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question. 8. Why do threads block on I/O? Threads block on i/o (i.e., Thread enters the waiting state) so that other threads may execute while the i/o Operation is performed. This is done to ensure that one thread does not hold on to resources while it is waiting for some user input -
like entering a password. 9. What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. For more details on why we need Synchronization and how to use it, you can visit the article on Thread Synchronization as it is a large topic to be covered as an answer to a single question. 10. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object. 11. What's new with the stop(), suspend() and resume() methods in JDK 1.2? Actually there is nothing new about these methods. The stop(), suspend() and resume() methods have been deprecated as of JDK 1.2. 12. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state. 13. How do you make threads to wait for one another to complete execution as a group? We can use the join() method to make threads wait for one another 14. What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. 15. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under
time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and many other factors. You can refer to articles on Operating Systems and processor scheduling for more details on the same. 16. When a thread blocks on I/O, what state does it enter? A thread enters the waiting state when it blocks on I/O. 17. What is a task's priority and how is it used in scheduling? A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. 18. When a thread is created and started, what is its initial state? A thread is in the ready state after it has been created and started. 19. What invokes a thread's run() method? After a thread is started, via its start() method, the JVM invokes the thread's run() method when the thread needs to be executed. 20. What method is invoked to cause an object to begin executing as a separate thread? The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread. 21. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods. 22. What are the high-level thread states? The high-level thread states are ready, running, waiting, and dead. 23. What is an object's lock and which object's have locks?
An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object. 24. What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. 25. How does multithreading take place on a computer with a single CPU? The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. 26. What happens when you invoke a thread's interrupt method while it is sleeping or waiting? When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown. 27. How can a dead thread be restarted? A dead thread cannot be restarted. Once a thread is dead, it stays dead and there is no way to revive it. 28. What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. 29. What method must be implemented by all threads? All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Without a run() method, a thread cannot execute.
30. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. A synchronized statement can be inside a regular method and vice versa. 31. What are volatile variables It indicates that these variables can be modified asynchronously. i.e., there is no need for synchronzing these variables in a multi-threaded environment. 32. Where does java thread support reside It resides in three distinct places The java.lang.Thread class (Most of the support resides here) The java.lang.Object class The java language and virtual machine 33. What is the difference between Thread and a Process Threads run inside process and they share data. One process can have multiple threads, if the process is killed all the threads inside it are killed 34. What happens when you call the start() method of the thread This registers the thread with a piece of system code called thread scheduler. The schedulers is the entity that determines which thread is actually running. When the start() method is invoked, the thread becomes ready for running and will be executed when the processor allots CPU time to execute it. 35. Does calling start () method of the thread causes it to run
No it just makes the thread eligible to run. The thread still has to wait for the CPU time along with the other threads, then at some time in future, the scheduler will permit the thread to run 36. When the thread gets to execute, what does it execute It executes all the code that is placed inside the run() method. 37. How many methods are declared in the interface runnable The runnable method declares only one method : public void run(); 38. Which way would you prefer to implement threading - by extending Thread class or implementing Runnable interface The preferred way will be to use Interface Runnable, because by subclassing the Thread class you have single inheritance i.e you wont be able to extend any other class in Java. 39. What happens when the run() method returns When the run() method returns, the thread has finished its task and is considered dead. You can't restart a dead thread. 40. What are the different states of the thread The different states of Threads are: New: Just created Thraed Running: The state that all threads want to be Various waiting states : Waiting, Sleeping, Suspended and Blocked Ready : Waiting only for the CPU Dead : Story Over 41. What is Thread priority Every thread has a priority, the higher priority thread gets preference over the lower priority thread by the thread scheduler 42. What is the range of priority integer that can be set for Threads? It is from 1 to 10. 10 beings the highest priority and 1 being the lowest
43. What is the default priority of the thread The default priority is 5. It is also called the Normal Priority. 44. What happens when you call Thread.yield() It causes 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 45. What is the advantage of yielding It allows a time consuming thread to permit other threads to execute 46. What happens when you call Thread.sleep() It causes the thread to while away 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 as mentioned in the argument to the sleep method. 47. 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. There is no guarantee that the thread will start running as soon as its sleep time is over. 48. What do you mean by thread blocking If a method needs to wait an indeterminable amount of time until some I/O occurrence takes place, then a thread executing that method should graciously step out of the Running state. All java I/O methods behave this way. A thread that has graciously stepped out in this way is said to be blocked. 49. 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 50. What is preemptive scheduling
Preemptive scheduing is a scheduling mechanism wherein, the scheduler puts a lower priority thread on hold when a higher priority thread comes into the waiting queue. The arrival of a higher priority thread always preempts the execution of the lower priority threads. The problem with this system is - a low priority thread might remain waiting for ever. 51. What is non-preemptive or Time sliced or round robin scheduling With time slicing the thread is allowd to execute for a limited amount of time. It is then moved to ready state, where it must wait along with all the other ready threads. This method ensures that all threads get some CPU time to execute. 52. 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 53. What happens when the wait() method is called The following things happen: The calling thread gives up CPU The calling thread gives up the lock The calling thread goes into the monitor's waiting pool 54. What happens when the notify() method is called One thread gets moved out of monitors waiting pool and into the ready state and The thread that was notified must reacquire the monitors lock before it can proceed execution 55. Using notify () method how you can specify which thread should be
notified You cannot specify which thread is to be notified, hence it is always better to call notifyAll() methoD =========================================== Object Based Interview Questions 1. How do you know if an explicit object casting is needed? If you assign a superclass object to a variable of a subclass's data type, you need to do explicit casting. Whereas, When you assign a subclass to a variable having a supeclass type, the casting happens automatically. 2. What's the difference between constructors and other methods? Constructors must have the same name as the class and cannot return a value, whereas methods can have any name and can return any value. Also, A constructor is called only called once when the class is instantiated, while methods could be called many times. 3. Can you call one specific constructor of a class, when it has multiple constructors Yes. Use this() syntax and pass the arguments pertaining to the constructor you wish to invoke 4. How can a subclass call a method or a constructor defined in a superclass? Use the super.xxx(); syntax to call methods of the super class and to just call the constructor use super(); 5. If you're overriding the method equals() of an object, which other method you might also consider? hashCode() 6. How would you make a copy of an entire Java object with all its state
information? Have the class implement Cloneable interface and call its clone() method. If the class doesnt implement the interface and still the clone() is called, you will get an exception. 7. Describe the wrapper classes in Java ? Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type and creates an Object. Ex: java.lang.Boolean is the Wrapper for boolean, java.lang.Long is the wrapper for long etc. 8. Which class is extended by all other classes? The Object class is extended by all other classes. 9. Does a class inherit the constructors of its superclass? A class does not inherit constructors from any of its superclasses. But, a class can invoke the constructors of its super class by calling super(); 10. When does the compiler supply a default constructor for a class? The compiler supplies a default constructor for a class if no other constructors are coded by the programmer who created the class. 11. What is casting? There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. 12. How are this and super used? this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance.
13. When a new object of derived Class is created, whose constructor will be called first, childs or parents Even when the new object of child class is created, first the Base class constructor gets executed and then the child classes constructor. This is because, super() is the first line of code in any constructor and so, classes get created top to bottom and hence, the constructor of the Object class gets created first and then all the other classes in the hierarchy. 14. Can constructors be overloaded Yes. 15. If you use super() or this() in a constructor where should it appear in the constructor It should always be the first statement in the constructor and a point to note is, you cannot have both super() and this() in the same constructor for a simple reason - you cannot have two first lines in a method. 16. What is the ultimate ancestor of all java classes Object class is the ancestor of all the java classes 17. What are important methods of Object class wait(), notify(), notifyAll(), equals(), toString(). -======================================================
Garbage Collection Based Interview Questions 1. How can you force garbage collection? You cannot force Garbage Collection, but could request it by calling System.gc(). Though you manually call this command from your program, the JVM does not guarantee that GC will be started immediately.
2. How can you minimize the need of garbage collection and make the memory use more effective? Use object pooling and weak object references. We need to ensure that all objects that are no longer required in the program are cleared off using finalize() blocks in your code. 3. Explain garbage collection ? Garbage collection is an important part of Java's security strategy. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects from the memory. The name "garbage collection" implies that objects that are no longer needed or used by the program are "garbage" and can be thrown away to create free space for the programs that are currently running. A more accurate and up-to-date term might be "memory recycling." When an object is no longer referenced by the program, the heap space it occupies must be recycled so that the space is available for subsequent new objects. The garbage collector must determine which objects are no longer referenced by the program and make available the heap space occupied by such unreferenced objects. This way, unused memory space is reclaimed and made available for the program to use. 4. Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection as well. Hence, the Garbage Collection mechanism is a "On Best Effort Basis" system where the GC tries to clean up memory as much as possible to ensure that the system does not run out of memory but it does not guarantee the same. 5. Can an object's finalize() method be invoked while it is reachable? An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.
6. What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. We usually nullify the object references of large objects like collections, maps etc in the finalize block. 7. How many times may an object's finalize() method be invoked by the garbage collector? An object's finalize() method may only be invoked once by the garbage collector. 8. Can an object be garbage collected while it is still reachable? A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected. The system will not do it and you cannot force it either. 9. If an object is garbage collected, can it become reachable again? Once an object is garbage collected, it ceases to exist. i.e., it is dead or deleted. It can no longer become reachable again. 10. What is the purpose of garbage collection? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused. 11. 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. 12. When is an object subject to garbage collection? An object is subject to garbage collection when it becomes unreachable to the program in which it is used. i.e., no other object or code in the system is going to
access this current object 13. Does System.gc() and Runtime.gc() guarantee garbage collection No. 14. Do we need memory management code in our application? No. Memory Management is a complicated activity and that is exactly why the creators of the Java language did it themselves so that programmers like us do not have to go through the pain of handling memory management. 15. What is OutOfMemoryError in java? How to deal with java.lang.OutOfMemeryError error? This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception. Two important types of OutOfMemoryError are often encountered 1. java.lang.OutOfMemoryError: Java heap space - The quick solution is to add these flags to JVM command line when Java runtime is started as follows: -Xms1024m -Xmx1024m 2. java.lang.OutOfMemoryError: PermGen space - The solution is to add these flags to JVM command line when Java runtime is started as follows: -XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks. ============================================================= ==== Serialization Based Interview Questions
1. Explain the usage of the keyword transient? The transient keyword indicates that the value of this variable need not be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (ex: 0 for integers). 2. What are the uses of Serialization? Serialization is widely used to: * To persist data for future use. * To send data to a remote computer using such client/server Java technologies as RMI or socket programming. * To "flatten" an object into array of bytes in memory. * To exchange data between applets and servlets. * To store user session in Web applications. * To activate/passivate enterprise java beans. * To send objects between the servers in a cluster. 3. What is serialization ? Serialization is the process of writing the complete state of java object into an output stream. This stream can be file or byte array or stream associated with a TCP/IP socket. 4. What does the Serializable interface do ? Serializable is a tagging interface which declares/describes no methods. It is just used to signify the fact that, the current class can be serialized. ObjectOutputStream serializes only those objects which implement this interface. 5. How do I serialize an object to a file ? To serialize an object into a stream perform the following steps: 1. Open one of the output streams, for exaample FileOutputStream 2. Chain it with the ObjectOutputStream - Call the method writeObject() providing the instance of a Serializable object as an argument. 3. Close the streams
6. How do I deserilaize an Object? To deserialize an object, perform the following steps: 1. Open an input stream 2. Chain it with the ObjectInputStream - Call the method readObject() and cast tthe returned object to the class that is being deserialized. 3. Close the streams 7. What is Externalizable Interface ? Externalizable interface is a subclass of Serializable. Java provides Externalizable interface so as to give you more control over what is being serialized and what is not. Using this interface, you can Serialize only the fields of the class you want serialize and ignore the rest. This interface defines 2 methods: readExternal() and writeExternal() and you have to implement these methods in the class that will be serialized. In these methods you'll have to write code that reads/writes only the values of the attributes you are interested in. Programs that perform serialization and deserialization have to write and read these attributes in the same sequence. 8. What interface must an object implement before it can be written to a stream as an object? An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. 9. What are the rules of serialization Some rules of Serialization are: 1. Static fileds are not serialized because they are not part of any one particular object 2. Fileds from the base class are handled only if the parent class itself is serializable 3. Transient fileds are not serialized. ============================================
1.What are the principle concepts of OOPS? There are four principle concepts upon which object oriented design and programming rest. They are: Abstraction Polymorphism
Inheritance
Encapsulation (i.e. easily remembered as A-PIE).
2.What is Abstraction? Abstraction refers to the act of representing essential features without including the background details or explanations. 3.What is Encapsulation? Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object. 4.What is the difference between abstraction and encapsulation? Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented. Abstraction solves the problem in the design side while Encapsulation is the Implementation.
Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
5.What is Inheritance? Inheritance is the process by which objects of one class acquire the properties of objects of another class. A class that is inherited is called a superclass.
The class that does the inheriting is called a subclass.
Inheritance is done by using the keyword extends.
The two most common reasons to use inheritance are: o
To promote code reuse
o
To use polymorphism
6.What is Polymorphism? Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. 7.How does Java implement polymorphism? (Inheritance, Overloading and Overriding are used to achieve Polymorphism in java). Polymorphism manifests itself in Java in the form of multiple methods having the same name. In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods). 8.Explain the different forms of Polymorphism. There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface. Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java: Method overloading Method overriding through inheritance
Method overriding through the Java interface
9.What is runtime polymorphism or dynamic method dispatch? In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. 10.What is Dynamic Binding? Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.
11.What is method overloading? Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type. Note: Overloaded methods MUST change the argument list Overloaded methods CAN change the return type
Overloaded methods CAN change the access modifier
Overloaded methods CAN declare new or broader checked exceptions
A method can be overloaded in the same class or in a subclass
12.What is method overriding? Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type. Note: The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected). You cannot override a method marked final
You cannot override a method marked static
13.What are the differences between method overloading and method overriding? Overloaded Method
Overridden Method
Arguments
Must change
Must not change
Return type
Can change
Can’t change except for covariant returns
Exceptions
Can change
Can reduce or eliminate. Must not throw new or broader checked exceptions
Access
Can change
Must not make more restrictive (can be less restrictive)
Invocation
Reference type determines which Object type determines which method i overloaded version is selected. Happens selected. Happens at runtime. at compile time.
14.Can overloaded methods be override too? Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future. 15.Is it possible to override the main method? NO, because main is a static method. A static method can't be overridden in Java. 16.How to invoke a superclass version of an Overridden method? To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.
// From subclass super.overriddenMethod(); 17.What is super? super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword. Note: You can only go back one level. In the constructor, if you use super(), it must be the very first code, and you cannot access anythis.xxx variables or methods to compute its parameters. 18.How do you prevent a method from being overridden? To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.
public final void exampleMethod() { // } 19.What is an Interface?
Method statements
An interface is a description of a set of methods that conforming implementing classes must have. Note: You can’t mark an interface as final. Interface variables must be static.
An Interface cannot extend anything but another interfaces.
20.Can we instantiate an interface? You can’t instantiate an interface directly, but you can instantiate a class that implements an interface. 21.Can we create an object for an interface? Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it. 22.Do interfaces have member variables? Interfaces may have member variables, but these are implicitly public, static, andfinal- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example. 23.What modifiers are allowed for methods in an Interface? Only public and abstract modifiers are allowed for methods in interfaces. 24.What is a marker interface? Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializable interface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized. 25.What is an abstract class? Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Note: If even a single method is abstract, the whole class must be declared abstract. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
You can’t mark a class as both abstract and final.
26.Can we instantiate an abstract class? An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed). 27.What are the differences between Interface and Abstract class? Abstract Class
Interfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden.
An interface cannot provide any code at all,just the signature.
In case of abstract class, a class may extend only one abstract class.
A Class may implement several interfaces.
An abstract class can have non-abstract methods. All methods of an Interface are abstract. An abstract class can have instance variables.
An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.
An Interface visibility must be public (or) none.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
An abstract class can contain constructors .
An Interface cannot contain constructors .
Abstract classes are fast.
Interfaces are slow as it requires extra indirectio to find corresponding method in the actual class.
28.When should I use abstract classes and when should I use interfaces? Use Interfaces when… You see that something in your design will change frequently. If various implementations only share method signatures then it is better to use Interfaces.
you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when… If various implementations are of the same kind and use common behavior or status then abstract class is better to use. When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
29.When you declare a method as abstract, can other nonabstract methods access it? Yes, other nonabstract methods can access a method that you declare as abstract. 30.Can there be an abstract class with no abstract methods in it? Yes, there can be an abstract class without abstract methods.
31.What is Constructor? A constructor is a special method whose task is to initialize the object of its class. It is special because its name is the same as the class name.
They do not have return types, not evenvoid and therefore they cannot return values.
They cannot be inherited, though a derived class can call the base class constructor.
Constructor is invoked whenever an object of its associated class is created.
32.How does the Java default constructor be provided? If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself. 33.Can constructor be inherited? No, constructor cannot be inherited, though a derived class can call the base class constructor. 34.What are the differences between Contructors and Methods? Constructors
Methods
Purpose
Create an instance of a class
Group Java statements
Modifiers
Cannot be abstract, final, native, static, or synchronized
Can be abstract, final, native, static, or synchronized
Return Type
No return type, not even void
void or a valid return type
Name
Same name as the class (first letter is capitalized by convention) -- usually a noun
Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action
this
Refers to another constructor in the same class. If used, it must be the first line of the constructor
Refers to an instance of the owning class. Cannot be used by static methods
super
Calls the constructor of the parent class. If used, must be the first line of the constructor
Calls an overridden method in the parent class
Inheritance
Constructors are not inherited
Methods are inherited
35.How are this() and super() used with constructors? Constructors use this to refer to another constructor in the same class with a different parameter list. Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain. 36.What are the differences between Class Methods and Instance Methods? Class Methods
Instance Methods
Instance methods on the other hand require an instance of the class to exist before they can be Class methods are methods which are declared as called, so an instance of a class needs to be static. The method can be called without created by using the new keyword. creating an instance of the class Instance methods operate on specific instances o classes.
Class methods can only operate on class members Instance methods of the class can also not be and not on instance members as class methods called from within a class method unless they are are unaware of instance members. being called on an instance of that class. Class methods are methods which are declared as static. The method can be called without Instance methods are not declared as static. creating an instance of the class. 37.How are this() and super() used with constructors? Constructors use this to refer to another constructor in the same class with a different parameter list.
Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
38.What are Access Specifiers? One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers.. 39.What are Access Specifiers available in Java? Java offers four access specifiers, listed below in decreasing accessibility: Public- public classes, methods, and fields can be accessed from everywhere. Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. Situation
public
protected
default
Accessible to class from same package?
yes
yes
yes
no
Accessible to class from different package?
yes
no, unless it is a subclass
no
no
40.What is final modifier? The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method. final Classes- A final class cannot have subclasses. final Variables- A final variable cannot be changed once it is initialized.
final Methods- A final method cannot be overridden by subclasses.
privat
41.What are the uses of final method? There are two reasons for marking a method as final: Disallowing subclasses to change the meaning of the method. Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code. 42.What is static block? Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute. 43.What are static variables? Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.
static type
varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type. Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables. 44.What is the difference between static and non-static variables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. 45.What are static methods? Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class. Note:The use of a static method suffers from the following restrictions: A static method can only call other static methods. A static method must only access static data.
A static method cannot reference to the current object using keywords super or this
46.What is an Iterator ?
The Iterator interface is used to step through the elements of a Collection. Iterators let you process each element of a Collection.
Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
Iterator is an Interface implemented a different way for every Collection.
47.How do you traverse through a collection using its Iterator? To use an iterator to traverse through the contents of a collection, follow these steps: Obtain an iterator to the start of the collection by calling the collection’siterator() method. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returnstrue.
Within the loop, obtain each element by calling next().
48.How do you remove elements during Iteration? Iterator also has a method remove() when remove is called, the current element in the iteration is deleted. 49.What is the difference between Enumeration and Iterator? Enumeration Enumeration doesn't have a remove() method
Iterator Iterator has a remove() method
Enumeration acts as Read-only interface, because Can be abstract, final, native, static, it has the methods only to traverse and fetch the orsynchronized objects Note: So Enumeration is used whenever we want to make Collection objects as Readonly. 50.How is ListIterator? ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element 51.What is the List interface? The List interface provides support for ordered collections of objects. Lists may contain duplicate elements. 52.What are the main implementations of the List interface ?
The main implementations of the List interface are as follows : ArrayList : Resizable-array implementation of the List interface. The best allaround implementation of the List interface. Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and doubleended queues (deques).
53.What are the advantages of ArrayList over arrays ? Some of the advantages ArrayList has over arrays are: It can grow dynamically It provides more powerful insertion and search mechanisms than arrays. 54.Difference between ArrayList and Vector ? ArrayList
Vector
ArrayList is NOT synchronized by default.
Vector List is synchronized by default.
ArrayList can use only Iterator to access the elements.
Vector list can use Iterator and Enumeration Interface to access the elements.
The ArrayList increases its array size by 50 percent if it runs out of room.
A Vector defaults to doubling the size of its array if it runs out of room
ArrayList has no default size.
While vector has a default size of 10.
55.How to obtain Array from an ArrayList ? Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList(); arrayList.add(… ObjectÂ
a[] = arrayList.toArray();
56.Why insertion and deletion in ArrayList is slow compared to LinkedList ?
ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array. During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
57.Why are Iterators returned by ArrayList called Fail Fast ? Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, nondeterministic behavior at an undetermined time in the future. 58.How do you decide when to use ArrayList and When to use LinkedList? If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation. 59.What is the Set interface ?
The Set interface provides methods for accessing the elements of a finite mathematical set Sets do not allow duplicate elements
Contains no methods other than those inherited from Collection
It adds the restriction that duplicate elements are prohibited
Two Set objects are equal if they contain the same elements
60.What are the main Implementations of the Set interface ? The main implementations of the List interface are as follows: HashSet TreeSet
LinkedHashSet
EnumSet
61.What is a HashSet ?
A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
62.What is a TreeSet ? TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time. 63.What is an EnumSet ? An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created. 64.Difference between HashSet and TreeSet ? HashSet
TreeSet
HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order.
TreeSet is under set i.e. it provides elements in a sorted order (acceding order).
We can add any type of elements to hash set.
We can add only similar types of elements to tree set.
65.What is a Map ?
A map is an object that stores associations between keys and values (key/value pairs). Given a key, you can find its value. Both keys and values are objects.
The keys must be unique, but the values may be duplicated.
Some maps can accept a null key and null values, others cannot.
66.What are the main Implementations of the Map interface ? The main implementations of the List interface are as follows: HashMap HashTable
TreeMap
EnumMap
67.What is a TreeMap ? TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure. 68.How do you decide when to use HashMap and when to use TreeMap ? For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. 69.Difference between HashMap and Hashtable ? HashMap
Hashtable
HashMap lets you have null values as well as one null key.
HashTable does not allows null values as key and value.
The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know).
The enumerator for the Hashtable is not fail-safe
HashMap is unsynchronized.
Hashtable is synchronized.
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values. 70.How does a Hashtable internally maintain the key-value pairs? TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to
the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure. 71.What Are the different Collection Views That Maps Provide? Maps Provide Three Collection Views. Key Set - allow a map's contents to be viewed as a set of keys. Values Collection - allow a map's contents to be viewed as a set of values.
Entry Set - allow a map's contents to be viewed as a set of key-value mappings.
72.What is a KeySet View ? KeySet is a set returned by the keySet()method of the Map Interface, It is a set that contains all the keys present in the Map. 73.What is a Values Collection View ? Values Collection View is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map. 74.What is an EntrySet View ? Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map. Entry each of which has both Key and Value. 75.How do you sort an ArrayList (or any list) of user-defined objects ? Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator). 76.What is the Comparable interface ? The Comparable interface is used to sort collections and arrays of objects using theCollections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered. The Comparable interface in the generic form is written as follows:
interface Comparable where T is the name of the type parameter.
All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:
int i = object1.compareTo(object2)
If object1 < object2: The value of i returned will be negative. If object1 > object2: The value of i returned will be positive.
If object1 = object2: The value of i returned will be zero.
77.What are the differences between the Comparable and Comparator interfaces ? Comparable
Comparato
It uses the compareTo() method.
t uses the compare() method.
int objectOne.compareTo(objectTwo).
int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose instance A separate class can be created in order to sort is going to be sorted. the instances. Only one sort sequence can be created.
Many sort sequences can be created.
It is frequently used by the API classes.
It used by third-party classes to sort instances.
1.What is an exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. 2.What is error?
An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself. 3.Which is superclass of Exception?
"Throwable", the parent class of all exception related classes. 4.What are the advantages of using exception handling?
Exception handling provides the following advantages over "traditional" error management techniques:
Separating Error Handling Code from "Regular" Code. Propagating Errors Up the Call Stack.
Grouping Error Types and Error Differentiation.
5.What are the types of Exceptions in Java
There are two types of exceptions in Java, unchecked exceptions and checked exceptions.
Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch clause or list each unhandled checked exception as a thrown exception. Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class Error and its subclasses also are unchecked.
6.Why Errors are Not Checked?
A unchecked exception classes which are the error classes (Error and its subclasses) are exempted from compile-time checking because they can occur at many points in the program and recovery from them is difficult or impossible. A program declaring such exceptions would be pointlessly. 7.Why Runtime Exceptions are Not Checked?
The runtime exception classes (RuntimeException and its subclasses) are exempted from compile-time checking because, in the judgment of the designers of the Java programming language, having to declare such exceptions would not aid significantly in establishing the correctness of programs. Many of the operations and constructs of the Java programming language can result in runtime exceptions. The information available to a compiler, and the level of analysis the compiler performs, are usually not sufficient to establish that such run-time exceptions cannot occur, even though this may be obvious to the programmer. Requiring such exception classes to be declared would simply be an irritation to programmers. 8.Explain the significance of try-catch blocks?
Whenever the exception occurs in Java, we need a way to tell the JVM what code to execute. To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. One or more catch clauses match a specific exception to a block of code that handles it.
9.What is the use of finally block?
The finally block encloses code that is always executed at some point after the try block, whether an exception was thrown or not. This is right place to close files, release your network sockets, connections, and perform any other cleanup your code requires. Note: If the try block executes with no exceptions, the finally block is executed immediately after the try block completes. It there was an exception thrown, the finally block executes immediately after the proper catch block completes 10.What if there is a break or return statement in try block followed by finally block?
If there is a return statement in the try block, the finally block executes right after the return statement encountered, and before the return executes. 11.Can we have the try block without catch block?
Yes, we can have the try block without catch block, but finally block should follow the try block. Note: It is not valid to use a try clause without either a catch clause or a finally clause. 12.What is the difference throw and throws?
throws: Used in a method's signature if a method is capable of causing an exception that it does not handle, so that callers of the method can guard themselves against that exception. If a method is declared as throwing a particular class of exceptions,
then any other method that calls it must either have a try-catch clause to handle that exception or must be declared to throw that exception (or its superclass) itself.
A method that does not handle an exception it throws has to announce this:
public void myfunc(int arg) throws MyException { … } throw: Used to trigger an exception. The exception will be caught by the nearest trycatch clause that can catch that type of exception. The flow of execution stops immediately after the throw statement; any subsequent statements are not executed.
To throw an user-defined exception within a block, we use the throw command:
throw new MyException("I always wanted to throw an exception!"); 13.How to create custom exceptions?
A. By extending the Exception class or one of its subclasses. Example:
class MyException extends Exception { public MyException() { super(); } public MyException(String s) { super(s); } } 14.What are the different ways to handle exceptions?
There are two ways to handle exceptions:
Wrapping the desired code in a try block followed by a catch block to catch the exceptions. List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.
1.What is the JDBC?
Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form Java. JDBC has set of classes and interfaces which can use from Java application and talk to database without learning RDBMS details and using Database Specific JDBC Drivers. 2.What are the new features added to JDBC 4.0?
The major features added in JDBC 4.0 include :
Auto-loading of JDBC driver class Connection management enhancements
Support for RowId SQL type
DataSet implementation of SQL using Annotations
SQL exception handling enhancements
SQL XML support
Learn more about JDBC 4.0 features
3.Explain Basic Steps in writing a Java program using JDBC?
JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database :
Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded). Open the connection to database which is then used to send SQL statements and get results back.
Create JDBC Statement object. This object contains SQL query.
Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.
Process the result set.
Close the connection.
4.Exaplain the JDBC Architecture.
The JDBC Architecture consists of two layers:
The JDBC API, which provides the application-to-JDBC Manager connection. The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the Java application is shown in Figure 1.
Figure 1: JDBC Architecture 5.What are the main components of JDBC ?
The life cycle of a servlet consists of the following phases:
DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.
Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only.
Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
ResultSet: The ResultSet represents set of rows retrieved due to query execution.
6.How the JDBC application works?
A JDBC application can be logically divided into two layers: 1. Driver layer 2. Application layer
Driver layer consists of DriverManager class and the available JDBC drivers. The application begins with requesting the DriverManager for the connection.
An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer.
The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results.
Figure 2: JDBC Application
7.How do I load a database driver with JDBC 4.0 / Java 6?
Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backwardcompatible, so no changes are needed to the existing JDBC code. 8.What is JDBC Driver interface?
The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver. 9.What does the connection object represents?
The connection object represents communication context, i.e., all communication with database is through connection object only. 10.What is Statement ?
Statement acts like a vehicle through which SQL commands can be sent. Through the connection object we create statement kind of objects. Through the connection object we create statement kind of objects.
People who read this, also read:-
Statement stmt = conn.createStatement(); This method returns object which implements statement interface. 11.What is PreparedStatement?
JSP Interview Questions JDBC Questions J2EE Certification iBatis an alternative to Hibernate Core Java Questions
A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.
PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?"); pstmt.setBigDecimal(1, 153833.00); pstmt.setInt(2, 110592); Here: conn is an instance of the Connection class and "?" represents parameters.These parameters must be specified before execution.
12.What is the difference between a Statement and a PreparedStatement? Statement
Prepare
A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database.
A PreparedStatement is a precompi the PreparedStatement is executed PreparedStatement SQL statement
Statement has to verify its metadata against the database every time.
While a prepared statement has to database only once.
If you want to execute the SQL statement once go for STATEMENT
If you want to execute a single SQL then go for PREPAREDSTATEMENT. P reused with passing different value
13.What are callable statements ?
Callable statements are used from JDBC application to invoke stored procedures and functions. 14.How to call a stored procedure from JDBC ?
PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall() method of the Connection object created. A call to this method takes variable bind parameters as input parameters as well as output variables and creates an object instance of the CallableStatement class. The following line of code illustrates this:
CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}"); Here conn is an instance of the Connection class. 15.What are types of JDBC drivers?
There are four types of drivers defined by JDBC as follows:
Type 1: JDBC/ODBC—These require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It provides no host redirection capability.
Type2: Native API (partly-Java driver)—This type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection.
Type 3: Open Protocol-Net—This is not vendor specific and works by forwarding database requests to a remote database source using a net server component. How the net server component accesses the database is transparent to the client. The client driver communicates with the net server using a database-independent protocol and the net server translates this protocol into database calls. This type of driver can access any database.
Type 4: Proprietary Protocol-Net(pure Java driver)—This has a same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client.
Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.
16.Which type of JDBC driver is the fastest one?
JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database. 17.Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
18.Which is the right type of driver to use and when?
Type I driver is handy for prototyping Type III driver adds security, caching, and connection control
Type III and Type IV drivers need no pre-installation
Note: Preferred by 9 out of 10 Java developers: Type IV. Click here to learn more about JDBC drivers. 19.What are the standard isolation levels defined by JDBC?
The values are defined in the class java.sql.Connection and are:
TRANSACTION_NONE TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_REPEATABLE_READ
TRANSACTION_SERIALIZABLE
Any given database may not support all of these levels. 20.What is resultset ?
The ResultSet represents set of rows retrieved due to query execution.
People who read this, also read:Webservices Interview Questions
ResultSet rs
Spring Questions
=
MyFaces Examples JSF Integration with Spring Framework webMethods Interview Questions
stmt.executeQuery(sqlQuery); 21.What are the types of resultsets?
The values are defined in the class java.sql.Connection and are:
TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it
can be advanced only in the forward direction. TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.
TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and
is affected by changes committed by other transactions or statements within the same transaction.
Note: A TYPE_FORWARD_ONLY resultset is always insensitive. 22.What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE? TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE
An insensitive resultset is like the snapshot of the data in the database when query was executed.
A sensitive resultset does NOT represent a snapshot o data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive.
After we obtain the resultset if the data is modified then such modifications are visible through resultset.
Performance not effected with insensitive.
Since a trip is made for every ‘get’ operation, the performance drastically get affected.
22.What is rowset?
A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support component-based development models like JavaBeans, with a standard set of properties and an event notification mechanism. 24.What are the different types of RowSet ?
There are two types of RowSet are there. They are:
Connected - A connected RowSet object connects to the database once and remains connected until the application terminates. Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected.
Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.
25.What is the need of BatchUpdates?
The BatchUpdates feature allows us to group SQL statements together and send to database server in one single trip. 26.What is a DataSource?
A DataSource object is the representation of a data source in the Java programming language. In basic terms,
A DataSource is a facility for storing data. DataSource can be referenced by JNDI.
Data Source may point to RDBMS, file System , any DBMS etc..
27.What are the advantages of DataSource?
The few advantages of data source are :
An application does not need to hardcode driver information, as it does with theDriverManager. The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details. The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.
28.What is connection pooling? what is the main advantage of using connection pooling?
A connection pool is a mechanism to reuse connections created. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested..
View more...
Comments