Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 72

Cognizant

Q1. How hashmap works internally? What all things are there in bucket?

HashMap works on the principle of Hashing.

What is Hashing

Hashing in its simplest form, is a way to assigning a unique code for any
variable/object after applying any formula/algorithm on its properties. A true
Hashing function must follow this rule:

Hash function should return the same hash code each and every time, when
function is applied on same or equal objects. In other words, two equal objects
must produce same hash code consistently.

To understand Hashing, we should understand the three terms first i.e Hash
Function , Hash Value and Bucket .

What is Hash Function , Hash Value and Bucket ?

hashCode() function which returns an integer value is the Hash function. The
important point to note that , this method is present in Object class ( Mother of all
class ) .

This is the code for the hash function(also known as hashCode method) in Object
Class :

public native int hashCode();

The most important point to note from the above line : hashCode method return int
value .
So the Hash value is the int value returned by the hash function .

So summarize the terms in the diagram below :


What is bucket?
A bucket is used to store key value pairs. A bucket can have multiple key-value pairs.
In hash map, bucket used simple linked list to store objects.

After understanding the terms we are ready to move next step, How hash map
works in java or How get() works internally in java .

Code inside Java Api (HashMap class internal implementation) for HashMap
get(Obejct key) method

1. Public V get(Object key)


{
2.if(key ==null)
3.//Some code

4.int hash = hash(key.hashCode());

5.// if key found in hash table then return value


6.// else return null
}

Hash map works on the principle of hashing

HashMap get(Key k) method calls hashCode method on the key object and applies
returned hashValue to its own static hash function to find a bucket location(backing
array) where keys and values are stored in form of a nested class called Entry
(Map.Entry) . So you have concluded that from the previous line that Both key and
value is stored in the bucket as a form of Entry object . So thinking that Only
value is stored in the bucket is not correct and will not give a good impression on the
interviewer.

* Whenever we call get( Key k ) method on the HashMap object . First it checks that
whether key is null or not. Note that there can only be one null key in HashMap .
If key is null , then Null keys always map to hash 0, thus index 0.

If key is not null then , it will call hashfunction on the key object , see line 4 in above
method i.e. key.hashCode() ,so after key.hashCode() returns hashValue , line 4 looks
like

4. int hash = hash(hashValue)

, and now ,it applies returned hashValue into its own hashing function .

We might wonder why we are calculating the hashvalue again using


hash(hashValue). Answer is,It defends against poor quality hash functions.

Now step 4 final hashvalue is used to find the bucket location at which the Entry
object is stored . Entry object stores in the bucket like this
(hash,key,value,bucketindex) .

Interviewer: What if when two different keys have the same hashcode ?

Solution, equals() method comes to rescue.Here candidate gets puzzled. Since


bucket is one and we have two objects with the same hashcode.Candidate usually
forgets that bucket is a simple linked list.

The bucket is the linked list effectively . Its not a LinkedList as in a


java.util.LinkedList - It's a separate (simpler) implementation just for the map .

So we traverse through linked list , comparing keys in each entries using


keys.equals() until it return true. Then the corresponding entry object Value is
returned.

One of our readers Jammy asked a very good question


When the functions 'equals' traverses through the linked list does it traverses
from start to end one by one...in other words brute method. Or the linked list is
sorted based on key and then it traverses?

Answer is when an element is added/retrieved, same procedure follows:

a. Using key.hashCode() [ see above step 4],determine initial hashvalue for the key

b. Pass intial hashvalue as hashValue in hash(hashValue) function, to calculate the


final hashvalue.

c. Final hash value is then passed as a first parameter in the indexFor(int ,int )method
.
The second parameter is length which is a constant in HashMap Java Api ,
represented by DEFAULT_INITIAL_CAPACITY

The default value of DEFAULT_INITIAL_CAPACITY is 16 in HashMap Java Api .

indexFor(int,int) method returns the first entry in the appropriate bucket. The linked
list in the bucket is then iterated over - (the end is found and the element is added or
the key is matched and the value is returned )

Explanation about indexFor(int,int) is below :

/**
* Returns index for hash code h.
*/
staticintindexFor(int h,int length){
return h &(length-1);
}

The above function indexFor() works because Java HashMaps always have a capacity,
i.e. number of buckets, as a power of 2.
Let's work with a capacity of 256,which is 0x100, but it could work with any power of
2. Subtracting 1
from a power of 2 yields the exact bit mask needed to bitwise-and with the hash to
get the proper bucket index, of range 0 to length - 1.
256 - 1 = 255
0x100 - 0x1 = 0xFF
E.g. a hash of 257 (0x101) gets bitwise-anded with 0xFF to yield a bucket number of
1.

Interviewer: What if when two keys are same and have the same hashcode ?
If key needs to be inserted and already inserted hashkey's hashcodes are same, and
keys are also same(via reference or using equals() method) then override the
previous key value pair with the current key value pair.

The other important point to note is that in Map ,Any class(String etc.) can serve
as a key if and only if it overrides the equals() and hashCode() method .

Interviewer: How will you measure the performance of HashMap?

According to Oracle Java docs,

An instance of HashMap has two parameters that affect its performance: initial
capacity and load factor.

The capacity is the number of buckets in the hash table( HashMap class is roughly
equivalent to Hashtable, except that it is unsynchronized and permits nulls.), 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.

The default size of load factor is 0.75. The default capacity is computed as initial
capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of
Map.

In HashMap class, the default value of load factor is (.75) .

Interviewer : What is the time complexity of Hashmap get() and put() method ?

The hashmap implementation provides constant time performance for (get and put)
basic operations
i.e the complexity of get() and put() is O(1) , assuming the hash function disperses
the elements properly among the buckets.
What is load factor? What is initial capacity of hashmap? [Explained]

Q2. Hashmap is thread safe or not ? What to be use if we need to make it


threadsafe?

In this example, we have a HashMap<Integer, String> it is having integer keys and


String type values. In order to synchronize it we are
using Collections.synchronizedMap(hashmap) it returns a thread-safe map backed
up by the specified HashMap. In order to guarantee serial access, it is critical that all
access to the backing map is accomplished through the returned map.

It is also mandatory that the user manually synchronizes on the returned map
when iterating over any of its collection views:

Map<Integer,
String> synchronizedHashMaps = Collections.synchronizedMap(new HashMap<>());

Set<Integer> mySet = m.keySet(); // Needn't be in synchronized block


