Spring MVC Framework Collection API Question - 2

This is the second set of questions that are generally asked for Collection Framework questions. These are a bit more advanced then the earlier set of questions.

Question 1: What is difference between ArrayList and LinkedList?
There are quiet a few difference between ArrayList and LinkedList:
  1. ArrayList uses a primitive array to store the values internally. However, LinkedList is made up of nodes where each nodes has three elements: value, pointer to next element and pointer to previous element.
  2. ArrayList implements the RandomAccess interface whereas LinkedList does not. RandomAccess is a marker interface which states that the implementation implements the fast algorithm to access the Nth element. So accessing Nth element is fast and takes constant-time for ArrayList whereas LinkedList has to scan the whole list to find the Nth element, hence making it slower for random access.
  3. Inserting and deleting an element at the start and end is faster in LinkedList as compared to ArrayList. While inserting an element in the LinkedList at the start and the beginning , we just need to create a node and assign the pointers whereas in ArrayList if you are inserting an element at the start, then first it will copy all the elements in a different list and then adds them after it, similarly while adding an element at the end means ArrayList will have to scan the whole list for inserting an element.
  4. LinkedList usually takes more memory than ArrayList as each node in the LinkedList will also store the next and previous pointers.
  5. ArrayList may also have issue if your list fills up quiet frequently as the ArrayList will create a new list with increased capacity and then copies all the elements whereas no such thing is required for LinkedList.
Question 2: Where will you use ArrayList and where will you use LinkedList?
If you have add elements at the start and end frequently or iterate over it for deleting elements then you should consider using LinkedList as it requires constant time for these operations and linear-time in ArrayList. If you have to access the positional elements then you should consider using ArrayList as it takes constant time for that and LinkedList take linear time for positional access.

Question 3: What is the difference between HashMap and HashTable?
The main difference is that HashTable is synchronised whereas HashMap is not. You need to provide external synchronisation if you want to synchronise the HashMap. Another difference is that HashTable does not allows null as keys or values whereas HashMap allow one null key and any number of null values.

Question 4: What is the difference between HashMap and TreeMap?
The basic difference is that in TreeMap objects are stored in an order decided either by the natural ordering of key or by the comparator that is defined at the the instantiation time of the TreeMap whereas HashMap does not guarantee any ordering. Since the elements are stored in an order, I think it is safe to say that the insertion of element in TreeMap will be slower as compared to HashMap whereas retrieval will be faster than HashMap.

Question 5: Explain how HashMap works or how the hashcode() and equals() method is used by the HashMap or how the get() method works in HashMap?
This question generally is the starting point for more complicated questions on HashMap. Basically what happens is when we call get(), put() method of HashMap. The HashMap uses the hashcode() method of the key to find the hashcode, then it uses its internal hashing mechanism to find the index of the correct "bucket" where the value might be stored. This bucket contains a list of Map.Entry objects in the form of a linked list. Once the bucket is identified, the map will traverse through the Map.Entry to find the exact key by using equals method, once found it will overwrite or return the value.

Question 6: How is HashSet implemented? or How will you implement the HashSet using HashMap?
Actually if you look closely on the HashMap methods there is already a set in the HashMap, they keySet. It has all the properties like no duplicates (HashMap does not allow duplicate keys). So, all you need to do is following, when you insert an object in HashSet, you insert the object as key in the HashMap and put the value as an EMPTY object. Same is the case when retrieving a value from HashSet, rather returning a value just return the key.

Question 7: Is Collection.synchronisedMap() is really thread-safe?
Question 8: What is the difference between ArrayList and Vector?
As per the Java API, the main difference between the ArrayList and Vector is that Vector is synchronised whereas ArrayList is not. The other difference is the way there size is incremented, Vector always doubles the size whereas ArrayList increases the size by half the initial capacity. So if there is a need for thread-safety is advisable to use Vector but since synchronisation takes a hit on the performance we may consider using the ArrayList and synchronise it using the Collections utility class.

Question 9: What are the mandatory  methods you should override while using TreeMap and why?

Spring MVC Framework Test Driven Development - using Eclipse

TDD is getting very important these days due to some of its benefits that most of the bugs are found at the development stage. Unit tests are already in place which gives you a better code coverage, more confident code and more importantly you always know that the addition of behaviour has not broken your previous code. Apart from that there are other benefits like you may end up getting a better design than you originally thought. It will also help in using a lot of patterns in your code, which may not be visible at the start.

