0% found this document useful (0 votes)
12 views50 pages

Of Course Java

This document provides answers to 100 Java interview questions covering core Java fundamentals, object-oriented programming concepts, and collections. Key topics include the differences between JDK, JRE, and JVM, the principles of OOP, and the characteristics of various data structures like HashMap and ArrayList. It serves as a comprehensive guide for individuals preparing for Java-related interviews.

Uploaded by

imghostlover143
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)
12 views50 pages

Of Course Java

This document provides answers to 100 Java interview questions covering core Java fundamentals, object-oriented programming concepts, and collections. Key topics include the differences between JDK, JRE, and JVM, the principles of OOP, and the characteristics of various data structures like HashMap and ArrayList. It serves as a comprehensive guide for individuals preparing for Java-related interviews.

Uploaded by

imghostlover143
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

Of course!

Here are the answers to the 100 Java interview


questions.

## Core Java Fundamentals

1. What is the difference between JDK, JRE, and JVM?

o JVM (Java Virtual Machine): An abstract machine


that provides the runtime environment for Java
bytecode to be executed. It's the component
that makes Java platform-independent.

o JRE (Java Runtime Environment): A software


package that contains what is required to run a
Java program. It includes the JVM, Java class
libraries, and other supporting files.

o JDK (Java Development Kit): A superset of the


JRE. It contains everything in the JRE, plus the
tools needed to develop Java applications, such
as the compiler (javac) and debugger (jdb).
2. Explain the meaning of public static void main(String[]
args).

o public: An access modifier that makes the


method accessible from anywhere, so the JVM
can invoke it.

o static: The method belongs to the class, not an


object. The JVM can call it without creating an
instance of the class.

o void: The method doesn't return any value.

o main: The name of the method, which is the


standard entry point for a Java application.

o String[] args: A parameter that accepts


command-line arguments as an array of strings.

3. What are the eight primitive data types in Java?

o There are eight primitive types: byte, short, int,


long, float, double, char, and boolean.
4. Explain the difference between == and the .equals()
method.

o == is an operator. For primitive types, it


compares values. For objects, it compares the
memory address (reference).

o .equals() is a method. For objects, it is intended


to compare the content or state. By default, the
method in the Object class behaves like ==, but
classes like String override it to perform a
content comparison.

5. Why is Java considered "platform-independent"?

o Because Java source code is compiled into an


intermediate format called bytecode. This
bytecode is not specific to any processor or OS. It
can be run on any machine that has a Java Virtual
Machine (JVM), which translates the bytecode
into native machine code. This principle is often
called "Write Once, Run Anywhere".

6. Explain the keywords final, finally, and finalize.


o final: A keyword used to apply restrictions. A final
class cannot be inherited, a final method cannot
be overridden, and a final variable cannot be
reassigned.

o finally: A code block used in exception handling.


The code inside the finally block is always
executed, whether an exception occurs or not.
It's used for cleanup (e.g., closing resources).

o finalize(): A method that the garbage collector


calls on an object just before reclaiming its
memory. Its use is discouraged.

7. What is the difference between method overloading


and method overriding?

o Method Overloading (Compile-time


Polymorphism): Occurs when two or more
methods in the same class have the same name
but different parameters (type, number, or
order).
o Method Overriding (Runtime Polymorphism):
Occurs when a subclass provides a specific
implementation for a method that is already
defined in its superclass. The method signature
must be identical.

8. What is a constructor? Can a constructor be private?

o A constructor is a special method used to


initialize objects. It has the same name as the
class and no return type.

o Yes, a constructor can be private. This is used to


restrict the instantiation of a class from outside.
It is commonly used in the Singleton design
pattern.

9. What is the use of the static keyword? Can you


override a static method?

o The static keyword indicates that a variable or


method belongs to the class itself, not to an
instance of the class.
o No, a static method cannot be overridden. If a
subclass defines a static method with the same
signature, it's called method hiding, not
overriding.

10. What is the difference between pass-by-value


and pass-by-reference? Which does Java use?

o Java is strictly pass-by-value.