...
synchronized(synchronizedHashMaps ) { // Synchronizing on map instance, not set
Iterator<Integer> i = mySet.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
That's all about how do you synchronize HashMap in Java.
Collections.synchronizedMap() is a useful method to achieve this but you also have
better options available in Java. For example, if you know from the start that your
HashMap will be shared between multiple threads then why not
use ConcurrentHashMap, which is specially designed for such use. Unfortunately, if
you have not yet on Java 1.5 then there is Hashtable which provides similar
functionality like synchronized HashMap.

Q3. Hashmap.get(key) will traverse over the loop or it will go to the particular
place and return the value?

It will traverse over the loop.

Q4. Entry object is class/interface/sub-interface?

Interface Map.Entry<K,V>
Q5. What is sub interface?

Interfaces can extend several other interfaces, using the same formula as described
below. For example,

publicinterfaceVenomousPredatorextendsPredator,Venomous{
//interface body
}

is legal and defines a subinterface. Note how it allows multiple inheritance, unlike
classes. Note also that Predator and Venomous may possibly define or inherit
methods with the same signature, say kill(Prey p) . When a class
implements VenomousPredator it will implement both methods simultaneously.

Q6. CME - What is Concurrent Modification Exception? And how can we avoid it
- if we want to remove element while traversing the list?

Apart from the NullPointerException and


ClassNotFoundException, ConcurrentModificationException is another nightmare
for Java developers. What makes this error tricky is the word concurrent, which always
mislead Java programmers that this exception is coming because multiple threads
are trying to modify the collection at the same time. Then begins the hunting, they
spent countless hours to find the code which has the probability of concurrent
modification. While in reality ConcurrentModficationException can also come on the
single threaded environment. To give you an example, just loop over a list using for
loop and try to remove one element, you will get the
ConcurrentModificatoinExcetpion? Why? because you broke the rule of not
modifying a Collection during iteration.

How does Java knows to throw ConcurrentModificationExeption? It uses a transient


variable called modCount, which keeps track of how many times a list is modified
structurally. Structural modifications are those that change the size of the list, which
may affect the progress of iteration and may yield incorrect results.
Both Iterator and ListIterator uses this field to detect unexpected change. Other
methods of List which structurally modify List also uses this method
e.g. add(), remove().

Problem: loop over an ArrayList and remove selected elements, but remove() is
throwing "Exception in thread "main"
java.util.ConcurrentModificationException".

Cause: The real cause of ConcurrentModfiicationException is inconsistent modCount.


When you are iterating over ArrayList then Iterator's next() method keep track of
modCount. If you modify the collection by adding or removing element
then modCount will change and it will not match with the expected modCount,
hence Iterator will throw ConcurrentModificationException.

Solution: Use Iterator if you are doing it on the single threaded environment,
otherwise use concurrent collection classes e.g. CopyOnWriteArrayList to remove
elements while you are looping over it.

Solving ConcurrentModificationException in ArrayList


Here is the Java program to demonstrate one scenario where you get the
ConcurrentModificationException even if just one thread is modifying the ArrayList.
In this example, we are looping over ArrayList using advanced for loop and removing
selected elements, but because we are using ArrayList's remove() method.

Here is summary of important points about solving ConcurrentModificationException


while looping over ArrayList in Java :
That's all about how to deal with ConcurrentModificationException in Java. The
biggest thing to learn and remember is that this error can come even if you have just
one thread modifying collection e.g. removing elements while looping over the list.

Q7. Why we use iterator? What are the benefits of it?

Interface Iterator<E>
 Type Parameters:
E - the type of elements returned by this iterator

 If your case is only iterating over list, use of for each loop should be preferred
since Java 1.5.
 But if your case is manipulating collection while iterating You need to
use Iterator interface to avoid concurrent modification exception.

Q8. What is listiterator?

public interface ListIterator<E>extends Iterator<E>

Difference between Iterator and ListIterator in Java with Example

1. Traversal Direction : ListIterator allows the programmers to iterate the list


objects in both directions i.e forward as well as backward direction using previous()
and next() method.
Iterator can be used to iterate the list,map and set object in one direction i.e
forward.

2. Set and Map implemented Objects Traversal : ListIterator can be used to


traverse List object only . But Iterator can be used to traverse Map, List and Set
implemented objects.

3. Add or Set operation at any index : According to ListIterator Oracle docs,


ListIterator can modify the list during iteration using add(E e) , remove() or set(E e).
Iterator can not add the element during traversal but they can remove the element
from the underlying collection during the iteration as they only consist of remove()
method. There is no add(E e) and set(E e) method in Iterator.

4. Determine Iterator's current position : ListIterator can obtain the iterator's


current position in the list. Iterator's current position during traversal can not be
determined using Iterator.

5. Retrieve Index of the element : ListIterator can obtain the index of the elements
using previousIndex(E e) or nextIndex(E e) methods. We can not obtain the index
using Iterator as there is no such methods present.

Difference between Iterator and ListIterator in Java with Example

ListIterator Iterator

Traversal Direction Both , forward and backward Forward

Objects traversal List only Map, Set and List

Add and Set operations Allows both operations Not possible

Iterator's current position Yes , can be determined Not possible.

Retrieve Index Yes Not possible

Q9. What is error and exception?

Dictionary Meaning: Exception is an abnormal condition.


In java, exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

 Exception and Error both are sub classes of java.lang.Throwable class.


 We can handle Exceptions at runtime but Errors we can not handle.

 Exceptions are the objects representing the logical errors that occur at run time and
makes JVM enters into the state of "ambiguity".
 The objects which are automatically created by the JVM for representing these run
time errors are known as Exceptions.
 An Error is a subclass of Throwable that indicates serious problems that a
reasonable application should not try to catch. Most such errors are abnormal
conditions.

Difference between Exceptions and Errors


 If exception occurs we can handle it by using try and catch block. If Error occurs we
can not handle it , program execution will be terminated.
 In Exception we have two types
1. Checked Exception
2.Unchecked Exceptions
 Error are by default unchecked exceptions.
 Exceptions are related to application where ad Error are related to environment in
which application is running.

 Exception are of type java.lang.Exception


 Errors are of type java.lang.Error
 Error will run at run time.
 In Exceptions Checked Exceptions will known to compiler so we need to handle
these exceptions at compile time itself otherwise compile time Error will come.
 Unchecked Exception will come at run time need to handle by using try and catch
blocks.

Q10. Can you handle error inside the application? – Ans is above

Q11. try {return 1;} catch {return 2;} finally {return 3;} – 3 will be returned

Q12. Exception overriding in case of parent-child class ? What is thumb rule?

Overriding method cannot throw checked Exception higher in hierarchy than


thrown by overridden method. Let’s say for example overridden method in parent
class throws FileNotFoundException, the overriding method in child class can
throw FileNotFoundException; but it is not allowed to
throw IOException or Exception, because IOException or Exception are higher in
hierarchy i.e. super classes of FileNotFoundException.
More to it, you can omit the exception declaration from overriding method. It’s allowed
and perfectly valid. Also overriding method can throw any unchecked (runtime)
exception, regardless of whether the overridden method declares the exception.

o If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but it can
declare unchecked exception.
o If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden
method can declare same, subclass exception or no exception but
cannot declare parent exception.

Q13. What is compile time checking and runtime checking?


Q14. Who does the compile time checking in Java?

Q15. Why we use throw and throws keyword? What purpose does it serve?

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception. We will see custom
exceptions later.

The syntax of java throw keyword is given below.

1. throw exception;

Let's see the example of throw IOException.

1. throw new IOException("sorry device error);

The Java throws keyword is used to declare an exception. It gives an information to


the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be
maintained.

Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as NullPointerException, it is programmers fault that
he is not performing check up before the code being used.

Syntax of java throws


1. return_type method_name() throws exception_class_name{
2. //method code
3. }
Which exception should be declared

Ans) checked exception only, because:

o unchecked Exception: under your control so correct your code.


o error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.

Advantage of Java throws keyword

Now Checked Exception can be propagated (forwarded in call stack).

It provides information to the caller of the method about the exception.


Rule: If you are calling a method that declares an exception, you must either caught
or declare the exception.

There are two cases:

1. Case1: You caught the exception i.e.


handle the exception using try/catch.
2. Case2: You declare the exception i.e.
specifying throws with the method.

No. throw throws

1) Java throw keyword is used to explicitly Java throws keyword is used to


throw an exception. declare an exception.

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method
signature.

5) You cannot throw multiple exceptions. You can declare multiple exceptions
e.g.
public void method()throws
IOException,SQLException.

Q16. What is concurrency?Why we use thread?

In simple words, concurrency is the ability to run several programs or several parts
of a program in parallel. Concurrency enable a program to achieve high performance
and throughput by utilizing the untapped capabilities of underlying operating system
and machine hardware. e.g. modern computers has several CPU’s or several cores
within one CPU, program can utilize all cores for some part of processing; thus
completing task much before in time in comparison to sequential processing.

What is multithreading?

Multithreading in java is a process of executing multiple threads simultaneously.


Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.

But we use multithreading than multiprocessing because threads share a common


memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation etc.

Q17. Can we start a thread twice? Why? No. Illegalstateexception

Q18. Who will handle the running of thread in java? - Thread scheduler

Q19. Wait,notify and notifyall in Thread package or Object package? Why not in
Thread package?

Java concurrency model uses locks to implement mutually exclusive access to


objects in a multi-threaded environment and locks are associated with every object
in Java (of type 'Object'), not only with Threads.

Thread.sleep and Thread.join - what is the difference?

The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.

The sleep() method of Thread class is used to sleep a thread for the specified amount
of time.

Q20. What is DI? What is IOC?

Dependency Injection (DI) is a design pattern that removes the dependency from the
programming code so that it can be easy to manage and test the application.
Dependency Injection makes our programming code loosely coupled.

The IoC container is responsible to instantiate, configure and assemble the objects.
The IoC container gets informations from the XML file and works accordingly. The
main tasks performed by IoC container are:

o to instantiate the application class


o to configure the object
o to assemble the dependencies between the objects

There are two types of IoC containers. They are:

1. BeanFactory
2. ApplicationContext
Q21. @Qualifier

In Spring, @Qualifier means, which bean is qualify to autowired on a field.

There may be a situation when you create more than one bean of the same type and
want to wire only one of them with a property. In such cases, you can use
the @Qualifier annotation along with @Autowired to remove the confusion by
specifying which exact bean will be wired.

Q22. When we'll go for setter injection and when we'll go for construction
injection?

Q23. What isauto wiring and different types?

In spring framework, setting bean dependencies in configuration files is a good


practice to follow, but the spring container is also able to autowire relationships
between collaborating beans. This means that it is possible to automatically let
Spring resolve collaborators (other beans) for your bean by inspecting the contents
of the BeanFactory. Autowiring is specified per bean and can thus be enabled for
some beans, while other beans will not be autowired.

Spring autowiring modes


The autowiring functionality has five modes. These are ‘no’, ‘byName’, ‘byType’,
‘constructor’, and ‘autodetect’. The default mode is “no” i.e. by default autowiring is
turned off.

Various autowiring modes used in bean configuration file

As shown in picture above, there are five auto wiring modes. Lets discuss them one
by one.

 no: This option is default for spring framework and it means that autowiring is
OFF. You have to explicitly set the dependencies using tags in bean definitions.

 byName: This option enables the dependency injection based on bean names.