I was going through some videos here, that explains how to use TDD in Java Development in Eclipse. The instructor has actually broken it down nicely and try to convince you of all the above points.

I liked some of his principle or things to remember, which are:
  • We are only doing one activity at a time
  • We can be doing any one activity of the four
    • Writing Test
    • Writing Production Code
    • Refactoring / updating / Cleaning Test code
    • Refactoring / updating / cleaning production code
  • We are only going to write production code when we have a failing test
  • When we add a test, earlier written test should not fail

Spring MVC Framework Basic Java Questions - 2

This is the second part of Basic Questions asked on Core Java. Please leave a comment if you think there is something wrong with an answer as it will help me greatly.
Question 1: What is data encapsulation in Java?
Data Encapsulation is the process of hiding the internal information from the external world. The information can only be manipulated using a set of operations exposed by the objects known as methods. This is also called as data hiding.

Question 2: What is the difference between Abstract Class and Interface?
Interface is a pure abstract class, means all the methods in interface are abstract whereas in Abstract class we can have non-abstract methods. All the methods in an interface are public by default, whereas Abstract class can have methods with other access modifier. All the method in an interface have only definition and no declaration, whereas an Abstract class can have method with the default implementation. All the member variables in the interface are final, whereas Abstract class can have non-final variables. An interface needs to be implemented using implements whereas an Abstract class needs to be extended using extends. A Java class can implement multiple interfaces but can only extend one Abstract class.

Question 3: Can I have an Abstract Class without any abstract method and vice-versa?
You can have an abstract class without any abstract method, if you don't declare a class as Abstract that have abstract methods, the class will give compilation error.

Question 4: What is the difference between Exception and Error?
Basically a user can recover from an exception at runtime but not from an Error. For example, a user program may recover from an FileNotFoundException, however, it wont be able to recover from an OutOfMemoryError. In other words, Exceptions are programmer generated and should be handled at the application level, whereas Errors are system generated and should be handled at the system level, if possible.

Errors are also a sub class of the Throwable, however we should try to avoid catching errors. If you have a catch Throwable, the block will also catch the Error, which is not a good practice.

Question 5: What is the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when the class is loaded using one of the following methods:
  • The forName method in class Class.
  • The findSystemClass method in class ClassLoader .
  • The loadClass method in class ClassLoader.
Whereas, NoClassDefFoundError is encountered, when the JVM is trying to load the class as part of a normal method call or as part of creating a new instance using the new expression.

Question 6: Under what condition does finally block will not execute?
Finally block is a block in Java program, which gets executed most of the times. There are only few conditions under which the finally clock will not get executed.
1. If the Application executing the try or catch block exits by calling System.exit or by shutting down JVM.
2. If a thread executing the try or catch block is killed or interrupted, the finally block will not execute.

Question 7: Can you have a finally block without catch?
Yes, you can have finally block with the try statement, without a catch statement.

Spring MVC Framework Spring Interview Questions - 1

Spring is one of the most widely used framework in the Java/J2EE application. Almost all the job postings / consultancy requirements list Spring as one of the key skills. So it is no surprise that most of the interviews contains a wide list of Spring related questions. Here we will try to list some of the basic questions asked on the Spring Framework.
Question 1: What is Spring Framework?
Spring is an open source lightweight inversion of control application framework that supports the various aspects of application development.

Question 2: What are its features?
Spring has the following features:
  • Lightweight
  • Inversion of Control - A component lists its dependencies rather than looking for dependent objects.
  • Container - Contains and manages the lifecycle of various application components.
  • Aspect Oriented - Cross cutting concerns are handled separately through AOP module.
  • Transaction Management - Spring container provides an abstract layer of components to handle the transaction management thus allowing the developers to concentrate more on the business logic and allowing them to demarcate the transactions without worrying about the low-level issues, by providing plugable transaction managers. The spring transaction management can be run in a container less environment as well.  
  • JDBC Handling - Spring can be easily integrated with the Hibernate, JDO and iBATIS.
  • MVC Framework - Spring comes with a MVC framework as well which can use various presentation technologies like JSP, JSF, Velocity and Tiles etc. However, if you wish you to use some other MVC framework spring can be easily integrated with them as well.