o When you pass a primitive type to a method, a


copy of the value is passed.

o When you pass an object to a method, a copy of


the reference value (the memory address) is
passed. You can modify the object's internal state
using this copied reference, but you cannot
change the original reference itself to point to a
new object.

11. What are wrapper classes? Explain autoboxing


and unboxing.

o Wrapper classes convert primitive data types into


objects (e.g., int to Integer).
o Autoboxing: The automatic conversion of a
primitive type to its corresponding wrapper class
object (e.g., Integer i = 100;).

o Unboxing: The reverse process of converting a


wrapper class object back to its primitive type
(e.g., int n = i;).

12. What is the purpose of the this and super


keywords?

o this: Refers to the current object instance. It can


be used to differentiate between instance
variables and local variables, or to call another
constructor of the same class.

o super: Refers to the immediate parent class


object. It is used to call the parent class's
methods or constructor.

13. Can a Java source file have more than one class?
o Yes, a source file can have multiple classes, but
there can be at most one public class. The name
of the source file must match the name of the
public class.

14. What are access modifiers in Java?

o Access modifiers control the visibility of classes,


fields, and methods.

o public: Accessible from anywhere.

o protected: Accessible within the same package


and by subclasses.

o default (no keyword): Accessible only within the


same package.

o private: Accessible only within the declared class.

15. What is an anonymous inner class?


o An inner class without a name. It is declared and
instantiated in a single statement. It is typically
used for one-time use cases, such as creating an
implementation of an interface (like Runnable or
Comparator) on the fly.

## Object-Oriented Programming (OOP) Concepts

16. What are the four main principles of OOP?

o Encapsulation: Bundling data (fields) and


methods that operate on the data into a single
unit (class) and hiding the internal state from the
outside.

o Inheritance: A mechanism where one class


(subclass) acquires the properties and behaviors
of another class (superclass), promoting code
reuse.
o Polymorphism: The ability of an object to take on
many forms. It allows a single action to be
performed in different ways (e.g., method
overriding).

o Abstraction: Hiding complex implementation


details and showing only the essential features of
an object to the user.

17. What is inheritance? Why doesn't Java support


multiple inheritance with classes?

o Inheritance allows a child class to inherit from a


parent class.

o Java doesn't support multiple inheritance with


classes to avoid the Diamond Problem, which
leads to ambiguity if two parent classes have a
method with the same name. A child class
wouldn't know which method to inherit.
However, multiple inheritance is possible through
interfaces.
18. What is polymorphism? Differentiate between
compile-time and runtime polymorphism.

o Polymorphism means "many forms." It allows


objects to be treated as instances of their parent
class.

o Compile-time (Static) Polymorphism: Achieved


via method overloading. The compiler decides
which method to call at compile time based on
the method signature.

o Runtime (Dynamic) Polymorphism: Achieved via


method overriding. The JVM decides which
method to call at runtime based on the actual
object's type.

19. What is abstraction? How is it achieved in Java?

o Abstraction is the concept of hiding


implementation details and exposing only
functionality.
o It is achieved in Java using abstract classes (which
can provide partial abstraction) and interfaces
(which provide full abstraction, before Java 8).

20. What is the difference between an abstract class


and an interface?
Feature Abstract Class Interface

Can have default and


Can have both
static methods since Java
Methods abstract and non-
8, but traditionally only
abstract methods.
abstract methods.

Can have final,


Can only have public
non-final, static,
Variables static final variables
and non-static
(constants).
variables.

A class can extend


A class can implement
Inheritance only one abstract
multiple interfaces.
class.

Can have a Cannot have a


Constructor
constructor. constructor.

To provide a base To define a contract that


Purpose for subclasses to implementing classes
build upon. must adhere to.
Export to Sheets

21. What is encapsulation? How do you achieve it in


Java?

o Encapsulation is the practice of bundling data


and methods together within a class. It's
achieved by declaring the instance variables of a
class as private and providing public getter and
setter methods to access and modify their
values.

22. What do you understand by coupling and


cohesion?

o Coupling: The degree of dependency between


