Java Interview Java Script
Friday, 4 September 2015
Collection : Data Structure Links ?
What are the main concerns when choosing a collection?
What is rehashing?
What is load factor?
What is collisions?
what is Red Black tree?
Collection Implementations are :
1.Linked implementation :- LinkedList, LinkedHashSet
2.Array implementation :- ArrayList
3.Hash Implementation :- HashSet, HashMap
4.Tree Implementation :- TreeMap, TreeSet
Collection : Difference between HashMap and HashTable in Java ?
Parameter | Hashmap | Hashtable |
---|---|---|
Synchronized | Not Syncronized | Syncronized |
Null key and Value | Allows one null key and any number of null values | Not allow null keys or values |
Fail fast | Iterator in Hashmap is fail fast | Enumeration in Hashtable is not fail fast |
ThreadSafe | No | Yes |
Extends | Extends AbstractMap class | Extends Dictionary class |
Performance | Faster then Hashtable | Slower then Hashmap |
Collection : Difference between HashMap and HashTable?
The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.
Collection : What are the differences between Map, Hashtable, HashMap, TreeMap, ConcurrentHashMap, LinkedHashMap?
- Map is an interface for a key-value map
- HashMap is a Map that uses a hash table for its implementation
- Hashtable is a synchronized version of HashMap
- TreeMap uses a tree to implement a map
- ConcurrentHashMap allows for multiple threads to access it at the same time safely
- LinkedHashMap preserves the iteration order that things were inserted in (others don’t provide a fixed iteration order)
A deeper discussion of the differences can be found in Advanced Java Programming.
Collection : How to avoid ConcurrentModificationException while iterating a collection?
We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.
Check this post for ConcurrentHashMap Example.
Check this post for ConcurrentHashMap Example.
Collection : What is difference between fail-fast and fail-safe?
Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection. By design, all the collection classes in java.util package are fail-fast whereas collection classes in java.util.concurrent are fail-safe. Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException. Check this post for CopyOnWriteArrayList Example.
Collection : What do you understand by iterator fail-fast property?
Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException.
All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.
Collection : What are different ways to iterate over a list?
We can iterate over a list in two different ways – using iterator and using for-each loop.
Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException.
When you serialize an object, what happens to the object references included in the object?
The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
How can I customize the seralization process? i.e. how can one have a control over the serialization process?
Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
Which methods of Serializable interface should I implement?
The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
What is serialization?
Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
What is serialization and deserialization?
Serialization is the process of converting a objects into a stream of bytes.
Serialization - Turn data into a stream of bytes.
De-Serialization - Turn a stream of bytes back into a copy of the original object.
A java class can be saved in byte stream with a version id and can be invoked again. Saving class in byte stream is called Serialization and fetching that class is called Deserialization.. To achieve this, a class has to implementjava.io.Serializable interface.
What synchronization constructs does Java provide? How do they work?
The two common features that are used are:
1. Synchronized keyword - Used to synchronize a method or a block of code. When you synchronize a method, you are in effect synchronizing the code within the method using the monitor of the current object for the lock.
The following have the same effect.
synchronized void foo() {
}
and
void foo() {
synchronized(this) {
}
2. wait / notify.
wait() needs to be called from within a synchronized block. It will first release the lock acquired from the synchronization and then wait for a signal.
When somebody calls notify() on the object, this will signal the code which has been waiting, and the code will continue from that point.
If there are several sections of code that are in the wait state, you can call notifyAll() which will notify all threads that are waiting on the monitor for the current object.
Remember that both wait() and notify() have to be called from blocks of code that are synchronized on the monitor for the current object.
Define strings?
Strings represent a sequence of characters.The easiest way to represent a sequence of characters in java is by using a character array.
Why character array is better than string for storing password in java?
Strings in Java are immutable objects. This means that they can't be modified once created, and so the only way for their contents to be removed from memory is when they are garbage collected, at which point the memory once used for them will be freed and can eventually be overwritten with other data.
The problem with garbage collection is that it doesn't happen at any kind of guaranteed interval. The strings may persist in memory for a long time, and if a process crashes during this time, the contents of the string may end up in a memory dump or the like. With a character array, you can read the password, finish working with it as soon as you can, and then immediately zero out the array, for example via Arrays.fill (passwordArray, (char)0).
Even this isn't fully secure, because it's just reducing the window of opportunity for someone's password to show up in a memory dump somewhere, not eliminating the core problem. You should try to always minimize the need to store any passwords at all and try to store cryptographically strong hashes of passwords instead when possible.
Why String class is final or immutable?
It is very useful to have strings implemented as final or immutable objects. Below are some advantages of String Immutability in Java
- Immutable objects are thread-safe. Two threads can both work on an immutable object at the same time without any possibility of conflict.
- Security: the system can pass on sensitive bits of read-only information without worrying that it will be altered
- You can share duplicates by pointing them to a single instance.
- You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret that makes Java substring implementation very fast.
- Immutable objects are good fit for becoming Hashtable keys. If you change the value of any object that is used as a hash table key without removing it and re-adding it you will lose the object mapping.
- Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth.
- If String were not final, you could create a subclass and have two strings that look alike when "seen as Strings", but that are actually different.
What is difference between String, StringBuffer and StringBuilder? When to use them?
The main difference between the three most commonly used String classes as follows.
- StringBuffer and StringBuilder objects are mutable whereas String class objects are immutable.
- StringBuffer class implementation is synchronized while StringBuilder class is not synchronized.
- Concatenation operator "+" is internally implemented by Java using either StringBuffer or StringBuilder.
Criteria to choose among String, StringBuffer and StringBuilder
- If the Object value will not change in a scenario use String Class because a String object is immutable.
- If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster).
- If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).
OOP : What is an abstract class?
Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.
JDBC:How do you register a driver?
There are 2 approaches for registering the Driver:
- Class.forName(): This method dynamically loads the driver's class file into memory, which automatically registers it. This method is preferable because it allows you to make the driver registration configurable and portable.
- DriverManager.registerDriver(): This static method is used in case you are using a non-JDK compliant JVM, such as the one provided by Microsoft.
JDBC:What is difference between statement and prepared statement?
Prepared statements offer better performance, as they are pre-compiled. Prepared statements reuse the same execution plan for different arguments rather than creating a new execution plan every time. Prepared statements use bind arguments, which are sent to the database engine. This allows mapping different requests with same prepared statement but different arguments to execute the same execution plan. Prepared statements are more secure because they use bind variables, which can prevent SQL injection attack.
What are the different types of JDBC Statements?
Types of statements are:
- Statement (regular SQL statement)
- PreparedStatement (more efficient than statement due to pre-compilation of SQL)
- CallableStatement (to call stored procedures on the database)
What is JDBC? Describe the steps needed to execute a SQL query using JDBC.
We can connect to databases from java using JDBC. It stands for Java DataBase Connectivity.
Here are the steps:
1. Register the jdbc driver with the driver manager
2. Establish jdbc connection
3. Execute an sql statement
4. Process the results
5. Close the connection
Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
What is Executors Class?
Executors class provide utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable classes.
Executors class can be used to easily create Thread Pool in java, also this is the only class supporting execution of Callable implementations.
What are Concurrent Collection Classes?
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 ConcurrentModificationException.
Concurrent Collection classes support full concurrency of retrievals and adjustable expected concurrency for updates.
Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet, check this post to learn how to avoid ConcurrentModificationException when using iterator.
Major classes are ConcurrentHashMap, CopyOnWriteArrayList and CopyOnWriteArraySet, check this post to learn how to avoid ConcurrentModificationException when using iterator.
What is FutureTask Class?
FutureTask is the base implementation class of Future interface and we can use it with Executors for asynchronous processing. Most of the time we don’t need to use FutureTask class but it comes real handy if we want to override some of the methods of Future interface and want to keep most of the base implementation. We can just extend this class and override the methods according to our requirements. Check out Java FutureTask Example post to learn how to use it and what are different methods it has.
What is Callable and Future?
Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
Check this post for Callable Future Example.
Check this post for Callable Future Example.
What is BlockingQueue? How can we implement Producer-Consumer problem using Blocking Queue?
java.util.concurrent.BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.
BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.
BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem.
Check this post for producer-consumer problem implementation using BlockingQueue.
Check this post for producer-consumer problem implementation using BlockingQueue.
What is Executors Framework?
In Java 5, Executor framework was introduced with the java.util.concurrent.Executor interface.
The Executor framework is a framework for standardizing invocation, scheduling, execution, and control of asynchronous tasks according to a set of execution policies.
Creating a lot many threads with no bounds to the maximum threshold can cause application to run out of heap memory. So, creating a ThreadPool is a better solution as a finite number of threads can be pooled and reused. Executors framework facilitate process of creating Thread pools in java. Check out this post to learn with example code to create thread pool using Executors framework.
What is Lock interface in Java Concurrency API? What are it’s benefits over synchronization?
Lock interface provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.
The advantages of a lock are
The advantages of a lock are
- it’s possible to make them fair
- it’s possible to make a thread responsive to interruption while waiting on a Lock object.
- it’s possible to try to acquire the lock, but return immediately or after a timeout if the lock can’t be acquired
- it’s possible to acquire and release locks in different scopes, and in different orders
Read more at Java Lock Example.
What is atomic operation? What are atomic classes in Java Concurrency API?
Atomic operations are performed in a single unit of task without interference from other operations. Atomic operations are necessity in multi-threaded environment to avoid data inconsistency.
int++ is not an atomic operation. So by the time one threads read it’s value and increment it by one, other thread has read the older value leading to wrong result.
To solve this issue, we will have to make sure that increment operation on count is atomic, we can do that using Synchronization but Java 5 java.util.concurrent.atomic provides wrapper classes for int and long that can be used to achieve this atomically without usage of Synchronization. Go to this article to learn more about atomic concurrent classes.
What is Thread Pool? How can we create Thread Pool in Java?
A thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed.
A thread pool manages the collection of Runnable threads and worker threads execute Runnable from the queue.
java.util.concurrent.Executors provide implementation of java.util.concurrent.Executor interface to create the thread pool in java. Thread Pool Example program shows how to create and use Thread Pool in java. Or read ScheduledThreadPoolExecutor Example to know how to schedule tasks after certain delay.
What is Java Timer Class? How to schedule a task to run after specific interval?
java.util.Timer is a utility class that can be used to schedule a thread to be executed at certain time in future. Java Timer class can be used to schedule a task to be run one-time or to be run at regular intervals.
java.util.TimerTask is an abstract class that implements Runnable interface and we need to extend this class to create our own TimerTask that can be scheduled using java Timer class.
Check this post for java Timer example.
What is Deadlock? How to analyze and avoid deadlock situation?
Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources.
To analyze a deadlock, we need to look at the java thread dump of the application, we need to look out for the threads with state as BLOCKED and then the resources it’s waiting to lock, every resource has a unique ID using which we can find which thread is already holding the lock on the object.
Avoid Nested Locks, Lock Only What is Required and Avoid waiting indefinitely are common ways to avoid deadlock situation, read this post to learn how to analyze deadlock in java with sample program.
What is Java Thread Dump, How can we get Java Thread dump of a Program?
Thread dump is list of all the threads active in the JVM, thread dumps are very helpful in analyzing bottlenecks in the application and analyzing deadlock situations. There are many ways using which we can generate Thread dump – Using Profiler, Kill -3 command, jstack tool etc. I prefer jstack tool to generate thread dump of a program because it’s easy to use and comes with JDK installation. Since it’s a terminal based tool, we can create script to generate thread dump at regular intervals to analyze it later on. Read this post to know more about generating thread dump in java.
What is Thread Group? Why it’s advised not to use it?
ThreadGroup is a class which was intended to provide information about a thread group. ThreadGroup API is weak and it doesn’t have any functionality that is not provided by Thread. Two of the major feature it had are to get the list of active threads in a thread group and to set the uncaught exception handler for the thread. But Java 1.5 has addedsetUncaughtExceptionHandler(UncaughtExceptionHandler eh) method using which we can add uncaught exception handler to the thread. So ThreadGroup is obsolete and hence not advised to use anymore.
1
2
3
4
5
6
7
8
| t1.setUncaughtExceptionHandler( new UncaughtExceptionHandler(){ @Override public void uncaughtException(Thread t, Throwable e) { System.out.println( "exception occured:" +e.getMessage()); } }); |
What is ThreadLocal?
Java ThreadLocal is used to create thread-local variables. We know that all threads of an Object share it’s variables, so if the variable is not thread safe, we can use synchronization but if we want to avoid synchronization, we can use ThreadLocal variables.
Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. Check this post for small example program showing ThreadLocal Example.
Every thread has it’s own ThreadLocal variable and they can use it’s get() and set() methods to get the default value or change it’s value local to Thread. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread. Check this post for small example program showing ThreadLocal Example.
How to create daemon thread in Java?
Thread class setDaemon(true) can be used to create daemon thread in java. We need to call this method before calling start() method else it will throw IllegalThreadStateException.
Which is more preferred – Synchronized method or Synchronized block?
Synchronized block is more preferred way because it doesn’t lock the Object, synchronized methods lock the Object and if there are multiple synchronization blocks in the class, even though they are not related, it will stop them from execution and put them in wait state to get the lock on Object.
What is volatile keyword in Java?
When we use volatile keyword with a variable, all the threads read it’s value directly from the memory and don’t cache it. This makes sure that the value read is the same as in the memory.
How can we achieve thread safety in Java?
There are several ways to achieve thread safety in java – synchronization, atomic concurrent classes, implementing concurrent Lock interface, using volatile keyword, using immutable classes and Thread safe classes. Learn more at thread safety tutorial.
Subscribe to:
Posts (Atom)