0% found this document useful (0 votes)
28 views44 pages

Core Java Interview Questions Guide

Uploaded by

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

Core Java Interview Questions Guide

Uploaded by

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

QSpiders|JSpiders|PySpiders, NOIDA

B-4, Block-B, Sector-3, Noida


Core Java Interview Questions by Shambhu Sir
Wednesday, 20 August 2025 @kumarsam07
@javac_java

➢ Basic Concept:
1. How java is a platform independent language?
2. What is Byte Code?
3. Explain the working of JVM?
4. What are the types of Error?
5. Explain compile time error and Run time Error.

➢ Structure of Java Program:


6. What will happen if a java program doesn’t have main method?
7. What are keywords? Mention few of them.
8. How many keywords are used in main method of java?
9. What are identifiers? Tell me all its rules.
10. What is difference between keywords and identifiers?
11. Why String[] args is used in main method of java? What is its use?

➢ Data Types:
12. Explain data type? Why it is used?
13. How many data types are in java? Explain them.
14. Mention at least 5 differences between primitive and non-primitive data.
15. Why java is called strictly typed programming language.

➢ Variable:
16. What is a variable? Why it is used?
17. What are different types of variables?
18. Explain local, static and non-static variables? How it is accessed in java
program?
19. What is default value of a local variable?
20. What is scope of a local variable?
21. What is scope of a static variable?
22. What is scope of a non-static variable?

QSpiders| JSpiders Shambhu Kumar


23. Can we have default value for a static or non-static variable?
24. Can we have a local variable and global (static or non-static) variable with the
same name? if so, then which variable gets preference?
25. Explain what is variable shadowing?

➢ Type casting:
26. What is primitive type casting?
27. Explain widening and narrowing?
28. Explain implicit and explicit conversion.
29. Why widening is called implicit conversion and narrowing is called explicit
conversion?

➢ JVM, JRE, JDK, JIT Compiler:

30. Explain JVM and its working.


31. Explain JRE.
32. Explain JDK.
33. Explain JIT Compiler.
34. What is Garbage Collection in Java?
➔Automatic process by JVM to free memory by destroying unwanted
members (such as unreachable objects, local variables etc)
35. Why is Garbage Collection needed?
➔Prevents memory leaks and OutOfMemoryError by reclaiming
memory from unused objects.
36. How does Java Garbage Collector identify unused objects?
➔Using Reachability Analysis
37. Can you force garbage collection in Java?
➔You can request it using [Link]()
38. Explain the working of garbage collector in java?
➔The Garbage Collector (GC) in Java is an automatic process managed
by the Java Virtual Machine (JVM) that reclaims memory by removing
objects that are no longer in use.

QSpiders| JSpiders Shambhu Kumar


39. What do you mean by automatic garbage collection in java?
➔ Automatic Garbage Collection in Java means that the Java Virtual
Machine (JVM) takes care of memory management by automatically
identifying and removing unused objects (garbage) from the heap,
without requiring the programmer to explicitly delete them.

40. Explain the difference between JVM, JRE and JDK.

Methods:
41. What is method? Why it is used?
42. How many methods can be designed inside a class?
43. How method is executed?
44. In which memory area method execution takes place?
45. Which mechanism is followed in method execution?
46. How we can call and execute a static type method?
47. How we can call and execute a non-static type method?
48. What is the main advantage of a method?
49. Why main method of java should be always declared as public?
50. Why main method should be always declared as static?
51. Why main method return type is always void?
52. If there are multiple methods inside a class along with main method then which
method will be executed?
53. If there are multiple methods inside a class without main method then which
method will be executed?
54. If there are multiple main methods inside a class with main(String[] args),
main(String args) and main(int args) method then which method will be
executed?
55. If there are multiple main methods inside a class with main(String args), main(int
args) and main(int[] args) method then which method will be executed?
56. What are the types of methods?
57. Which method can be used to transfer values from one method frame to another
method frame?
58. What value is returned from a method with return type void?
59. How many values can we return from a method?
60. Which type of method can be directly called inside [Link]()?
61. How many access modifiers can be used in declaration of a method?
62. How many non-access modifiers can be used in declaration of a method?
63. Can we use static and abstract keyword together?

QSpiders| JSpiders Shambhu Kumar


➢ OOP Programming:
64. What is Object Oriented programming? Why it is used?
65. What are the four pillars of OOP?
66. Is java a 100% object-oriented language? Explain.
67. What is class and object? Define it.
68. What are the properties of a class?
69. Explain new keyword.
70. Explain how object is created in java?
71. What is the work of constructor?
72. What are reference data type? What is its default value?
73. Explain reference variable? What is its default value?
74. What do you mean by instantiation?
75. How Is an Object Deleted in Java?
➔In Java, objects are not explicitly deleted by the programmer like in
C/C++ (no delete keyword). Instead, object deletion is handled
automatically by the Garbage Collector (GC).

Once there are no references to the object, Object becomes


unreachable and it becomes eligible for garbage collection.

Student s = new Student(); // Object created in heap memory


S=null; // Now the Student object is unreachable

Student s1 = new Student();


Student s2 = new Student();
s1 = s2; // The original object referenced by s1 is now unreachable and
s1 object will be eligible for garbage collection

76. Explain static type members?


77. What is the main purpose of static members?
78. How many copies of static members are loaded in a program execution?
79. Why main method is always static?
80. Explain non-static members?
81. What is the main purpose of static members?
82. How many copies of non-static members are loaded in a program execution?
83. What are class members?
84. What are instance members?
85. Why non-static members are called instance members?

QSpiders| JSpiders Shambhu Kumar


86. What is the different memory block are created by JVM at run time. Explain
them.
87. Explain the difference between Stack and Heap Area?
88. Which type members can be accessed directly inside a static method?
89. Which type members can be accessed directly inside a non-static method?
90. Can we access a static member directly inside static block?
91. Can we access a non-static member directly inside non-static block?
92. Can we access a static member directly inside non-static block?
93. Can we access a non-static member directly inside a static block?
94. Explain variable shadowing?
95. How variable shadowing is resolved in case of static variables?
96. How variable shadowing is resolved in case of non-static variables?
97. Explain this keyword?
98. What will be inside this keyword? OR, what does this keyword contain?

