Professional Documents
Culture Documents
Cognizant: Function, Hash Value and Bucket
Cognizant: Function, Hash Value and Bucket
Q1. How hashmap works internally? What all things are there in bucket?
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 .
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 :
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 .
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
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
, and now ,it applies returned hashValue into its own hashing function .
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 ?
a. Using key.hashCode() [ see above step 4],determine initial hashvalue for the key
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
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 )
/**
* 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 .
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.
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]
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<>());
Q3. Hashmap.get(key) will traverse over the loop or it will go to the particular
place and return the value?
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?
Problem: loop over an ArrayList and remove selected elements, but remove() is
throwing "Exception in thread "main"
java.util.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.
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.
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.
ListIterator Iterator
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.
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
Q15. Why we use throw and throws keyword? What purpose does it serve?
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.
1. throw exception;
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.
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.
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?
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?
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.
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:
1. BeanFactory
2. ApplicationContext
Q21. @Qualifier
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?
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.
Q24. Same Bean with different id and doing auto wire by type. Does this
work? What is the exception?
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.,
index.jsp:
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()
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]
2) get() method always hit the load() method doesn't hit the database.
database.
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.
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Types of Synchronization
1. Process Synchronization
2. 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
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.
When a thread invokes a synchronized method, it automatically acquires the lock for
that object and releases it when the thread completes its task.
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.
If you make any static method as synchronized, the lock will be on the class not on
object.
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.
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:
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(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:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
public final void notifyAll()
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>
<id name="id">
<generator class="increment"></generator>
</id>
<property name="qname"></property>
<key column="qid"></key>
<index column="type"></index>
<one-to-many class="com.javatpoint.Answer"/>
</list>
</class>
<id name="id">
<generator class="increment"></generator>
</id>
<property name="answername"></property>
<property name="postedBy"></property>
</class>
</hibernate-mapping>
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.
<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>
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.
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.
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:
Let's see the second level cache implementation and cache usage.
1. <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</pr
operty>
2. <property name="hibernate.cache.use_second_level_cache">true</property>
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.
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.
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.
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
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
Delete - DML
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
Drop command is used to drop the table or keys like primary,foreign from a table.
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
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).
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.
sh -x
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.
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.
Inner class is a part of nested class. Non-static nested classes are known as inner
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.
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.
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.
Write the code inside try catch block or throws the exception and calling method
should handle that exception.
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
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.
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.
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 −
Create an interface without any method and that is your marker interface.
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:
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
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
/*
* There are many immutable classes like String, Boolean, Byte, Short, Integer, Long,
Float, Double etc.
* The instance variable of the class is final i.e. we cannot change the value
of it after creating an object.
*/
ImmutableExample(String name) {
this.name = name;
return name;
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.
Employeeemp2= (Employee)
Class.forName("org.programming.mitra.exercises.Employee").newInstance();
Or:
Employeeemp2=Employee.class.newInstance();
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.
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
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
3) 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?
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?
Q74. What is the concept of Spring BDI? – Bean Dependency Injection (Above)
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.
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:
Spring framework provides following 4 ways for controlling life cycle events of
bean:
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:
The default init and destroy methods in bean configuration file can be defined in two
ways:
<beans>
<bean id="demoBean" class="com.howtodoinjava.task.DemoBean" init-method="customInit" de
method="customDestroy"></bean>
</beans>
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.
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.
The property element invokes the setter method. The value subelement of property
will assign the specified value.
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]
Comparable Comparator
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.
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 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.
Java Design Patterns are divided into three categories – creational, structural,
and behavioural design patterns.
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
/**
* Thread Safe Singleton in Java using Double checked locking.
* @author WINDOWS 8
*
*/
public class Singleton {
/**
* 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;
}
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.
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.
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.
package com.journaldev.util;
publicclassStringPool{
/**
* @param 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));
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;
The views are virtual tables. Unlike tables that contain data, views simply contain
Advantages:
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
Disadvantages:
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.
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.
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
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.
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"
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.
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.
Q94. What are the different ways to create Thread class and which way you will
choose and why?
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]
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.
6) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
"CALL GetStocks(:stockCode)")
.addEntity(Stock.class)
.setParameter("stockCode","7277");
System.out.println(stock.getStockCode());
2. NamedNativeQuery in annotation
Declare your store procedure inside the @NamedNativeQueries annotation.
//Stock.java
...
@NamedNativeQueries({
@NamedNativeQuery(
name ="callStockStoreProcedure",
resultClass = Stock.class
})
@Entity
@Table(name ="stock")
publicclassStockimplementsjava.io.Serializable{
...
System.out.println(stock.getStockCode());
...
<hibernate-mapping>
</id>
</property>
...
</class>
<sql-query name="callStockStoreProcedure">
<![CDATA[CALL GetStocks(:stockCode)]]>
</sql-query>
</hibernate-mapping>
.setParameter("stockCode","7277");
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]
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).
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?
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?
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
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);
}
}
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;
publicHashSet(){
map =new HashMap<>();
}
publicbooleanadd(E e){
return map.put(e, PRESENT)==null;
}
// SOME CODE ,i.e Other methods in Hash Set
}
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
The main point to notice in above code is that put (key,value) will return
Q111. There is huge csv file and how to identify the occurrence of a particular
word?
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.
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*/
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;
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:
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:
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.
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