When autowiring a property in bean, property name is used for searching a
matching bean definition in configuration file. If such bean is found, it is
injected in property. If no such bean is found, a error is raised.
 byType: This option enables the dependency injection based on bean types.
When autowiring a property in bean, property’s class type is used for
searching a matching bean definition in configuration file. If such bean is
found, it is injected in property. If no such bean is found, a error is raised.
 constructor: Autowiring by constructor is similar to byType, but applies to
constructor arguments. In autowire enabled bean, it will look for class type of
constructor arguments, and then do a autowire by type on all constructor
arguments. Please note that if there isn’t exactly one bean of the constructor
argument type in the container, a fatal error is raised.
 autodetect: Autowiring by autodetect uses either of two modes i.e.
constructor or byType modes. First it will try to look for valid constructor with
arguments, If found the constructor mode is chosen. If there is no constructor
defined in bean, or explicit default no-args constructor is present, the autowire
byType mode is chosen.

Fatal exception is BeanCreationException when exact one match is not found.

Q24. Same Bean with different id and doing auto wire by type. Does this
work? What is the exception?

Fatal Exception will be thrown.

Q25. What is lazy loading in hibernate? Explain with example.

Q.26 What is proxy design pattern in Hibernate? What is Proxy object?

Q27. What is the difference between load and get method?


 Both are from Session interface, and we will call them as session.get()
& session.load()
 Both will be use for retrieving the object (a row) from the database

Then what’s the difference them ? lets start with load() and then get() method.
Consider a Student class having 3 properties stdId, stdName, stdCountry
1. session.load()

 When you call session.load() method, it will always return a “proxy” object, whats
the meaning of proxy object ?
 Proxy means, hibernate will prepare some fake object with given identifier value in
the memory without hitting the database, for example if we
call session.load(Student.class,new Integer(107)); > hibernate will create one fake
Student object [row] in the memory with id 107, but remaining properties of Student
class will not even be initialized, observe this graphical representation…

 It will hit the database only when we try to retrieve the other properties of Student
object i mean stdName, stdCountry. If we call s2.getStdName() then hibernate will
hit the database and search the row with student id 107 and retrieve the values, if
object [row] not found in the database it will throws ObjectNotFoundException.,

Let me explain each point by taking an example


Example of session.load()

index.jsp:

1 System.out.println("Student is calling with load()");


2 s2 =(Student) session.load(Student.class,new Integer(107));
3 System.out.println("Student called with load()");
4 System.out.println("Printing Student Name___"+s2.getStdtId());
5 System.out.println("Printing Student Name___"+s2.getStdName());

Output

Explanation:

In index.jsp > line number 4, i have called s2.getStdtId() and hibernate simply
printed 107 [at Output > line number 3] without creating any database query why ?
because as i have explained hibernate will prepare some fake object with
given identifier value in the memory without hitting the database. So when we call
load() method (at index.jsp > line number 2 ) with 107 value, hibernate will create a
fake object with 107 as identifier value, i mean temporarily it will consider the
student id as 107. If you observe the output, hibernate was generated the database
query (at Output > line number 4 ) when we called s2.getStdName(); ( index.jsp >
line number 5 ).
That’s it, so finally we came to know that session.load() will hit the database only
when we start retrieving the object (row) values.
2. session.get()

 When you call session.get() method, it will hit the database immediately and returns
the original object
 If the row is not available in the database, it returns null

Example of session.get()

1 System.out.println("Student is calling with get()");


2 s1 = (Student) session.get(Student.class,new Integer(107));
3 System.out.println("Student called with get()");
4 System.out.println("Printing Student Name___"+s1.getStdtId());
5 System.out.println("Printing Student Name___"+s1.getStdName());

Output

Explanation:

 Nothing to explain here as i told, when we call session.get() method hibernate will
hit the database and returns the original object [ row ], that’s the reason it was
generated a query [ check line number 2 in the output screen]

No. get() load()

1) Returns null if object is not found. Throws ObjectNotFoundException if object


is not found.

2) get() method always hit the load() method doesn't hit the database.
database.

3) It returns real object not proxy. It returns proxy object.

4) It should be used if you are not It should be used if you are sure that
sure about the existence of instance exists.
instance.

Q28. First level cache associated with? Session

Q29. Second level cache associated with?SessionFactory


Q30. SessionFactory is Singleton? Threadsafe?

SessionFactory is singleton and threadsafe.

Q31. What is the purpose of synchronized keyword?

Synchronization in java is the capability to control the access of multiple threads to


any shared resource.

Java Synchronization is better option where we want to allow only one thread to
access the shared resource.

Why use Synchronization

The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization

There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization

There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive

Mutual Exclusive helps keep threads from interfering with one another while sharing
data. This can be done by three ways in java:
1. by synchronized method
2. by synchronized block
3. by static synchronization

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent
access to an object's fields has to acquire the object's lock before accessing them,
and then release the lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock


implementations.

Java synchronized method

If you declare any method as synchronized, it is known as synchronized method.

Synchronized method is used to lock an object for any shared resource.

When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.

Synchronized block in java

Synchronized block can be used to perform synchronization on any specific resource


of the method.

Suppose you have 50 lines of code in your method, but you want to synchronize only
5 lines, you can use synchronized block.

If you put all the codes of the method in the synchronized block, it will work same as
the synchronized method.

Points to remember for Synchronized block


o Synchronized block is used to lock an object for any shared resource.
o Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


1. synchronized (object reference expression) {
2. //code block
3. }
Static synchronization

If you make any static method as synchronized, the lock will be on the class not on
object.

Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and
object2.In case of synchronized method and synchronized block there cannot be
interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a
common object that have a single lock.But there can be interference between t1 and
t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want
no interference between t1 and t3 or t2 and t4.Static synchronization solves this
problem.

Synchronized block on a class lock:

The block synchronizes on the lock of the object denoted by the reference .class
name .class. A static synchronized method printTable(int n) in class Table is
equivalent to the following declaration:

1. static void printTable(int n) {


2. synchronized (Table.class) { // Synchronized block on class A
3. // ...
4. }
5. }
Inter-thread communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is


paused running in its critical section and another thread is allowed to enter (or lock)
in the same critical section to be executed.It is implemented by following methods
of Object class:

o wait()
o notify()
o notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes
the notify() method or the notifyAll() method for this object, or a specified amount of
time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws waits until object is notified.


InterruptedException

public final void wait(long timeout)throws waits for the specified amount of time.
InterruptedException

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is arbitrary
and occurs at the discretion of the implementation. Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor
state of the object.

Q32. How to do one to many mapping in Hibernate?

Q33. Employee class and Address class. Employee has many addresses. How to
configure this in Hibernate? What all thing you will write in Employee class and
Address class?

<hibernate-mapping>

<class name="com.javatpoint.Question" table="q501">

<id name="id">

<generator class="increment"></generator>

</id>
<property name="qname"></property>

<list name="answers" cascade="all">

<key column="qid"></key>

<index column="type"></index>

<one-to-many class="com.javatpoint.Answer"/>

</list>

</class>

<class name="com.javatpoint.Answer" table="ans501">

<id name="id">

<generator class="increment"></generator>

</id>

<property name="answername"></property>

<property name="postedBy"></property>

</class>

</hibernate-mapping>

Q34. How interact with spring and Hibernate? Project configuration?

In hibernate framework, we provide all the database information hibernate.cfg.xml


file.

But if we are going to integrate the hibernate application with spring, we don't need
to create the hibernate.cfg.xml file. We can provide all the information in the
applicationContext.xml file.

Advantage of Spring framework with hibernate

The Spring framework provides HibernateTemplate class, so you don't need to


follow so many steps like create Configuration, BuildSessionFactory, Session,
beginning and committing transaction etc.

So it saves a lot of code.


Q35. What all things need to be changed if Database changes in hibernate?

Below properties in hibernate.cfg.xml

<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>

<property
name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

Q36. Have you implemented any cache in Hibernate?

Hibernate second level cache uses a common cache for all the session object of a
session factory. It is useful if you have multiple session objects from a session factory.

SessionFactory holds the second level cache data. It is global for all the session
objects and not enabled by default.

Different vendors have provided the implementation of Second Level Cache.

1. EH Cache
2. OS Cache
3. Swarm Cache
4. JBoss Cache

Each implementation provides different cache usage functionality. There are four
ways to use second level cache.

1. read-only: caching will work for read only operation.


2. nonstrict-read-write: caching will work for read and write but one at a time.
3. read-write: caching will work for read and write, can be used simultaneously.
4. transactional: caching will work for transaction.

The cache-usage property can be applied to class or collection level in hbm.xml file.
The example to define cache usage is given below:

1. <cache usage="read-only" />

Let's see the second level cache implementation and cache usage.

Implementation read-only nonstrict-read-write read- transactional


write
EH Cache Yes Yes Yes No

OS Cache Yes Yes Yes No