Constructor:
99. What is constructor? What is its use?
100. Explain the difference between method and constructor?
101. What is the return type of a constructor?
102. What are the different types of constructors?
103. Can we make a constructor static?
104. Explain default constructor with its use?
105. Explain parameterized constructor? What is its use?
106. How a constructor is called?
107. Explain constructor overloading with its use?
108. What is the advantage of constructor overloading?
109. Explain “Boilerplate code”.
110. Explain constructor chaining with its use?
111. What is the advantage of constructor chaining?
112. Explain this() statement.
113. How many constructors can be called by one constructor?
114. Can we make this() as the second statement?
115. Explain copy constructor with a program. What is its use?

➢ Inheritance:

QSpiders| JSpiders Shambhu Kumar


116. What is inheritance? How it is achieved in java?
117. What are the different types of inheritance?
118. Explain hierarchical inheritance.
119. Explain super keyword.
120. Explain the difference between this and super keyword.
121. Explain super() statement.
122. Explain the difference between this() and super() statement.
123. Can we use this() and super() together inside same constructor?
124. Can we use multiple super() statement inside a constructor?
125. How parent and child relationship is created internally?
126. Explain implicit and explicit super() statement?
127. Explain multiple inheritance?
128. Why multiple inheritance is not supported in java with class?
129. Explain “Diamond Shape Problem”? How it is resolved in java?
130. Which type of members are not inherited from parent class to child class?
131. Can a child class inherit constructors of parent class? Why?
132. Which class is the super most parent class of every class in java?

➢ Upcasting/ Downcasting:
133. What is non-primitive type casting in Java?
134. What is upcasting? Give an example.
135. Is upcasting implicit or explicit in Java?
136. What is downcasting? Give an example.
137. Is downcasting implicit or explicit?
138. Explain generalization and specialization.
139. What is the difference between upcasting and downcasting?
140. Can we type cast any class to any other class in Java? Explain.
141. What members are accessible after upcasting?
142. What are the risks of downcasting in Java?
143. What is ClassCastException and when does it occur?
144. How can you safely perform downcasting in Java?
145. Give a real-world example where both upcasting and downcasting are used.
146. Write a Java program demonstrating both upcasting and downcasting.
147. In which situations would you use type casting in real projects?

QSpiders| JSpiders Shambhu Kumar


➢ Polymorphism:
148. What is polymorphism?

149. Explain different types of polymorphism.


150. What is compile time and run time polymorphism? How it is
achieved in java?
151. Explain method overloading with programming examples.
152. What is advantage of method overloading?
153. Can we overload both static and non-static methods?
154. Can we overload main method of java?
155. If we have multiple main methods with different arguments then
which main method will get executed by JVM?
156. If there are multiple main methods inside a class with
main(String[] args), main(String args) and main(int args) method
then which main() method will be executed?
157. If there are multiple main methods inside a class with
main(String args), main(int args) and main(int[] args), method then
which method will be executed?
158. Why operator overloading is not allowed in java?
159. Explain method overriding with programming examples.
160. Explain all the conditions for method overriding.
161. Explain what is covariant return type in java?
162. What is advantage of method overriding?
//We can achieve/update new features from child class by changing
//old implementations of parent class at run time
163. Can we override main method?
164. Can we override static method?
165. Mention all the differences between method Overloading and
method Overriding.
166. Mention all the differences between Compile Time Polymorphism
and Run time Polymorphism.
167. Explain static method dispatch and dynamic method dispatch.
168. Explain variable shadowing.
169. Explain variable hiding.
170. Explain method shadowing/ method Hiding.

QSpiders| JSpiders Shambhu Kumar


171. Can we overload constructor?
172. Can we override constructor? why?
173. Give some examples of method overloading?
174. Give some examples of method overriding?

Encapsulation:
175. What is encapsulation?
176. How we can achieve encapsulation?

177. Explain getters() and setters() method.

178. What is data hiding?

179. What is java Bean class? What are the criteria for a bean class?

180. What is the advantage of Bean class?

181. What is POJO? What are the characteristics of it?

182. If we have to design a class and we need to set the details only after validation,
then which concept we should use?

183. Design one program to demonstrate encapsulation.

Abstraction:
Abstract class:
184. What is abstraction?
185. How to achieve abstraction?
186. Explain abstract class?
187. Can we create object of an abstract class?
188. Why we can’t create object of an abstract class/interface?
189. Which type of methods are allowed inside an abstract class?
190. Explain abstract type method?

QSpiders| JSpiders Shambhu Kumar


191. Can we have a static method as abstract?
➔NO
192. Can we have an abstract method as static?
➔NO
193. Is it mandatory to have abstract methods inside an abstract class?
=➔No
194. Is it possible to extend one abstract class by another abstract class?
➔Yes
195. Can we make an abstract method as final?
➔No
196. Can we make an abstract method as private?
➔No
197. Can we have constructors inside an abstract class? explain its use.
➔Yes
198. Difference between class and abstract class.
199. What is the difference between Encapsulation and abstraction?

➢ Interface:
200. What is interface? How we can design an interface?
201. What is the description of a variable inside interface?
➔public static and final
202. Can we have non-static variables inside interface?
➔NO
203. Can we create object of an interface?
➔NO
204. Why we can’t create object of interface?
205. Is constructor allowed inside an interface? Why?
➔NO
206. What is the default access of methods inside interface?
➔public
207. What type of features for interface was introduced in java8 update?
➔default and static type method
208. What type of features for interface was introduced in java9 update?
➔private type method
209. Can an interface extend another interface?
➔Yes
210. Can a class extend an interface?
➔NO
211. How a class provide implementation to abstract methods of interface?
➔by using implements keyword and method overriding mechanism

