Thursday, February 27, 2014

java exception interview questions and answers

What is Exception in Java ?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

What happens when a method throws an exception ?
After a method throws an exception, the runtime system attempts to find an exception handler to handle it. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. If the runtime system is unable to find an appropriate exception handler,the runtime system terminates.

For example : Suppose the main method calls a method named A . A calls B and B calls a method C . C method throws exception . The problem can be described with the below diagram .



We can understand this in the steps given below :
  1. Exception occurs at method C() . The method creates an exception object and gives it to the runtime system. 
  2. The runtime system starts looking for a matching exception handler . The search starts from method C() but because it does not provide any exception handler , the call propogates down the call stack. 
  3. The runtime system looks for a handler in method B() . B also does not provide any handler so the call propagates down the call stack. 
  4. A() provides a try/catch block that catches the type of exception that was thrown by C() so runtime system passes the exception to this handler.
Explain Java Exception Hierarchy ?
The top level class in exception hierarchy is Throwable. Error and Exception extends from Throwable. Errors are the conditions that can't be recovered from so they are not handled by a java program. Exception is further extended by RuntimeException.

java exception hierarchy


What are important methods of Java Exception Class?
Below are some important methods of Exception class :

public String getMessage() 
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor.

public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 

public String toString() Returns the name of the class concatenated with the result of getMessage()

public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream.

public StackTraceElement[] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack.

public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

What is OutOfMemoryError in Java?
OutOfMemoryError is 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. OutOfMemoryError in Java is a subclass of VirtualMachineError.

What is the concept of multi-catch block ?
In multi-catch block , we can catch multiple exceptions in a single catch block.

Benefits : This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Example : 
Without multi catch
catch (IOException ex){
       logger.log(ex);
       throw ex;
}
catch (SQLException ex){
       logger.log(ex);
       throw ex;
}

With multi catch
catch(SQLException | SQLException ex)
{
       logger.log(ex);
       throw ex;
}

What is difference between Checked and Unchecked Exception in Java?


Checked exeptions unchecked exceptions
Checked Exceptions follows handle or declare rule. so a method throwing a checked exception should either handle it using try-catch block or decalare it in method signature using throws keyword.Unchecked Exceptions are not required to be handled in the program or to mention them in throws clause.
Exception is the super class of all checked exceptions.RuntimeException is the super class of all unchecked exceptions.
Checked exceptions are error scenarios that are not caused by program, for example FileNotFoundException in reading a file that is not present.Unchecked exceptions are mostly programming bugs , for example NullPointerException when invoking a method on an object reference without making sure that it’s not null.


What is difference between throw and throws keyword in Java?
throws is as much a part of the method signature . Clients know if they call that method, they need to handle that exception by simply throwing it or by catching it and handling it . throws is addressed at compile time. 

public void getUserDetails() throws SQLException{
       // code
 }

throw is the actual act of letting the runtime know that something bad has happened and allows to through the exception manually.

 public public void getUserDetails() {
     if(!user.exists()) {
           throw UserNotFoundException("User does not exists in database");
     }
 }

What happens when exception is thrown by main method?
When exception is thrown by main , Java runtime system terminates.

Can we have the try block without catch or finally block?
NO . try block must have a catch or finally associated with it.

What is difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when an application tries to load in a class through its string name using:
  • The forName method in class Class. 
  • The findSystemClass method in class ClassLoader . 
  • The loadClass method in class ClassLoader.
but no definition for the class with the specified name could be found.

NoClassDefFoundError is thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

What is StackOverflowError?
StackOverflowError error is thrown by JVM when it encounters that there is no memory left in the stack to store variables . Parameters and local variables are allocated on the stack . The common cause for a stack overflow is a bad recursive call. Typically this is caused when your recursive functions doesn't have the correct termination condition, so it ends up calling itself for ever.

What does 'Ducking' the exception mean?
If a method does not handle the exception but simply declares it using throws , the method is said to be ducking the exception.


Tuesday, February 25, 2014

Servlet interview questions

What is a Servlet ?
Servlet can be defined in two ways :
  • As a technology 
  • From web application point of view 
As a technology , servlet represents an API that is partially implemented by application programmers and partially by web server vendors. From web application point of view, Servlet is a java class that is executed by web server to generate dynamic contents.


What is the hierarchy of servlet api ?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , by extending a class that implements it. The implementations of Servlet interface are javax.servlet.GenericServlet andjavax.servlet.http.HttpServlet. Below diagram shows the hierarchy of servlet.