Swarm Cache Yes Yes No No

JBoss Cache No No No Yes

3 extra steps for second level cache example using EH cache

1) Add 2 configuration setting in hibernate.cfg.xml file

1. <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</pr
operty>
2. <property name="hibernate.cache.use_second_level_cache">true</property>

2) Add cache usage setting in hbm file

1. <cache usage="read-only" />

3) Create ehcache.xml file

1. <?xml version="1.0"?>
2. <ehcache>
3.
4. <defaultCache
5. maxElementsInMemory="100"
6. eternal="true"/>
7.
8. </ehcache>

defaultCache will be used for all the persistent classes. We can also define
persistent class explicitely by using the cache element.

eternal If we specify eternal="true", we don't need to define timeToIdleSeconds


and timeToLiveSeconds attributes because it will be handled by hibernate
internally. Specifying eternal="false" gives control to the programmer, but we
need to define timeToIdleSeconds and timeToLiveSeconds attributes.

timeToIdleSeconds It defines that how many seconds object can be idle in the
second level cache.
timeToLiveSeconds It defines that how many seconds object can be stored in
the second level cache whether it is idle or not.

Q37. What is cursor? Why we use cursor?

When you work with Oracle database, you work with a complete set of rows returned
from an SQL SELECT statement. However the application in some cases cannot work
effectively with the entire result set, therefore, the database server needs to provide a
mechanism for the application to work with one row or a subset of the result set at a
time. As the result, Oracle created PL/SQL cursor to provide these extensions.

A PL/SQL cursor is a pointer that points to the result set of an SQL query against
database tables.

Q38. What is the difference between function and procedure?

Q39. How will you handle exception in PL/SQL?

In PL/SQL, any kind of errors is treated as exceptions. An exception is defined as a


special condition that change the program execution flow. The PL/SQL provides you
with a flexible and powerful way to handle such exceptions.

PL/SQL catches and handles exceptions by using exception handler architecture.


Whenever an exception occurs, it is raised. The current PL/SQL block execution halts
and control is passed to a separate section called exception section.

In the exception section, you can check what kind of exception has been occurred
and handle it appropriately. This exception handler architecture enables separating
the business logic and exception handling code hence make the program easier to
read and maintain.
PL/SQL Exception

There are two types of exceptions:

 System exception: the system exception is raised by PL/SQL run-time when it


detect an error. For example, NO_DATA_FOUND exception is raised if you
select a non-existing record from the database.
 Programmer-defined exception: the programmer-defined exception is
defined by you in a specific application. You can map exception names with
specific Oracle errors using the EXCEPTION_INIT pragma. You can also assign a
number and description to the exception using RAISE_APPLICATION_ERROR.

Q40. How to print list of employees using PL/SQL block?

SET SERVEROUTPUT ON SIZE 1000000


BEGIN
DBMS_OUTPUT.PUT_LINE('Hello PL/SQL');
Select * from table_name;
END;
/
Q41. What is DML command?

DML is used for manipulation of the data itself. Typical operations are Insert, Delete,

Update and retrieving the data from the table. The Select statement is considered as

a limited version of the DML, since it can't change the data in the database. But it
can perform operations on data retrieved from the DBMS, before the results are

returned to the calling function.

Q42. What is truncate? [Explained]

Q43. Truncate, drop, delete – DML or DDL?

Truncate and Drop – DDL

Delete - DML

Q44. Difference between drop and truncate?

Once delete operation is performed, Commit and Rollback can be performed to

retrieve data.

Once the truncate statement is executed, Commit and Rollback statement cannot

be performed. Where condition can be used along with delete statement but it can't

be used with truncate statement.

Drop command is used to drop the table or keys like primary,foreign from a table.

Q45. What is the purpose of IN/OUT variable?

 An IN parameter is a read-only parameter. If the function tries to change the


value of the INparameters, the compiler will issue an error message. You can
pass a constant, literal, initialized variable, or expression to the function as
the IN parameter.
 An OUT parameter is a write-only parameter. The OUT parameters are used to
return values back to the calling program. An OUT parameter is initialized to a
default value of its type when the function begins regardless of its original
value before being passed to the function.
 An IN OUT parameter is read and write parameter. It means the function reads
the value from an IN OUT parameter, change its value and return it back to the
calling program.
Q46. ls –ltr what will happen?
It will sort the list by displaying recently modified filed at top.

Q47. Mv

Linux mv command is used to move existing file or directory from one location to
another. It is also used to rename a file or directory. If you want to rename a single
directory or file then 'mv' option will be better to use.

Q48. Rm

remove files or directories


Q49. How to change the mode?

chmod is used to change the permissions of files or directories.

chmod 754 myfile

Here the digits 7, 5, and 4 each individually represent the permissions for the user,
group, and others, in that order. Each digit is a combination of the numbers 4, 2, 1,
and 0:
 4 stands for "read",
 2 stands for "write",
 1 stands for "execute", and
 0 stands for "no permission."
So 7 is the combination of permissions 4+2+1 (read, write, and
execute), 5 is 4+0+1 (read, no write, and execute), and 4 is 4+0+0 (read, no write,
and no execute).

Q50. How to debug shellscript?

Start your bash script with bash -x ./script.sh or add in your script set -x to
seedebug output. You can use option -p of logger command to set an individual
facility and level to write output via local syslog to its own logfile.

Q51. How to runshell script?

sh -x

Q52. Which tool you’re using for continuous integration?SVN


MPHASIS MUMBAI R1:

Q53. What is the difference between local class and inner class? What are the
real time scenario where we can use it?

Java inner class or nested class is a class i.e. declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it
can be more readable and maintainable.

Additionally, it can access all the members of outer class including private data
members and methods.

Syntax of Inner class


1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable


code because it logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as inner
classes.

Types of Nested classes

There are two types of nested classes non-static and static nested classes.The non-
static nested classes are also known as inner classes.

1. Non-static nested class(inner class)


o a)Member inner class
o b)Annomynous inner class
o c)Local inner class
2. Static nested class

Type Description

Member Inner Class A class created within class and outside method.

Anonymous Inner A class created for implementing interface or extending class. Its
Class name is decided by the java compiler.

Local Inner Class A class created within method.

Static Nested Class A static class created within class.

Nested Interface An interface created within class or interface.

Q54. What will happen when object will be created in Java?

1. Memory is allocated.
2. Fields are initialized to their default values.
3. The "first line" of the chosen constructor is invoked, unless it's an Object. By first
line I mean either explicit call to super() or this(), or an implicit call to super().
4. The instance initializer is executed and the fields are initialized to their requested
values (actually field initialization is usually compiled as an inline part of the
instance initializer).
5. The rest of the constructor code is executed.

Q55. String str = new String(); will create how many instances ?

It depends whether the object already exists in String Pool or not. It String literal is
already there in String Constant Pool then it will create only one instance in heap
memory otherwise it will create 2, one in pool and another in heap.

Q56.What will happen when return keyword will be placed inside try lock?
There is 10 lines of code in try block and 5th line is the return keyword then rest
of code will be executed or not? Catch and finally block is also there after try.
Compilation Error - Unreachable Code. Return statement should be the last
statement inside any block.

Q57. How to handle exception inside Catch block?

Write the code inside try catch block or throws the exception and calling method
should handle that exception.

Q58. When the garbage collector will be called?

You as Java programmer can not force garbage collection in Java; it will only trigger
if JVM thinks it needs a garbage collection based on Java heap size.

There are methods like System.gc() and Runtime.gc() which is used to send request
of Garbage collection to JVM but it’s not guaranteed that garbage collection will
happen

Q59.What is the diff between JVM, JRE and JDK?

Here we will discuss about various terms like JDK, JRE, JVM, JIT and applications
like javac, java.

 Java Development Kit (JDK):Java Development Kit contains two parts. One
part contains the utilities like javac, debugger, jar which helps in compiling
the source code (.java files) into byte code (.class files) and debug the
programs. The other part is the JRE, which contains the utilities
like java which help in running/executing the byte code. If we want to write
programs and run them, then we need the JDK installed.

 Java Compiler (javac):javac is the executable/application which compiles the


.java source files into the byte code (.class files). javac is included inJDK.

 Java Run-time Environment (JRE):Java Run-time Environment helps in


running the programs. JRE contains the JVM, the java classes/packages and
the run-time libraries. If we do not want to write programs, but only execute
the programs written by others, then JRE alone will be sufficient.

 Java Virtual Machine (JVM):Java Virtual Machine is important part of


the JRE, which actually runs the programs (.class files), it uses the java class
libraries and the run-time libraries to execute those programs. Every
operating system(OS) or platform will have a different JVM.
 Java Executable(java):java is the application which runs/executes the .class
files. This internally calls the JVM for running the programs.

 Just In Time Compiler (JIT):JIT is a module inside the JVM which helps
in compiling certain parts of byte code into the machine code for higher
performance. Note that only certain parts of byte code will be compiled to
the machine code, the other parts are usually interpreted and executed.