QSpiders| JSpiders Shambhu Kumar


212. Can an abstract class implement interface?
➔Yes
213. Does interface allow multiple inheritance? Explain.
➔Yes, because there is no ambiguity in case of interface
214. Is it possible to have multiple interface parents for a class?
➔yes
215. Is it possible to have multiple interface parents for an interface?
➔Yes
216. Explain Functional interface?
➔Only One Abstract method
217. Explain Marker/Tagged interface.
➔Empty interface
218. Can we have static type methods inside interface?
➔Yes, Since java8 Update
219. Can we have main methods inside interface?
➔Yes, Since java8 Update
220. Explain default type method and its use?
221. Explain static type method and its use?
222. Explain private type method and its use?
223. Can a private method be static inside interface?
➔Yes
224. Can a private method be non-static inside interface?
➔Yes
225. What is Co-Variant return type? Explain.
226. Explain briefly the below interface:
a. Runnable
b. Comparable
c. Comparator
d. Predicate
e. Supplier
f. Consumer
g. Function
h. Serializable
i. Cloneable
227. Can we make a method of interface as protected?
➔NO
228. Mention at least 5 differences between class and interface.
229. Mention at least 5 differences between abstract class and interface.
230. Give some real time examples of abstraction /interface.
231. Mention important features of java8. [vvi]
232. Is interface 100% abstract after java8?
➔NO
233. Explain interface to interface reference casting.
234. Why we require to use abstract class?
235. Why we require to use interface?

QSpiders| JSpiders Shambhu Kumar


➢ HAS-A Relationship:
236. Explain HAS-A relationship.
237. What is association?
Association

• Association is a general relationship where one class is connected or


related to another class.
• It can be:
o One-to-One (A Person has one Passport)
o One-to-Many (A Library has many Books)
o Many-to-One (Many Employees work in one Department)
o Many-to-Many (A Student can enroll in many Courses and a
Course can have many Students)

HAS-A = Association

• When one class contains a reference to another class, it is association, often


expressed as a HAS-A relationship.