two classes. Low coupling is desirable because it
means changes in one class will have minimal
impact on another.
o Cohesion: The degree to which elements within a
single class are related to a single, well-defined
purpose. High cohesion is desirable because it
means the class is focused and easier to
understand and maintain.

23. Can an interface extend another interface?

o Yes, an interface can extend one or more other


interfaces.

24. From Java 8, can interfaces have method


implementations?

o Yes. Java 8 introduced default and static


methods, which allow interfaces to have method
implementations.

o default methods provide a default


implementation that can be overridden by
implementing classes.

o static methods belong to the interface and can


be called directly using the interface name.
25. Explain the concept of composition over
inheritance.

o This is a design principle that favors a "has-a"


relationship (composition) over an "is-a"
relationship (inheritance). Composition is often
more flexible than inheritance. Instead of a class
inheriting behavior, it holds a reference to
another class that provides the desired behavior.

## Strings, Arrays, and Collections

26. Why are String objects immutable in Java?

o Security: Prevents malicious code from changing


string values like file paths or database
connections.

o Thread Safety: Immutable objects are inherently


thread-safe.
o Performance: The JVM can optimize string usage
by creating a String Pool. Since strings are
immutable, it can reuse the same string object
for multiple references.

27. What is the difference between String,


StringBuilder, and StringBuffer?

o String: Immutable. Every modification creates a


new String object.

o StringBuilder: Mutable and not thread-safe. It is


fast and should be used in single-threaded
environments for string manipulation.

o StringBuffer: Mutable and thread-safe. The


methods are synchronized, making it slower than
StringBuilder. Use it in multi-threaded
environments.

28. What is the String Constant Pool?


o A special memory area in the heap where Java
stores string literals. When a new string literal is
created, the JVM checks the pool first. If the
string already exists, it returns a reference to it
instead of creating a new object.

29. What is the root interface of the Java Collections


Framework?

o The Collection interface. Note that the Map


interface does not extend Collection.

30. What is the difference between List, Set, and


Map interfaces?

o List: An ordered collection that allows duplicate


elements. (Example: ArrayList)

o Set: A collection that does not allow duplicate


elements. It is generally unordered. (Example:
HashSet)

o Map: A collection of key-value pairs. Keys must


be unique. (Example: HashMap)
31. What is the difference between ArrayList and
LinkedList?

o ArrayList: Backed by a dynamic array. Fast for


random access (get(index)). Slower for
adding/removing elements from the middle as it
requires shifting subsequent elements.

o LinkedList: Backed by a doubly linked list. Fast for


adding/removing elements. Slower for random
access as it needs to traverse the list.

32. What is the difference between HashMap,


Hashtable, and LinkedHashMap?

o HashMap: Not synchronized. Allows one null key


and multiple null values.

o Hashtable: Synchronized (thread-safe). Does not


allow any null keys or values. It is a legacy class.

o LinkedHashMap: A subclass of HashMap that


maintains insertion order.

33. How does a HashMap work internally?


o HashMap stores data in an array of nodes
(buckets) as key-value pairs.

1. When you put(key, value), it calculates the


hash code of the key ([Link]()).

2. This hash code is used to determine the


index of the bucket in the array.

3. If a collision occurs (multiple keys map to the


same index), the entries are stored in that
bucket as a linked list (or a balanced tree
after a certain threshold in modern Java).
The equals() method is used to differentiate
keys within the bucket.

34. What is the contract between the hashCode()


and equals() methods?
o

1. If two objects are equal according to


equals(), they must have the same
hashCode().

2. If two objects have the same hashCode(),


they are not required to be equal according
to equals() (this is a collision).

3. When you override one of these methods,


you should override the other.

35. What is the difference between HashSet and


TreeSet?

o HashSet: Stores elements in a HashMap


internally. It does not maintain order. Offers
constant-time performance O(1) for basic
operations.
o TreeSet: Stores elements in a self-balancing
binary search tree (TreeMap). It stores elements
in sorted order. Offers O(log n) performance.

36. What is the difference between a fail-fast and a


