Java Interview Questions

Difference between JDK, JRE and JVM


JVM

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.
The JVM performs following main tasks:
  • Loads code
  • Verifies code
  • Executes code
  • Provides runtime environment

JRE

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at runtime.
If you want to run any java program, you need to have JRE installed in the system. JRE is targeted for execution of Java files i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime libraries.
jre

JDK

JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools. JDK is mainly targeted for java development. i.e. You can create a Java file (with the help of Java packages), compile a Java file and run a java file.
jdk
Diagram to show the relations between JVM, JRE and JDK


Difference between Array and ArrayList in Java 

ArrayArrayList
ResizableNoYes
PrimitivesYesNo
Iterating valuesfor, for eachIterator , for each
Lengthlength variablesize method
PerformanceFastSlow in comparision
MultidimensionalYesNo
Add ElementsAssignment operatoradd method

Difference between ArrayList and LinkedList in Java 

 ArrayList LinkedList
ImplementationResizable ArrayDouby-LinkedList
ReverseIteratorNoYes , descendingIterator()
Initial Capacity10Constructs empty list
get(int) operationFastSlow in comparision
add(int) operationSlow in comparisionFast
Memory OverheadNoYes
Difference between HashMap and Hashtable in Java 

HashMapHashtable
SynchronizedNoYes
Thread-SafeNoYes
Null Keys and Null valuesOne null key ,Any null valuesNot permit null keys and values
Iterator typeFail fast iteratorFail safe iterator
PerformanceFastSlow in comparison
Superclass and LegacyAbstractMap , NoDictionary , Yes
Explain the relation between hashCode() and equals() method ? 
The contract for Object requires that if two objects are equal according to equals() method, then they must have the same hashCode() value.
a.  If  object1.equals(object2) , then  object1.hashCode() == object2.hashCode() should always be true.
b. If object1.hashCode() == object2.hashCode() is true does not guarantee object1.equals(object2)

How ConcurrentHashMap gives better performance as compared to Synchronized HashMap?

Ans: ConcurrentHashMap maintains  a list of 16 locks by default ( number of locks equal to the initial capacity , which is by default  16) each of which is used to lock on a single bucket of the Map.This indicates that 16 threads (number of threads equal to the concurrency level , which is by  default 16) can modify the collection at the same time , given ,each thread works on different bucket. So unlike hashtable, we perform any sort of operation ( update ,delete ,read ,create) without locking on entire map in ConcurrentHashMap.

What is difference between StringBuffer and StringBuilder in Java ?

StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized.
What will happen if you call return statement or System.exit on try or catch block ? will finally block execute?
Ans: finally block will execute even if you put return statement in try block or catch block but finally block won’t run if you call System.exit form try or catch.
Can you override private or static method in Java ?
Ans: you can not override private or static method in Java, if you create similar method with same return type and same method arguments that’s called method hiding.
What will happen if we put a key object in a HashMap which is already there ?
Ans: if you put the same key again than it will replace the old mapping because HashMap doesn’t allow duplicate keys.

What is the difference between final, finally, and finalize?

Final:
When applied to a variable (primitive): The value of the variable cannot change.
When applied to a variable (reference): The reference variable cannot point to any other object on the heap.
When applied to a method: The method cannot be overridden.
When applied to a class: The class cannot be sub-classed.
Finally:
There is an optional finally block after the try block or after the catch block. Statements in the finally block will always be executed (except if JVM exits from the try block). The finally block is used to write the clean up code.
Finalize:
This is the method that the JVM runs before running the garbage collector.

What is the difference between creating String as new() and literal?

Ans: When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.
String s = new String(“Test”);

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = “Test” Java automatically put that into String pool.

What is immutable object? Can you write immutable object?

Ans: Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

Volatile and Synchronized in Java


This can be best understood by looking at the effects that volatile & synchronized on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1; int geti1() {return i1;}
volatile int i2; int geti2() {return i2;}
int i3; synchronized int geti3() {return i3;}
geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it’s thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a “main” memory, and this is the memory that holds the current “correct” value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the “main” memory. So in fact, it is possible for the “main” memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to “main” memory or other threads.
On the other hand, geti2() effectively accesses the value of i2 from “main” memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in “main” memory. Effectively, a variable declared volatile must have it’s data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than “plain” variables, since the reason threads can have their own copy of data is for better efficiency.
Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That’s the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with “main” memory. So executing geti3() does the following:
The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
The thread memory flushes all its variables, i.e. it has all of its variables effectively read from “main” memory (JVMs can use dirty sets to optimize this so that only “dirty” variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from “main” memory).
(Any changes to variables would normally now be written out to “main” memory, but for geti3() we have no changes.)
The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and “main” memory, synchronized synchronizes the value of all variables between thread memory and “main” memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
Using the volatile keyword ensures that the variable is never kept in a register. This guarantees that the variable is truly shared between threads.
Synchronization boundaries signal to the virtual machine that it must invalidate its registers.
When the virtual machine enters a synchronized method or block, it must reload data it has cached in its local registers. Before the virtual machine exits a synchronization method or block, it must store its local registers to main memory.