Java is distributed in two packages - JDK and JRE. When JDK is installed it also
contains the JRE, JVM and JIT apart from the compiler, debugging tools.
When JRE is installed it contains the JVM and JIT and the class libraries.

The two most important things we need to remember from this topic before we
proceed further is javac and java. javac helps in compiling the program
and java helps in running the program. When the words Java
Compiler, Compiler or javac is used it refers to javac, when the words JRE, Run-
time Environment, JVM, Virtual Machine are used, it refers to java.

Q60. What is the diff between final,finally and finalize?

No. final finally finalize

1) Final is used to apply restrictions Finally is used to place Finalize is used to


on class, method and variable. important code, it will be perform clean up
Final class can't be inherited, executed whether exception is processing just
final method can't be overridden handled or not. before object is
and final variable value can't be garbage collected.
changed.

2) Final is a keyword. Finally is a block. Finalize is a


method.

Q61. How to serialize object of Test manually and what will be the value of x
and y after deserialization?

Class Tets {

int x = 10;

int y = 20

}
Classes ObjectInputStream and ObjectOutputStream are high-level streams that
contain the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data
types, but one method in particular stands out −

public final void writeObject(Object x) throws IOException


The above method serializes an Object and sends it to the output stream. Similarly,
the ObjectInputStream class contains the following method for deserializing an
object −

public final Object readObject() throws IOException, ClassNotFoundException


This method retrieves the next Object out of the stream and deserializes it. The
return value is Object, so you will need to cast it to its appropriate data type.

Q62. How to write custom marker interface?

Create an interface without any method and that is your marker interface.

Q63. When to use interface and when to use abstract class?

Consider using interfaces if any of these statements apply to your situation:

1. You expect that unrelated classes would implement your interface. For
example, the interfaces Comparable and Cloneable are implemented by many
unrelated classes.
2. You want to specify the behaviour of a particular data type, but not concerned
about who implements its behaviour.
3. You want to take advantage of multiple inheritances.

Consider using abstract classes if any of these statements apply to your situation:

1. You want to share code among several closely related classes.


2. You expect that classes that extend your abstract class have many common
methods or fields or require access modifiers other than public (such as
protected and private).
3. You want to declare non-static or non-final fields. This enables you to define
methods that can access and modify the state of the object to which they
belong

Q64. What is the diff between Hashmap and HashTable and what is the internal
implementation of both?
HashMap Hashtable

Synchronized No Yes

Thread-Safe No Yes

Null Keys and Null One null key,Any null Not permit null keys and
values values values

Enumeration - Fail safe


Iterator type Iterator - Fail fast iterator
iterator

Performance Fast Slow in comparison

Superclass and Legacy AbstractMap, No Dictionary, Yes

Q65. Two objects having same hash code then how hashing technique will
handle it?–[Explained]

Q66. List of 10 Lacs records and 20K are duplicate records then how to remove
duplicate records? In terms of Collection

Use HashSet or – no order


LinkedHashSet – insertion order

Q67. How to create immutable class?

/*

* There are many immutable classes like String, Boolean, Byte, Short, Integer, Long,
Float, Double etc.

* In short, all the wrapper classes and String class is immutable.

* The below class is immutable because:

* The instance variable of the class is final i.e. we cannot change the value
of it after creating an object.

* The class is final so we cannot create the subclass.


* There is no setter methods i.e. we have no option to change the value
of the instance variable.

*/

public final class ImmutableExample {

private final String name;

ImmutableExample(String name) {

this.name = name;

public String getName() {

return name;

Q68. In java there are how many ways to create Object?

Using new keyword } → constructor gets called

Using newInstance() method of Class class } → constructor gets called

Using newInstance() method of Constructor class } → constructor gets called

Using clone() method } → no constructor call

Using deserialization } → no constructor call

1. Using new keywords: It is the most common and regular way to create an object
and a very simple one also. By using this method we can call whichever constructor
we want to call (no-arg constructor as well as parameterized).

Employeeemp1=newEmployee();
2. Using newInstance() method of Class class: We can also use the newInstance()
method of a Class class to create an object. This newInstance() method calls the no-
arg constructor to create the object.

We can create an object by newInstance() in the following way:

Employeeemp2= (Employee)
Class.forName("org.programming.mitra.exercises.Employee").newInstance();
Or:

Employeeemp2=Employee.class.newInstance();

3. Using newInstance() method of Constructor class: Similar to the newInstance()


method of a Class, there is one newInstance() method in
the java.lang.reflect.Constructor class, which we can use to create objects. We can
also call a parameterized constructor and private constructor by using this
newInstance() method.

Constructor<Employee>constructor=Employee.class.getConstructor();
Employeeemp3=constructor.newInstance();

4. Using clone() method: Whenever we call clone() on any object, the JVM actually
creates a new object for us and copies all content of the previous object into it.
Creating an object using the clone method does not invoke any constructor.

To use clone() method on an object we need to implement Cloneable and define the
clone() method in it.

Employeeemp4= (Employee) emp3.clone();

5. Using deserialization: Whenever we serialize and deserialize an object, the JVM


creates a separate object for us. In deserialization, the JVM doesn’t use any
constructor to create the object.

To deserialize an object we need to implement a Serializable interface in our class.

ObjectInputStreamin=newObjectInputStream(newFileInputStream("data.obj"));
Employeeemp5= (Employee) in.readObject();
Q69. What is the diff between Statement and Prepaid Statement?

JDBC API provides 3 different interfaces to execute the different types of SQL
queries. They are,

1) Statement – Used to execute normal SQL queries.

2) PreparedStatement – Used to execute dynamic or parameterized SQL queries.

1) Statement

Statement interface is used to execute normal SQL queries. You can’t pass the
parameters to SQL query at run time using this interface. This interface is preferred
over other two interfaces if you are executing a particular SQL query only once. The
performance of this interface is also very less compared to other two interfaces. In
most of time, Statement interface is used for DDL statements
like CREATE, ALTER, DROP etc. For example,

2) PreparedStatement

PreparedStatement is used to execute dynamic or parameterized SQL queries.


PreparedStatement extends Statement interface. You can pass the parameters to SQL
query at run time using this interface. It is recommended to use PreparedStatement if
you are executing a particular SQL query multiple times. It gives better performance
than Statement interface. Because, PreparedStatement are precompiled and the
query plan is created only once irrespective of how many times you are executing
that query. This will save lots of time.

Q70. How to call stored procedure in JDBC?

CallableStatement – Used to execute the stored procedures.

3) CallableStatement

CallableStatement is used to execute the stored procedures. CallableStatement


extends PreparedStatement. Usng CallableStatement, you can pass 3 types of
parameters to stored procedures. They are : IN – used to pass the values to stored
procedure, OUT – used to hold the result returned by the stored procedure and IN
OUT – acts as both IN and OUT parameter. Before calling the stored procedure, you
must register OUT parameters using registerOutParameter() method of
CallableStatement. The performance of this interface is higher than the other two
interfaces. Because, it calls the stored procedures which are already compiled and
stored in the database server.

//Creating CallableStatement object


CallableStatement cstmt = con.prepareCall("{call anyProcedure(?, ?, ?)}");

//Use cstmt.setter() methods to pass IN parameters

//Use cstmt.registerOutParameter() method to register OUT parameters

//Executing the CallableStatement

cstmt.execute();

//Use cstmt.getter() methods to retrieve the result returned by the stored procedure

Q71. What will happen after deploying the war file in servlet container and
staring the server?

Q72. What is the difference between Session and SessionFactory?

Sessionfactory:
 It is one instance per datasource/database.
 It is thread safe.
 It is a heavy weight object, because it maintains datasources, mappings,
hibernate configuration information’s etc.
 Sessionfactory will create and manage the sessions.
 If you have 5 datasources/databases, then you must create 5 session factory
instances.
 sessionfactory is an immutable object and it will be created as singleton while
the server initializes itself.

session:
 It is one instance per client/thread/one transaction.
 It is not thread safe.
 It is light weight.
 sessions will be opened using sessionfactory.openSession() and some database
operations will be done finally session will be closed using session.close().

Q73. After submitting the data from JSP how to store that data in 10 different
database at same time in Hibernate?

You need to provide a cfg.xml for each database.

Q74. What is the concept of Spring BDI? – Bean Dependency Injection (Above)

Q75. What are the different Bean scope?

singleton: This bean scope is default and it enforces the container to have only one
instance per spring container irrespective of how much time you request for its
instance. This singleton behaviour is maintained by bean factory itself.
prototype: This bean scope just reverses the behaviour of singleton scope and
produces a new instance each and every time a bean is requested.

Remaining three bean scopes are web applications related. Essentially these are
available through web aware application context (e.g. WebApplicationContext).
Global-session is a little different in sense that it is used when application is portlet
based. In portlets, there will be many applications inside a big application and a bean
with scope of ‘global-session’ will have only one instance for a global user session.