fail-safe iterator?

o Fail-fast: Throws a
ConcurrentModificationException if the
collection is modified while iterating over it. (e.g.,
iterators of ArrayList, HashMap).

o Fail-safe: Works on a clone of the collection, so it


does not throw an exception if the collection is
modified. (e.g., iterators of ConcurrentHashMap,
CopyOnWriteArrayList).

37. What are the Comparable and Comparator


interfaces used for?

o Both are used for sorting objects.

o Comparable: Provides a natural sorting order for


a class. The class itself implements Comparable
and its compareTo() method.
o Comparator: Provides a custom sorting order.
You create a separate class that implements
Comparator and its compare() method.

38. What is the difference between HashMap and


ConcurrentHashMap?

o HashMap is not thread-safe.

o ConcurrentHashMap is thread-safe. It uses


techniques like lock-striping or fine-grained
locking to allow multiple threads to access the
map concurrently with high performance.

39. How would you reverse a String in Java?

o The simplest way is to use the StringBuilder class:

Java

String reversed = new


StringBuilder("hello").reverse().toString();

40. What is the Collections class?


o Collections is a utility class in [Link] that
provides static methods for operating on
collections, such as sorting, searching, shuffling,
and creating synchronized wrappers.

## Exception Handling

41. What is the base class for all exceptions in Java?


Draw the exception hierarchy.

o The base class is Throwable.

o Hierarchy: Object -> Throwable -> (Error |


Exception). Exception further divides into
checked exceptions and RuntimeException
(unchecked).

42. What is the difference between checked and


unchecked exceptions?
o Checked Exceptions: Exceptions that are checked
at compile-time. You must handle them (try-
catch) or declare them (throws). They are for
predictable, recoverable conditions (e.g.,
IOException).

o Unchecked Exceptions (RuntimeExceptions):


Exceptions that are not checked at compile-time.
They typically represent programming errors
(e.g., NullPointerException,
ArrayIndexOutOfBoundsException).

43. Explain the try-catch-finally block.

o try: Encloses the code that might throw an


exception.

o catch: Catches and handles the exception if one


is thrown in the try block.

o finally: Encloses code that is always executed,


regardless of whether an exception occurred. It's
used for resource cleanup.
44. Will the finally block always be executed? What
are the scenarios where it won't?

o It is almost always executed. It will not be


executed if:

▪ The program exits by calling [Link]().

▪ The JVM crashes.

▪ The thread running the code is killed.

45. What is the difference between the throw and


throws keywords?

o throw: Used to manually throw an exception


object within a method.

o throws: Used in a method signature to declare


the types of checked exceptions that the method
might throw.

46. How do you create a custom exception?


o Create a new class that extends Exception (for a
checked exception) or RuntimeException (for an
unchecked exception).

Java