class Student {

String name;

class Department {

Student student; // Department HAS-A Student → This is association/HAS-A Relationship

238. How is HAS-A relationship different from IS-A relationship in Java?


239. How do you implement a HAS-A relationship using Java classes?
240. What is the benefit of using a HAS-A relationship in Java?
241. HAS-A relationship is of how many types?
242. Explain composition and aggregation with some examples.
243. Write a Java program to demonstrate a Car class that HAS-A Engine.
244. Write code to inject a dependency into a class via constructor and setter
(demonstrating HAS-A).
245. Given a use case (e.g., a Library Management System), identify the HAS-A
relationships between classes.
246. Can you implement dependency injection using HAS-A relationship?
247. Why is HAS-A preferred over inheritance in some scenarios?
248. Explain with an example how to use constructor injection in a HAS-A
relationship.

QSpiders| JSpiders Shambhu Kumar


249. Explain with an example how to use method injection in a HAS-A relationship.
250. How does the principle “Favor HAS-A over inheritance (IS-A)” relate to HAS-A
relationship?
251. Explain the difference between HAS-A relationship and IS-A relationship.
252. Explain [Link]() statement of java.
253. Explain “S” in “SOLID” design principle.

The “S” in SOLID stands for the Single Responsibility Principle


(SRP).
Definition:
A class should have only one reason to change, meaning it
should have only one responsibility or job.
Each class or module should focus on only one task.
If a class does too many things, changes in one part can break or
affect unrelated parts.

Example (Bad - Violates SRP):

Here, the Student class is handling:

• Student task
• Data persistence (saveToDatabase)
• Reporting (printReport)

Violates SRP – three responsibilities to one class: student task, storage


and reporting.
QSpiders| JSpiders Shambhu Kumar
Correct Example (Follows SRP):

Now:
Student handles student data only.
StudentRepository handles database.
ReportPrinter handles reporting.

➔Now each class has a single responsibility.


Why SRP is Important:
• Makes code easier to read and test
• Changes in one part don’t affect others
• Encourages reusability and maintainability

QSpiders| JSpiders Shambhu Kumar


254. What is Cohesion in Java (and OOP)?

Cohesion refers to how focused and related the responsibilities


of a class or module are.

In simple terms:

Cohesion = how well the parts of a class belong together.

a. A highly cohesive class does one job and does it well.

Class has a single, well-defined responsibility. Methods are


closely related.

b. A low cohesive class tries to do many unrelated things,


making it hard to understand, maintain, or reuse.

Class handles multiple unrelated tasks. Looks like a "god class" (too
much code doing too many things).

Example:

• If a class only handles student details, like storing name,


age, and marks — it has high cohesion.
• If a class handles student details, file saving, and payment
processing, it has low cohesion — because it mixes
unrelated tasks.

High cohesion = better readability, easier maintenance.


Low cohesion = confusion, harder to manage.
c. Why High Cohesion is Good
• Easier to understand
• Easier to maintain and debug
• Easier to test (focused functionality)
• Promotes Single Responsibility Principle (from SOLID)

QSpiders| JSpiders Shambhu Kumar


Example: High vs Low Cohesion
Low Cohesion Example

This class does too many unrelated things — salary, database,


email, reporting. It violates SRP and has low cohesion.

High Cohesion Example

Each class here has one job — this is high cohesion,


which makes each part reusable and maintainable

QSpiders| JSpiders Shambhu Kumar


255. Provide one Code sample showing bad → good cohesion
transformations?

BAD COHESION Example: One class doing too many things

Problems:

• This class violates Single Responsibility Principle


• It handles:
o Business logic (employee management)
o File I/O
o Reporting
• Difficult to maintain, extend, or test

QSpiders| JSpiders Shambhu Kumar


GOOD COHESION Example: Split responsibilities into focused classes

1. Employee management logic

2. File handling logic

3. Report generation logic

QSpiders| JSpiders Shambhu Kumar


Usage:

Summary:
• Bad cohesion = “God classes” doing everything

• Good cohesion = Multiple classes doing only one thing well

• Improves readability, reuse, unit testing, and team


collaboration

QSpiders| JSpiders Shambhu Kumar


256. What is a God Class?
God Class — a key anti-pattern that every Java developer and
student must understand, especially when learning about object-
oriented design, cohesion, and SRP (Single Responsibility
Principle).

Definition:
A God Class is a class that has too many responsibilities and tries
to do everything by itself.
It violates the Single Responsibility Principle and often has low
cohesion and high coupling.

It’s called a God Class because it "knows everything",


"does everything", and "controls everything".

Characteristics of a God Class


• Too many fields and methods
• Handles multiple unrelated concerns (business logic, data
access, UI, validation…)
• Becomes a maintenance nightmare
• Other classes rely heavily on it (tight coupling)
• Breaks encapsulation by accessing many other classes
directly

QSpiders| JSpiders Shambhu Kumar


Example of a God Class (in Java):

Problem: This class has to:

• Manages employee data


• Handles salary calculations
• Connects to database
• Sends emails
• Does reporting
• Deals with UI

This is low cohesion, tight coupling, and poor design — classic God Class.

How to Refactor the God Class

Break it down into multiple focused classes:

QSpiders| JSpiders Shambhu Kumar


✔ Each class now has one responsibility — high cohesion, easier to test, extend, and
maintain.

257. When do God Classes typically appear?


• In initial stages of development where everything is dumped into one class
• When developers lack understanding of SRP, encapsulation, and modular
design
• In procedural mindset (not thinking in terms of OOP)
• When deadlines lead to "quick fixes" and adding all logic into a single file

258. How to Avoid God Classes?


• Follow SRP (Single Responsibility Principle)

• Use composition and delegation

• Apply cohesion and loose coupling principles

• Continuously refactor large classes as your app grows

God Class A massive, all-knowing, all-doing class that handles too many things
Problem Low cohesion, high coupling, hard to maintain
Solution Break it into focused classes with one responsibility each

QSpiders| JSpiders Shambhu Kumar


259. What is coupling? Explain Tight and
Loose coupling.
Coupling refers to the degree of direct knowledge or
dependency one class or module has about another.

• Tight Coupling → Strong interdependence


• Loose Coupling → Minimal dependency, more
flexibility

Tight Coupling

When one class is highly dependent on another class's


concrete implementation, it is tightly coupled.

Problem:

• You cannot easily replace Engine with ElectricEngine,


PetrolEngine or Mock Engine.
• Car is hard to test and hard to change if Engine changes.

QSpiders| JSpiders Shambhu Kumar


Loose Coupling:

When one class depends on abstractions (e.g., interfaces)


instead of concrete implementations, it is loosely coupled.

Benefits:
• Easily swap Engine with other types (PetrolEngine, ElectricEngine or
MockEngine, …etc)
• More testable
• More flexible and maintainable

Coupling Type Example


Tight Coupling ===➔ Car class creates Engine itself

Loose Coupling ===➔ Car takes Engine via constructor or setter

QSpiders| JSpiders Shambhu Kumar


Summary

• Loose Coupling = Good (preferred)


• Tight Coupling = Bad (hard to scale and test)
• Use Dependency Injection and interfaces to achieve loose
coupling

260. What is Dependency Injection?

Dependency Injection is a design pattern where the


dependencies of a class are provided (injected) from
outside rather than being created by the class itself.

In Simpler Words:

• A class depends on another class to do its work.


• Instead of creating the dependency itself using new, the
dependency is "injected" from outside.
• This leads to loose coupling, better testability, and
flexibility.

Without DI (Tight Coupling):

QSpiders| JSpiders Shambhu Kumar


Car is hard-wired to use Engine.

You can’t easily replace Engine with ElectricEngine or a mock.

With Dependency Injection (Loose Coupling):

• Car doesn’t create the Engine


• It accepts any implementation of Engine
• Easy to test, swap, and extend

QSpiders| JSpiders Shambhu Kumar


Types of Dependency Injection:

1. Constructor DI
Dependency is passed via constructor
new Car(new DieselEngine());
2. Setter DI
Dependency is set using setter methods
[Link](engine);
3. Field DI
Dependency is injected directly into field
Common in Spring @Autowired

Why Use Dependency Injection?


Benefit Explanation
Classes depend on abstractions, not
✓ Loose Coupling
implementations
✓ High Testability Easily inject mocks or stubs
✓ Flexibility Swap different implementations at runtime
✓ Follows SOLID Especially DIP (Dependency Inversion
Principles Principle)
✓ Promotes Reusability Reuse the same component in multiple places

QSpiders| JSpiders Shambhu Kumar


Dependency Injection in Frameworks (e.g.,
Spring)

• Spring automatically injects Engine into Car


• No need to new anything manually
• Managed by IoC (Inversion of Control) Container

"Dependency Injection helps reduce coupling by providing


dependencies from outside the class, improving modularity,
testing, and maintainability. It can be done through constructors,
setters, or frameworks like Spring that manage dependencies for
you."

QSpiders| JSpiders Shambhu Kumar


261. What is a Mock?
A mock is a fake object that simulates the behaviours of real
objects in a controlled way during testing.
You use a mock when:
• You want to test a class independently from its
dependencies.
• The real dependency is too complex, slow, or external
(e.g., DB, file, API).
• You want to verify interactions (e.g., "Was a method
called?" or "How many times?").

262. Explain IOC (Inversion of Control).


Inversion of Control (IoC) is a design principle in which the control of object
creation and dependency management is transferred from the program itself to a
container or framework.

Instead of a class creating its own dependencies, they are injected from outside.

Traditional Approach (Without IoC):

Problem:

• Service class is responsible for creating its own dependency (Repository).


• Hard to test, reuse, or modify (tight coupling).

QSpiders| JSpiders Shambhu Kumar


IoC Approach (With IoC Container):

Now the object creation will be handled by an external system, like Spring
Framework and this process is called IOC.

Real Example in Spring:

Spring Framework:

• Scans classes (@Component)


• Creates objects (Beans)
• Injects dependencies automatically (@Autowired)

Why It's Called "Inversion of Control"?

Normally:

• Object controls the creation of dependencies

With IoC:

• The framework controls the flow:


o What object to create
o When to create
o How to inject

So, the control is inverted from your code to the framework.

QSpiders| JSpiders Shambhu Kumar


Benefits of IoC:

• Loose coupling
• Better testability
• Easier code maintenance
• Promotes modularity and flexibility

IoC(Inversion Of Control) vs DI(Dependency Injection):

• IoC is the principle


• Dependency Injection (DI) is one way to implement IoC

263. Mention some comprehensive list of principles and


characteristics that contribute to a good software
design, in object-oriented systems.
1. Loose Coupling
2. High Cohesion
3. Dependency Injection (DI)
4. Single Responsibility Principle (SRP)
5. HAS-A Over Inheritance
6. DRY Principle (Don't Repeat Yourself)
7. KISS Principle (Keep It Simple, Stupid)
8. YAGNI (You Aren’t Gonna Need It)
9. Modularity
[Link]
[Link]
[Link] & Clarity
[Link]

QSpiders| JSpiders Shambhu Kumar


Nested class:
264. . What is a nested class in Java?
265. What are the different types of nested classes in Java?
266. What is the difference between static and non-static inner classes?
267. Can an outer class be declared private or protected?
➔NO
268. Can a nested class be declared private or protected?
➔Yes
269. Which type of members we can have inside a non-static inner class?
➔Only non-static members before java 16
270. Which type of members we can have inside a static inner class?
➔static as well as non-static members
271. Can a static nested class access all static members of the outer class?
➔Yes, it can be accessed directly
272. Can a static nested class access instance members of the outer class?
➔No, It can be accessed through object refrence

273. Can a non-static nested class [Member class] access all members of the
outer class?
➔Yes, all members can be accessed
274. How do you instantiate a static inner class?
275. How do you instantiate a non-static inner class?
276. Can we declare a static method inside a non-static inner class?
➔It is allowed after java16 Update

277. In what scenarios would you use inner class/nested class?


➔if better encapsulation is required
➔if we need to put real-world logic in code to have better readability
278. Are inner classes compiled into separate .class files?

QSpiders| JSpiders Shambhu Kumar


Garbage Collection:
279. What is Garbage Collection in Java?
➔Automatic process by JVM(Garbage collector) to free memory by
destroying unwanted members (such as unreachable objects, local
variables etc)

280. Why is Garbage Collection needed?


➔Prevents memory leaks and OutOfMemoryError by reclaiming
memory from unused objects.

281. How does Java Garbage Collector identify unused objects?


➔Using Reachability Analysis

282. Can you force garbage collection in Java?


➔You can request it using [Link](), but it’s not guaranteed.
It is just a request and JVM can ignore it.

283. Explain the working of garbage collector in java?


➔The Garbage Collector (GC) in Java is an automatic process managed
by the Java Virtual Machine (JVM) that reclaims memory by removing
objects that are no longer in use.

284. What do you mean by automatic garbage collection in java?


➔ Automatic Garbage Collection in Java means that the Java Virtual
Machine (JVM) takes care of memory management by automatically
identifying and removing unused objects (garbage) from the heap,
without requiring the programmer to explicitly delete them.

285. How Is an Object Deleted in Java?


➔In Java, objects are not explicitly deleted by the programmer like in
C/C++ (no delete keyword). Instead, object deletion is handled
automatically by the Garbage Collector (GC).

QSpiders| JSpiders Shambhu Kumar


Once there are no references to the object, Object becomes
unreachable and it becomes eligible for garbage collection.

Student s = new Student(); // Object created in heap memory


S=null; // Now the Student object is unreachable

Student s1 = new Student();


Student s2 = new Student();
s1 = s2; // The original object referenced by s1 is now unreachable and
s1 object will be eligible for garbage collection

286. What are the disadvantages of garbage collector?

➔While the Garbage Collector (GC) makes Java memory management easier and
safer, it comes with some disadvantages as well:

1. Unpredictable Performance (GC Pauses)

• The GC may stop application threads to reclaim memory.


• These pauses can affect performance, especially in real-time or latency-
sensitive applications.

Example: In a high-frequency trading app, even a small pause can


cause loss of money.

2. Less Control Over Memory

• In languages like C/C++, developers manually allocate and deallocate


memory.
• In Java, the GC decides when and what to clean — developers can’t force it
to run.

Calling [Link]() is just a suggestion; the JVM may ignore it.

3. Overhead and CPU Usage

• GC consumes CPU cycles to monitor, trace, and clean memory.


• In large applications, this can result in increased CPU load.

4. Memory Overhead

• Some GC algorithms may use extra memory to manage regions, generations,


or threads.
• More metadata and thread stacks → more memory consumed.

QSpiders| JSpiders Shambhu Kumar


➢ Exception Handling:
287. What is exception?
288. What is exception handling?
289. How exception is handled?
290. Explain about try catch block.
291. What happens when exception is generated?
292. How many catches block can be used with one try block?
293. How many exceptions can be thrown at a time from one try block?
294. What happens if an exception is not caught?
295. What is nested try catch block?
296. Can you catch multiple exceptions in a single catch block?
297. What is the order of catch blocks when catching multiple
exceptions?
298. What is finally block?
299. What is its use?
➔Special block which is used with try and catch block to execute
some important conditions
300. What are the situations when finally block will not execute?
301. How many finally block can be used with one try block?
302. Can we use try block without catch block?
303. Can a finally block be executed without a catch block?
304. Can a finally block modify the return value of a method?
305. What happens when an exception is thrown inside a catch block?
306. What are the different types of exceptions?
307. Explain the difference between checked and unchecked
exceptions?
308. Which class is the parent class for all exceptions and errors?
309. What is the difference between Exception and RuntimeException?
310. Can you catch Error in Java?
311. What is a “NullPointerException” and how can you avoid it?
312. Can we catch and throw the same exception in a method?
313. What happens if two exceptions are thrown — one in try and
another in finally?
314. Which class is the parent class for all exceptions?
315. What is the difference between exception and error?
316. Give me some examples of checked and unchecked exceptions?
317. Explain throw keyword.

QSpiders| JSpiders Shambhu Kumar


318. Explain throws keyword.
319. Explain throw and throws keyword with the difference.
320. Can you explain the syntax and usage of throw?
321. Can you explain the syntax and usage of throws?
322. What is exception propagation in Java?
323. How is exception propagation achieved?
324. Can we rethrow an exception?
325. What is custom exception? How to create it?

➢ Miscellaneous Questions:
Design Principles & Coding Practices
326. Explain SOLID principles in Java with examples.
327. Explain SRP Principle.
328. Explain OCP Principle.
329. Explain LSP Principle.
330. Explain ISP Principle.
331. Explain SRP Principle.
332. Explain DIP Principle.
333. What is a Fat Interface (Polluted interface)? Why is it bad?
334. What is DRY (Don’t Repeat Yourself) principle?
335. What is KISS (Keep It Simple, Stupid) principle?
336. What is YAGNI (You Aren’t Gonna Need It)?
337. What is a Marker Interface? Give examples.
338. What is a Functional Interface? Give examples.
339. Give some examples of method overloading.
340. Give some examples of method overriding.
➔toString(), equals(), hashCode(), finalize() of Object class
341. What is Boilerplate code? Can you reduce it in Java?
342. What is Spaghetti code? Why is it considered harmful?
343. What is Cyclomatic Complexity and why does it matter?
344. Give examples where you have used all the fours pillars of Object oriented
programming in framework.

QSpiders| JSpiders Shambhu Kumar


Code Quality & Patterns
345. What is coupling?
346. Explain tight coupling and loose coupling?
347. What is cohesion?
348. What is high cohesion and low cohesion?
349. How does Java support Dependency Injection (DI)?
350. Explain the Factory Pattern using Java.
351. Explain method chaining with a program. What is its use.
352. Write one example program for method chaining.
353. What is the Builder Pattern and when to use it?

Class Structures: POJO, Beans, DTOs


354. What is a POJO (Plain Old Java Object)?

A POJO (Plain Old Java Object) is a simple, lightweight Java class that:
• Does not depend on any specific framework, technology, or external
restrictions (like EJB, JPA, Spring).
• Primarily holds data and may have simple behavior (getters, setters,
toString, etc.).
• Is not bound by special naming conventions, annotations, or inheritance
rules.
It’s basically a normal Java object used to represent data in a clean,
reusable, and flexible way.

Key Characteristics of a POJO


A POJO:
• Does not extend or implement any framework-specific class or interface.
• Uses private fields for encapsulation.
• Provides public getters and setters to access or modify data.
• May contain constructors, toString(), equals(), and hashCode().
• Has no heavy annotations or business logic.
In Short:
A POJO is just a plain, simple Java class with private fields, public
getters/setters, constructors, and no special framework dependencies, used
mainly for holding and transferring data.

QSpiders| JSpiders Shambhu Kumar


355. What is a Java Bean class? How is it different from a POJO?

A Java Bean is a special type of POJO that follows specific rules and conventions
defined by the JavaBeans specification.
JavaBeans are commonly used for encapsulation, data transfer, and working
with frameworks (like JSP, Spring, Hibernate, etc.) that rely on this standardized
structure.
Rules for a Java Bean Class
A class is considered a Java Bean if it follows these rules:
1. Private Fields: All instance variables must be private.
2. Public Getters and Setters: To access and modify fields.
3. Public No-Arg Constructor: Allows easy instantiation.
4. Serializable (Optional but Recommended): Should implement
Serializable for object persistence and transfer across networks or files.

356. What is a DTO (Data Transfer Object)? Why do we use it?

A DTO (Data Transfer Object) is a simple Java object (often a POJO) used to
carry data between different layers or processes of an application.
It is mainly used to transfer data:
• Between client and server
• Between service layer and presentation layer
• Across remote calls (e.g., REST APIs, microservices, distributed
systems)
Key Characteristics of DTO:
• Contains only data (fields) and getters/setters.
• No business logic (just holds data).
• Usually Serializable to transfer data over network or file.
• Helps reduce multiple calls by sending a combined data object.

Why Do We Use DTO?


1. Decoupling:

o Separates internal data models (Entities) from external data


representation.

o Prevents exposing sensitive database structure to clients.

2. Efficiency:

o Instead of making multiple calls for each field, DTO can send all
required data in one object.

3. Data Transformation:

QSpiders| JSpiders Shambhu Kumar


o Helps prepare customized data views for APIs or UI without changing
the database schema.

4. Serialization:

o DTOs are easily converted to JSON/XML for sending over network in


REST APIs.

357. What is a DAO (Data Access Object)? Why do we use it?

The DAO (Data Access Object) is a design pattern used in Java to separate
data persistence logic (interacting with a database or data source) from the
business logic of the application.
• It provides a clean abstraction layer between the application and the
database, making the code:
o Easier to maintain
o Easier to test
o Independent from specific database technologies or queries

Why DAO Pattern?


Without DAO:
• Database access code is mixed directly with business logic.
• Difficult to change the database layer (e.g., moving from MySQL to
Oracle or Hibernate) without rewriting business code.
With DAO:
• All database operations (CRUD: Create, Read, Update, Delete) are
centralized in DAO classes.
• The rest of the application uses DAO methods instead of writing SQL
directly.
Benefits of DAO Pattern
• Loose Coupling: Business logic is not tied to database queries or
technologies.
• Reusability: Same DAO methods can be reused in multiple places.
• Flexibility: Easy to change the database or ORM (JDBC → Hibernate)
without changing other layers.
• Testability: DAO can be easily mocked for unit testing.
• Separation of Concerns: Clear division between persistence and
application logic.

QSpiders| JSpiders Shambhu Kumar


Summary
• DAO Pattern = An object that abstracts and encapsulates all access to a
data source.
• Helps keep database operations in one place and separate from business
rules.
• Works well with frameworks like JDBC, JPA, Hibernate, Spring Data JPA.

358. What is a Value Object (VO)? How is it different from DTO?

A Value Object (VO) is a simple, immutable object that represents a descriptive


attribute or value in a domain model.
It:
• Does not have an identity (no unique ID) – two VOs with the same values are
considered equal.
• Is immutable (values cannot change after creation).
• Used to represent a concept, measurement, or property in a domain-driven
design (DDD) context.
Characteristics of a VO
• No unique identity – equality is based only on attribute values, not memory
address.
• Immutable – fields are set once (via constructor) and cannot be modified.
• Self-validating – can contain simple rules to ensure valid values.
• Often used to represent domain concepts like Money, Address, Coordinates,
Email, DateRange, etc.

359. What is a Business Object (BO)? Why do we use it?

A Business Object (BO) is a Java object that encapsulates the business logic and
rules of an application.
It represents a real-world business entity or process and contains:
• Business-related data (attributes)
• Business operations or rules (methods)
BOs are typically used in the service or business layer, acting as a bridge
between DAO (data layer) and Controller/UI layer.

QSpiders| JSpiders Shambhu Kumar


Purpose of a BO
• To group business data and behavior together in a single object.
• To separate business rules from persistence (DAO) and presentation (UI).
• To represent real-world domain concepts like:
o OrderBO
o CustomerBO
o PaymentBO
This leads to cleaner, layered architecture and better reusability.

Why Do We Use BO?


1. Encapsulation of Business Rules:
o Keeps core business logic in one place rather than spreading it across
DAO or controllers.
2. Layered Architecture:
o Separates:
▪ DAO → Database operations only.
▪ BO → Business rules and calculations.
▪ Controller/UI → Input/output handling.
3. Reusability:
o Business logic can be reused by multiple components (e.g., different
APIs or UIs).
4. Easier Maintenance:
o Any change in business rules can be made in BO without touching
other layers.
5. Domain Representation:
o Provides a real-world model of the problem space (Order, Payment,
Loan, Policy, etc.).

360. What is an Entity class in Java?


An Entity class in Java represents a table in a relational database, where:
• Each instance of the class = one row (record) in the table.
• Each field = a column in the table.
Entity classes are typically used in JPA (Java Persistence API) or Hibernate ORM
frameworks for mapping Java objects to database tables (Object-Relational
Mapping - ORM).

Characteristics of an Entity Class


1. Annotated with @Entity – Tells JPA/Hibernate that this class should be
mapped to a database table.
2. Must have a primary key – Defined using @Id.
3. Must have a default (no-argument) constructor.

QSpiders| JSpiders Shambhu Kumar


4. Implements Serializable (recommended for distributed applications).
5. Uses getters and setters to access private fields.
6. Maps table columns using annotations like @Column, @Table,
@GeneratedValue, etc.
Summary
• An Entity class is a persistent Java object that maps to a database table using
JPA/Hibernate annotations.
• Each field → column, and each object → row.
• It is mainly used in the Persistence Layer (DAO) to perform CRUD operations
using ORM frameworks.

361. What is an Entity Object (EO)? Why do we use it?

An Entity Object (EO) is a runtime instance of an Entity class that represents a


single, persistent record in a database table.
• Entity Class: Defines the structure (blueprint) of a database table (columns,
relationships).
• Entity Object (EO): Represents a specific row in that table at runtime.

In other words:
• Class → Table Schema
• Object → Table Row (Record)

When we do

Here, e1 is an Entity Object (EO) that holds data for one row of the Employee
table.

Why Do We Use Entity Objects (EO)?


Entity Objects are used to:
1. Represent database rows as Java objects for easy manipulation.
2. Perform CRUD operations (Create, Read, Update, Delete) using ORM
frameworks like JPA or Hibernate.
3. Reduce direct SQL handling, allowing developers to work with objects
instead of tables and columns.

QSpiders| JSpiders Shambhu Kumar


4. Enable caching and transaction management, as ORM frameworks can track
changes in EO and update the database automatically.

Benefits of EO
• Bridges gap between Java objects and DB tables (ORM concept).
• Easy CRUD operations without writing SQL manually.
• Works well with JPA/Hibernate, leveraging caching, transactions, and lazy
loading.
• Improves code readability by treating DB records as first-class objects.

Summary
• An Entity Object (EO) is an instance of an Entity class representing a single
row in a database table.
• EOs are used in ORM frameworks (like JPA/Hibernate) for object-oriented
database operations.
• Developers can manipulate EO like normal Java objects, while the
framework handles SQL and persistence automatically.

Other questions:
362. Explain Call by Value vs Call by Reference in Java.
363. Why java doesn’t support call by reference?
364. Why Java doesn’t support pointers?
365. What happens when we assign an object reference to another object?
366. What is object cloning? How does Java handle object cloning?
367. What is a shallow copy and a deep copy? Give examples.

➢ Final Keyword:
368. What is final keyword?
369. Can a class be declared final?
370. Can we extend a class if it is final?
371. Can a method be declared final?
372. Can we make an abstract class or abstract method final?
373. Can we override a final type method?
374. How we can initialize a static type final variable?
375. Can a final method be overloaded?
376. What happens if you try to override a final method?
377. Can we declare a constructor as final?
378. How we can initialize a non-static type final variable?
379. Give some examples of final type classes?

QSpiders| JSpiders Shambhu Kumar


380. Explain what is mutable and immutable type class?
381. How can we design an immutable class?
382. What is the use of immutable class?
383. Tell me the scenarios where u have used immutable class/Objects in
framework?
384. What is the difference between final, finally, and finalize()?

➢ Package and Access Modifiers:

385. What is package? What is its use?


386. How to create a custom package?
387. What is the purpose of the import statement in Java?
388. What is the naming convention for Java packages?
389. Can a package have sub-packages in Java?
390. What are the advantages of package?
391. Explain access modifiers? Why it is required?
392. Explain public, protected, default and private members with its access
range.
393. What is the difference between public, private, protected, and default
(package-private) access modifiers?
394. Can we declare outer class as private?
395. Can we declare outer class as protected?
396. What access modifiers are allowed for top-level classes?
397. What is the difference between protected and default access?
398. What is package private?
399. Can a class/interface be declared abstract?
400. Is it possible to access protected members from a different package?
401. Can a nested class be private?
402. Can you explain access control from the perspective of encapsulation?
403. Can we override a private method?
404. Can a private method be inherited?
405. Can we reduce the visibility of an overridden method in subclass?
406. Can we inherit a class if its constructors are declared private?
407. Can we have a private constructor? What is its use?
408. Explain singleton class with its use.
1. Configuration Settings
To maintain application-wide configuration settings that are read from a file
or database once and accessed globally. Storing application-wide
configuration settings. A singleton ensures that all parts of the application
use the same configuration.
2. Logging
A logger class is usually a Singleton because having multiple instances might
lead to inconsistent logs or file access issues.

QSpiders| JSpiders Shambhu Kumar


3. Database Connections (Connection Pool)
To manage a single shared access point to a database connection pool,
reducing overhead and ensuring thread safety.

4. Caching
For managing in-memory caches like frequently accessed data. Having a
single access point simplifies cache management.
5. Thread Pool Management
Only one instance of a thread pool should exist to avoid excessive resource
usage and manage concurrent task execution properly.
6. Service Locators
In large applications, a Singleton can serve as a central point to locate
services or components.
7. Device Communication or Hardware Access
When interacting with external hardware like printers or cameras, a
Singleton class ensures only one connection or handler is active.

8. Resource Manager
For managing shared resources such as file systems, sockets, or network
configurations. Managing access to shared resources like database
connections or file handles. A singleton can control the number of
connections, preventing resource exhaustion.
9. WebDriver object in selenium framework

409. Explain lazy and eager instantiation.


410. Where singleton is used in frameworks?

QSpiders| JSpiders Shambhu Kumar

Common questions

Powered by AI

Java's garbage collector works by automatically identifying and reclaiming memory from objects that are no longer in use. It employs a process called Reachability Analysis to determine which objects are unreachable and therefore eligible for garbage collection. This frees up memory by destroying these objects, helping to prevent memory leaks and OutOfMemoryErrors .

The 'main' method is declared as static in Java because it needs to be invoked by the JVM without the need for creating an instance of the class. Since static methods belong to the class rather than instances, this allows the JVM to call the 'main' method directly using the class name. This is crucial because the 'main' method serves as the entry point of the program's execution, and creating an object just to access it would lead to inefficiencies and unnecessary complexities .

Java Beans provide additional structure and benefits over POJOs by adhering to a strict set of conventions such as implementing Serializable, having a no-arg constructor, and providing getter and setter methods for accessing properties. These conventions allow Java Beans to be easily manipulated by development environments and frameworks, facilitating tasks such as serialization and deserialization for data persistence, manipulation, and display. This makes them particularly useful for Java EE applications and UI components that benefit from predictable and standardized data operations .

The Data Access Object (DAO) pattern provides an abstraction layer for accessing data sources, separating database interaction and persistence logic from business logic. This separation results in more maintainable and testable code, as changes to the database or business logic can be made independently. By using the DAO pattern, applications can switch databases or query methods without affecting overall business rules, leading to cleaner architecture and easier maintenance .

In Java, the 'this' keyword is used to refer to the current instance within a method or constructor of a class. It helps in differentiating between instance variables and parameters or other local variables with the same name within methods or constructors, thereby resolving context. Additionally, 'this' can be used to invoke other constructors of the same class, which is useful in constructor chaining .

Java is considered platform-independent because it uses the Java Virtual Machine (JVM) to run compiled programs. Java code is compiled into bytecode, which is a platform-independent code interpreted by the JVM specific to each platform, allowing the same Java program to run unmodified on different operating systems. This abstraction from the underlying hardware and OS is what makes Java platform-independent .

The Single Responsibility Principle (SRP) states that a class should have only one reason to change, meaning it should handle only one responsibility or task. By following SRP, code becomes easier to read, test, and maintain, as changes in one part do not affect unrelated parts. This modular approach encourages reusability and makes it simpler to scale and refactor code, thereby significantly enhancing maintainability and reducing the complexity typically associated with tightly coupled and high-cohesion classes .

Cohesion refers to how focused a class or module's responsibilities are. High cohesion means that a class or module has a clear purpose and closely related functionalities, making it easy to understand, maintain, and test. It promotes the Single Responsibility Principle and reduced complexity by ensuring that each class has a well-defined role. Conversely, low cohesion results in convoluted, monolithic classes that handle multiple unrelated tasks, making the system difficult to manage and prone to errors. High cohesion contributes to better software design by enhancing modularity and facilitating easier updates and bug fixes .

Java is considered a strictly typed language because every variable and expression type is known at compile time. This ensures strong type checking, which helps prevent type errors and increases the reliability and robustness of Java applications. The use of explicit type declarations in variable and method signatures allows the compiler to enforce type correctness throughout the code, which minimizes runtime errors and aids in early error detection .

Variable shadowing in Java occurs when a variable declared within a certain scope (such as a method) has the same name as a variable declared in its outer scope (such as the class level). In such cases, the variable in the inner scope 'shadows' the outer variable. To resolve shadowing, one can use 'this' keyword to access instance variables or explicitly scope variables using class or method references to distinguish between them. Shadowing is typically resolved by using fully qualified names if needed or accessing the outer variable uniquely .

You might also like