What are the uses of Servlet ?
Typical uses for Servlets are :
  • Processing and/or storing data submitted by an HTML form. 
  • Providing dynamic content, e.g. returning the results of a database query to the client. 
  • Manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer

What are the advantages of Servlet over CGI ?
  • In CGI based application, a new process is created for each request . A lot of overhead is involved in creation and destruction of processes . In Servlet , a new thread is created to process a request. 
  •  CGI scripts were platform dependent but Servlet is not. 
  •  A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.

Define servlet life cycle.
  1. Servlet class loading 
  2. Servlet instantiation 
  3. Initialization init() 
  4. Request handling service()
  5. Removal from service destroy()
Step 1, 2 and 3 are executed only once, when the servlet is initially loaded. By default the servlet is not loaded until the first request is received for it.
Step 4 is executed for every HTTP request to the servlet .
Step 5 is executed when the servlet container unloads the servlet.

Why do we need a constructor in a servlet if we use the init method ?
The purpose of init is to initialize the Servlet but before that container needs an instance of the servlet .Constructor is used for the same purpose.


How the servlet is loaded ?
A servlet can be loaded in the following ways : 
  • When the first request for the servlet comes. 
  • At the time of server startup.
How a Servlet is unloaded ?
A Servlet gets unloaded when : Administrator manually unloads the servlet. Server shuts down.


What is the GenericServlet ?
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. It is named GenericServlet because the class is protocol independent. GenericServlet makes writing servlets easier.
This class also provides simple versions of the lifecycle methods init and destroy and of the methods in ServletConfig interface. It also implements the log method declared in the ServletContext interface.


What is the difference between GenericServlet and HttpServlet ?
Below table shows the differences between GenericServlet and HttpServlet .


GenericServletHttpServlet
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
GenericServlet is not specific to any protocol.HttpServlet only supports HTTP and HTTPS protocol.


Why is HttpServlet declared as abstract ?
HttpServlet is abstract because the http handler methods in HttpServlet does nothing and must be overridden. The implementation of service method has provided convinience that not all http handlers methods needs to be implemented.
For example if your custom servlet is required to handle the GET request , just implement doGet() method and there is no need to implement the doPost().

Can servlet have a constructor ?
YES , servlet can have a constructor and we can perform operations with that constructor as we normally do.The only thing is that it can not be called explicitly with the new keyword. Servlet container is responsible for instantiating a servlet , so the constructor is only called by the container only.

What are the types of protocols supported by HttpServlet ?
HttpServlet is specifically made for HTTP protocol so it can only suppory HTTP and HTTPS protocols.


What is the difference between doGet() and doPost()?
Below table shows the differences between doGet() and doPost()


doGet()doPost()
The request parameters gets appended to the URL hence visible in address bar.Request parameters are sent as a part of body so are not visible.
Limited data can be sent as request parameters are sent as a part of header and size of http header is fixed.Unlimited data can be sent because request parametrs are sent as part of the body.
Parameters are not encrypted.Parameters are encrypted.
GET request pages can be cached ( Allows bookmarking ).Disllows bookmarking.
GET request should be idempotent i.e repeating the request over and over again should not have any side effect.POST request does not need to be idempotent


When to use doGet() and when doPost()?
As we have seen the differences between a GET and POST request , we should prefer using GET requests apart for the scenarios mentioned below. Use POST if data is sensitive. Use POST if the size of data is greater than 1024 characters.

Can we support both GET and POST from the same Servlet ?
YES .

Can we override the service() method ?
YES we can but we should not . If a class overrides the service() method , then it will have to provide its own implementation for detecting the method type ( GET or POST ) of incoming request , and then invoking the corresponding handler method such as doGet or doPost.

What is a servlet context ?
ServletContext provides an interface of the servlet container to the servlets of an application. It means that the servlets communicates with the servlet container through ServletContext object. Foe example - to get MIME type of a file , dispatch requests or write a log file. There is only one context per web application per java virtual machine.

What are the differences between the ServletConfig and ServletContext ?
Below table shows the differences between ServletConfig and ServletContext.


ServletConfigServletContext
The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
There is one ServletConfig per servlet.There is one ServletContext for the entire webapp and all the servlets in a webapp share it.

What are the differences between forward() and sendRedirect()?
Below table shows the differences between forward and sendRedirect


