Wednesday, 9 November 2016

Top tricky Java interview questions 2016

Top tricky Java interview questions 2016

Here are some Java interview questions which are  un-common
 
  1. What is the performance effect of a large number of import statements which are not used?
    Answer: They are ignored if the corresponding class is not used.
  2. Give a scenario where hotspot will optimize your code?
    Answer: If we have defined a variable as static and then initialized this variable in a static block then the Hotspot will merge the variable and the initialization in a single statement and hence reduce the code.
  3. What will happen if an exception is thrown from the finally block?
    Answer: The program will exit if the exception is not catched in the finally block.
  4.  How does decorator design pattern works in I/O classes?
    Answer:  The various classes like BufferedReader , BufferedWriter workk on the underlying stream classes. Thus Buffered* class will provide a Buffer for Reader/Writer classes.
  5. If I give you an assignment to design Shopping cart web application, how will you define the architecture of this application. You are free to choose any framework, tool or server?
    Answer:  Usually I will choose a MVC framework which will make me use other design patterns like Front Controller, Business Delegate, Service Locater, DAO, DTO, Loose Coupling etc. Struts 2 is very easy to configure and comes with other plugins like Tiles, Velocity and Validator etc. The architecture of Struts becomes the architecture of my application with various actions and corresponding JSP pages in place.
  6. What is a deadlock in Java? How will you detect and get rid of deadlocks?
    Answer:  Deadlock exists when two threads try to get hold of a object which is already held by another object.
  7. Why is it better to use hibernate than JDBC for database interaction in various Java applications?
    Answer:  Hibernate provides an OO view of the database by mapping the various classes to the database tables. This helps in thinking in terms of the OO language then in RDBMS terms and hence increases productivity.
  8. How can one call one constructor from another constructor in a class?
    Answer:  Use the this() method to refer to constructors.
  9. What is the purpose of intern() method in the String class?
    Answer:  It helps in moving the normal string objects to move to the String literal pool
  10. How will you make your web application to use the https protocol?
    Answer:  This has more to do with the particular server being used  than the application itself. 
Servlet Interview Question and Answers

Servlet Interview Question and Answers


1. What are Servlets?
Java Servlet is a server side program which is run to connect http/https request to application or web server.

2. What is called servlet container?
Servlet container resides in the web server where servlet run. It is a part of the web server which handles the request and response. Servlet container manages the servlet life cycle.

3. What is servlet life cycle?
Servlet life cycle is a process from creation of servlet to destroy. Steps of servlet life cycle is as follows.
  • Initialize of servlet – init()
This init() method is called only once when servlet is requested. It is one time initialization.
  • Service of servlet – service()
Each time servlet get the request, service() method is called. Depending on the request type, doGet(), doPost() etc are called.
  • Terminate of servlet – destroy()
destroy() method is called only once, the time of destruction of servlet.

4. What is the difference between doGet() and doPost() method?
  • In doGet(), the parameters are appended to the URL and sent along with header information. Where as in doPost() it is not. In doPost(), parameters are sent separately.
  • doGet() has the limitation constrain of sending header information, whcih is 1024 bytes. But doPost() doesn’t have the limitation.
  • doGet() is used in the case of insensitive data transfer. doPost() is used for the case of large number of sensitive data.
  • doGet() is the default method, where as to use of doPost() developer needs to call explicitly

5. What is Session?
Session is a object used by Servlet. It is used to track user information across the web application for multiple request.

6. What is Generic Servlet Class?
Generic servlet is the basic implementation of a servlet. It comes in javax.servlet package. Generic servlet is an abstract class and unlike HttpServlet, GenericClass class can handle any types of request which means protocol independently.

7. What is Http Servlet?
HttpServlet class is the sub class of GenericServlet class and HttpServlet can handle only Http protocols request. It provides specific methods such as doGet, doPost, doPut, doDelete etc.

8. What is ServletConfig Interface?
ServletConfig get initiated during the initialization of servlet. ServletConfig is available in the life span of servlet. It comes in javax.servlet package. Servlet config is accessible from a particular servlet for which is set in web.xml

9. What is ServletContext Interface?
ServletContext get initiated during loading of web application. ServletContext is available once per web application. It is global object. It comes in javax.servlet package. ServletContext is defined in tag in web.xml.

10. What is Servlet Request?
ServletRequest helps to provide the information about client request. Information about Parameter name and value, request header, request attribute etc. To implement the ServletRequest we need to use javax.servlet.ServletRequest or javax.servlet.http.HttpServletRequest packages. We will discuss mainly on HttpServletRequest and its important methods.

11. What is Send Redirect?
sendRedirect() method will redirect the control to other resource. It could be other domain also. sendRedirect() works only on response object.
Importent features of sendRedirect() method:
  • Request and response object are lost for every sendRedirect() method call.
  • sendRedirect() can transfer the control to the other domain also.
  • It is happening in the client side.

12. What is MIME Type?
The “Content-Type” of response header is known as MIME Type. Server sends MIME type to client to let them know the kind of data it is sending. It helps client in rendering the data for user. Some of the mostly used mime types are text/html, text/xml, application/xml etc.

13. What are servlets filters?
Filters is a java class used by Servlet. Servlet Filter is used to intercept user request before accessing the server resources.

14. What are cookies?
Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies.

15. What is internalization?
Internalization means enabling a web site to provide different versions of content translated into the visitor’s language.
Top 20 Java Collections Interview Questions and Answers

