Monday, 10 March 2014

Java Interview Questions

JDBC Interview Questions
1 - What is JDBC? JDBC stands for java database connectivity, It was developed by JavaSoft, a subsidiary of Sun Microsystems. it is a java api that is use to connect with database and execute sql statement. It is an application programming interface that defines how a java programmer can access the database from Java code. 2 - What are the new features added to JDBC 4.0? Features added in jdbc 4.0 are: (a)Connection management enhancements (b)Support for RowId SQL type (c)SQL exception handling enhancements (d)Auto-loading of JDBC driver class (e)SQL XML support (f)DataSet implementation of SQL using annotations 3 - What are the main steps in java to make JDBC connectivity There are several steps for jdbc connectivity: Load the driver using Class.forName(driver name); as it communicate with the database. Create Connection object which use to send sql statement and get results from database. Create Statement object as this contain SQL query. Execute Statement that return resultSet. Process data in ResultSet. Close the connections. 4 - What is the mean of "dirty read" in database? As name suggest "reading data which may or may not be correct". when one transaction is executing and on other hand changing some field value at same time, some another transaction comes and read the change field value before first transaction commit or rollback the value, which cause unnecessary value for that field, this scenario is known as dirty read. 5 - What is two phase commit? Two phase commit is used in distributed environment where multiple process take part in distributed transaction process. In other words if any transaction is executing and it will effect multiple database then two phase commit will be used to make all database synchronized with each other. In two phase commit, commit and rollback is done in two phases Commit request phase - In this phase main process take feedback of other processes, if all process complete successfully then they go to next phase and if any process is incomplete then rollback is performed. Commit phase - if all the votes are yes then commit is done. 6 - What are different types of Statement? Statement object is used to send SQL query to database and get result from database, there are 3 type of statement: Statement - It is common and used for getting data from database, when using static SQL statement. Syntax: Statement statement = connection.createStatement( ); ResultSet resultSet = statement.executeQuery(); PreparedStatement - It is another useful statement to get data from database, you can use placeholder in place of data in sql query Syntax: PreparedStatement pstmt = conn.prepareStatement("insert into table_name(name,age) values(?,?)"); pstmt.setString(1,"abc"); pstmt.setString(2,"xyz"); int count = pstmt.executeUpdate(); Callable Statement - to access stored procedure use callable statement. Syntax: CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executeQuery(); 7 - What is connection pooling? Connection pooling mechanism is used to reuse the resource like Connection object. In this mechanism Connection object is stored in connection pool so that no need to create Connection object every time while integrating with database, instead of that you can use connection object stored in connection pool. This technique increase the application performance. 8 - What are the locking system in JDBC If multiple user reading records simultaneously then there is no problem but if two or more user updating records simultaneously, in this case records will conflict and you need some locking technique that prevent from this situation. There are two type of locking in jdbc. Optimistic Locking - it locks the record only when updates take place. Optimistic locking does not use lock while reading Pessimistic locking - In this record are locked as you selects the row to update. 9 - Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? No, You can open only one Statement object per connection while you are using the JDBC-ODBC Bridge. 10 - What are stored procedures? How is it useful? Stored procedure is a set of SQL statement . It contain repeated code that increase reusability, reduce code complexity, it increase application security from sql injection and hacking. Maintenance work become easy using stored procedure. Syntax: CREATE PROCEDURE procedure_name @param data_type = default_value, @param data_type = default_value, @param data_type = default_value AS BEGIN DELETE FROM Employees WHERE EmployeeId = @EmployeeId; END 11 - What is a Transaction? Transaction is a logical unit of work. It is used to provide data integrity, correct application semantics, and a consistent view of data during concurrent access. By default setAutoCommit() is true, for transaction management in java you need to do con.setAutoCommit() false because if one of the steps to the unit of work files fails, all the work done as part of that logical unit of work can be undone and the database can return to its previous state from where transaction began. 12 - What are the different types of ResultSet? ResultSet contain result of SQl query. There are three type of ResultSet Forward-only - This type only move forward and non-scrollable. Scroll-insensitive - This is scrollable that mean that cursor can move in any direction and insensitive implies that any change to database will not show in the resultset while it open. Scroll-sensitive - This allows cursor to move in any direction and sensitive implies that any changes to database will show in resultset. 13 - How can you retrieve data from the ResultSet? Create a ResultSet Object that will contain all data of SQl query. Syntax: ResultSet rs = stmt.executeQuery("select * from emp"); retrive each row from rs.next() method. Get the data from the row using column index or column name. Syntax: rs.getString(1); or rs.getString("column-name"); 14 - What is diference between PreparedStatement and Statement? PreparedStatement Statement It has ability to create an incomplete query and supply parameter values at execution time. It supply complete query with parameters. The query execution include 4 steps: parsing query,compile query,optimized query and executing query.In PreparedStatement first 3 steps perform only once when query is submitted initially, only the last step is performed each time at the time of query submitted. Statement perform 4 steps each time when query is executing. PreparedStatement is faster than Statement. Statement is relatively slow. 15 - What are the different type of RowSet A RowSet is an object that encapsulates a set of rows from either JDBC result sets or tabular data sources. RowSets were introduced in JDBC 2.0 as a optional packages. Their are five type of RowSet: CachedRowSet - A CachedRowSet is a RowSet in which the rows are cached and the RowSet is disconnected, that is, it does not maintain an active connection to the database. JdbcRowSet - A JdbcRowSet is a RowSet that wraps around a ResultSet object. It is a connected RowSet that provides JDBC interfaces in the form of a JavaBean interface. WebRowSet - A WebRowSet is an extension to CachedRowSet. It represents a set of fetched rows or tabular data that can be passed between tiers and components in such a way that no active connections with the data source need to be maintained. FilteredRowSet - A FilteredRowSet is an extension to WebRowSet that provides programmatic support for filtering its content. This enables you to avoid the overhead of supplying a query and the processing involved. JoinRowSet - A JoinRowSet is an extension to WebRowSet that consists of related data from different RowSets. There is no standard way to establish a SQL JOIN between disconnected RowSets without connecting to the data source. 16 - What is DAO? Why is it a best practice to use a DAO Design Pattern? DAO stands for Data Access Object. Use a DAO to abstract and encapsulate all access to the data source, DAO manages the connection with the data source to obtain and store data. DAO is used when underlying data source need to change acccording to requirement. 17 - What is the difference between JDBC-1.0 and JDBC-2.0? Scrollable ResultSets - In JDBC-1.0 you have only one way to move the cursor by call to next() method. But in JDBC-2.0 you also have previous with next to move cursor backward. Updateable ResultSets - JDBC-2.0 introduce updatable ResultSet that can insert a new row, delete a existing row and modify the column value in ResultSet object, that is not in JDBC-1.0 Batch updates - In JDBC-1.0 Statement objects submit updates to the database individually with executeUpdate() method. Multiple executeUpdate statements can be sent in the same transaction, but even though they are committed or rolled back as a unit, they are still processed individually. whereas in in JDBC-2.0 Statement, PreparedStatement, and CallableStatement objects have the ability to maintain a list of sql statement that execute as a batch. addBatch() method add sql command to list, clearBatch() method empty the list and executeBatch() method send all command in list to database. The JDBC 2.0 provides interfaces that represent the mapping to new SQL3 datatypes into the Java programming language. 18 - What is Meta Data? how you can get it? Data about data is called meta data. Database metadata is information about a database. JDBC provide 4 type of interface to deal with metadata: java.sql.DatabaseMetaData provides the metadata about the database like table names, table indexes, database name and version. Syntax: DatabaseMetaData dbmd = connection.getMetaData(); java.sql.ResultSetMetaData provides the types and properties of the columns in a ResultSet object. Syntax: ResultSetMetaData rsmd = resultSet.getMetaData(); java.sql.ParameterMetaData provides the types and properties of the parameters in a PreparedStatement object. javax.sql.RowSetMetaData provides data about the columns in a RowSet object. 19 - What is Use of Callable Statement ? A CallableStatement object provides a way to call stored procedures in a standard way for all DBMSs. The call to the stored procedure is what a CallableStatement object contains. Syntax to create CallableStatement object and call stored procedure CallableStatement cstmt = con.prepareCall("{call getTestData(?, ?)}"); 20 - How will you control two concurrent transactions accessing a database? If two concurrent transactions accessing a database for reading data then there is no issue but problem arise when two concurrent transactions update the same column value at same time, in this situation you need some locking technique that prevent from this situation.
JSP Interview Questions
1 - Explain JSP life Cycle? JSP life cycle include
(a)Translation - convert the JSP source code file to servlet. (b)Compilation - compile the servlet to .class file. (c)Loading - servlet class is loaded into the container. (d)Phase - In this the container manage one or more instances of this class in response to requests and other events. (e)Initialization - jspInit() method is called. _jspService() execution - called for every request of this JSP during its life cycle. jspDestroy() execution - called when this JSP is destroyed. 2-What can be done with JSP that cannot be done with Servlet and vice-a-versa? JSP is meant for web-developers those who are good at HTML. In JSP you can create your custom tags but you cannot create tags in servlet. JSP are http protocol based but servlet can use any protocol. 3 - What are the implicit objects in JSP? JSP has pre-available object on which you can work. These objects are parsed by the JSP engine and inserted into the generated servlet. The some of the implicit objects are list below. (a)request (b)response (c)pageContext (d)session (e)application (f)out (g)config (h)page (i)exception 4 - How many JSP scripting elements and what are they? There are 3 scripting language elements (a)Declarations (b)Scriptlets (c)Expressions 5 - What is EL in JSP? EL stands for Expression Language. It provides many objects that can be used directly like param, requestScope, applicationScope, request, session etc. 6 - What are JSP directives? JSP directives are message to web container that how to translate a jsp to servlet. (a)page directive : <%@ page attribute=" "%> (b)include directive : <%@ include file=" " %> (c)taglib directive : <%@ taglib uri=" " prefix=" " %> 7 - Can I override JSP Life Cycle? You can only override the JSP life cycle by overriding jspInit() and jspDestroy() methods. jspInit() is useful for allocating resources like database connections, network connections etc for the JSP page. jspDestroy() method is use to free allocated resource. 8 - What is the difference between include directive and include action? include directive include action include directive, includes the content of the other file during the translation to a servlet. include action, includes the response generated by executing the specified page during the request processing phase. It is a static import. It is a dynamic import. Need to compile after changes in file. No need to compile after changes in file as change data will show in next request. Syntax : <%@ include file="import.jsp'%> Syntax : <%@ include page="import.jsp" %> Include Directive used file attribute to include a file. Include Action used page attribute to include a file. 9 - What is the include directive? include directive is use to include the content of any JSP, HTML, text file. The include directive include the original content of the included resource at page translation time. Syntax : : <% @include file="file name"%> 10 - What are the standard actions available in JSP? There are following standard actions available in JSP <jsp:include> : It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time. <jsp:forward> : It forwards a response from a servlet or a JSP page to another page. <jsp:useBean> : It makes a JavaBean available to a page and instantiates the bean. <jsp:setProperty> : It sets the properties for a JavaBean. <jsp:getProperty> : It gets the value of a property from a JavaBean component and adds it to the response. <jsp:param> : It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a parameter to a request. These parameters are provided using the name-value pairs. <jsp:plugin> : It is used to include a Java applet or a JavaBean in the current JSP page. 11 - What are the attributes of page directive? There are several page directive attributes given below (a)Buffer (b)autoFlush (c)contentType (d)errorPage (e)isErrorPage (f)extends (g)import (h)info (i)isThreadSafe (j)language (k)session (l)isELIgnored (m)isScriptingEnabled 12 - What is a scriptlet? A scriptlet can contain any number of JAVA code, variable or method declarations, or expressions. Syntax : <% java code %> 13 - What are JSP declarations? Declaration is use to define one or more variables or method that you can use later in jsp file. Syntax : <%! int i = 0; %> 14 - What is a JSP expression? It is mainly use to print values of variable or method. Instead of writing out.print() to write data expression is used. Syntax : <%= statement %> 15 - Is it possible for one JSP to extend another java class if yes how? Use page directive to extend any java class. <%@ page extends="your.java.class"> 16 - How can one JSP Communicate with Java file. You can communicate with any java file in JSP, you just want to use page directive to extend any java class. Syntax : <%@ page extends="your.java.class"> 17 - In JSP page how can we handle runtime exception? You can use the errorPage attribute of the page directive, when run-time exceptions occur page directive will automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %> redirects the browser to the error.jsp page. 18 - What is the need of tag library? Tag library in jsp is called JSTL [Java Strandard Tag Library] , it is a collection of jsp tags which encapsulate core functionality common to many jsp applications. It is introduce in jsp to avoid the java code inside the jsp file and follow MVC pattern, as jsp meant for view in this pattern and view part should not contain java code. That why JSTL use tags which are easy for web developers to write in jsp file. 19 - What is JSESSIONID in Java? When JSESSIONID gets created? JSESSIONID is a cookie generated by servlet container. JSESSIONID is used for session management in J2EE web application for http protocol. As Http is a connectionless protocol, there is no way for the server to identify from which client the request is coming, so to identify client server maintain the JSESSIONID for each client. 20 - How do you define application wide error page in JSP? There are two to define error page in jsp application Page wise error - It is define on each page of jsp, if any runtime unhandled exception occur it shows the error page. Default error page - It is shown if any unhandled exception occur the default error page will display, no page specific error.
Servlet Interview Questions
1 - What are the new features added to Servlet 2.5? Following are the changes introduced in Servlet 2.5: Support for annotations Loading the class A handful of removed restrictions Some edge case clarifications A new dependency on J2SE 5.0 Several web.xml conveniences 2 - What are difference between Servlet and CGI? Servlet CGI The Servlets runs as a thread in the web-container instead of in a seperate OS process. CGI script runs as a new OS process for each request. Only one object is created first time when first request comes, other request share the same object. CGI create object every time when request comes to it. Servlet is platform independent CGI is platform dependent. Servlet is fast. CGI is slow. 3 - What's the difference between GenericServlet and HttpServlet? HttpServlet GenericServlet Only for HTTP protocol. General for all protocol. Inherit GenericServlet class. Implements Servlet interface. Use doPost, doGet method instead of service method. Use service method. 4 - Why do we need a constructor in a servlet, if we use the init() method? init() method in a servlet is used when any initialization that your servlet needs to have done before handling a request should be done from the init() method. Constructor is used by the container (container uses the constructor to cretae an instance of the servlet). Just like a normal POJO class that might have an init() method, it is no use calling the init() method if you have not constructed an object to call it. 5 - Why is HttpServlet declared abstract? The HTTPServlet class is abstract because HTTPServlet class service methods do nothing and need to be overridden by subclass. This is an implementation of Servlet interface, which mean you need not to implement all methods. 6 - Can servlet have a constructor ? Yes, you can have constructors in servlet. you can perform normal operations with the constructor, but cannot call that constructor explicitly by the new keyword. servlet container is responsible for instantiating the servlet. 7 - What is Servlet Container? Servlet container or web container is the web server component that interacts with servlets. Servlet container load, initialize and execute servlets. The Servlet container is use to dynamically generate the web page on the server side. A container handles large number of requests as it can hold many active servlets, listeners etc. 8 - What's the difference between doGet() and doPost()? doGet() doPost() doGet() method is limited to send 2k of data. It has no limitation to send data and It is possible to send files and even binary data such as serialized Java objects Data is send in header Data is send in request body. doGet Parameters are not encrypted doPost Parameters are encrypted It is faster and commonly used. Slower in compare to doGet. It allow bookmaks. It doesn't allow bookmarks. doGet() should be idempotent. doPost() does not need to be idempotent. 9 - What's the difference between ServletConfig and ServletContext? ServletConfig ServletContext Use it to pass deploy the Information to Servlet e.g-( A DataBase name or EJB look up name). Use it to access Web-application parameter(it has setAttribute/getAttribute method). ServletContext also configure in Deployment Descriptor. Use it access the servletContext Use it as a kind of application bulletin-board,where you can put up messages or use it to get the server information including the name version of container ServletConfig sc = this.getServletConfig(); ServletContext sc=this.getServletConfig.getServletContext(); String a=sc.getInitParameter("email"); String a=sc.getInitParameter("Company-email"); One Servlet Config Object per Servlet. One Servlet Context per Web-Application. Entry in web.xml: <servlet> <servlet-name>LoginServlet</servlet-name> <sevlet-class>LoginServlet</sevlet-class> <init-param> <param-name>email</param-name> <param-value>abc@yahoo.com</param-value> </init-param> </servlet> Entry in web.xml: <web-apps> <context-param> <param-name>companyemail</param-name> <param-value>efg@rkgit.com</param-value> </context-param> </web-apps> No setAttribute and getAttribute in ServletConfig. ServletContext has setAttribute(String name,Object o)to set value during coding and getAttribute to reterive the set value. 10 - When declaring a listener in the DD, which sub-element of the element is required. <listener-class> sub-element of the <listener> element is required. 11 - What is difference between forward and include? forward include Used to forward a request from one servlet to another servlet. This method must be used when the output is completely generated by the secondservlet. If the PrintWriter object is accessed by the first servlet already, then an exception is thrown by this method. This method is used to invoke one servlet from another servlet like the forward() method. However, you can also include the output of the first servlet with the current putput. The first servlet with the current output. The first servlet can make use of the PrintWriter object even after calling the inclide method. ServletContext sc = this.getServletConfig.getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher("/SecondServlet"); rd.forward(request,response); ServletContext sc = this.getServletConfig().getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher("/SecondServlet"); rd.include(request,response); 12 - What is the difference between forward and sendRedirect()? Forward () run on server side and sendRedirectv() run on client as well as on server side. Using sendRedirect() you can forward request to any other site weather on same or other server but in forward () the request has to be forwarded to same web application. Forward () hold the previous request and response object but sendRedirect () create fresh request and response object. sendRedirect () is slower than forward() as it create new request and response objects. Use forward() when you want to use same data in new resource we can use request.setAttribute () as you have request object available. But in sendRedirect ifyou want to use we have to store the data in session or pass along with the URL. 13 - What is cookie? Cookies are small text files that are used by a Web server to keep track of users. A cookie has value in the form of key-value pairs. They are created by the server and sent to the client with the HTTP response headers. A server can send one or more cookies to the client. A web-browser, which is the client software, is expected to support 20 cookies per host and the size of each cookie can be a maximum of 4 bytes each. 14 - How to set cookie and how to delete a cookie? To set a cookie you need to follow below steps: Create a cookie object - Cookie c= new Cookie("user preference","red"); c.setMaxAge(int); method is use to specify the maximum amount of time for which the client browser retains cookie value. HttpServletResponce.addChoice(c); use to send cookie to the client. To delete a cookie you need to set the setMaxAge(0), a zero value causes the cookie to be deleted. 15 - What is XML? XML stands for a Extensible Markup Language, it is design to carry data not to display data. There are not predefine tags, you must define your own tag. It is plateform indepentdent. 16 - What is Session? Session is used to store the conversational state across multiple requests from the same client. Between several request and response server not able to identify which client is getting request. When there is need to maintain the conversational state, session is needed. 17 - What are the different ways to generate session-tracking? Approaches to Session-Tracking:
(a)Session API (b)URL - rewriting (c)Cookies (d)Hidden Form Field 18 - How many servlet objects are created if we have 10 servlets in web application? We need instace for each servlet to access it thats why 10 servlet object willbe created for first client request. 19 - What is the difference in between encodeRedirectURL and encodeURL? Both are method of HttpResponse object. Both rewrite the URL to include session data if necessary encodeURL is a normal link on html page. encodeRedirectURLis for a link you're passing to response.sendRedirect(). 20 - What is filter in Java? Filters are Java Components very similar to servlets that you can use to intercept and process requests before they are sent to the servlet, or to process responses after the servlet has completed, but before the response goes back tothe client. The container decides when to invoke your filters based on deceleration in theDD.
Collections Framework Interview Questions
1 - What is java collection framework? The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures, it took shape with the release of JDK 1.2 and was expanded in JDK 1.4. It is a java data structure. 2 - What are the basic interfaces of Java Collections Framework? The basic interfaces of java collection framework are: Collection - It declares the core methods that all collections will have. Set - HashSet, LinkedHashSet classes implements this interface as it declare common method. List - ArrayList, LinkedList, Vector classes implements this interface as it declare common method Map - Hashtable, LinkedHashMap classes implements this interface as it declare common method SortedSet - TreeSet Class implements this interface to pre-sort its elements. SortedMap - TreeMap class implements this interface to pre-sort its emenets. 3 - What are difference between ArrayList and Vector? ArrayList Vector Introduced in jdk 1.2 . Introduced in jdk first version. All methods are non-synchronized. All method are synchronized. Use index based insertion and searching. Use index based insertion and searching. Use dynamic resizing array internally as data structure. Use dynamic resizing array as data-structure internally. ArrayList increases by half of its size when its size is increased. Vector doubles the size of its array when its size is increased. 4 - What are difference between ArrayList and LinkedList? ArrayList use array internally to insert and search the element whereas LinkedList use doubly LinkedList to insert and search the element. Random access is fast with arraylist as it find element by index, whereas LinkedList is slow as it traverse to find element. ArrayList is fast and easy to use whereas LinkedList take more memory in comparison to ArrayList. 5 - What is difference between HashMap and HashSet? HashMap HashSet: HashMap is a implementation of Map interface. HashSet is an implementation of Set Interface. HashMap Stores data in form of key and pair. HashSet Store data in form of objects. To add elements put() methods is used. To add element add() methods is used. In HashMap hashcode value is calculated using key object. Member object is used for calculating hashcode value. Two object may have same hash code. HashMap is faster than hashSet because unique key is used to access object. HashSet is slower than HashMap. 6 - What is difference between HashMap and Hashtable? Both HashMap and Hashtable implements Map interface. They are differ in following ways HashMap allows null key and value whereas Hashtable doesn't allow nulls. HashMap is non synchronized whereas Hashtable is synchronized. HashMap use iterator whereas Hashtable use enumeration. HashMap is faster than Hashtable. 7 - What is difference between Enumeration and Iterator? The major difference between enumeration and iterartor is that iterartor has a remove() method while enumeration doesn't have. Hence, enumerator behave as a read-only interface because it has a method to retrieve and traverse the object. Also Iterator is more secure and safe as compared to Enumeration because it doesn't allow other thread to modify the collection object while some thread is iterating over it and throws. 8 - When do you override hashcode and equals()? equals() method is used to compare objects for equality while hashCode is used to generate an integer code corresponding to that object. To remove delicacy from user define objects from the the HashMap then you need to override equals() and hashCode() methods. As equals() method compare objects for equality and hashCode() method generate same hashcode for both object if they are equal. 9 - What is difference between Comparable and Comparator interface? You need to use comparable and comparator when you want to sort user define objects. Use Comparable when you want only one sort sequence and use Comparator when you want many sort sequence. Comparable interface has only one method (int compareTo(Object o)) whereas Comparator interface has two methods (int compare (Object o1, Object o2); ,boolean equals(Object o); ) Comparable lies in java.lang.Comparable package while Comparator lies in java.util.Comparator. 10 - What is Generic? The Java Generics features were added to the Java language from Java 5. Now with generics, you can put only customer objects in the ArrayList, so the objects come out as customer references. You no need to cast the object while retrieving but Before generics, there was no way to declare the type of an ArrayList, so its add() method took type Object. 11 - How can we make Hashmap synchronized? You can make HashMap synchronized by using Collection class static method synchronizeMap. Map m = Collections.synchronizeMap(hashMap); 12 - What is the difference between Sorting performance of Arrays.sort() and Collections.sort() ? Collections.sort(List list) internally calls Arrays.sort(object a) method to do sorting. Arrays.sort(Object a) is for arrays so the sorting is done directly on the array. Arrays.sort() is faster than Collections.sort() because Collection.sort() method first elements into array and then pass it to Arrays.sort () whereas Arrays.sort ()the sorting is done directly on the array. 13 - What is difference between Array and ArrayList? Array is a fixed length data structure, you can,t change length of array once created whereas ArrayList is of dynamic data structure, it resize itself when gets full depending upon capacity and load factor. You can’t use generics on array whereas ArrayList can be generics to ensure type-safety. Length keyword is use to calculate array length whereas ArrayList use size() method to get length. Array is capable to store both primitive as well as non-primitive while you can’t store primitives in ArrayList. 14 - What is ConcurrentHashMap and When do you use ConcurrentHashMap in Java? ConcurrentHashMap is introduced as an alternative to Hashtable in jdk 1.5 as part of java concurrency package. ConcurrentHashMap performs better than Hashtable and synchronizedMap because it only locks a portion of Map, instead of whole Map. Use ConcurrentHashMap can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. 15 - What is toString()? toString() is a Object class that returns the string representation of the object. If you print any object compiler invokes the Object class toString() method, So sub-classes overrides toString() for desire output. 16 - What are difference between Iterator and ListIterator? Iterator ListIterator : Use Iterator to traverse Set, List and also Map Objects. Use ListIterator to traverse list objects. Iterator iterate elements of collection in the forward direction only. ListIterator iterate elements of collection in the forward and backward direction. Iterator cannot add elements to collection. ListIterator can add elements to collection. Iterator can't replace existing object with new object. ListIterator can replace existing object with new object. Iterator can't get index of elements. ListIterator get index of elements list. 17 - Why do you get a ConcurrentModificationException when using an iterator? Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw a ConcurrentModificationException. 18 - What are Wrapper Classes and Why the wapper class is needed? Wrapper classes are those which encapsulate a primitive type within an object. Wrapper classes are Byte, Short, Integer, Long, Character, Boolean, Double, Float, they offers methods that allow to fully integrate with the primitive types into Java’s object. We need wrapper classes as sometimes it is easier to deal with primitives as objects. Most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these reasons we need wrapper classes. We can also make objects of these classes to store in collection. 19 - How HashMap works in Java? HashMap works on hashing priciple. put(key, value) and get(key) methods are there for storing and retrieving Objects from HashMap. . When you pass Key and Value to put() method , HashMap implementation calls hashCode method on Key object and applies returned hashcode into its own hashing function to find a bucket location for storing Entry object , HashMap in stores both key and value object as Map. 20 - What is the Properties class? Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, to get the system properties you use System.getProperties( ) that gives you properties like os, jdk version etc.

No comments:

Post a Comment