forwardsendRedirect
A forward is performed internally by the servlet.A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
Both resources must be part of the same context.This method can be used to redirect users to resources that are not part of the current context, or even in the same domain.
Forward is marginally faster than redirect.Redirect is marginally slower than a forward, since it requires two browser requests, not one.
Request is forwarded to a new servlet so the request objects remains the same.A completely new request is sent by the browser so the request object changes.
The original URL does not changes.The browser is making a new request , so the URL changes .


What is the difference between the include() and forward()?
Below table shows the differences between include and forward 


includeforward
include() method inserts the contents of the specified resource directly in the flow of the servlet response.forward() forwards the request to another resource in the same context . Response is generated by the same servlet.
Included resource must not attempt to change the response status code or http headers. Any such attempt will be ignored.forwaded resource may be another servlet, jsp or a static html document but the response is issued under the same URL that was originally requested.

What are wrapper classes and what is their purpose ?
The wrapper classes can be used to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behavior is to pass all method calls directly to the underlying objects.

HttpServletRequestWrapper and HttpServletResponseWrapper are the servlet wrapper classes.

What is a deployment descriptor ?
Deployment descriptor ( DD ) is an xml file that defines component's deployment settings. The information provided by the deployment descriptor is declarative and therefore can be modified without changing the source code. The server reads the DD at runtime and acts upon the components accordingly.

What is the difference between the getRequestDispatcher(String path) method of ServletRequest interface and ServletContext interface ?
The getRequestDispatcher(String path)of ServletRequest accepts the relative path , relative to the current servlet. On the other hand, the same method in ServletContext can't accept relative paths . All the paths must start with "/" and are interpreted as relative to the current context root.

What is preinitialization of a servlet ?
Container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

What is the  <load-on-startup> element ?
The  element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The  element is defined in deployment descriptor ( web.xml ).

<servlet>

   <servlet-name>name</servlet-name>
   <servlet-class>class</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

What is servlet lazy loading?
Container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.

What is Servlet Chaining?
Servlet Chaining means the output of one servlet act as a input to another servlet. Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with a common servlet alias. The output from first Servlet is sent as input to other Servlet and so on. The Output from the last Servlet is sent back to the browser. The entire process is called Servlet Chaining.

What are the functions of the Servlet container?
The various functions of a servlet container are :
Lifecycle Management
Container is responsible for managing the life cycle of the servlets.

Communication Management
Servlet container manages the communication between webserver and a servlet.

Multithreading support
Container creates a new thread each time a new request comes for a servlet.

Declarative Security
Servlet container manages the security through deployment descriptor file.

JSP Support
Servlet container is responsible for translating JSPs into servlets and maintaining them.

Monday, February 24, 2014

Object Oriented Programming ( OOP ) concepts interview questions

What is an Object ? 
Well It is the most basic concept and a key to understand the Object-Oriented programming . Object is an entity that has two characteristics , State and Behavior . Some examples of real world object can be : Bike , Chair , Dog etc. Lets take an example of a Bike . Bike has some state ( current gear , current speed ) and behavior ( change gear , apply brake ) . One way to begin thinking in an object-oriented way is to identify the state and behavior of real world objects . Software objects are also similar to the real world objects. They too contains State and Behavior . An Object stores its state in fields and exposes the behavior through methods.

What is Class ? 
Class is a blueprint from which objects of same type can be created . Lets take an example of a Bike again . There are thousands of bikes with the same characteristics i.e having same make and model . They are created from the same prototype / blueprint called class.

What are the principles concepts of OOPS? 
The principle concepts of OOPs are :

  • Inheritance 
  • Polymorphism
  • Abstraction 
  • Encapsulation
What is Inheritance? 
Inheritance is the capability of one class to acquire the common state and behavior of another class while adding its own functionality . In Object Oriented programming , the concept of inheritance provides the idea of re-usability . This means we can add additional features to a class without modifying it. 

How to achieve Inheritance in Java ? 
extends keyword is used to inherit features of a class .

What is Polymorphism? 
Polymorphism means ability of one type to take more than one form . This can also be applied in Java where in sub-classes of a class can define their own unique behaviors and yet share some of the common functionalites of the parent class. 
Example : Lets take an example of Bike . A company can produce different kind of bikes say , a mountain bike , and a roadbike . Now the two different types of bikes inherit the common features of a bike but also define their own separate features. 

How to achieve Polymorphism in Java ? 
Overloading and Overriding are the two ways to achieve Polymorphism.

