SELECT e1.name AS MaxName, MAX(e1.
sal) AS MaxSalary,
e2.name AS MinName, MIN(e2.sal) AS MinSalary
FROM employees e1 CROSS JOIN employees e2
Dependency Injection (DI) is a design pattern used to implement IoC. It allows the
creation of dependent objects outside of a class and provides those objects to a class
through different ways. Using DI, we move the creation and binding of the dependent
objects outside of the class that depends on them.
The Dependency Injection pattern involves 3 types of classes.
1. Client Class: The client class (dependent class) is a class which depends on the service
class
2. Service Class: The service class (dependency) is a class that provides service to the
client class.
3. Injector Class: The injector class injects the service class object into the client class.
The following figure illustrates the relationship between these classes:
Dependency Injection
As you can see, the injector class creates an object of the service class, and injects that
object to a client object. In this way, the DI pattern separates the responsibility of
creating an object of the service class out of the client class.
Types of Dependency Injection
As you have seen above, the injector class injects the service (dependency) to the client
(dependent). The injector class injects dependencies broadly in three ways: through a
constructor, through a property, or through a method.
Constructor Injection: In the constructor injection, the injector supplies the service
(dependency) through the client class constructor.
Property Injection: In the property injection (aka the Setter Injection), the injector
supplies the dependency through a public property of the client class.
Method Injection: In this type of injection, the client class implements an interface
which declares the method(s) to supply the dependency and the injector uses this
interface to supply the dependency to the client class.
Let's take an example from the previous chapter to maintain the continuity. In the
previous section of DIP, we used Factory class inside
the CustomerBusinessLogic class to get an object of
the CustomerDataAccess object, as shown below.
public interface ICustomerDataAccess
{
string GetCustomerName(int id);
}
public class CustomerDataAccess: ICustomerDataAccess
{
public CustomerDataAccess() {
}
public string GetCustomerName(int id) {
return "Dummy Customer Name";
}
}
public class DataAccessFactory
{
public static ICustomerDataAccess GetCustomerDataAccessObj()
{
return new CustomerDataAccess();
}
}
public class CustomerBusinessLogic
{
ICustomerDataAccess _custDataAccess;
public CustomerBusinessLogic()
{
_custDataAccess =
DataAccessFactory.GetCustomerDataAccessObj();
}
public string GetCustomerName(int id)
{
return _custDataAccess.GetCustomerName(id);
}
}
There are four things we should know about before going into internals of how HashMap
works -
HashMap works on the principal of hashing.
Map.Entry interface - This interface gives a map entry (key-value pair).
HashMap in Java stores both key and value object, in bucket, as Entry
object which implements this nested interface Map.Entry.
hashCode() -HashMap provides put(key, value) for storing and get(key)
method forretrieving Values from HashMap. When put() method is used to
store (Key, Value) pair, HashMap implementation calls hashcode on Key
object to calculate a hash that is used to find a bucket where Entry object
will be stored. When get() method is used to retrieve value, again key
object is used to calculate a hash which is used then to find a bucket where
that particular key is stored.
equals() - equals() method is used to compare objects for equality. In
case of HashMap key object is used for comparison, also using equals()
method Map knows how to handle hashing collision (hashing collision
means more than one key having the same hash value, thus assigned to the
same bucket. In that case objects are stored in a linked list.
Interview Questions and Answers for 'Deloitte' - 46
question(s) found - Order By Newest
Advanced level question. Frequently asked in High end product companies. Frequently asked in
Google , Cognizant and Deloitte ( Based on 2 feedback )
Q1. Why is String immutable in Java ? Core Java
Ans. 1. String Pool - When a string is created and if it exists in the
pool, the reference of the existing string will be returned instead of
creating a new object. If string is not immutable, changing the
string with one reference will lead to the wrong value for the other
references.
Example -
String str1 = "String1";
String str2 = "String1"; // It doesn't create a new String and rather
reuses the string literal from pool
// Now both str1 and str2 pointing to same string object in pool,
changing str1 will change it for str2 too
2. To Cache its Hashcode - If string is not immutable, One can
change its hashcode and hence it's not fit to be cached.
3. Security - String is widely used as parameter for many java
classes, e.g. network connection, opening files, etc. Making it
mutable might possess threats due to interception by the other
code segment.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java oops string string class
immutable immutability advanced Asked in 38 Companies expert frequent
Correction
Try 4 Question(s) Test
Very frequently asked in different variations. Frequently asked in Deloitte ( 2 feedback ) , HCL
Tech ( 3 feedback ) and Coginizant (CTS)
Q2. Explain the scenerios to choose between String , StringBuilder and Core Java
StringBuffer ?
or
What is the difference between String , StringBuilder and StringBuffer ?
Ans. If the Object value will not change, use String Class because a
String object is immutable.
If the Object value can change and will only be modified from a
single thread, use StringBuilder because StringBuilder is
unsynchronized(means faster).
If the Object value may change, and can be modified by multiple
threads, use a StringBuffer because StringBuffer is thread
safe(synchronized).
Sample Code for String
Sample Code for StringBuffer
Sample Code for StringBuilder
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java string class string stringbuilder
stringbuffer Asked in 28 Companies basic frequent
Correction
Try 3 Question(s) Test
Very frequently asked. Favorite question in Walk in Drive of many Indian service companies.
Q3. What is the difference between ArrayList and LinkedList ? Core Java
Ans. Underlying data structure for ArrayList is Array whereas
LinkedList is the linked list and hence have following differences -
1. ArrayList needs continuous memory locations and hence need to
be moved to a bigger space if new elements are to be added to a
filled array which is not required for LinkedList.
2. Removal and Insertion at specific place in ArrayList requires
moving all elements and hence leads to O(n) insertions and removal
whereas its constant O(1) for LinkedList.
3. Random access using index in ArrayList is faster than LinkedList
which requires traversing the complete list through references.
4. Though Linear Search takes Similar Time for both, Binary Search
using LinkedList requires creating new Model called Binary Search
Tree which is slower but offers constant time insertion and deletion.
5. For a set of integers you want to sort using quicksort, it's
probably faster to use an array; for a set of large structures you
want to sort using selection sort, a linked list will be faster.
Sample Code for ArrayList
Sample Code for LinkedList
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve collections java data structures arraylist
linkedlist Asked in 61 Companies Basic frequent
Correction
Try 1 Question(s) Test
Frequently asked question in companies using Hibernate.
Q4. What is Lazy Initialization in Hibernate ? Hibernate
Ans. It's a feature to lazily initialize dependencies , relationship and
associations from the Database. Any related references marked as
@OneToMany or @ManyToMany are loaded lazily i.e when they are
accessed and not when the parent is loaded.
Sample Code for Lazy Initialization
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve hibernate lazy loading hibernate lazy
initialization hibernate architecture Asked in 77 Companies Basic frequent
Correction
Try 2 Question(s) Test
Basic and Very Frequently asked.
Q5. What is Polymorphism in Java ? Core Java
Ans. Polymorphism means the condition of occurring in several
different forms.
Polymorphism in Java is achieved in two manners
1. Static polymorphism is the polymorphic resolution identified at
compile time and is achieved through function overloading whereas
2. Dynamic polymorphism is the polymorphic resolution identified at
runtime and is achieved through method overriding.
Sample Code for overloading
Sample Code for overriding
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve polymorphism object oriented programming
(oops) oops concepts oops concepts Asked in 107 Companies Basic frequent
Correction
Try 2 Question(s) Test
Advanced level question. Recently asked in few Indian service companies ( Based on 3 inputs )
Q6. What are various types of Class loaders used by JVM ? Core Java
Ans. Bootstrap - Loads JDK internal classes, java.* packages.
Extensions - Loads jar files from JDK extensions directory - usually
lib/ext directory of the JRE
System - Loads classes from system classpath.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java jvm memory management class loaders
bootstrap extensions system classloaders advanced technical lead technical architect Asked in 7
Companies
Correction
Q7. How to implement an immutable class ? Core Java
Ans. We can make a class immutable by
1. Making all methods and variables as private.
2. Setting variables within constructor.
Public Class ImmutableClass{
private int member;
ImmutableClass(int var){
member=var;
}
}
and then we can initialize the object of the class as
ImmutableClass immutableObject = new ImmutableClass(5);
Now all members being private , you cant change the state of the
object.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java oops immutable immutability
immutable immutability class technical lead Asked in 5 Companies intermediate frequent
Correction
Try 2 Question(s) Test
Q8. Can we serialize static variables ? Core Java
Ans. No. Only Object and its members are serialized. Static
variables are shared variables and doesn't correspond to a specific
object.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve serialization java oops static static
variables Asked in 1 Companies intermediate rare
Correction
Try 2 Question(s) Test
Q9. Difference between Vector and ArrayList ? Core Java
Ans. Vectors are synchronized whereas Array lists are not.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java basic interview question vector arraylist
collections synchronization Asked in 35 Companies basic frequent
Correction
Q10. What is the use of Transient Keyword ? Core Java
Ans. It in Java is used to indicate that a field should not be
serialized.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java oops serialization transient java
keywords Asked in 39 Companies intermediate frequent
Correction
Try 2 Question(s) Test
Very Frequently asked. Usually asked along with String Class related questions.
Q11. What is an immutable class ? Core Java
Ans. Class using which only immutable (objects that cannot be
changed after initialization) objects can be created.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java oops immutable immutability
immutable immutability class string class basic interview question Asked in 18 Companies
Basic frequent
Correction
Try 2 Question(s) Test
Q12. what is fail fast and Fail Safe in collections? Core Java
Ans. Iterators in java are used to iterate over the Collection objects.
Fail-Fast iterators immediately throw
ConcurrentModificationException if there is any addition, removal or
updation of any element.
Fail-Safe iterators don't throw any exception if a collection is
structurally modified while iterating over it. This is because, they
operate on the clone of the collection and not on the original
collection.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve ail fast fail saf Asked in 9
Companies intermediate
Correction
Q13. What is ConcurrentModificationException ? Core Java
Ans. This is the exception that is thrown when we try to modify the
non concurrent collection class while iterating through it.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java collections
concurrentmodificationexception exception concurrency Asked in 14 Companies intermediate
Correction
Frequently asked in high end product companies. Frequently asked in Deloitte.
Q14. How is Hashmap internally implemented in Java ? Core Java
Ans. https://www.quora.com/How-is-Hashmap-in-Java-
implemented-internally-What-are-the-pros-and-cons-to-use-it-
What-are-the-complexities-it-provides-for-insert-delete-and-
lookup/answer/Anshudeep-Bajpai?srid=iwnK
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve hashmap collections hashmap internal
implementation Asked in 19 Companies expert frequent
Correction
Frequently asked at HCL Technologies ( Based on 3 feedback )
Q15. Difference between Checked and Unchecked exceptions ? Core Java
Ans. Checked exceptions are the exceptions for which compiler
throws an errors if they are not checked whereas unchecked
exceptions are caught during run time only and hence can't be
checked.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java exceptions checked exceptions unchecked
exceptions exception handling basic interview question Asked in 38 Companies basic
frequent
Correction
Try 1 Question(s) Test
Q16. Write an algorithm / Java Program to show duplicates in an array of n Algorithm
elements?
Ans. int duplicateArray[] = { 1, 2, 2, 3, 4, 5, 6, 8, 9}
Set unique = new HashSet();
for (int i = 0; i < duplicateArray.length; i) {
if (unique.contains(duplicateArray[i])) {
System.out.println(duplicateArray[i]);
} else {
unique.add(duplicateArray[i]);
}
}
Complexity O(n) = nHashSet contains and add has O(n) = 1
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve coding code Asked in 2 Companies
Correction
Q17. What is a binary tree ? Algorithm
Ans. Binary tree is a tree in which each node has up to two
children.Tree is a data structure composed of nodes.Each tree has a
root node(not necessary in graph theory). The root node has zero
or more child nodes.Each child node has zero or more child nodes,
and so on.The tree cannot contain cycles.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve binary tree Asked in 1 Companies
Correction
Q18. Can we have multiple inheritance in java using abstract class ? Core Java
Ans. No
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve abstract class multiple inheritance object
oriented programming (oops) oops concepts Asked in 2 Companies
Correction
Q19. Describe structure of a Web application. architecture
Ans. WEB APP |WEB-INF - META-INF | | | META-INF.MF | lib -
WEB.xml - Classes
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve web application Asked in 3
Companies intermediate frequent
Correction
Web
Q20. What are the types of authentication used in Web services ?
Service
Ans. Encrypted User Name / Password
Encrypted Password within Cookie
Encrypted Tokens
IP
Client Certificates
Oauth
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve authentication security web service Asked
in 12 Companies basic frequent
Correction
Very Frequently asked. Favorite question in walkins and telephonic interviews. Usually among first
few questions. Asked in different variants. Must know for intermediate and expert
professionals.Among Top 10 frequently asked questions.
Q21. What is rule regarding overriding equals and hashCode method ? Core Java
Ans. A Class must override the hashCode method if its overriding
the equals method.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java collections hashcode hash code equals
collections Asked in 44 Companies intermediate frequent
Correction
Try 1 Question(s) Test
Q22. Can we have null keys in TreeMap ? Core Java
Ans. No, results in exception.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java collections treemap Asked in 6
Companies Basic frequent
Correction
Very frequently asked. Usually followed by questions related to private constructor and
synchronized access. Frequently asked in JPMorgan and TCS (Based on 2 feedback)
Q23. Explain Singleton Design Pattern ? Design
Ans. http://www.buggybread.com/2014/03/java-design-pattern-
singleton-interview.html
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java design pattern singleton at&t
ebay fidelity india united healthcare india Asked in 46 Companies intermediate frequent
Correction
Q24. What is ArrayIndexOutOfBoundException ? Core Java
Ans. Exception thrown by the application is we try to access an
element using an index which is not within the range of array i.e
lower than 0 or greater than the size of the array.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java exceptions
arrayindexoutofboundexception Asked in 1 Companies
Correction
Q25. Difference between jar , war and ear ? Java EE
Ans. Jar is Java Archieve i.e compressed Class or Class / Java files.
War comprises of compressed Servlet class files,JSP
FIles,supporting files, GIF and HTML files.
Ear comprise of compressed Java and web module files ( was files ).
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java j2ee jar web development war ear
build management release management Asked in 12 Companies basic frequent
Correction
Q26. What is Jenkins ? Jenkins
Ans. It is a continuous integration tool written in Java.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve java jenkins Asked in 6 Companies
Basic frequent
Correction
Q27. What are the disadvantages of multithreading ? Core Java
Ans. 1. Switching Overheads - Even though multi threading aims at
improving performance by reducing the wait time and hence
improving overall throughput, there is a cost of switching resources
between threads and sometime this cost can surpass the benefits if
there isnt much wait for IO or external communication.
2. Debugging is hard with multi threaded code.
3. Deadlock - Execution of multi threaded code many a times lead
to deadlock due to shared resources.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve multithreading threads Asked in 4
Companies
Correction
Very frequently asked.
Q28. What is the use of synchronized keyword ? Core Java
Ans. Synchronize is used to achieve mutual exclusion i.e at one
time, the segment of the code, method that has been declared
synchronized should be executed by single thread only and hence
the lock needs to be retrieved before executing the segment and
then released.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve threads multithreading synchronized
Asked in 5 Companies basic frequent
Correction
Q29. What is an exception and exception handling in Java ? Core Java
Ans. An Exception in java is the occurrence during computation that
is anomalous and is not expected.
Exception handling is the mechanism which is used to handle such
situations.
Help us improve. Please let us know the company, where you were asked this
question :
Like Discuss Correct / Improve exception handling Asked in 18
Companies basic frequent
Correction
Q30. Write an algorithm / java program for Heap Sort ? Algorithm
Ans. https://www.geeksforgeeks.org/heap-sort/