request: With this bean scope, a new bean instance will be created for each web
request made by client. As soon as request completes, bean will be out of scope and
garbage collected.

session: Just like request scope, this ensures one instance of bean per user session.
As soon as user ends its session, bean is out of scope.

global-session: global-session is something which is connected to Portlet


applications. When your application works in Portlet container it is built of some
amount of portlets. Each portlet has its own session, but if your want to store
variables global for all portlets in your application than you should store them
in global-session. This scope doesn’t have any special effect different
from session scope in Servlet based applications.

Q76. What is the Spring Bean Life cycle?

Spring bean factory is responsible for managing the life cycle of beans created
through spring container. The life cycle of beans consists of call back
methods which can be categorized broadly in two groups:

 Post initialization call back methods


 Pre-destruction call back methods

Spring framework provides following 4 ways for controlling life cycle events of
bean:

1. InitializingBean and DisposableBean callback interfaces


2. Other Aware interfaces for specific behavior
3. custom init() and destroy() methods in bean configuration file
4. @PostConstruct and @PreDestroy annotations
InitializingBean and DisposableBean callback interfaces

The org.springframework.beans.factory.InitializingBean interface allows a bean to


perform initialization work after all necessary properties on the bean have been set
by the container. The InitializingBean interface specifies a single method:

void afterPropertiesSet() throws Exception;

This is not a preferrable way to initialize the bean because it tightly couples your
bean class with spring container. A better approach is to use “init-method” attribute
in bean definition in applicationContext.xml file.

Similarly, implementing
the org.springframework.beans.factory.DisposableBean interface allows a bean to get
a callback when the container containing it is destroyed. The DisposableBean
interface specifies a single method:

void destroy() throws Exception;


Custom init() and destroy() methods in bean configuration file

The default init and destroy methods in bean configuration file can be defined in two
ways:

 Bean local definition applicable to a single bean


 Global definition applicable to all beans defined in beans context

Local definition is given as below.

<beans>
<bean id="demoBean" class="com.howtodoinjava.task.DemoBean" init-method="customInit" de
method="customDestroy"></bean>
</beans>

 Where as global definition is given as below. These methods will be invoked


for all bean definitions given under tag. They are useful when you have a
pattern of defining common method names such as init() and destroy() for all
your beans consistently. This feature helps you in not mentioning the init and
destroy method names for all beans independently.

<beans default-init-method="customInit" default-destroy-method="customDestroy">


<bean id="demoBean" class="com.howtodoinjava.task.DemoBean"></bean>
</beans>

@PostConstruct and @PreDestroy annotations

Spring 2.5 onwards, you can use annotations also for specifying life cycle methods
using @PostConstruct and @PreDestroy annotations.

 @PostConstruct annotated method will be invoked after the bean has been
constructed using default constructor and just before it’s instance is returned to
requesting object.
 @PreDestroy annotated method is called just before the bean is about be
destroyed inside bean container.

Q77. What additional features are added in Application Context those are not
in Bean Factory?

1) BeanFactory Container is basic container, it can only create objects and inject
Dependencies.But we can not attach other services like security, transaction
,messaging etc. To provied all the services we have to use ApplicationContext
Container.

2) BeanFactory Container doesn't support the feature of AutoScanning , but


ApplicationContext Container supports.

3) Beanfactory Container will not create a bean object upto the request time.It means
Beanfactory Container loads beans laziely. While ApplicationContext Container
creates objects of Singleton bean at the time of loading only.It means there is early
loading.

4) Beanfactory Container support only two scopes (singleton & prototype) of the
beans. But ApplicationContext Container supports all the beans scope.

Q78. How to inject the data using setter injection?

The property element invokes the setter method. The value subelement of property
will assign the specified value.

Q79. How to configure Hashset in spring configuration file?

set element can be used inside the property element.


MPHASIS BANGLORE R1:

How hash map works in Java? [Explained]

Which methods need to be override to treat any class as the Key in HashMap?
[Explained]

What happens when hashcode returns 1 for all the objects? [Explained]

Q80. Difference between comparable and comparator?

Comparable Comparator

1) Comparable provides single sorting sequence. In Comparator provides multiple sorting


other words, we can sort the collection on the basis sequence. In other words, we can sort the
of single element such as id or name or price etc. collection on the basis of multiple elements
such as id, name and price etc.

2) Comparable affects the original class i.e. actual Comparator doesn't affect the original
class is modified. class i.e. actual class is not modified.

3) Comparable provides compareTo() method to Comparator provides compare() method to


sort elements. sort elements.

4) Comparable is found in java.lang package. Comparator is found in java.util package.

5) We can sort the list elements of Comparable type We can sort the list elements of Comparator
by Collections.sort(List) method. type
by Collections.sort(List,Comparator) method.

Q81. What is TreeSet? And what will happen if you do not override comparable
/ comparator and try to add non-primitive object in sorted set?

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements NavigableSet interface. The objects of TreeSet class
are stored in ascending order.

The important points about Java TreeSet class are:

o Contains unique elements only like HashSet.


o Access and retrieval times are quiet fast.
o Maintains ascending order.
If we do not implement comparable or comparator and try to add Object in sorted
set, it’ll allow to add one object but if you try to add second object it will throw
compile time error as there is no comparable / comparator implementation is
available.

Q82. What if we call run() method directly instead start() method?

o Each thread starts in a separate call stack.


o Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.

Q83. What is Busy Spinning?

The busy waiting is a wait strategy, where one thread wait for a condition to become
true, but instead of calling wait or sleep method and releasing CPU, it just spins. This
is particularly useful if the condition is going to be true quite quickly i.e. in a
millisecond or microsecond.

The advantage of not releasing CPU is that all cached data and instruction remain
unaffected, which may be lost, had this thread is suspended on one core and
brought back to another thread. If you can answer this question, that rest assure of a
good impression.

Q84. Design Patternsin Java?

Java Design Patterns are divided into three categories – creational, structural,
and behavioural design patterns.

 Creational Design Patterns


 Singleton Pattern
 Factory Pattern
 Abstract Factory Pattern
 Builder Pattern
 Prototype Pattern
Structural Design Patterns
 Adapter Pattern
 Composite Pattern
 Proxy Pattern
 Flyweight Pattern
 Facade Pattern
 Bridge Pattern
 Decorator Pattern
Behavioural Design Patterns
 Template Method Pattern
 Mediator Pattern
 Chain of Responsibility Pattern
 Observer Pattern
 Strategy Pattern
 Command Pattern
 State Pattern
 Visitor Pattern
 Interpreter Pattern
 Iterator Pattern
 Memento Pattern

Q85. What is double check locking in Singleton?

In Singleton pattern, a class has just one instance throughout its lifetime and that
instance is shared between multiple clients. Singleton class has two responsibility,
first to ensure that only instance of the class gets created and second, provide a
method getInstance() so that everyone can get access to that single instance i.e.
global access. One of the issue, faced by Singelton design pattern in the multi-
threading program is to ensure that just one instance of the class gets created, even
if multiple clients called getInstance() method same time. Many programmers solved
this problem by making whole getInstance() method synchronized, which results in
poor performance because every time a thread enters a synchronization method, it
acquires the lock and while it's been inside the method, no other thread are allowed
to enter, even if they are not creating instance and just accessing already created
instance.

How do you solve this problem? Well, you can use Double checked locking
idiom

Threadsafe Singleton using Double Checked Locking Idiom


Double checked locking idiom solves this problem by allowing you to eat your cake
and have it as well, it ensures synchronization is used only when instance of
Singleton is created, when getInstance() method is called first time and all other time,
same instance is returned without any synchronization overhead. As the name
suggests, it's double-checked, which means it checked two times
whether _instnace (the singleton instance) is initialized or not, one without
synchronization and other with synchronization. This double check ensures that
locking is only used when an instance is null i.e. when first time someone
calls getInstance(), all subsequent call will see _instnace not null hence they will not
enter into synchronization block.
Here is the code of thread-safe singleton pattern using double-checked
locking idiom:

/**
* Thread Safe Singleton in Java using Double checked locking.
* @author WINDOWS 8
*
*/
public class Singleton {

private static volatile Singleton _instance;

/**
* Double checked locking code on Singleton
* @return Singelton instance
*/
public static Singleton getInstance() {
if (_instance == null) {
synchronized (Singleton.class) {
if (_instance == null) {
_instance = new Singleton();
}
}
}
return _instance;
}

How Double Checked Locking Idiom Works


To illustrate the point, how this idiom prevents from two instances being created
when two thread simultaneously calls the getInstance() method, let's see the theory.
Suppose, thread T1 calls getInstance() very the first time and sees
that _instance is null then it will go inside synchronization block and that point of
time it paused. Now, thread T2 calls getInstance()and it will also
see _instance variable null, but it cannot go inside synchronization block because the
lock is held by Thread T1, which is inside the synchronization block. Now, thread T1
wake up and creates a new instance of singleton and come out of synchronized
block. After this when thread T2 goes inside synchronized block, it again checks
whether _instance is nulland this time check fails because _instnace is no more null.
So thread T2 come out of the synchronized block without creating another instance.
Further calls to this method return from first check only.

By the way, double checked locking idiom was broken before Java 5. It was
possible for a thread to see half initialized instance which will fail the first null check,
resulting in returning a half-initialized Singleton. That's why it's absolutely critical to
make _instnace a volatile variable. The Java memory model updates and happens-
before makes double checked locking works again.

That's all about how to create thread-safe Singleton in Java, but this is not the
only way to create the thread-safe singleton. You can use Enum as Singleton then
Java itself will guarantee that only one instance will be created even in the case of
multiple threads trying to access it the same time. Alternatively, you can also eagerly
initialized the Singleton, in that case, it would be initialized on static initializer
block at the time of class loading in a thread-safe manner. If you decide to use
double-checked locking idiom to make Singleton creation thread-safe, don't forget
the volatile modifier.

Where should we put synchronized block, before if condition or inside if


condition? [Explained]

Q86. Where all String objects will be created in Java?


What is Java String Pool?

As the name suggests, String Pool in java is a pool of Strings stored in Java Heap
Memory. We know that String is special class in java and we can create String object
using new operator as well as providing values in double quotes.

String Pool in Java

Here is a diagram which clearly explains how String Pool is maintained in java heap
space and what happens when we use different ways to create Strings.

String Pool is possible only because String is immutable in Java and it’s
implementation of String interning concept. String pool is also example of Flyweight
design pattern.

String pool helps in saving a lot of space for Java Runtime although it takes more
time to create the String.

When we use double quotes to create a String, it first looks for String with same
value in the String pool, if found it just returns the reference else it creates a new
String in the pool and then returns the reference.

However using new operator, we force String class to create a new String object in
heap space. We can use intern() method to put it into the pool or refer to other
String object from string pool having same value.

Here is the java program for the String Pool image:

package com.journaldev.util;
publicclassStringPool{

/**

* Java String Pool example

* @param args

*/

publicstaticvoid main(String[] args){

String s1 ="Cat";

String s2 ="Cat";

String s3 =newString("Cat");

System.out.println("s1 == s2 :"+(s1==s2));

System.out.println("s1 == s3 :"+(s1==s3));

Output of the above program is:

s1 == s2 :true

s1 == s3 :false

Sometimes in java interview, you will be asked question around String pool. For
example, how many string is getting created in below statement;

String str =newString("Cat");


In above statement, either 1 or 2 string will be created. If there is already a string
literal “Cat” in the pool, then only one string “str” will be created in the pool. If there
is no string literal “Cat” in the pool, then it will be first created in the pool and then in
the heap space, so total 2 string objects will be created.

Q87. How to transfer String created on Heap to String Pool?

String interning using inter() method


Java by default doesn't put all String object into String pool, instead they gives you
flexibility to explicitly store any arbitrary object in String pool. You can put any object
to String pool by calling intern() method of java.lang.String class. Though, when you
create using String literal notation of Java, it automatically call intern() method to put
that object into String pool, provided it was not present in the pool already. This is
another difference between string literal and new string, because in case of new,
interning doesn't happen automatically, until you call intern() method on that object.

Q88. What is the purpose of View in database?

The views are virtual tables. Unlike tables that contain data, views simply contain

queries that dynamically retrieve data when used.

Advantages:

1. Views don't store data in a physical location.

2. The view can be used to hide some of the columns from the table.

3. Views can provide Access Restriction, since data insertion, update and deletion is

not possible with the view.

Disadvantages:

1. When a table is dropped, associated view become irrelevant.

2. Since the view is created when a query requesting data from view is triggered, its

a bit slow.
3. When views are created for large tables, it occupies more memory.

Q89. What do the steps need to be performed to improve the performance of


table?

 check for indexes


 work with the smallest data set required
 remove unnecessary fields and tables and
 remove calculations in your JOIN and WHERE clauses.

Q90. What is the drawback of using index on table?

A clustered index reorders the way records in the table are physically stored. There

can be only one clustered index per table. It makes data retrieval faster.

A non clustered index does not alter the way it was stored but creates a completely

separate object within the table. As a result insert and update command will be

faster.

What is the difference of Singleton and Prototype scope? [Explained]

CAPEGEMINI MUMBAI R1:

Q91. There are two interfaces A and B. B is child of A and there is class P which
is child of B. Then what is the relationship?

Ans:

B extends A

P implements B

Q92. What are the utility methods in Java?

Q93. What is Method overloading and Method overriding?

Rules of overloading a method in Java


1) First and foremost rule to overload a method in Java is to change method
signature. method signature is made of number of arguments, type of arguments
and order of arguments if they are of different types. You can change any of these or
combinations of them to overload a method in Java.

2) Return type of method is not part of method signature, so just changing the return
type will not overload a method in Java. In fact, just changing the return type will
result in compile time error as "duplicate method X in type Y.

Method Overriding Rules in Java


Overriding is completely different than overloading and so it's rules are also different.
For terminology, original method is known as overridden method and new method is
known as overriding method. Following rules must be followed to correctly override
a method in Java :

1) A method can only be overridden in sub class, not in same class. If you try to
create two methods with same signature in one class compiler will complain about it
saying "duplicate method in type Class"

2) Overriding method cannot throw checked Exception which is higher in hierarchy,


than checked Exception thrown by overridden method. For example if overridden
method throws IOException or ClassNotfoundException, which are checked
Exception, than overriding method can not throw java.lang.Exception because it
comes higher in type hierarchy (it's super class of IOException and
ClassNotFoundExcepiton). If you do so, compiler will catch you

3) Overriding method can not reduce access of overridden method. It means if


overridden method is defined as public than overriding method can not be protected
or package private. Similarly if original method is protected then overriding method
cannot be package-private. You can see what happens if you violate this rule in Java,
as seen in this screenshot it will throw compile time error saying "You cannot reduce
visibility of inherited method of a class".

4) Overriding method can increase access of overridden method. This is opposite of


earlier rule, according to this if overridden method is declared as protected than
overriding method can be protected or public.

5) private, static and final method can not be overridden in Java. See other articles in
this blog to learn why you cannot override private, static or final method in Java. By
the way, you can hide private and static method but trying to override final method
will result in compile time error "Cannot override the final method from a class" as
shown in below screenshot :
6) Return type of overriding method must be same as overridden method. Trying to
change return type of method in child class will throw compile time error "return
type is incompatible with parent class method" as shown in following screenshot.

Difference between Overloading and Overriding in Java

1) First and major difference between Overloading and Overriding is that former
occur during compile time while later occur during runtime.

2) Second difference between Overloading and Overriding is that, you can overload
method in same class but you can only override method in sub class.

3) Third difference is that you can overload static method in Java but you can not
override static method in Java. In fact when you declare same method in Sub Class
it's known as method hiding because it hide super class method instead of overriding
it.

4) Overloaded methods are bonded using static binding and Type of reference
variable is used, while Overridden method are bonded using dynamic bonding based
upon actual Object.

5) Rules of Overloading and Overriding is different in Java. In order to overload a


method you need to change its method signature but that is not required for
overriding any method in Java.

6) Another difference between method overloading and overriding is that private


and final method can not be overridden but can be overloaded in Java.

7) Overloaded method are fast as compare to Overridden method in Java.

Q94. What are the different ways to create Thread class and which way you will
choose and why?

There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

If you are not extending the Thread class,your class object would not be treated
as a thread object.So you need to explicitely create Thread class object.We are
passing the object of your class that implements Runnable so that your class run()
method may execute.

Q95. Single / Multiple instance of bean created when requested? (Refer - Bean
Scopes) [Explained]

Q96. Spring Security

What is marker interface? [Explained]

Q97. Difference between abstract and interface

Abstract class Interface

1) Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.
2) Abstract class doesn't support multiple Interface supports multiple inheritance.
inheritance.

3) Abstract class can have final, non-final, Interface has only static and final
static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to declare The interface keyword is used to


abstract class. declare interface.

6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface


achieves fully abstraction (100%).

Q98. Difference between comparable and comparator [Explained]

Capegemini Mumbai R1:

Q99. How to execute procedure in hibernate? What are the steps?

In Hibernate, there are three approaches to call a database store procedure.

1. Native SQL – createSQLQuery


You can use createSQLQuery() to call a store procedure directly.

Query query = session.createSQLQuery(

"CALL GetStocks(:stockCode)")

.addEntity(Stock.class)

.setParameter("stockCode","7277");

List result = query.list();


for(int i=0; i<result.size(); i++){

Stock stock =(Stock)result.get(i);

System.out.println(stock.getStockCode());

2. NamedNativeQuery in annotation
Declare your store procedure inside the @NamedNativeQueries annotation.

//Stock.java

...

@NamedNativeQueries({

@NamedNativeQuery(

name ="callStockStoreProcedure",

query ="CALL GetStocks(:stockCode)",

resultClass = Stock.class

})

@Entity

@Table(name ="stock")

publicclassStockimplementsjava.io.Serializable{

...

Call it with getNamedQuery().

Query query = session.getNamedQuery("callStockStoreProcedure")


.setParameter("stockCode","7277");

List result = query.list();

for(int i=0; i<result.size(); i++){

Stock stock =(Stock)result.get(i);

System.out.println(stock.getStockCode());

3. sql-query in XML mapping file


Declare your store procedure inside the "sql-query" tag.

<!-- Stock.hbm.xml -->

...

<hibernate-mapping>

<class name="com.mkyong.common.Stock" table="stock" ...>

<id name="stockId" type="java.lang.Integer">

<column name="STOCK_ID" />

<generator class="identity" />

</id>

<property name="stockCode" type="string">

<column name="STOCK_CODE" length="10" not-null="true" unique="true" />

</property>

...

</class>
<sql-query name="callStockStoreProcedure">

<return alias="stock" class="com.mkyong.common.Stock"/>

<![CDATA[CALL GetStocks(:stockCode)]]>

</sql-query>

</hibernate-mapping>

Call it with getNamedQuery().

Query query = session.getNamedQuery("callStockStoreProcedure")

.setParameter("stockCode","7277");

List result = query.list();

for(int i=0; i<result.size(); i++){

Stock stock =(Stock)result.get(i);

System.out.println(stock.getStockCode());

Conclusion
The above three approaches are doing the same thing, call a store procedure in
database. There are not much big different between the three approaches, which
method you choose is depend on your personal prefer.
Bean scopes and difference [Explained]

Q100. What are the advantage of tableau over ireport?

Q101. Procedure create insert, create, insert, and create rollback - state of
database?
Q102. What is transaction? By default, commit or not?

A transaction simply represents a unit of work. In such case, if one step fails, the
whole transaction fails (which is termed as atomicity). A transaction can be described
by ACID properties (Atomicity, Consistency, Isolation and Durability).

Q103. What is immutable object and how to create it? [Explained]

Q104. How to create Linked list?

Hashmap internal structure [Explained]

Method overloading vs method overriding [Explained]

Q105. super - io , data, arthmetic throw - sub class override / hide ? [Explained]

Q106. What is rest and why used rest in your project instead of jsp / servlet?

Genpact Capital Market

Q107. There are 2 beans of same class with different id and scope is Singleton
then both the object reference will be same or different? how == and .equals
will behave?

What is autowiring? [Explained]

Q108. What is the internal working of Hashset and Hashmap?

Set Implementation Internally in Java


Each and every element in the set is unique . So that there is no duplicate element in
set .

So in java if we want to add elements in the set then we write code like this

publicclassJavaHungry{

publicstaticvoidmain(String[] args)
{
// TODO Auto-generated method stub

HashSet<Object> hashset =new HashSet<Object>();


hashset.add(3);
hashset.add("Java Hungry");
hashset.add("Blogspot");
System.out.println("Set is "+hashset);
}
}

It will print the result : Set is [3, Java Hungry, Blogspot]

Now let add duplicate element in the above code

publicclassJavaHungry{

publicstaticvoidmain(String[] args)
{
HashSet<Object> hashset =new HashSet<Object>();
hashset.add(3);
hashset.add("Java Hungry");
hashset.add("Blogspot");
hashset.add(3);// duplicate elements
hashset.add("Java Hungry");// duplicate elements
System.out.println("Set is "+hashset);
}
}

It will print the result : Set is [3, Java Hungry, Blogspot]

Now , what happens internally when you pass duplicate elements in the add()
method of the Set object , It will return false and do not add to the HashSet , as the
element is already present .So far so good .

But the main problem arises that how it returns false . So here is the answer

When you open the HashSet implementation of the add() method in Java Apis that is
rt.jar , you will find the following code in it

publicclassHashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

{
privatetransient HashMap<E,Object> map;

// Dummy value to associate with an Object in the backing Map

privatestaticfinal Object PRESENT =new Object();

publicHashSet(){
map =new HashMap<>();
}

// SOME CODE ,i.e Other methods in Hash Set

publicbooleanadd(E e){
return map.put(e, PRESENT)==null;
}
// SOME CODE ,i.e Other methods in Hash Set
}

So , we are achieving uniqueness in Set,internally in java through HashMap .


Whenever you create an object of HashSet it will create an object of HashMap as you
can see in the italic lines in the above code .
We already discussed How HashMap works internally in java .

As we know in HashMap each key is unique . So what we do in the set is that we pass
the argument in the add(Elemene E) that is E as a key in the HashMap . Now we need
to associate some value to the key , so what Java apis developer did is to pass the
Dummy value that is ( new Object () ) which is referred by Object reference PRESENT
.

So , actually when you are adding a line in HashSet like hashset.add(3) what java
does internally is that it will put that element E here 3 as a key in the
HashMap(created during HashSet object creation) and some dummy value that is
Object's object is passed as a value to the key .

Now if you see the code of the HashMap put(Key k,Value V) method , you will find
something like this

public V put(K key, V value) {


//Some code
}

The main point to notice in above code is that put (key,value) will return

1. null , if key is unique and added to the map


2. Old Value of the key , if key is duplicate

So , in HashSet add() method , we check the return value of map.put(key,value)


method with null value
i.e.

public boolean add(E e) {


return map.put(e, PRESENT)==null;
}

So , if map.put(key,value) returns null ,then


map.put(e, PRESENT)==null will return true and element is added to the HashSet.

So , if map.put(key,value) returns old value of the key ,then


map.put(e, PRESENT)==null will return false and element is not added to the
HashSet .

Q109. How hashmap determines the location/index to put key/value pair?

Q110. Reverse the elements of Array using algorithm?

Q111. There is huge csv file and how to identify the occurrence of a particular
word?

Q112. What are the joins?

Select all records from Table A and Table B, where the join condition is met.

Select all records from Table A, along with records from Table B for which the join
condition is met (if at all).
Select all records from Table B, along with records from Table A for which the join
condition is met (if at all).

Select all records from Table A and Table B, regardless of whether the join condition
is met or not.
Self-join is query used to join a table to itself. Aliases should be used for the same

table comparison.

Q113. Query to find nth maximum salary

Find the nth highest salary in Oracle using rownum

Oracle syntax doesn’t support using an offset like MySQL and SQL Server, but we can
actually use the row_number analytic function in Oracle to solve this problem. Here is
what the Oracle-specific SQL would look like to find the nth highest salary:

select * from (
select Emp.*,
row_number() over (order by Salary DESC) rownumb
from Employee Emp
)
where rownumb = n; /*n is nth highest salary*/

Find the nth highest salary in Oracle using RANK

Oracle also provides a RANK function that just assigns a ranking numeric value (with
1 being the highest) for some sorted values. So, we can use this SQL in Oracle to find
the nth highest salary using the RANK function:

select * FROM (
select EmployeeID, Salary
,rank() over (order by Salary DESC) ranking
from Employee
)
WHERE ranking = N;

Find the nth highest salary in MySQL

In MySQL, we can just use the LIMIT clause along with an offset to find the nth
highest salary. If that doesn’t make sense take a look at the MySQL-specific SQL to
see how we can do this:

SELECT Salary FROM Employee


ORDER BY Salary DESC LIMIT n-1,1

Find the nth highest salary using the TOP keyword in SQL Server

We can also use the TOP keyword (for databases that support the TOP keyword, like
SQL Server) to find the nth highest salary. Here is some fairly simply SQL that would
help us do that:

SELECT TOP 1 Salary


FROM (
SELECT DISTINCT TOP N Salary
FROM Employee
ORDER BY Salary DESC
) AS Emp
ORDER BY Salary

Synchronous vs Asynchronous web service. How about REST and SOAP?

Synchronous Web services can be defined as services that are invoked over existing
Web protocols by a client that blocks/waits for a response. Synchronous Web
services that are generally better served by RPC-oriented messaging.

Asynchronous Web services can be defined as services that are invoked over existing
Web protocols by a client that does not wait for a response, but does expect a
response at a later time. Document-oriented messaging is often used for
asynchronous Web services along with some form of workflow infrastructure.

"Synchronous" or "Asynchronous" is the behavior of the client that is requesting the


resource. It has nothing to do with REST web service, its structure, or the supporting
server.
Synchronous behavior:

 Client constructs an HTTP structure, sends over the socket connection.


 Waits for the response HTTP.
Asynchronousbehavior:

 Client constructs HTTP structure, sends the request, and moves on.
 There's another thread that is waiting on the socket for the response. Once
response arrives, the original sender is notified (usually, using a callback like
structure).

Java packages
REST vs SOAP

What is the difference between Web Server and App Server?

What is the difference between ClassCastException and


ClassNotFoundException?

You might also like