What is Abstraction? 
Abstraction is an essential element of Object Oriented programming . It refers to the act of presenting essential features without including the background details or explanations. We can say that abstraction is purposeful suppression , hiding of some details of a process or artifact , in order to bring out more clearly other aspects , details or structures. Abstraction can be of control ( abstraction of actions ) or data . 

How to achieve Abstraction in Java ?
Abstract classes and Interfaces are used to achieve Abstraction in Java.

What is Encapsulation?
Encapsulation is the binding of data and its associated functions in a single unit called Class . Access to the code and data inside the wrapper is tightly controlled through a well defined interface. Encapsulation provides a protective barrier that prevents the access of code and data from outside the class. 

The main benefit of encapsulation is the ability to re-factor the implemented code without breaking the code of others and thus provides flexibility and maintainability.

What is the difference between abstraction and encapsulation? 
The two concepts are distinct , but closely related and are often found together. 

  • Abstraction focuses on the outside view of an object and hides any unnecessary detail while Encapsulation provides a protective barrier that prevents the access of code and data from outside the class. 
  • Abstraction solves the problem in the design side while Encapsulation is the Implementation and infact I would say that Encapsulation in effect provides Abstraction.


Explain the different types and forms of Polymorphism. 
Polymorphism is of two types i.e Compile time and run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface. 

Different forms of polymorphism are - Method overloading and  Method overriding ( through inheritance and interfaces ).

What is runtime polymorphism or dynamic method dispatch? 
In Java, runtime polymorphism is a process in which call to an overridden method is resolved at runtime rather than at compile-time. The overridden method is called through the reference variable of the superclass but the determination of actual method to be invoked is based on the type of object created at run time.

What is Dynamic Binding? 
Resolving the actual method to be invoked on basis of a method call is called Binding.Methods can be resolved at compile time or run time. 
Types of binding are : 

  • Static binding ( early binding ) - Method call is resolved at compile time.
  • Dynamic binding ( late binding ) - Method call is resolved at run time.
What is method overloading? 
Defining multiple methods with same name in the same class but different arguments is overloading . 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.
Important points about Overloading :

  • Overloaded methods MUST change either the number of arguments or the type of arguments. 
  • 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.
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. The overriding method cannot have a more restrictive access modifier than the method being overridden. The overriding method cannot have more restrictive access modifier. The subclass can not override a method marked final or static.

What are the differences between method overloading and method overriding?
Below table shows the differences :
ParametersOverloadingOverriding
ArgumentsMust changeMust not change
Return typeCan changeCan’t change except for covariant returns
ExceptionsCan changeCan reduce or eliminate. Must not throw new or broader checked exceptions
AccessCan changeMust not make more restrictive (can be less restrictive)
InvocationReference type determines which overloaded version is selected. Happens at compile time.Object type determines which method is selected. Happens at runtime.

Can we override already overloaded method ? 
YES , sub classes can override the overloaded methods.

Is it possible to override the main method?
Static method can't be overridden in Java.

Sunday, February 23, 2014

Collections interview questions in java

GENERAL COLLECTION QUESTIONS
LIST INTERFACE
SET INTERFACE
MAP INTERFACE
What is Java collection framework ?
A collections framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details. A collection is an object that represents a group of objects .

Why Collection does not extend Serializable or Cloneable ?
Think of a scenario where a collection is backed by a large database. Is it really meaningful to clone this collection ? I think no.
I agree that some collections might require cloning , but not all . Thats why the Collection interface does not extend Cloneable but some concrete implementations do provide a public clone method.
This holds true for Serialization as well. Serializing a collection that holds very large data is not at all good.


Why Map interface does not extends Collection interface ?
Map is not a collection of objects like List or Set , rather it is a collection of mappings ( key-value pair ) . Map and collection have a separate hierarchy because they are not compatible . Collection provides a method add() which can't be used by a map.
On the other hand , map provides collection views through the methods keySet , entrySet and values.


What is UnsupportedOperationException?
UnsupportedOperationException is a runtime exception that is used by the collections to indicate that the requested operation is not supported.


For example - UnmodifiableCollection throws this exception for add and remove methods.

What is read-only collection ? How can we create the same?
The read-only collections are those whose contents cannot be modified and any such attempt will result in UnsuppotedOperationException.
Collections utility class provides various methods that returns unmodifiable views of the specified collection.

For example , If we create a unmodifiable list and then try to add some data in it , we get UnsuppotedOperationException.


Collection readOnlyList = Collections.unmodifiableCollection(list);
// Any attempt to modify the list will result in UnsuppotedOperationException.
readOnlyList.add("new data");