Question 3: What is Inversion of Control / IoC?
Inversion of Control or IoC is a phenomenon used by frameworks to invert the control. Basically, in traditional programming the user / developer control the calling of a procedure, however when using IoC the framework controls the calling mechanism. Hence, saying simply that the framework calls us, we don't call it. Although the above statement state the calling of procedure, this can be used for any development term like instantiation etc. A better and elaborated discussion can be found here by Martin Fowler. Servlets, EJB, template method pattern can be stated as examples of Inversion of Control, in general they are Inverting the control. (Hint: Don't call us, we will call you.)

Question 4: How is Inversion of Control different from Dependency Injection?
Inversion of Control is a principle that is being followed in many frameworks, however dependency injection in one such patter that is built on top of IoC. IoC is generally followed in all framework as they are trying to invert some sort of control, however every framework may not provide you with dependency injection. In dependency injection it is the dependency creation control that is being inverted. In DI, rather than object creating the dependencies the framework will invert the control and inject dependencies. More on this can be found here.

Question 5: What pattern does Spring uses to create beans?
Generally there are lot of design patterns used in Spring to create beans. For Example,
  • Proxy interface, in case of AOP
  • Singleton, beans created in spring are singleton by default
  • Template method, in case of JdbcTemplate, JmsTemplate etc.
  • Abstract Factory pattern, is use to register and then instantiate various beans defined in the Configuration file.
Question 6: What are the ways to inject beans in Spring and which one should be used where?
In Spring beans can be inject by the setter method or by constructor. In Setter Injection, the bean is created using the default constructor or no-arg constructor and then the setter methods are called in to inject various beans. In Constructor Injection, the bean is created using the Constructed with a number of arguments and then these arguments can be inject while instantiation. Now the question arises which one should be used. IMHO I think we should use a combination of both. You should have a constructor with the "Required" arguments or collaborators and should have setter injection for dependencies which are optional. In this way, you are also making sure that you have all the required dependencies during its instantiation and optional properties can be set using setter injection. You can refer to the following blog at springsource to learn more about the above reason.

Question 7: What is JdbcTemplate in Spring DAO?
JDBCTemplate is the central class in the Spring DAO module, it has the template methods to open and close various resources, hence decreasing the programming errors. This class provides the basic workflow for a JDBC like opening the connection, preparing the statement , executing and then closing the connection thus leaving the application code to only provide the SQL and retrieve the results. It has methods for executing SQL queries, update statements and procedure calls. It also provides the methods for iterating over a result set. This class also catches SQL Exceptions and generates more informative exceptions defined in the Spring Exception hierarchy.



Spring MVC Framework Basic Java Questions - 1

This page contains the list of question that are generally asked in the Java General Questions. They can also be termed as questions asked on Basic Java Language.
Question 1: What is the difference between java.util.Date and java.sql.Date?
The main difference is that java.util.Date represents "date and time" stored upto a milisecond. However, java.sql.Date only stores data value which is required for the SQL DATE type. java.sql.Date has a java.sql.Time counterpart which stores only time.

Question 2: What is the difference between String, StringBuffer and String Builder?
  • String is immutable whereas StringBuffer/StringBuilder are not. It means it gives faster performance while update operations. 
  • StringBuffer is synchronised whereas StringBuilder is not.
  • Use String if you need immutability, use StringBuffer is you need mutability and thread-safety, use StringBuilder if you need mutability but not thread safety. 

Question 3: What are various visibility modifiers in Java and what is the difference between them?
There are four access modifiers : public, private, protected and default. There accessibility is as defined below:

public - Any class can access it directly.
protected - It is available to class, subclasses and package.
default or no-modifier: It has the package accessibility but is not available to subclasses.
private: This is only visible with the class itself.

Question 4: What is difference between .equals and "=="?
"==" checks whether the two references refer to the same instance whereas .equals check if the two different instances are equal.

Question 5: What is the relationship between .equals and hashcode()? or Why is it a good practise to either override both .equals() and hashcode() or none at all?
The relationship can be explained in simple way as, if two objects returns true for .equals() then their .hashcode() method must return the same value. However, if .hashcode() value returns same value .equals() may not return true, provided .hashcode() and .equals() uses the same fields for evaluation.

You should always override both these methods together because they should use the same fields to evaluate hashcode() and compare the two objects in .equals().

Question 6: Why is clone method "protected" in the Object class?
Default method in the Object class does not provide any implementation, so it does not make sense to make it public. Also, the object which needs to be cloned needs to implement Cloneable interface. Any object that wishes to be available for cloning can override this method and make it public.