Top 20 Java Collections Interview Questions and Answers



Q1  What is Collection ? What is a Collections Framework ? What are the benefits of Java Collections Framework ?


Collection : A collection (also called as container) is an object  that groups multiple elements into a single unit.

Collections Framework : Collections framework provides unified architecture for manipulating and representing collections.

Benefits of Collections Framework :

1. Improves program quality and speed
2. Increases the chances of reusability of software
3. Decreases programming effort.




Q2 What is the root interface in collection hierarchy ? 

Root interface in collection hierarchy is Collection interface . Few interviewer may argue that
Collection interface extends Iterable interface. So iterable should be the root interface. But you should reply iterable interface present in java.lang package not in java.util package .It is clearly mentioned in Oracle Collection  docs , that Collection interface is a member of the Java Collections framework.  For Iterable interface Oracle doc , iterable interface is not mentioned as a part of the Java Collections framework .So if the question includes  collection hierarchy , then you should answer the question as Collection interface (which is found in java.util package).





Q3 What is the difference between Collection and Collections ?

Collection is  an interface while Collections is a java class , both are present in java.util package and  part of java collections framework.

Q4 Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe). 


Q5 What is the difference between List and Set ?

Set contain only unique elements while List can contain duplicate elements.
Set is unordered while List is ordered . List maintains the order in which the objects are added .

Q6 What is the difference between Iterator and Enumeration ?

The main difference between Iterator and Enumeration is that Iterator has remove() method while Enumeration doesn't.
Hence , using Iterator we can manipulate objects by adding and removing the objects from the collections. Enumeration behaves like a read only interface as it can only traverse the objects and fetch it .


Q7 Which methods you need to override to use any object as key in HashMap ?

To use any object as key in HashMap , it needs to implement equals() and hashCode() method .


Q8  What is the difference between Queue and Stack ?

Queue is a data structure which is based on FIFO ( first in first out ) property . An example of Queue in real world is buying movie tickets in the multiplex or cinema theaters.

Stack is a data structure which is based on LIFO (last in first out) property . An example of Stack in real world is  insertion or removal of CD  from the CD case.


Q9 How to convert the array of strings into the list ?

Arrays class of java.util package contains the method asList() which accepts the array as parameter.
So,

String[]  wordArray =  {"Love Yourself"  , "Alive is Awesome" , "Be in present"};
List wordList =  Arrays.asList(wordArray);


Q10 How to reverse the List in Collections ?

There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.


Q11 What is the difference between ArrayList and Vector ?

It is one of the frequently asked collection interview question , the main differences are
Vector is synchronized while ArrayList is not . Vector is slow while ArrayList is fast . Every time when needed, Vector increases the capacity twice of its initial size while ArrayList increases its ArraySize by 50%. find detailed explanation   ArrayList vs Vector  .



Q12 What is the difference between Array and ArrayList in Java ?

This question checks whether student understand the concept of static and dynamic array. Some main differences between Array and ArrayList are :
a. Array is static in size while ArrayList is dynamic in size.
b. Array can contain primitive data types while ArrayList can not contain primitive data types.
find detailed explanation ArrayList vs Array in Java


Q13 What is the difference between HashSet and TreeSet ?

Main differences between HashSet and TreeSet are :
a.  HashSet maintains the inserted elements in random order while TreeSet maintains elements in the sorted order
b. HashSet can store null object while TreeSet can not store null object.
find detailed explanation here TreeSet vs HashSet in Java


Q14 Write the code for iterating the list in different ways in java ? 

There are two ways to iterate over the list in java :
a. using Iterator
b. using for-each loop

Coding part : Do it  yourself (DIY) , in case of any doubts or difficulty please mention in the comments .


Q15 What is the difference between HashMap and ConcurrentHashMap ?

This is also one of the most popular java collections interview question . Make sure this question is in your to do list before appearing for the interview .
Main differences between HashMap and ConcurrentHashMap are :
a. HashMap is not synchronized while ConcurrentHashMap is synchronized.
b. HashMap can have one null key and any number of null values while ConcurrentHashMap does not allow null keys and null values .
find detailed explanation here ConcurrentHashMap vs HashMap in Java


Q16 Arrange the following in the ascending order (performance):
HashMap , Hashtable , ConcurrentHashMap and Collections.SynchronizedMap 

Hashtable  <  Collections.SynchronizedMap  <  ConcurrentHashMap  <  HashMap

Q17 How HashMap works in Java ?

This is one of the most important question for java developers. HashMap  works on the principle of Hashing . Find detailed information here to understand what is hashing and how hashmap works in java .

Q18 What is the difference between LinkedList and ArrayList in Java ?

Main differences between LinkedList and ArrayList are :
a. LinkedList is the doubly linked list implementation of list interface , while , ArrayList is the resizable array implementation of list interface.
b. LinkedList can be traversed in the reverse direction using descendingIterator() method  provided by the Java Api developers , while , we need to implement our own method to traverse ArrayList in the reverse direction . find the detailed explanation here ArrayList vs LinkedList in java.




Q19 What are Comparable and Comparator interfaces ? List the difference between them ?


We already explained what is comparable and comparator interface in detail along with examples here,  Comparable vs Comparator in Java

Q20 Why Map interface does not extend the Collection interface in Java Collections Framework ?

One liner answer : Map interface is not compatible with the Collection interface.