11. What is the difference between processes and threads ?A process is an execution of a program, while a is a single execution sequence within a process. A process can contain multiple threads. A is sometimes called a lightweight process.
12. Explain different ways of creating a thread. Which one would you prefer and why ? There are three ways that can be used in order for a to be created:
- A class may extend the
- A class may implement the
- An application can use the
framework, in order to create a thread pool.
interface is preferred, as it does not require an object to inherit the class. In case your application design requires multiple inheritance, only interfaces can help you. Also, the thread pool is very efficient and can be implemented and used very easily.
13. Explain the available thread states in a high-level. During its execution, a thread can reside in one of the following :
: The thread becomes ready to run, but does not necessarily start running immediately.
: The Java Virtual Machine (JVM) is actively executing the thread’s code.
: The thread is in a blocked state while waiting for a monitor lock.
: The thread waits for another thread to perform a particular action.
: The thread waits for another thread to perform a particular action up to a specified waiting time.
: The thread has finished its execution.
14. What is the difference between a synchronized method and a synchronized block ? In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in a method level (coarse grained lock) or block level of code (fine grained lock).
15. How does thread synchronization occurs inside a monitor ? What levels of synchronization can you apply ?The JVM uses locks in conjunction with monitors. A monitor is basically a guardian that watches over a sequence of synchronized code and ensuring that only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. The thread is not allowed to execute the code until it obtains the lock.
16. What’s a deadlock ? A condition that occurs when two processes are waiting for each other to complete, before proceeding. The result is that both processes wait endlessly.
17. How do you ensure that N threads can access N resources without deadlock ? A very simple way to avoid deadlock while using N threads is to impose an ordering on the locks and force each thread to follow that ordering. Thus, if all threads lock and unlock the mutexes in the same order, no deadlocks can arise.
18. What are the basic interfaces of Java Collections Framework ? provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are:
, which represents a group of objects known as its elements.
, which is a collection that cannot contain duplicate elements.
, which is an ordered collection and can contain duplicate elements.
, which is an object that maps keys to values and cannot contain duplicate keys.
19. Why Collection doesn’t extend Cloneable and Serializable interfaces ? The interface specifies groups of objects known as elements. Each concrete implementation of a can choose its own way of how to maintain and order its elements. Some collections allow duplicate keys, while some other collections don’t. The semantics and the implications of either cloning or serialization come into play when dealing with actual implementations. Thus, the concrete implementations of collections should decide how they can be cloned or serialized.
20. What is an Iterator ? The interface provides a number of methods that are able to iterate over any . Each Java contains the method that returns an instance. Iterators arecapable of removing elements from the underlying collectionduring the iteration. 21. What differences exist between Iterator and ListIterator ? The differences of these elements are listed below:
can be used to traverse the and collections, while the can be used to iterate only over .
can traverse a collection only in forward direction, while the can traverse a in both directions.
implements the interface and contains extra functionality, such as adding an element, replacing an element, getting the index position for previous and next elements, etc.
22. What is difference between fail-fast and fail-safe ? The fail-safe property works with the clone of the underlying collection and thus, it is not affected by any modification in the collection. All the collection classes in java.util package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw a, while fail-safe iterator never throws such an exception.
23. How HashMap works in Java ? A HashMap in Java stores key-value pairs. The requires a hash function and uses and equals methods, in order to put and retrieve elements to and from the collection respectively. When the put method is invoked, the calculates the hash value of the key and stores the pair in the appropriate index inside the collection. If the key exists, its value is updated with the new value. Some important characteristics of a are its capacity, its load factor and the threshold resizing.
24. What is the importance of hashCode() and equals() methods ? In Java, a uses the and methods to determine the index of the key-value pair and to detect duplicates. More specifically, the method is used in order to determine where the specified key will be stored. Since different keys may produce the same hash value, the method is used, in order to determine whether the specified key actually exists in the collection or not. Therefore, the implementation of both methods is crucial to the accuracy and efficiency of the .
25. What differences exist between HashMap and Hashtable ? Both the and classes implement the Map interface and thus, have very similar characteristics. However, they differ in the following features:
allows the existence of null keys and values, while a doesn’t allow neither null keys, nor null values.
is synchronized, while a is not. Thus, is preferred in single-threaded environments, while a is suitable for multi-threaded environments.
provides its set of keys and a Java application can iterate over them. Thus, a is fail-fast. On the other hand, a provides an of its keys.
class is considered to be a legacy class.
26. What is difference between Array and ArrayList ? When will you use Array over ArrayList ? The and classes differ on the following features:
can contain primitive or objects, while an can contain only objects.
have fixed size, while an is dynamic.
provides more methods and features, such as , , , etc.
- For a list of primitive data types, the collections use autoboxing to reduce the coding effort. However, this approach makes them slower when working on fixed size primitive data types.
27. What is difference between ArrayList and LinkedList ?Both the and classes implement the List interface, but they differ on the following features:
is an index based data structure backed by an . It provides random access to its elements with a performance equal to O(1). On the other hand, a stores its data as list of elements and every element is linked to its previous and next element. In this case, the search operation for an element has execution time equal to O(n).
- The Insertion, addition and removal operations of an element are faster in a
compared to an , because there is no need of resizing an array or updating the index when an element is added in some arbitrary position inside the collection.
consumes more memory than an , because every node in a stores two references, one for its previous element and one for its next element.
Check also our article ArrayList vs. LinkedList.
28. What is Comparable and Comparator interface ? List their differences. Java provides the interface, which contains only one method, called . This method compares two objects, in order to impose an order between them. Specifically, it returns a negative integer, zero, or a positive integer to indicate that the input object is less than, equal or greater than the existing object. Java provides the interface, which contains two methods, called and . The first method compares its two input arguments and imposes an order between them. It returns a negative integer, zero, or a positive integer to indicate that the first argument is less than, equal to, or greater than the second. The second method requires an object as a parameter and aims to decide whether the input object is equal to the comparator. The method returns true, only if the specified object is also a comparator and it imposes the same ordering as the comparator.
29. What is Java Priority Queue ? The is an unbounded queue, based on a priority heap and its elements are ordered in their natural order. At the time of its creation, we can provide a Comparator that is responsible for ordering the elements of the . A doesn’t allow null values, those objects that doesn’t provide natural ordering, or those objects that don’t have any comparator associated with them. Finally, the Java is not thread-safe and it requires O(log(n)) time for its enqueing and dequeing operations.
30. What do you know about the big-O notation and can you give some examples with respect to different data structures ? The Big-O notation simply describes how well an algorithm scales or performs in the worst case scenario as the number of elements in a data structure increases. The Big-O notation can also be used to describe other behavior such as memory consumption. Since the collection classes are actually data structures, we usually use the Big-O notation to chose the best implementation to use, based on time, memory and performance. Big-O notation can give a good indication about performance for large amounts of data.
31. What is the tradeoff between using an unordered array versus an ordered array ? The major advantage of an ordered array is that the search times have time complexity of O(log n), compared to that of an unordered array, which is O (n). The disadvantage of an ordered array is that the insertion operation has a time complexity of O(n), because the elements with higher values must be moved to make room for the new element. Instead, the insertion operation for an unordered array takes constant time of O(1).
32. What are some of the best practices relating to the Java Collection framework ?
- Choosing the right type of the collection to use, based on the application’s needs, is very crucial for its performance. For example if the size of the elements is fixed and know a priori, we shall use an
, instead of an .
- Some collection classes allow us to specify their initial capacity. Thus, if we have an estimation on the number of elements that will be stored, we can use it to avoid rehashing or resizing.
- Always use Generics for type-safety, readability, and robustness. Also, by using Generics you avoid the
- Use immutable classes provided by the Java Development Kit (JDK) as a key in a Map, in order to avoid the implementation of the
and equals methods for our custom class.
- Program in terms of interface not implementation.
- Return zero-length collections or arrays as opposed to returning a null in case the underlying collection is actually empty.
33. What’s the difference between Enumeration and Iterator interfaces ? is twice as fast as compared to an Iterator and uses very less memory. However, the is much safer compared to , because other threads are not able to modify the collection object that is currently traversed by the iterator. Also, allow the caller to remove elements from the underlying collection, something which is not possible with .
34. What is the difference between HashSet and TreeSet ?The is Implemented using a hash table and thus, its elements are not ordered. The add, remove, and contains methods of a have constant time complexity O(1). On the other hand, a is implemented using a tree structure. The elements in a are sorted, and thus, the add, remove, and contains methods have time complexity of O(logn).