Question 7: Is Generics a compile-time feature or runtime feature?
Generics are a compile-time feature, they help us to find some of the bugs at compile-time itself. Generics helps in ensuring the strong type checking. This information is not kept along with the compiled version of class.

Question 8: What is the use of serialVersionUId in Serializable class?
serialVersionUId is used in the serialization and de-serialization process. While serialization and de-serialization the serialVersionUId needs to be same. In case, the serialVersionUId is changed in a class the JVM will throw an "InvalidClassException". You should only change the serialVersionUId only,  when your serialization class is updated by some incompatible Java types changes to a serializable class. Please refer this for further explanation on serialVersionUId.

Question 9: What is the difference between Serializable and Externalizable?
When a class implement the serializable interface, the JVM will serialize and de-serialize the class variables by itself, however, if you want to change the way serialization is done you need to implement the Externalizable interface. When you implement the Serializable interface you dont need to implement any method the JVM will use reflection to serialize your class. However, if you implement Externalizable interface, you need to implement two methods readExternal() and writeExternal(). If you have implemented Serializable you can still control the serialization by writing two methods in your class namely, readObject() and writeObject().

Question 10: How can you control which fields should be serialized?
There are three exceptions to the Serialization process. They are:
1) Static fields are not serialized.
2) transient fields are not serialized.
3) Base class variables are only serialized if the Base class itself implement Serializable.

Spring MVC Framework Collection API Questions - 1

Java Collection Framework is one of the hot favourite among interviewers. The reason for that is any Java program uses Java Collection Framework intensively and any manager hiring for his team would like to see that you have basic and some advanced knowledge in the Collection API. Other reason that I find for interest in Collection Framework is that the questions will help in identifying whether the candidate knows how the various Data Structures are implemented in Java explaining his interest. 

In this post I will try to list some of the beginner to advanced level questions asked on the Collection Framework.


Question 1: What is the Java's collection API?
Java's Collection API is a unified architecture of interfaces, classes and algorithms that are required for representing and manipulation of Collections. For example, List, Map, Set and the like. Benefit of these classes is as follows:
1.        It reduces the programming effort for the developers.
2.        It increases the program speed and quality, since the Collection API provides the high-performance and high quality implementation of the data structure and the algorithms required for their manipulation.
2.        It increase software re-usability.
3.        Reduces efforts to learn and create basic data structures API’s

An excerpt from the Java's Collection Trail 



















Question 2: What are the basic interfaces in the Collection API?
Basic interfaces in the collection API are:

1. Collection: This is the parent interface and all other interfaces extend this interface.
2. Set: This is a core interface to represent a mathematical set, the basic thing about a set is it 
             does not have duplicate values and at most have one null value.
3. List: An ordered collection or sequence, the user of this interface has precise control over 
            where each element is inserted. The user can access each element by its index /  
            position. It differs from the set in the way, that it allows duplicates and null values.
4. Queue: This is a collection used to hold multiple elements prior to processing. Queues 
                  typically, but do not necessarily, order elements in a FIFO (first-in, first-out) manner. 
                 Among the exceptions are priority queues, which order elements according to a  
                 supplied comparator or the elements' natural ordering. Whatever the ordering used, 
                 the head of the queue is the element that would be removed by a call to remove or  
                 poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other 
                 kinds of queues may use different placement rules.
5. Map: This is a collection of key-value pair. A Map cannot contain duplicate keys; each key 
              can map to at most one value.

The other two core interfaces are merely sorted versions of set and map.

1. SortedSet: This is a Set that maintains its elements in ascending order. Several additional  
                        operations are provided to take advantage of the ordering.
2. SortedMap: This is a Map that maintains its mappings in ascending key order.

Their hierarchy is depicted in the below diagram.


Question 3: What is the difference between Set and List?
The basic difference between a Set and List is that set does not allow duplicates and allows at most one null value. Also, List is an ordered collection of elements whereas set is an unordered collection of elements.

Question 4: Why doesn't Map interface extend Collection?
Theoretically, let us assume that Map extends Collection, So what exactly are the elements of this collection? The only answer to this is "key-value" pair. But you cannot really iterate over these elements without knowing the value of key. However, Map can be viewed as a collection of the keys, values, key-value pair or entrySets. Depicting this behaviour Map does provide the collection view method keySets(), values(), entrySets().