What are thread safe collections ? Thread safe collection classes are those which are properly synchronized to be used in a multithreaded environment. For example Vector and Hashtable. Collections class contains some utility methods to make a thread safe collection.
For Example - Collections.synchronizedCollection returns a thread-safe collection backed by the specified collection.

What are concurrent collection classes?
Java 5 added a new Java package to the Java platform , the java.util.concurrent package.  This package contains a set of classes that makes it easier to develop concurrent applications in Java.
Some examples are :
ConcurrentMap
ConcurrentNavigableMap
CountDownLatch


What is List interface? What are its main implementations?
List is an ordered collection of elements ( also known as sequence ) . The ordering is index based. A list can have duplicate elements in it and permite multiple null values.
ArrayList , LinkedList , Stack , Vector are some of its implementations.


What is the difference between Array and ArrayList?

  • ArrayList is a growing array . That means the size of an Array is fixed but the ArrayList can grow dynamically.The size of an array need to be defined at the time of its initialization.
  • Array can contain primitives or Objects whereas ArrayList can only contain Objects.
  • ArrayList provides a lot more methods for insertion/retrieval of data as compared to an array.


What is the difference between ArrayList and Vector?

  • Vector is synchronized whereas ArrayList is not.
  • ArrayList is faster than Vector because it is not synchronized. 
  • By default , Vector doubles the size of its array when it is re-sized internally , whereas an ArrayList increases by half of its size when re-sized. 

In general ArrayList is prefered over Vector because we can easily get an unmodifiable list or a synchronized list by using methods of Collections class.


What is the difference between ArrayList and LinkedList?

  • LinkedList stores the elements in a doubly-linked list where as ArrayList is backed by an array.
  • Adding and removal of elements is faster in a LinkedList (constant time insertion or removal ) .The addition and removal of elements is slower in an array because it involves shifting of elements when an element is added in the middle.
  • Searching an element is faster in ArrayList as it allows random access and thus gives constant time performance. 


How to get an array from an ArrayList?
List contains  method toArray that can be used for converting a list into an array.
Example :
List<String> names = new ArrayList<String>();
list.add("prakash");
list.add("chauhan");
list.add("java");
list.add("world");


String [] namesArray = names.toArray(new String[list.size()]);


How to sort list in reverse order?
Use reverse method of Collections utility class.
Collections.reverse(list);

How to convert an array of String to ArrayList?
The utility class Arrays provides a method asList that can be used to convert a list into an array.
Example :
String[] namesArray = {"prakash", "chauhan", "java", "world"};
List names = Arrays.asList(words);



What is Set interface ?
Set is the collection of unique elements i.e it does not support duplicate elements. Set is an unordered collection.
Some of the concrete implementations are HashSet , LinkedHashSet , TreeSet


What is EnumSet?
EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. Any attempt to insert null element will throw NullPointerException.


Difference between HashSet and TreeSet ?
HashSet is Implemented using a hashtable. HashSet is unordered collection . The add, remove, and contains methods have constant time complexity O(1).
TreeSet is implemented using a red-black tree. TreeSet is a sorted collection , but add, remove, and contains methods has time complexity of O(log (n)). It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.


What is Map?
Map is collection of mappings i.e key-value pairs. It does not extend Collection interface.
Map is an object that maps keys to values. A map cannot contain duplicate keys and each key can map to at most one value.

Some concrete implementations of map are HashMap, Hashtable, LinkedHashMap.

What are different collection views provided by Map interface?
Three collection views are provided by Map :
  • keySet() : Returns a Set view of the keys contained in the map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
  • values(): Returns a Collection view of the values contained in the map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.
  • entrySet(): Returns a Set view of the mappings contained in the map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.


What is the difference between HashMap and Hashtable?
HashMap and Hashtable both implements Map interface. Below are some differences between them : 
  • Hashtable is synchronized but HashMap is not . Choose Hashtable if thread safety is a concern.
  • HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow anything that is null.
what is capacity and load factor in HashMap?
The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. 
When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

What is collision in HashMap?
Collision occurs in a HashMap if two objects have same hashcode . Now because the hascode is same , bucket location needs to be the same for both the objects .
In such a situation , HashMap uses a linked list to store objects.


What is the difference between HashMap and TreeMap?

  • HashMap is an unordered collection whereas TreeMap is sorted.
  • For inserting, deleting, and locating elements in a Map, the HashMap is the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is the right choice .

Depending upon the size of collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorting.