[Go to site: main page, start]

0% found this document useful (0 votes)
4 views15 pages

Java Spring Interview Questions Formatted

The document provides a comprehensive overview of key concepts in Spring Framework, including Dependency Injection, IOC principles, and various types of collections in Java. It covers different injection methods such as Field, Setter, and Constructor Injection, along with their advantages and disadvantages. Additionally, it explains the workings of collections like List, Set, and Map, and discusses multithreading concepts including thread creation and lifecycle.

Uploaded by

badityaa1977
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views15 pages

Java Spring Interview Questions Formatted

The document provides a comprehensive overview of key concepts in Spring Framework, including Dependency Injection, IOC principles, and various types of collections in Java. It covers different injection methods such as Field, Setter, and Constructor Injection, along with their advantages and disadvantages. Additionally, it explains the workings of collections like List, Set, and Map, and discusses multithreading concepts including thread creation and lifecycle.

Uploaded by

badityaa1977
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Interview Questions (Formatted Notes)

Q.1 What is Dependency Injection?


Ans: 1. Dependency Injection is a core feature of Spring. 2. Instead of we create the object
ne
w
using keyword, Spring will create object for us. 3. With the help of dependency injection
we can make our application loosely coupled. 4. With the help of dependency injection we
can inject the dependency into the required field. 5. Basically Spring Boot provide 4 types
of injection:

• @Autowir (Field Injection)


ed
•Constructor Injection
•Setter Injection
•Lookup Method Injection

Q.2 What is Field Injection ( @Autowir Annotation)?


Ans: 1. Field injection is denoted by ed
@Autowired annotation. 2. We can achieve the field
injection by
@Autowir
using the @Autowir Annotation. 3. @Autowired Injection is ed internally
Java ed slow. 4. uses
Reflection.

Q.3 Why @Autowir is slow?


ed
Ans: 1. Because it internally uses Java Reflection.@Autowir
2. annotation uses reflection for
dependency injection therefore field injection is edconsidered slower. 3. Let say we have 100
classes and
we are using the@Autowir annotation, so autowiring object is a time consuming process.
4. It can ed
impact application startup time because internally it uses Java reflection. 5. Therefore
Constructor Injection is generally preferred.

Q.4 Setter Injection


Ans: 1. Setter Injection is a part of Dependency Injection. 2. Setter Injection is an optional
Injection. 3. We can achieve Setter Injection by using setter method. 4. If you inject
dependency optional we can go for Setter Injection.

Q.5 Constructor Injection


Ans: 1. Constructor Injection is a type of Dependency Injection. 2. With the help of
constructor we can achieve constructor injection. 3. If we want to inject dependency
mandatory then we can go for Constructor Injection. 4. As per company standard
constructor injection is fast and mandatory.

1
Q.6 Why Constructor Injection is fast?
Ans: 1. Because Spring inject the dependency directly through constructor at the time of
object creation process.

Q.7 How we can achieve field injection when multiple beans


exist?
Ans: 1. We can achieve the field injection by using
@Prima annotation and@Qualifi
annotation. 2. When multiple beans at same time ry exist that time use. er

Q.8 Difference Between


@Qualifi and @Prima
er ry
What is @Prima Annotation?
Ans: 1.
ry
Annotation is a part of Dependency Annotation use to
@Prima Injection. 2. @Prima
ry as the default. 3. When multiple beans of the samerytype are present in the spring
mark bean
container
@Prima
but we have to make one bean as default then we can go for the Annotation.
ry

Q.9 What is @Qualifi ?


er
Ans: 1. @Qualifi annotation is used to make bean unique. 2. Whenever we have multiple
beans of
er
@Qualifi annotation to show uniqueness of each bean. 3. If
same type that time we can use
we er
@Prima annotation and
have more than same type of beans and we are not declaring
ry
@Qualifier annotation it will conflict which bean should be injected, that time getting
NoUniqueBeanDefinitionException .

Example:

public interface
PaymentService{ public void
pay();
}

@Primary
public class PaypalService implements
PaymentService{ @Override
public void pay(){
return "paypal service executed";
}
}

public class CreditCardService implements


PaymentService{ @Override
public void pay(){

2
return "credit card service executed";
}
}

Q. How we can inject multiple implementation of same interface in


Spring?
Ans: If multiple beans implemented the same interface, Spring can inject all of them using a
Collection such as:

•List
•Set
•Map

@RestController
public class Payment {

@Autowired
private List<PaymentService> paymentService;

@GetMapping("payment")
public List<String> getPayment(){
return
[Link]().map(PaymentService::pay).toList();
}
}

IOC Principle / Container


Q.10 What is IOC Principle?
Ans: 1. IOC principle means Inversion of Control principle instead we create object ne using
w
keyword
Spring will create object for us. 2. It means object creation is not in our hands it is Spring’s
hands.

Q.11 What is IOC Container?


Ans: 1. When Spring Boot application start those classes having stereotype annotation it will
scan all classes and create beans. 2. It stores those beans inside logical memory called IOC
Container. 3. Inside IOC container beans are stored in the form of key and value. 4.
Spring provide two types of IOC container:

•ApplicationContext (Eager Loading)


•BeanFactory (Lazy Loading)

3
Q.12 Why ApplicationContext is eager loading?
Ans: 1. When Spring Boot application starts those classes having stereotype annotation it
scans and creates beans. 2. Those beans register in ApplicationContext. 3. That is called
eager loading.

Q.13 Why BeanFactory is lazy loading?


Ans: 1. BeanFactory uses lazy loading because it creates beans only when requested using
getBea . 2. Spring will not create object at application startup. 3. Object created
n() only when is called.
getBea

BeanFactory factory = new XmlBeanFactory(...);


Student s = [Link]("student", [Link]);

Q.14 What are stereotype annotations?


Ans:

• @Controller
• @RestControl
• ler @Service
• @Repository
• @Component

Q.15 Is there any way to create bean without stereotype


annotation?
Ans: 1. We can create bean using
@Bea annotation.
n

Q.16 How to create custom bean in Spring?


Ans: 1. Custom bean means we manually define a bean instead of using stereotype like:

• @Compon
• ent
@Service
• @Reposit
ory

•We create it
using @Bea annotation class.
n inside @Configurat
ion

• @Configurat is class level.


ion

4
• @Bea is method level.
n

@Configuration
public class AppConfig{

@Bean
public StudentService
studentService(){ return new
StudentService();
}
}

Here:

• @Configuration tells Spring this class contains bean definition.


• @Bean tells Spring to create and register object in IOC container.

Q.17 What is @RestContro ?


Ans: 1.
ller
@RestContro is combination @Controll an @ResponseBo . 2. It is used in
REST APIs.
ller3. It of er d dy
handles:

• @GetMappin
• g
• @PostMappin
• g
@PutMappin
• @DeleteMap
ping

•It returns JSON or XML response.

•This annotation used on API layer.

Q.18 What is @Controll ?


er
Ans: 1. @Controll annotation is used in Spring MVC. 2. It returns view HTML, JSP or
Thymeleaf.
er 3.
@ResponseBo
It does not return JSON directly. 4. If we want then we can use .
dy

Q.19 What if we replace @RestContro with @Servi ?


Ans: 1.
ller ce
is web layer because they are mapping is not a
@RestContro request. 2. @Servi web
ller
layer annotation ceit may give 404
so we cannot replace. 3. If replaced API will not work and
error.

5
Q.20 Same endpoint and same HTTP method?
Ans: If two APIs have same endpoint and same HTTP method:

•Spring Boot throws Ambiguous Mapping Exception.


•Application will not start.

Fix:

1. Use Different Endpoints


2. Use Different HTTP Methods
3. Use Request Parameters

Collections
Q21 What is Collection?
Ans:

•Collection is an interface in Java.


•It is used to store group of objects.
•It can store:
•Homogeneous data
•Heterogeneous data
•Dynamic in nature.
•CRUD operations supported.

Child implementations: 1. List 2. Set 3. Queue

Q22 What is List?


Ans:

•List is child implementation of Collection interface.


•Insertion order maintained.
•Duplicates allowed.
•Multiple null values allowed.
•Indexed collection.
•Dynamic in nature.

Implementations: 1. ArrayList 2. LinkedList 3. Vector

6
Q23 What is Set?
Ans:

•Set is child interface of Collection.


•Insertion order not maintained (HashSet).
•Duplicates not allowed.
•One null allowed in HashSet.
•Not indexed.

Implementations: 1. HashSet 2. LinkedHashSet 3. TreeSet

Q24 What is Map?


Ans:

•Map is not part of Collection interface but part of Java Collection Framework.
•Stores key-value pairs.
•Keys unique.
•Values duplicated allowed.
•One null key and multiple null values in HashMap.

Implementations: 1. HashMap 2. LinkedHashMap 3. TreeMap 4. Hashtable 5.


IdentityHashMap 6. WeakHashMap

Q25 What is ArrayList?


Ans:

•ArrayList implements List.


•Uses dynamic array.
•Good for reading.
•Frequently bad for insertion and writing.
•Duplicates and null allowed.

Why ArrayList good for reading?

•Supports random access.


•Continuous memory.
• get(ind O(1).
ex)
Why bad for insertion?

•Shifting required.
•Time complexity O(n).

7
Q26 What is LinkedList?
Ans:

•LinkedList implements List.


•Uses doubly linked list.
•Good for insertion and deletion.
•Slow for reading.
•Duplicates and null allowed.

Why good for insertion?

•No shifting.
•Only references updated.

Q27 What is Vector?


Ans:

•Vector implements List.


•Uses growable array.
•Synchronized.
•Insertion order maintained.
•Duplicates and null allowed.

Why ArrayList fast compared to Vector?

•Vector synchronized.
•Only one thread access at a time.

Q28 What is HashSet?


Ans:

•HashSet implements Set.


•Insertion order not maintained.
•Duplicates not allowed.
•One null allowed.
•Based on hashing.
•Internally uses HashMap.

Q29 What is LinkedHashSet?


Ans:

•Maintains insertion order.

8
•No duplicates.
•One null allowed.
•Internally HashSet + Linked List.

Q30 What is TreeSet?


Ans:

•Natural sorting order.


•Duplicates not allowed.
•Null not allowed.
•Uses TreeMap / Red Black Tree.

If add null:

•NullPointerException.

Q31 What is HashMap?


Ans:

•Stores key-value.
•Keys unique.
•One null key.
•Multiple null values.
•Not synchronized.
•Based on hashing.

Q32 What is LinkedHashMap?


Ans:

•Maintains insertion order.


•HashMap + Linked List.
•Unique keys.
•Duplicate values allowed.

Q33 What is TreeMap?


Ans:

•Natural sorting by keys.


•No null key.
•Multiple null values.
•Uses Red Black Tree.

9
Q34 What is IdentityHashMap?
Ans:

•Implementation of Map.
•Uses = operator.
•Faster=than equals in some cases.

Q35 What is Hashtable?


Ans:

•Map implementation.
•Synchronized.
•Thread safe.
•Null key/value not allowed.

Why HashMap fast compared Hashtable?

•HashMap not synchronized.


•Multiple threads access.

Q36 What happens in Hashtable if add null?


Ans:

•Throws NullPointerException.

Q37 Internal Working of HashMap


Ans:

•Default size 16 buckets.


•Uses hashcode to select bucket.
•Formula used to locate bucket.
•If same bucket selected collision occurs.
• equals used to check duplicate key.
•If()
true replace value.
•If false new node same bucket.

10
Q38 What is Hash Collision?
Ans:

•Two different objects same hashcode select same bucket.


•Called hash collision.

Q39 What happens if two objects same hashcode?


Ans:

•Hash collision occurs.

Q40 Duplicate key in HashMap?


Ans:

•Duplicate keys not allowed.


•Existing value replaced.

Q41 equals overridden but hashCode not overridden?


Ans:

•HashSet may allow duplicates.

Q42 hashCode overridden but equals not overridden?


Ans:

•Duplicate objects may be stored.

Q43 Contract between equals and hashCode?


Ans:

•If equals returns true hashcode should be same.

11
Q45 What is Concurrent Collection?
Ans:

•If want reading and writing simultaneously use concurrent collection.

Types: 1. ConcurrentHashMap 2. CopyOnWriteArrayList 3. CopyOnWriteArraySet

Q46 What is ConcurrentModificationException?


Ans:

•Reading and writing same time may throw ConcurrentModificationException.


•Size changed during iteration causes exception.

Q47 What is Fail Fast?


Ans:

•Immediately throws exception if collection modified while iterating. Examples:

•ArrayList

•HashSet
•HashMap

Q48 What is Fail Safe?


Ans:

•Works on copy.
•No exception during modification.

Examples:

•ConcurrentHashMap
•CopyOnWriteArrayList

12
Multithreading
Q1 What is Thread in Java?
Ans:

•If you want perform multiple independent task we use thread.


•Improve performance.
•Smallest unit of execution.

Q2 Types of Thread
1. User Thread
2. Main Thread
3. Daemon Thread

Q3 What is Main Thread?


•First thread created by JVM.
•Executes main method.

Q4 Who creates main thread?


•JVM.

Q5 Name of main thread?


•main

Q6 Verify code running in main thread?


• [Link]().get
Name()
Q7 Change main thread name?
•Yes using setNam
e()
Q8 Change priority?
•Yes using setPriorit
y()
Q9 Can main create child thread?
•Yes.

13
Q10 What if main thread finishes?
•If no user thread JVM terminates.

Q11 Is main daemon thread?


•No.

Q12 Can make main daemon?


•No.

Q13 Default priority?


•5

Q14 Can call sleep on main?


•Yes.

Q15 Main belongs to thread group?


•Yes main group.

Q16 Can override main thread?


•No.

Q17 How to create Thread?


Ans:

•Extend Thread class.


•Override run method.
•Put logic in run.

Q18 Ways to create Thread


1. Extend Thread class
2. Runnable Interface
3. Lambda Expression
4. Callable

14
Q19 What is run method?
Ans:

•Present in Runnable.
•Logic executed by new thread written inside run.

Q20 What is start() method?


Ans:

•Present in Thread class.


•Registers thread with thread scheduler.

Q21 Which preferred?


Ans:

•Runnable preferred.
•Advantage of multiple inheritance.

Q22 Life cycle of thread


1. Born
2. Ready
3. Running
4. Dead

Q23 Can change thread name?


•Yes using setName().

Q24 What is sleep method?


•Pause thread for specific time.

Q25 Can start same thread again?


•No.

Q26 Can call start() two times?


•No.

15

You might also like