Similary, if the Collection interface extends Map interface, then what are the keys of these elements. There is no satisfactory example.While it is possible to view List as a possible map with the indices as the keys, this has a property that when you remove an element from the List, it changes the keys of the elements preceding it and hence the reason that we don't have Map view operations on the list.

Question 5: Why doesn't Collection extends Cloneable or Serializable interface?
The only answer I can think of is that it is rarely required to clone or serialize the whole collection. There are serializable / cloneable implementations of the Collection. So, if the user want to create a Cloneable/Serializable collection, he can create a generic collection and then can use addAll() to insert the collection in a cloneable / serializable collection implementation.

Question 6: What are the other useful interfaces in Collection Framework?
Other useful interfaces are:

  • Iteration : Enumerator, Iterator, ListIterator
  • Ordering: Comparable, Comparator
  • Performance: RandomAccess
Question 7: What is the difference between Enumerator, Iterator and ListIterator?
Property
Enumeration
Iterator
ListIterator
Number of method
2
3
9
Method names
hasMoreElements(), nextElement()
hasNext(), next(), remove().
add(), hasNext(), next(), hasPrevious(), previous(), nextIndex(), previousIndex(), set(),remove().
Access Direction
Forward-only
Forward only
Bi-directional
Summary
It provides a read only traversal of the collection. Legacy classes such as Vector and HashTable returns this
Iterator provides a method to remove an element from the iterator. Java Collection Framework classes return this.
It provides a bi-directional access on the collection and hence has methods to support it, like previous() and next(). It also allows the modification of elements using set() and add() operation.


Spring MVC Framework Multi threading Interview Questions - 1

Multi-threading is a concept that even some of the experience developers also find difficult to understand. If you are appearing for investment bank, insurance or healthcare technology services company, the chances are that you will be tested thoroughly on the multi-threading concepts. Depending upon your experience, the questions may vary from basic to advanced levels. There are generally a set of written questions as well on this topic, which I will try to compile very soon. So, here is the list of basic questions on multi-threading.

Question 1: What is difference between a process and thread?
A process is a single execution of a program whereas a thread is a single execution sequence within a process. A process may contain multiple threads. A thread is sometimes referred to as a lightweight process. Threads in a JVM share the same heap space. Hence, threads can share same object. Threads have their own stack space, this is how one invocation of a method and its local variables are kept thread safe. Heap is not thread safe and hence must be synchronised for thread safety. 

Question 2: What are the different ways of creating Threads?
1) By implementing Runnable
2) By Extending Thread class
3) By using Executor Framework

Question 3: Which of the above method should be use?
Generally we should try to create threads by implementing Runnable as it will come in handy, when we need multiple inheritance.

Question 4: What are Thread states possible?
Thread can have the following states:
1) Runnable - Thread has started and is waiting for the Thread Scheduler to pick and execute.
2) Running - Thread is actively executing the code.
3) Waiting - Waiting for some external event like finish a file I/O to finish.
4) Sleeping - Thread are put to sleep for a certain period of time and will become runnable when it wakes from sleeping duration.
5) Blocked on I/O or Synchronised: Blocked by an external call to I/O or waiting to acquire lock.
6) Dead - Thread has finished executing code.
Question 5: What is difference between sleep and wait method?
Sleep method is used to stop the thread execution for a certain period of time, whereas wait method is used to make the thread wait for some external event or woke up by another thread by calling notify() or notifyAll().

Question 6: What is the difference between notify() and notifyAll()?
notify() and notifyAll() methods are used to pass the control to another thread that might be in the waiting state. When we call notify() it only means that the call will wake up the thread next in line. However, by calling notifyAll() we are actually passing the control to a larger number of threads which in turn may again compete to get control.

Question 7: What is difference between Thread.start() and Thread.run()?
Thread.start() actually does the job of calling Thread.run(). If we call the Thread.run() directly then it would be a simple method call from the main thread. It will not cause the thread to run independently.

Question 8: When is the InvalidMonitorStateException is thrown? why?
This exception is thrown when we try to call wait(), notify() or notifyAll() methods on an object in your program where you do not have the lock on the object. InvalidMonitorStateException extends RuntimeException and hence we do not need to catch it.

Question 9: What happens if the static method is defined as synchronized?
Executing such a method would mean that the thread has acquired a "Class" level lock, which means other threads cannot executed any other "static synchronized" method. This is different then the instance method synchronization in the way that two threads can execute the same synchronized instance method as long as they are executing it on the different instance of the object.