Difference between “implements Runnable” and “extends Thread” in Java


1. Inheritance Option:   The limitation with “extends Thread” approach is that if you extend Thread,  you can not extend anything else . Java does not support multiple inheritance.  In reality , you do not need Thread class behavior , because in order to use a thread you need to instantiate one anyway.
On the other hand,
Implementing the Runnable interface gives you the choice to extend any class you like , but still define behavior that will be run by separate thread.
2. Reusability :  In “implements Runnable” , we are creating a different Runnable class for a specific behavior  job (if the work you want to be done is job). It gives us the freedom to reuse the specific
behavior job whenever required.
“extends Thread”  contains both thread and job specific behavior code. Hence once thread completes execution , it can not be restart again.
3. Object Oriented Design:  Implementing Runnable should be preferred . It does not specializing or modifying the thread behavior . You are giving thread something to run. We conclude that Composition is the better way. Composition means two objects A and B satisfies has-a  relationship.
“extends Thread”  is not a good Object Oriented practice.
4. Loosely-coupled : “implements Runnable” makes the code loosely-coupled and easier to read .
Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code.
“extends Thread”  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.
5. Functions overhead :  “extends Thread”  means inheriting all the functions of the Thread class which we may do not need .  job can be done easily by Runnable without the Thread class functions overhead.
Example of  “implements Runnable” and “extends Thread” 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div>
<pre>public class RunnableExample implements Runnable {
     
    public void run() {</pre>
<pre>        System.out.println("Alive is awesome");</pre>
<pre>    }</pre>
<pre>}
</pre>
</div>
<div>
<pre>public class ThreadExample extends Thread {
     
    public void run() {</pre>
<pre>        System.out.println(" Love Yourself ");</pre>
<pre>   }</pre>
<pre>}
Recap : Difference between “implements Runnable”  and “extends Thread”
 implements Runnable extends Thread
Inheritance optionextends any java classNo
ReusabilityYesNo
Object Oriented DesignGood,allows compositionBad
Loosely CoupledYesNo
Function OverheadNoYes

What is BlockingQueue in Java Collections Framework? 


BlockingQueue implements the java.util.Queue interface . BlockingQueue supports  operations that wait for the queue to become non-empty when retrieving an element , and wait  for space to become available in the queue when storing an element .
It does not accept null elements.
Blocking queues are primarily designed for the producer-consumer problems.
BlockingQueue implementations are thread-safe and can also be used in inter-thread communications. This concurrent Collection class was added in jdk 1.5

Difference between wait and sleep methods

1.  Class  belongs :  The wait() method belongs to java.lang.Object class, thus can be called on any Object. The sleep() method belongs to java.lang.Thread class, thus can be called on Threads.
2. Context :  The wait() method can only be called from Synchronized context i.e. using synchronized block or synchronized method. The sleep() method can be called from any context.
3. Locking :  The wait() method releases the lock on an object and gives others chance to execute. The sleep() method does not releases the lock of an object for specified time or until interrupt.
4. Wake up condition :  A waiting thread can be awake by notify() or notifyAll() method. A sleeping can be awaked by interrupt or time expires.
5. Execution :  Each object has each wait() method for inter-communication between threads. The sleep() method is static method belonging to Thread class. There is a common mistake to write t.sleep(1000) because sleep() is a class method and will pause the current running thread not t. 
Recap  : Difference between Sleep and Wait in Java 
SleepWait
Class  belongsjava.lang.Threadjava.lang.Object
ContextCalled from any contextOnly synchronized context
LockingDoes not release the lock
for specified time  or until
interrupt.
Releases the lock
Wake up ConditionWhen time expires or
due to interruption
Awake by call to notify()
or notifyAll() method
ExecutionExecution of sleep will
pause the current running
thread not the object on which
it is called.
Thread wait()
continues till a specific condition
holds true

How can we create a Thread in Java?


Ans: There are two ways to create Thread in Java – first by implementing Runnable interface and then creating a Thread object from it and second is to extend the Thread Class.
Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?
Ans: Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks.
Can two threads call two different synchronized instance methods of an Object?
Ans: No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
Can we synchronize the run method? If yes then what will be the behavior?
Ans: Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object.
Can we call run() method of a Thread class?
Ans: Yes, we can call run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, we need to start it using Thread.start() method.
What is thread pool? Why should we use thread pools?
Ans: A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment.
Can we synchronize the constructor of a Java Class?
Ans: As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it.
What is a volatile keyword?
Ans: The copy of volatile variable is stored in the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time from the main memory. The volatile variable also have performance issues.
What is the difference between wait() and sleep()?
Ans:
1) The wait() method is defined in Object class. The sleep() method is defined in Thread class.
2) The wait() method releases the lock. The sleep() method does not release the lock.
3) The wait() method should be called from synchronized method or block. There is no such requirement for sleep() method.
4) The wait() method is an instance specific method and only got wake up if some other thread calls notify or notifyAll methods on same object.The sleep() method is a static method and applies on current thread.
What is the difference between yield() and sleep()?
Ans: yield() allows the current the thread to release its lock from the object and scheduler gives the lock of the object to the other thread with same priority.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock.
How many locks does an object have?
Ans: Each object has only one lock.
What does join() method do?
Ans: t.join( ) allows the current thread to wait indefinitely until thread “t” is finished. t.join (5000) allows the current thread to wait for thread “t” to finish but does not wait longer than 5 seconds. Note that join() can also take times in milliseconds and nanoseconds as parameters. These values specify the maximum amount of time to wait before returning the blocked thread’s state to RUNNABLE.
The following statements are true.
1. wait( ), notify( ), notifyall( ) are defined as final & can be called only from within a synchronized method
2. Among wait( ), notify( ), notifyall( ) the wait() method only throws IOException
You have thread T1, T2 and T3, how will you ensure that thread T2 run after T1 and thread T3 run after T2?
Ans: It can be achieved by using join method of Thread class.
Why we call start() method which in turns calls run() method, why not we directly call run() method ?
Ans: when you call start() method it creates new Thread and execute code declared in run() while directly calling run() method doesn’t create any new thread and execute code on same calling thread.
What is Java Thread Dump, How can we get Java Thread dump of a Program?
Ans: 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.
What is ReentrantLock? How it is different from synchronized?
Ans: The ReentrantLock has the same concurrency and memory semantics as synchronized. It also provides features like lock polling, timed lock waits, and interruptible lock waits. Additionally, it offers far better performance under heavy contention.
Protecting a block of code with ReentrantLock:
1
2
3
4
5
6
7
8
9
Lock lock = new ReentrantLock();
lock.lock();
try {
// update object state
}
finally {
lock.unlock();
}
We can use the ReentrantLock when we actually need something it provides that synchronized doesn’t, like timed lock waits, interruptible lock waits etc. It also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention. However, the existences of these obvious benefits are not a good enough reason to always prefer ReentrantLock over synchronized.
In majority of the cases, synchronized works just fine, works on all JVMs, is understood by a wider range of developers, and is less error-prone. So make the decision on the basis of need.
How to Stop a Thread in java?
Ans: We can use Thread.interrupt() to stop a Thread.
Difference between run() and start() methods of Thread?
Ans: The start() method creates a new thread and then execute the run() method.
The run() method just executes in the current thread, without starting a new thread.
When will a ConcurrentModificationException happen?

A ConcurrentModificationException will happen if an iterator of a collection is being traversed while at the time the collection is being modified. For example, if you are looping through an iterator of a set and at the time you try to remove or add element to the set.

What is AtomicInteger class and how is it different than using volatile or synchronized?

Ans: An int value that may be updated atomically. An AtomicInteger is used in applications where we need to atomically increment counters.
If the variable declared as Volatile then it always takes master copy of variable instead of local copy of a variable.
If the method or block of code marked as syschronized then it prevents multiple threads accessing that part of the code

What are all the possible ways to make a class is not extendable in java?

Ans:
 1. Let’s create a class as final class.
2. Let’s make all the constructors in a class as private.

Difference between HashTable and HashMap


1. HashTable is synchronized, whereas HashMap it not synchronized.
2. HashTable does not allow null keys or values. HashMap allows one null key and any number of null vlaues.

Difference between ConcurrentHashMap and HashTable


The major advantage of using ConcurrentHashMap is “performance” as the lock is not applied on whole Map as is the case with Hashtable.
ConcurrentHashMap is offering all the features of Hashtable with a performance almost as good as a HashMap. ConcurrentHashMap’s accomplish this by a very simple mechanism. Instead of a map wide lock, the collection maintains a list of 16 locks by default, each of which is used to guard (or lock on) a single bucket of the map. This effectively means that 16 threads can modify the collection at a single time (as long as they’re all working on different buckets). Infact there is no operation performed by this collection that locks the entire map. The concurrency level of the collection, the number of threads that can modify it at the same time without blocking, can be increased. However a higher number means more overhead of maintaining this list of locks.

How will you awake a blocked thread in java?

Ans: We can awake the thread by throwing InterruptedException if it is blocked by calling wait(), sleep() or join() methods. I don’t think there is a way to awake the thread if it is blocked on IO.

Different ways to create objects in Java


Here are four different ways to create objects in java:
1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName(“subin.rnd.MyObject”).newInstance();
3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
Now you know how to create an object. But its advised to create objects only when it is necessary to do so.

No comments:

Post a Comment