class MyCustomException extends Exception {

public MyCustomException(String message) {

super(message);

47. What is the try-with-resources statement?

o Introduced in Java 7, it's a try statement that


ensures each resource declared in it is
automatically closed at the end of the statement.
The resource must implement the AutoCloseable
interface.

48. What are chained exceptions?


o A technique where you wrap an original
exception inside a new one. This is useful for re-
throwing an exception as a different type while
preserving the original cause.

49. What happens if an exception is thrown from a


finally block?

o If an exception was already thrown from the try


or catch block, that original exception is
suppressed, and the exception from the finally
block is propagated up the call stack.

50. What is the difference between an Error and an


Exception?

o Error: Represents a serious, unrecoverable


problem that an application should not try to
catch (e.g., OutOfMemoryError,
StackOverflowError).

o Exception: Represents a condition that an


application might want to catch and handle (e.g.,
FileNotFoundException).
## Multithreading and Concurrency

51. What is a thread? How is it different from a


process?

o A process is an independent program with its


own memory space.

o A thread is a lightweight unit of execution within


a process. Threads within the same process
share the same memory space.

52. What are the two ways to create a thread in


Java?

1. Extend the Thread class and override its


run() method.

o
2. Implement the Runnable interface and pass
an instance of it to a Thread's constructor.
Implementing Runnable is generally
preferred because it allows the class to
extend other classes.

53. Explain the lifecycle of a thread.

o New: Thread is created but not started.

o Runnable: Thread is ready to run and waiting for


CPU time.

o Running: Thread is currently being executed by


the CPU.

o Blocked/Waiting: Thread is inactive, waiting for a


lock, I/O, or another thread's action.

o Terminated: Thread has completed its execution.

54. What is synchronization and why is it important?


o Synchronization is a mechanism to control access
to shared resources by multiple threads. It is
important to prevent race conditions and ensure
data consistency in concurrent applications.

55. What is the difference between a synchronized


method and a synchronized block?

o Synchronized Method: Locks the entire object


(this). It is simpler to implement.

o Synchronized Block: Locks only a specific block of


code and can lock on any object. It provides
more fine-grained control and can improve
performance by reducing the scope of the lock.

56. What is a deadlock? How can you prevent it?

o A deadlock is a situation where two or more


threads are blocked forever, each waiting for a
resource held by another thread.

o Prevention: Avoid nested locks, acquire locks in a


fixed order, or use timeouts when trying to
acquire a lock.
57. What is the purpose of the volatile keyword?

o The volatile keyword ensures that any change to


a variable's value is immediately visible to all
other threads. It prevents threads from using a
cached copy of the variable from their own stack.

58. What is the difference between the sleep() and


wait() methods?

o sleep(): A static method of the Thread class. It


pauses the current thread for a specified time
and does not release any locks it holds.

o wait(): A method of the Object class. It causes


the current thread to release the lock on the
object and go into a waiting state until notify() or
notifyAll() is called on the same object.

59. What is a thread pool? Explain the


ExecutorService.

o A thread pool is a collection of reusable threads.


It avoids the overhead of creating new threads
for every task.
o The ExecutorService is a framework that provides
a higher-level API for managing a thread pool and
executing tasks asynchronously.

60. What is the difference between Runnable and


Callable?

o Runnable: Its run() method does not return a


value and cannot throw a checked exception.

o Callable: Its call() method can return a value (via


a Future object) and can throw a checked
exception.

61. What is a race condition?

o A situation where the outcome of a program


depends on the unpredictable sequence or
timing of operations from multiple threads
accessing shared data. This can lead to corrupted
data.

62. Explain the Java Memory Model (JMM).


o The JMM defines the rules for how and when
changes made by one thread to shared memory
become visible to other threads. It ensures
memory consistency across threads in a
concurrent application.

63. What are atomic operations? Give an example.

o An atomic operation is an operation that is


guaranteed to execute as a single, indivisible
unit. The [Link] package
provides classes like AtomicInteger and
AtomicLong that support lock-free, thread-safe
operations on single variables.

64. What are Future and CompletableFuture?

o Future: Represents the result of an asynchronous


computation. You can use it to check if the
computation is complete and retrieve its result.
o CompletableFuture (Java 8+): A more advanced
version of Future. It can be explicitly completed
and allows you to chain and combine
asynchronous tasks in a non-blocking, functional
style.

65. What are daemon threads?

o A daemon thread is a low-priority thread that


runs in the background. The JVM will exit as soon
as all user (non-daemon) threads have finished,
without waiting for daemon threads to complete.
Example: the garbage collector thread.

## Java 8 and Modern Java Features

66. What are the main features introduced in Java 8?

o Lambda Expressions, Stream API, Functional


Interfaces, Optional Class, Default and static
methods in interfaces, and a new Date and Time
API ([Link]).
67. What is a lambda expression? What is its syntax?

o A lambda expression is an anonymous function


that allows you to treat functionality as a method
argument.

o Syntax: (parameters) -> { body }. For example, (a,


b) -> a + b.

68. What is a functional interface? Give an example.

o An interface that contains exactly one abstract


method. It can be annotated with
@FunctionalInterface. Examples include
Runnable, ActionListener, and Predicate.

69. What is the Stream API?

o The Stream API provides a functional way to


process sequences of elements from a source
(like a collection). Streams support aggregate
operations like filter, map, reduce, and collect.

70. What is the difference between intermediate and


terminal operations in a Stream?
o Intermediate Operations: Return a new stream
and are lazy (e.g., filter(), map()). They don't
execute until a terminal operation is called.

o Terminal Operations: Produce a result or a side


effect and trigger the stream processing (e.g.,
forEach(), collect(), count()).

71. What is the purpose of the Optional class?

o It is a container object that may or may not


contain a non-null value. It is used to represent
optional values explicitly and avoid
NullPointerException.

72. What are method references?

o A shorthand syntax for a lambda expression that


executes a single existing method. Example:
[Link]::println is a method reference for the
lambda x -> [Link](x).

73. What is the difference between map() and


flatMap() in Streams?
o map(): Transforms each element of a stream into
another single element (one-to-one
transformation).

o flatMap(): Transforms each element into a


stream of other elements and then flattens all
the resulting streams into a single stream (one-
to-many transformation).

74. What is the Collectors class used for?

o A utility class that provides implementations of


the Collector interface. It is used as a terminal
operation in streams to collect elements into a
List, Set, Map, or to perform summary
operations.

75. What is the var keyword introduced in Java 10?

o var allows for local variable type inference. You


can declare a local variable, and the compiler will
infer its type from the initializer. It makes code
more concise.

76. What are Records (introduced in Java 14)?


o Records are a concise syntax for creating
immutable data carrier classes. A record
automatically generates a constructor, private
final fields, accessors, equals(), hashCode(), and
toString().

77. What are Sealed Classes (introduced in Java 15)?

o Sealed classes restrict which other classes or


interfaces can extend or implement them. You
use the sealed and permits keywords to define
the allowed hierarchy.

78. Explain switch expressions.

o An enhanced switch that can be used as an


expression to return a value. It uses -> syntax,
prevents fall-through (no break needed), and can
be exhaustive, which the compiler can verify.

79. What is the jShell tool?


o Introduced in Java 9, jShell is an interactive
command-line tool (REPL) that allows you to
execute Java code snippets and get immediate
feedback.

80. What are Text Blocks?

o Introduced in Java 15, Text Blocks are a


convenient way to create multiline string literals
without needing concatenation or explicit escape
sequences like \n. They start and end with three
double-quotes (""").

## JVM, Garbage Collection, and I/O

81. Explain the JVM architecture.

o The JVM consists of three main parts:

▪ Classloader Subsystem: Loads, links, and


initializes .class files.
▪ Runtime Data Areas: Memory areas like the
Heap, Stack, Method Area, PC Registers.

▪ Execution Engine: Executes bytecode using


an interpreter and a Just-In-Time (JIT)
compiler.

82. What are the different types of classloaders in


Java?

o Java uses a hierarchy of three classloaders:

▪ Bootstrap Classloader: The top-level loader


for core Java libraries ([Link]).

▪ Extension Classloader: Loads classes from


the JDK extensions directory.

▪ Application (System) Classloader: Loads


classes from the application's classpath.

83. What is heap memory vs. stack memory?


o Stack Memory: Used for thread execution. Each
thread has its own stack. It stores local variables
and method call information. Memory is short-
lived.

o Heap Memory: Shared by all threads. It is where


all objects are dynamically allocated. Garbage
collection runs on the heap.

84. What is garbage collection? Can you force it to


run?

o Garbage Collection (GC) is the process of


automatically reclaiming memory occupied by
objects that are no longer in use.

o No, you cannot force GC. Calling [Link]() is


only a suggestion to the JVM.

85. Explain how generational garbage collection


works.
o The heap is divided into generations (e.g., Young
and Old). New objects are created in the Young
Generation. Most objects die young and are
collected frequently by a Minor GC. Objects that
survive long enough are promoted to the Old
Generation, which is collected less frequently by
a Major GC.

86. What is a memory leak in Java?

o A memory leak occurs when objects are no


longer needed but are still referenced,
preventing the garbage collector from reclaiming
their memory. A common cause is adding objects
to a static collection and never removing them.

87. What is serialization and deserialization?

o Serialization: The process of converting a Java


object into a byte stream to be stored or
transmitted.

o Deserialization: The reverse process of recreating


the object from the byte stream.
o A class must implement the [Link]
marker interface to be serializable.

88. What is the purpose of the transient keyword?

o When a field is marked as transient, it will not be


included in the object's serialized form. During
deserialization, it will be initialized to its default
value (e.g., null, 0).

89. What is the difference between FileInputStream


and FileReader?

o FileInputStream: A byte stream for reading raw


binary data (e.g., images, audio).

o FileReader: A character stream for reading text


files. It handles the conversion from bytes to
characters based on a character encoding.

90. What is a marker interface?

o An interface with no methods or fields. It is used


to provide metadata to the JVM or frameworks.
Examples include Serializable and Cloneable.
## Design Patterns, JDBC, and Best Practices

91. What are design patterns? Name a few you have


used.

o Design patterns are proven, reusable solutions to


common problems in software design.

o Common examples:

▪ Creational: Singleton, Factory, Builder.

▪ Structural: Decorator, Adapter, Facade.

▪ Behavioral: Observer, Strategy, Template


Method.

92. Explain the Singleton design pattern. How do you


create a thread-safe singleton?

o The Singleton pattern ensures that a class has


only one instance and provides a global point of
access to it.
o A simple and thread-safe way to create one is
using an enum:

Java

public enum EasySingleton {

INSTANCE;

public void doSomething() { /* ... */ }

93. Explain the Factory design pattern.

o A creational pattern that provides an interface


for creating objects in a superclass but lets
subclasses decide which concrete class to
instantiate. This decouples client code from the
specific classes it creates.

94. What are the SOLID principles of object-oriented


design?

o S - Single Responsibility Principle: A class should


have only one reason to change.
o O - Open/Closed Principle: Software entities
should be open for extension but closed for
modification.

o L - Liskov Substitution Principle: Subtypes must be


substitutable for their base types.

o I - Interface Segregation Principle: Clients should


not be forced to depend on interfaces they do
not use.

o D - Dependency Inversion Principle: High-level


modules should not depend on low-level
modules; both should depend on abstractions.

95. What is JDBC? What are the main steps to


connect to a database in Java?

o JDBC (Java Database Connectivity) is an API for


connecting to and interacting with databases.

o Steps:

1. Load the driver (often automatic now).


2. Establish a connection using
[Link]().

3. Create a Statement or PreparedStatement.

4. Execute the query.

5. Process the ResultSet.

6. Close the connection and other resources.

96. What is the difference between Statement and


PreparedStatement?

o Statement: Compiles the SQL query every time


it's executed. Vulnerable to SQL injection.

o PreparedStatement: Pre-compiles the SQL query,


making it more efficient for repeated execution.
It is secure against SQL injection. It is almost
always the better choice.

97. What is dependency injection?


o A design pattern where an object's dependencies
are "injected" into it by an external source (like a
framework) rather than being created by the
object itself. This promotes loose coupling and
makes code more testable.

98. What is reflection and why is it useful?

o The Reflection API allows a program to inspect


and modify its own structure and behavior at
runtime. It's useful for creating dynamic
frameworks, testing tools, and IDEs that need to
analyze code.

99. What are annotations in Java?

o Annotations are a form of metadata that can be


added to code. They provide information to the
compiler or runtime frameworks but do not
directly affect the execution of the code itself.
Examples include @Override, @Deprecated, and
Spring's @Autowired.
100. What is the difference between JAR, WAR, and
EAR files? * JAR (Java Archive): Packages Java classes
and resources. Used for libraries and standalone
applications. * WAR (Web Application Archive):
Packages a web application, including servlets, JSPs,
HTML, and other web resources. Deployed on a web
server like Tomcat. * EAR (Enterprise Application
Archive): Packages an enterprise application, which
can contain multiple JAR and WAR modules.
Deployed on an application server like JBoss or
WebSphere.

You might also like