Core Java Interview Question

 


===================  CORE JAVA INTERVIEW QUESTION =======================


1. What are the main principles of Object-Oriented Programming (OOP)?

2. Differentiate between JDK, JRE, and JVM.

3. Explain the concept of platform independence in Java.

4. What is the significance of the main method in Java?

5. How does Java achieve memory management?

6. What are constructors in Java? How are they different from methods?

7. Explain method overloading and method overriding with examples ?

8. What is inheritance in Java? Discuss its types

9. Define polymorphism and its types in Java.

10. What is an interface in Java, and how does it differ from an abstract class?

11. Describe the access modifiers in Java.

12. What is encapsulation? How is it implemented in Java?

13. What are static variables and methods? Provide examples.

14. Discuss the lifecycle of a thread in Java.

15. What is exception handling? How is it implemented in Java?

16. Differentiate between throw and throws keywords.

17. What are checked and unchecked exceptions? Give examples.

18. Explain serialization and deserialization in Java.

19. What is the Java Collections Framework? Name its main interfaces.

20. Differentiate between ArrayList and LinkedList.

21. What is a HashMap? How does it work internally?

22. Explain the significance of the equals() and hashCode() methods.

23. What is the difference between Comparable and Comparator interfaces?

24. Describe the Java Memory Model (JMM) ?

25. What is garbage collection in Java? How does it work?

26. Explain the concept of Java annotations.

27. What are lambda expressions? Provide a use case.

28. Discuss the Stream API in Java.

29. What is the purpose of the Optional class?

30. Explain the try-with-resources statement.

31. What is the difference between final, finally, and finalize()?

32. How does the volatile keyword affect thread behavior?

33. What are design patterns? Name a few commonly used ones in Java.

34. Explain the Singleton design pattern and its implementation.

35. What is JDBC? How is it used in Java applications?

36. Discuss the differences between Statement and PreparedStatement.

37. What is the purpose of the transient keyword?

38. What are inner classes? Differentiate between static and non-static inner classes.

39. Describe the use of the synchronized keyword.

40. What is the difference between String, StringBuilder, and StringBuffer?

41. Explain the concept of immutability in Java.

42. How does Java handle memory leaks?

43. What are functional interfaces? Provide examples.

44. Discuss the role of the default keyword in interfaces.

45. What is the enum type in Java? How is it used?

46. Explain the concept of reflection in Java.

47. What are modules in Java? Discuss their significance ?

48. Data Hiding Method internally working ?

49. Explain the Shallow and deep copy ?

50. Why java is not pure  object ?

51. Which Object class Method  ?

52. Multithreading locks ? 

53. Can we create Object of Abstract class ? No bcoz it incomplete clas

54. Can we override static Method ? No

55. Difference between Treemap & HashMap ? 

56. What is  Custom Exception  & How we can implement ?

57. Difference btw Stack and Heap  &  Use of it ?

58. Difference btw "==" operator and .equals() Method ?

59. Best practices to implement equals() & hashcode().

60. How many ways we can create thread ?

61. Can we overload the run Method , and How we can call the run() generally.

62. What is the difference between execute() & submit() method ?

63. What is fail-Safe & fail-Fast ?

64. Difference between HashTable & ConcurrentHashMap ?

65. is Singleton threadSafe ?

66. what is FileNotFoundException ?

67. What is ClassNotFoundException and How to Solve that ?

68. Which is Pure Abstraction ? Why interface 100 % and Abstract not purely 100% ?

69. Can we Convert ArrayList to Map ?

70. What is Constructor Overloading ?

71. if we want  finally block not executed if then exception occur or not then how would do that ? 

72. What is Difference between Runnable and Callable ?

73. What is Thread Local ?  

74. What is Future Object ? : whatever the object that you want to return after thread logic is executed can be called as future object. 

75. What is Default value(Capacity) has HashMap and Load Factor ? 16 Bucket and 0.75 Load factor. 

76. What call by value ? 

77. Is Java support  Pass By Reference ?

78. Can we use HashMap in a multi-threaded environment ? No 

79. Is there any difference in defining or creating a String by using String literal and by using the new() Operator ? 

80. When you use Thread Class  and Runnable interface on the Specific condition which are main other requirement ?

81. Why we Cannot extends multiple classes in Java ?

82. HashMap vs ConcurrentHashMap 

83. volatile, transient, ThreadLocal ?

84. Thread life cycle & ExecutorService ?

85. Different way to create object ?

86. Internal Working of ConcurrentHashMap ?





=================== Answers ==========================


1. What are the main principles of Object-Oriented Programming (OOP)?

Answer : 

1. Encapsulation 


- The process of binding data and corresponding methods (behavior) together into a single unit is called encapsulation in Java.

-Every Java class is an example of encapsulation because we write everything within the class only that binds

variables and methods together and hides their complexity from other classes.


class{ 

data member 

   +

Mmethod (behaviour)

}


- Data Hiding : In the encapsulation technique, we declare fields as private in the class to prevent from other classes by accessing them directly & cannot access anyone from outside the class. 

- The required encapsulated data can be accessed by using public Java getter and setter method.

-Ex : Bank Account .


-Implement Encapsulation in Java

1. Declaring the instance variable of the class as private so that it cannot be accessed directly by anyone from outside the class.


2. Provide the public setter and getter methods in the class to set/modify the values of the variable/fields.


2. Abstraction

 - It is a process of hiding complex internal implementation details from the user and providing only necessary functionality to the users.

Ex : ATM Machine


- How to achieve Abstraction in Java?

There are two ways to achieve or implement abstraction in java program. They are as follows:

1. Abstract class (0 to 100%)

2. Interface (100%)


Advantage of abstraction in Java

- It reduces the complexity of viewing the things as it shows only essential information.

- It allows the flexibility to modify/change implementation logic if needed, as long as the outcome of behavior is not affected by the modification.

- It helps to increase security of an application or program as only important details are provided to the user.

- It also helps to avoid code duplication and increases reusability.



3. Inheritance

- Inheritance is a core OOP concept where one class (child/subclass) can acquire properties and behaviors (fields & methods) of another class (parent/superclass).

- It helps in code reusability, better structure, and method overriding.


- Types of Inheritance in Java

1. Single Inheritance : One child class inherits from one parent class.

2. Multilevel Inheritance : A class inherits from another class, and another class inherits from that class (chain).  Example: Employee → Developer → TeamLead

3. Hierarchical Inheritance: One parent class is inherited by multiple child classes.

4. Multiple Inheritance (Not supported using classes) : Java does not support multiple inheritance through classes because it creates ambiguity (diamond problem). But Java supports multiple inheritance using interfaces:


- Java supports Single, Multilevel, and Hierarchical inheritance through classes. Multiple and Hybrid inheritance are not supported using classes due to ambiguity issues, but they can be achieved using interfaces.


 

4. Polymorphism


- Polymorphism means one object behaving in many different forms.

- Polymorphism allows the same method to perform different tasks depending on the object. In Java, we achieve polymorphism in two ways: Method Overloading at compile time and Method Overriding at runtime. This enables flexibility and improves code maintainability.



- Compile time : Because the decision of which method to call is taken by the compiler during compilation.

- Run time :  Because the method to execute depends on the actual object created in memory at runtime. and method selection happens during program execution, not while compiling → so called Run-time Polymorphism.


- Difference between compile & Run Time polymorphism ?

- 1. Method Overloading is compile-time polymorphism because the compiler decides which method to call based on parameter list.

- 2. Method Overriding is runtime polymorphism because the method call is resolved by the JVM based on the actual object created at runtime.



- The word polymorphism is derived from two Greek words: poly and morphs. The word “poly” implies many and “morphs” means forms.


Types of Polymorphism in Java


Basically, there are two types of polymorphism in java. They are:


1. Static polymorphism / Compile time poly /Early binding

2. Dynamic polymorphism /Runtime poly / Late Binding



1. Static polymorphism / Compile time poly /Early binding


- A polymorphism that exhibited during compilation is called static polymorphism in java. 

In static polymorphism, the behavior of a method is decided at compile-time.


-Hence, Java compiler binds method calls with method definition/body during compilation. 

Therefore, this type of polymorphism is also called compile-time polymorphism in Java.


-Since binding is performed at compile-time, it is also known as early binding. 

Compile-time polymorphism can be achieved/implemented by method overloading in java.


-Method overloading is a mechanism in which a class has multiple methods having the same name but different signatures.

It is one of the ways that Java implements polymorphism.




---------

2. Differentiate between JDK, JRE, and JVM.

Answer : 

1. JDK (Java Development Kit): Provides tools for development (compiler, debugger).

2. JRE (Java Runtime Environment): Includes libraries and JVM for running Java

applications.

3. JVM (Java Virtual Machine): Converts bytecode into machine code and executes it.



---------

3. Explain the concept of platform independence in Java.

Answer : 

- Java is called platform independent because Java programs can run on any operating system (Windows, Linux, Mac, etc.) without changing the code. This is possible due to the Java Virtual Machine (JVM).

-  When we write Java code, it is compiled into bytecode (.class file), not directly into machine code of any OS.

- This bytecode can be executed on any system that has a JVM installed.

- The JVM converts the bytecode into machine-specific instructions at runtime.

- So Java follows the rule: “Write Once, Run Anywhere” (WORA)



---------

4. What is the significance of the main method in Java?

Answer :

- The main() method is the starting point of a Java program. JVM uses this method to start execution. It must be public, static, and void so that JVM can call it directly without an object and it doesn’t return anything.




---------

5. How does Java achieve memory management?

Answer : 

- Java manages memory automatically using garbage collection. Memory is divided into stack and heap. Stack stores method-level data and references, while heap stores objects. When objects are no longer referenced, the garbage collector removes them to free memory.


| Component                  | Description                                      |

| -------------------------- | ------------------------------------------------ |

| **Stack Memory**           | Stores method calls, local variables, references |

| **Heap Memory**            | Stores objects created using `new` keyword       |

| **Garbage Collector (GC)** | Automatically deletes unused objects             |

| **JVM Memory Manager**     | Allocates and deallocates memory at runtime      |




---------

6. What are constructors in Java? How are they different from methods?

Answer :

- A constructor is a special type of method used to initialize an object when it is created.

- It is automatically called at the time of object creation using the new keyword.

- Constructors are special methods used to initialize objects. They have the same name as the class and no return type. A method performs actions and can return values, while a constructor only runs once when an object is created.


Notes

- Constructor does not have a return type, not even void.

- Constructor name must match class name.

- Constructors are used to initialize objects.


- Two main types of constructors:

1. Default Constructor

2. Parameterized Constructor


---------

7. Explain method overloading and method overriding with examples ?

Answer :

1. Method Overloading (Compile-Time Polymorphism)

- Occurs when multiple methods have the same name but different parameters (type/number/order) within the same class.

- Improves readability and allows methods to perform similar tasks in different ways.

- Decided at compile time (Static binding).


Ex: 

class Calculator {

    int add(int a, int b) { return a + b; }

    int add(int a, int b, int c) { return a + b + c; }

}



2. Method Overriding (Runtime Polymorphism)

- Occurs when child class redefines a method of the parent class with same name, same parameters, and same return type.

- Used to provide specific implementation in subclass.

- Decided at runtime (Dynamic binding).

- Uses @Override annotation and can use super to call parent method.


Ex: 

class Employee {

    void work() { System.out.println("Employee working"); }

}

class Developer extends Employee {

    @Override

    void work() { System.out.println("Developer coding"); }

}




---------

8. What is inheritance in Java? Discuss its types

Answer : in Q. No 1



---------

9. Java doesn’t support multiple Inheritance. Why?

Answer : 

- To maintain a simpler and more manageable class hierarchy, Java does not support multiple inheritances to avoid ambiguity and complexity which arises from inheriting multiple classes.

- Java avoids multiple inheritance because a subclass inheriting from two parent classes may receive conflicting implementations of the same method. 


Ex:

class A {

    void show() { System.out.println("Show from Class A");}

}


class B {

    void show() {        System.out.println("Show from Class B"); }

}


// Hypothetical scenario (Not allowed in Java)

class C extends A, B { }




---------

10. What is an interface in Java, and how does it differ from an abstract class?

Answer : 

1. Variable : variable in interface are by default public static and final & variable in Abstract class can have final, non-final, static, and non-static variables.

2. Method : interface method by default public and abstract and in abstract class  both abstract and non-abstract (concrete) methods. 

3. Constructor : Inside an interface, we cannot declare/define a constructor because the purpose of constructor is to perform initialization of instance variable but inside interface every variable is always static. and Since an abstract class can have instance variables. Therefore, we can define constructors within the abstract class to initialize instance variables.

4. instance and static block : we cannot declare both of in interface and  in abstract class we can declare.

5. Single vs Multiple inheritance : abstract class extend only one class but in interface  one class can implement multiple interfaces.

6. Uses: If you know nothing about the implementation. You have just requirement specification then you should go to use interface. and If you know about implementation but not completely (i.e. partial implementation) then you should go for using abstract class.



-----------

11. Describe the access modifiers in Java.

Answer : 

 - Public: Accessible everywhere.

 - Protected: Accessible within the same package and subclasses.

 - Default: Accessible within the same package only.

 - Private: Accessible within the same class only.



-----------

12. What is encapsulation? How is it implemented in Java?

Answer:


 - Encapsulation is bundling data (variables) and methods into a single unit (class). It's 

implemented using:

 1. Private access modifiers for fields.

 2. Public getter and setter methods for access



-----------

13. What are static variables and methods? Provide examples.

Answer: 

- static in Java means something that belongs to the class, not to an object.

Static members are shared among all objects and memory is allocated only once in the Method Area.


1. Static Variable

- A static variable is also called a class variable.

- It is used when we want data to be common for all objects.

- Only 1 copy exists for all objects.


2. Static Method

- A static method belongs to the class and can be called without creating an object.

- we Cannot use this or super inside static method.

- static method Used for utility/helper methods.


3. Static Block

- Static block is a block of code that runs automatically when the class is loaded, before main() method.

- Purpose : Used for initialization of static variables, loading drivers, configuration, etc.


Q - Why Static Block Runs Before main()?

- When we run a Java program, JVM first loads the class and processes all static things before anything else. It creates memory for static variables, runs static blocks, and then calls the main() method. So, static content executes first, even before any object is created. Static means first priority — it runs before main() and before objects.



4. Static Class (Nested Class Only)

- Java does not allow static top-level classes, but inner nested classes can be static.



- Difference between Static & Instance method 

1. static method 

2. Instance method 


1. Belongs to the class, not to objects

1. Belongs to the object (instance) of the class


2. Can be called without creating an object

2. Requires creating an object to call


3. Can only access static variables directly

3. Can access both static and instance variables


4. Memory allocated once in class loading

4. Memory allocated separately for each object


5. Common utility methods are generally static

5. Used when behavior depends on object data


6. Example: Math.max(), main() method

6. Example: employee.getSalary()


-----------

14. Discuss the lifecycle of a thread in Java.

Answer :

In Java, a thread goes through several stages from creation to completion:

1. New (Created State) 

 - Thread object is created but not started yet.


2. Runnable (Ready-to-run State) 

 - After calling start(), the thread moves to runnable. It is ready to run, waiting for CPU allocation.


3. Running

  - When JVM's thread scheduler picks the thread, it goes to running state. It executes the run() method.


4. Blocked / Waiting / Timed Waiting

Thread temporarily pauses due to situations like:

- waiting for input/output

- calling sleep(), wait(), join()

- trying to access resource locked by another thread

- It will stay paused until the condition is resolved.


5. Terminated (Dead State)

- The thread finishes execution of run()

- Or forcibly stopped due to error

- It cannot restart again


- A thread can be terminated automatically when the run() method finishes Or we can terminate it manually using a flag (recommended) or interrupt() when it is waiting or sleeping. The stop() method exists but is unsafe and deprecated.



-----------

15. What is exception handling? How is it implemented in Java?

Answer : 


Exception Handling : Exception handling in Java is a mechanism to handle runtime errors so that the normal flow of the program can continue without crashing the application.

Java provides five keywords to handle exceptions:

1. try : The try block contains the code that may generate an exception. & We write risky or error-prone code inside try.


2. catch : The catch block handles the exception that occurs in the try block. & It prevents application crash and prints a meaningful message.


3. finally : The finally block always executes whether exception occurs or not & Used for cleanup code such as closing database connection, file, or resources.

 

4. throw : Used to manually throw an exception inside a method & Commonly used for custom validations.


5. throws :  Used in method signature to indicate that a method may throw an exception, and it should be handled by the caller.  

- It does NOT handle the exception; it passes it to the caller.



-----------

16. Differentiate between throw and throws keywords.

Answer : 

- throw is used to explicitly throw an exception inside a method, usually for validation or custom logic.

- throws is used in the method declaration to indicate that the method may throw an exception, and the caller must handle it.




-----------

17. What are checked and unchecked exceptions? Give examples.

1. Checked Exception 

2. Unchecked Exception 


1. Checked exceptions are checked at compile time.

1. Unchecked exceptions are checked at run time.

2. Derived from Exception.

2. Derived from RuntimeException.


3. Caused by external factors like file I/O and database connection cause the checked Exception.

3. Caused by programming bugs like logical errors cause unchecked Exceptions.



4. Checked exceptions must be handled using a try-catch block or must be declared using the throws keyword

5. No handling is required.


Checked : 1. ClassNotFoundException 2.FileNotFoundException  3. IOException 4. SQLException 5. InstatiationException   6. InterruptedException 

Unchecked : 1. ArithmeticException 2. ClassCastException 3. NullPointerException

4. ArrayIndexOutOfBoundsException 5. ArrayStoreException 6. IllegalThreadStateException.



-----------

18. Explain serialization and deserialization in Java.

Answer : 

- Serialization converts an object into a byte stream to store or transfer it, and deserialization converts the byte stream back into an object. Used for caching, networking, storing data, and communication between microservices. We Requires to implement Serializable interface and may use transient and serialVersionUID.



-----------

19. What is the Java Collections Framework? Name its main interfaces.

Answer : 

- The Java Collections Framework (JCF) is a ready-made architecture in Java that provides classes and interfaces for storing and manipulating groups of objects efficiently. It provides ready-made data structures (like List, Set, Map, Queue) and algorithms (like sorting, searching).


Benefits of Java Collections Framework

- Reusability: Provides reusable data structure classes

- Performance: Well-optimized data structures

- Consistency: Common interfaces and methods across collections

- Reduces effort: No need to write custom data structure logic


    

    Iterable (Interface)

   |

   ---> Collection (Interface)

          |

          |--- List (Interface)

          |       |

          |       |--- ArrayList (Class)

          |       |--- LinkedList (Class)

          |       |--- Vector (Class)

          |       |--- Stack (Class)

          |

          |--- Queue (Interface)

          |       |

          |       |--- PriorityQueue (Class)

          |       |--- Deque (Interface)

          |               |

          |               |--- ArrayDeque (Class)

          |

          |--- Set (Interface)

                  |

                  |--- HashSet (Class)

                  |--- LinkedHashSet (Class)

                  |

                  |--- SortedSet (Interface)

                          |

                          |--- TreeSet (Class)



Map (Interface)

    |

    |--- HashMap (Class)

    |--- LinkedHashMap (Class)

    |--- Hashtable (Class)

    |

    |--- SortedMap (Interface)

            |

            |--- TreeMap (Class)






-----------

20. Differentiate between ArrayList and LinkedList.


Answer : 


| Feature                    | ArrayList                | LinkedList                      |

| -------------------------- | ------------------------ | ------------------------------- |

| Internal Structure         | Dynamic array            | Doubly Linked List              |

| Access/Read                | Fast (O(1)) using index  | Slower (O(n)) — needs traversal |

| Insert/Delete in Middle    | Slow (shifting required) | Fast (no shifting needed)       |

| Insert/Delete at Beginning | Very slow                | Very fast                       |

| Memory usage               | Less (stores data only)  | More (stores data + pointers)   |

| Best Use Case              | Frequent read operations | Frequent add/remove operations  |





-----------

21. What is a HashMap? How does it work internally?

Answer : 

- HashMap : HashMap in Java is a data structure that stores data in key–value pairs.


- Internal Working of hashmap

1. HashMap stores data in key–value pairs..

2. Default initial capacity is 16 arrays of buckets of HashMap.

3. Each stored item is represented as an Entry/Node object containing which 

key, value, hash, next.

4. HashMap uses hashing and applies hashCode() method to decide in which bucket data will be stored.

5. If two keys generate the same bucket index, a collision occurs, and HashMap stores entries in a linked list (Java 7) or LinkedList + Balanced Tree (TreeNode) if list size > 8 (Java 8).


1. During put(key, value) operation:

- HashMap checks if a bucket already contains nodes

- It compares keys using the equals() method

- If the key already exists → value is replaced (updated)

- If it does not exist → a new node is added


2. During get(key):

- HashMap calculates the hash, goes to bucket, and finds node by comparing keys using equals()



Note : Find bucket index = hash % bucket size

put("name", "Datta")


Step 1: Key → "name"

Step 2: hashCode() is calculated

          |

          v

       123456  (example hash)

          |

          v

    hash % 16 = 4     (16 = default bucket size)

          |

          v

   Bucket Index = 4



- What is Hashing? (Simple Explanation)

- Hashing is a technique used to convert data (like a key) into a small numeric value called a hash code, which is used to store and retrieve data quickly.



-----------

22. Explain the significance of the equals() and hashCode() methods.


1. equals() Method

2. hashcode() Method .


- Both are equals() and hashcode() method override from Object class. 

- equals() checks for content equality, while hashCode() generates a unique code for an object.

- equals() is used for comparison, while hashCode() is used for storage and retrieval in hash-based collections.

- equals() takes an Object as a parameter, while hashCode() takes no parameters.

- Contract between equals() and hashCode():

- If two objects are equal according to the equals() method, then they must have the same hash code according to the hashCode() method.

- If two objects have the same hash code, it does not mean they are equal according to the equals() method.

1. The equals() method is used to compare the content of two objects.

1. The hashCode() method is used to generate a hash code value for an object.

2. It checks whether the values of the objects are equal or not.

2. It is used to store and retrieve objects from a hash-based collection like HashMap or HashSet.


3. It return Boolean value either true or false.

3. It takes no parameters and returns an int value.



-----------

23. What is the difference between Comparable and Comparator interfaces?

Answer

- Why  we need of Comparable & Comparator interface in java  ??

- we need of both because java cannot our custom object (Our own object) its only sort the array of primitive Objects.

Java provides two interfaces to sort objects using data members of the class: 


1. Comparable 

2. Comparator


1. Comparable provide a single sorting sequence. In other word, can sort the collection on the basis of single element such as id, name and price.

1. Comparator provide multiple sorting sequences. In other word can sort the collection on the basis of multiple element such as id, name and price.


- Comparable : We can Use Comparable to define default Natural Sorting Order.

- Comparator : We can use Comparator to define Customized Sorting Order.

- Comparable : All Wrapper classes & String Class implement Comparable Interface.

- Comparator : No predefined Class Implement & Comparator Interface .


2. Comparable affects the original class. that is the actual class is modified. 

2. Comparator doesn't affect the original class that is actual class is not modified.


3. Comparable provides compareTo() method to sort element.( CompareTo() used internally Quicksort sorting Algorithm)

3. Comparator provide compare() method to sort elements.

4. Comparable is present in java.lang package.

4. A comparator is present in java.util package.

5. We can sort the list element of Comparable type by Collections.sort(List) method.

5. We can sort the list elements of Comparator type Collections.sort(List, Comparator) method.



----

Comparable :

- CompareTo() Method contain in Comparable 

public int compareTo(Object obj)

Obj1.compareTo(Obj2);

- return -ve if obj1 has come before obj2 .

- return +ve if obj1 has come after obj2 .

- return 0 if both  obj1 &  obj2 are equals.

- Comparable ment for default natural Sorting Order.

- Comparator ment for Customized Sorting Order.

Comparator

- Compare() Method contain in Comparator 

public int compare(Object obj1, Object obj2)

- return -ve if obj1 has come before obj2 .

- return +ve if obj1 has come after obj2 .

- return 0 if both  obj1 &  obj2 are equals.


Obj1 : Which object we are trying to add

Obj2 : object which already exist.

- When ever we are implementing Comparator interface Compulsory we should provide implementation for compare(), 2nd method .equal() implementation is optional , because it is already available for our class from Object class through Inheritance.



-----------

24. Describe the Java Memory Model (JMM) ?

Answer:

- Java Memory Model (JMM) – Simple Answer

- The Java Memory Model (JMM) defines how Java threads read and write data from memory.

- It explains how changes made by one thread become visible to other threads.

- JMM separates memory into main memory (shared) and working memory (thread-local).

- It supports concepts like volatile, synchronized, and happens-before to ensure visibility and avoid data inconsistency in multithreading.



-----------

25. What is garbage collection in Java? How does it work?

Answer : 

- Garbage Collection (GC) in Java is an automatic process that removes unused objects from memory to free up space and improve performance.

- Java identifies objects that are no longer referenced by any part of the program.

- These unused objects are marked for deletion and removed by the Garbage Collector.

- GC mainly works in two steps: Marking (finding unreachable objects) and Sweeping (removing them from memory).

- It runs automatically, so developers don’t need to manually free memory like in C/C++.



-----------

26. Explain the concept of Java annotations.

Answer : 

- Java Annotations are special metadata used to provide additional information about code without affecting its execution.


-----------

27. What are lambda expressions? Provide a use case.

Answer: 

- Lambda expressions in Java are short blocks of code that allow us to write functions in a compact, readable, and functional style.

- They were introduced in Java 8 and are mainly used to implement functional interfaces (interfaces with only one abstract method).


- Benefits 

- Less boilerplate code

- More readable and clean

- Useful in streams, collections, threading




-----------

28. Discuss the Stream API in Java.

Answer : 

- A Stream is a sequence of elements supporting sequential and parallel aggregate operations.

- It does not store data; it just processes data from a source (like a Collection or Array).

- A stream is sequence of data elements that supports various methods which can be pipelined to produce the desired result.

- Stream Pipeline:

A typical stream pipeline has 3 parts:

1. Source → Collection, array, or I/O channel.

- Source : This is the starting point of the stream — where the data comes from.

Example: List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);


2. Intermediate Operations → Transform data. (Return a Stream)

- Intermediate Operation : These are transformations applied on the stream. They return another Stream, allowing multiple operations to be chained together.

Example: filter(), map(), sorted().


3. Terminal Operation → Produce the result.

- Terminal Operation : These end the stream pipeline and produce a result (like a value, collection, or output).

Example: collect(), forEach(), count(), reduce().




-----------

29. What is the purpose of the Optional class?

Answer : 

- The Optional class in Java is used to handle null values and avoid NullPointerException.

- It is a container object that may or may not contain a value.

- Instead of returning null, methods can return Optional to indicate that a value might be missing.

- Optional provides methods like isPresent(), orElse(), orElseThrow(), and ifPresent() to safely access values.



-----------

30. Explain the try-with-resources statement.

Answer : 

- Try-with-resources automatically manages and closes resources, avoiding memory leaks and removing the need for a finally block.



-----------

31. What is the difference between final, finally, and finalize()?

Answer : 

- final is a keyword for restriction, finally is a block for cleanup, and finalize() is a method for garbage collection cleanup.


1. final

- Used to restrict the user.

1. final variable → value cannot be changed

2. final method → cannot be overridden

3. final class → cannot be inherited


2. finally

- A block in exception handling that always executes (whether exception occurs or not).

- Mostly used to close resources.


3. finalize()

- A method called by the Garbage Collector before destroying an object to perform cleanup. (Not recommended in modern Java due to unpredictability)



-----------

32. How does the volatile keyword affect thread behavior?

Answer : 

- Ensures proper visibility of changes to a variable between threads and prevents object creation issue due to JVM instruction reordering.

-  Ensures visibility of changes to a variable across threads, preventing caching.

- volatile ensures that updates to a variable are immediately visible to all threads and prevents instruction reordering.


- The volatile keyword ensures that a variable’s value is always read from main memory and not from a thread’s local cache.

- It guarantees visibility of changes made by one thread to all other threads immediately.

- It also prevents instruction reordering, maintaining the correct execution order.

- volatile is used in multithreading situations like status flags, stop signals, and configuration updates where multiple threads share the same variable.



-----------

33. What are design patterns? Name a few commonly used ones in Java.

Answer : 

- The design pattern is a reusable solution to a common problem that occurs in software design.

- Design pattern represent and Idea.

use 

- Design Patterns help us to solve a programming problem during project development. Moreover, Design Patterns will help us in fixing performance and memory related issues. 


1. Creational Patterns: 

These patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The main focus is on abstracting the object creation process and making the system independent of how objects are created, composed, and represented. Examples include Singleton, Factory Method, Abstract Factory, Builder, and Prototype patterns.



-----------

34. Explain the Singleton design pattern and its implementation.

Answer : 

1. private constructors :  if it public then we can create multiple object (Constructor use to initialize of object)

2. Static Instance Variable: - we create static instance variable for holds the instance of the class.

- Within the Singleton class, there is a static member variable that holds the single instance of the class.

3. public static method : this method allow to other classes to access the single instance of object. & according to condition object will create once & if we access to get object then we get same object every time.


# Implementation 


public class Singleton {


    private static Singleton instance; // Step 2: static reference


    private Singleton() {} // Step 1: private constructor


    public static Singleton getInstance() { // Step 3: public method

        if (instance == null) {

            instance = new Singleton();

        }

        return instance;

    }

}



Problem : Above code is NOT thread-safe.

- If multiple threads call getInstance() at the same time, multiple instances can be created.


- Thread-Safe Singleton Using synchronized

    public static synchronized Singleton getInstance() 


Why use synchronized?

- Because synchronized ensures that only one thread can access the method at a time.

So multiple threads cannot create multiple objects simultaneously.


Disadvantage

- synchronized makes method slower because every call locks the method, even after the instance is created.


Here are some common use cases for the Singleton design pattern:

1. Database Connections

2. Thread Pools

3. Logging 




# Better Approach: Double-Checked Locking Singleton

- This improves performance by synchronizing only during first object creation.


public class Singleton {


    private static volatile Singleton instance;


    private Singleton() {}


    public static Singleton getInstance() {

        if (instance == null) {                   // 1st check

            synchronized (Singleton.class) {      // lock

                if (instance == null) {           // 2nd check

                    instance = new Singleton();

                }

            }

        }

        return instance;

    }

}



# 2. Factory Design Pattern 

- The Factory Design Pattern is a Creational design pattern that provides a way to create objects without exposing the creation logic to the client.

- The Factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-classes. This pattern takes out the responsibility of instantiation of a class from a client program to the factory class. 

- Super class in factory pattern can either be an interface, or an abstract class, or a normal Java class.


Steps to Implement Factory Pattern

1. Create a common interface (e.g., Shape)

2. Create multiple implementations (e.g., Circle, Square)

3. Create a factory class with a method that returns objects based on input

4. Client calls the factory instead of using new keyword



Why Factory Pattern is Useful?

- Reduces tight coupling between client and object creation

- Helps maintain clean, scalable code

- New shapes can be added easily without changing client code



-----------

35. What is JDBC? How is it used in Java applications?

Answer :

- JDBC is a Java API used to connect applications to databases and execute SQL queries.

Steps to use JDBC in Java

1. Load & register the database driver

2. Create a connection using DriverManager

3. Create a Statement / PreparedStatement

4. Execute SQL queries

5. Process ResultSet

6. Close the connection



-----------

36. Discuss the differences between Statement and PreparedStatement.

Answer : 

- Statement is used for simple static queries, while PreparedStatement is used for dynamic, parameterized, secure, and faster queries.


Example of Statement

Statement st = con.createStatement();

ResultSet rs = st.executeQuery("SELECT * FROM users WHERE id = " + userId);


Example of PreparedStatement

PreparedStatement ps = con.prepareStatement("SELECT * FROM users WHERE id = ?");

ps.setInt(1, userId);

ResultSet rs = ps.executeQuery();




-----------

37. What is the purpose of the transient keyword?

Answer :

- transient is used to stop a field from being serialized, mainly for sensitive or unnecessary data.

- The transient keyword in Java is used to prevent a variable from being serialized.

- When an object is serialized, transient fields are ignored and not saved in the file or stream.

- It is used when certain data is sensitive, temporary, or derived and should not be stored permanently, such as passwords or session values.



-----------

38. What are inner classes? Differentiate between static and non-static inner classes.

Answer : 

- Inner classes are classes defined inside another class in Java.


| **Static Inner Class**                                                   | **Non-Static (Regular) Inner Class**                     |

| ------------------------------------------------------------------------ | -------------------------------------------------------- |

| Declared using `static` keyword                                          | Declared without `static`                                |

| Cannot access outer class’s non-static members directly                  | Can access all outer class variables including private   |

| Object created **without outer class object**                            | Requires an **instance of outer class** to create object |

| Used when inner class functionality is independent of outer class object | Used when inner class depends on outer class instance    |

| Example: Utility/helper classes                                          | Example: Node class in LinkedList                        |



Example


public class Outer {


    private String message = "Hello";


    // Non-static inner class

    class Inner {

        void display() {

            System.out.println(message);  // Can access outer variable

        }

    }


    // Static inner class

    static class StaticInner {

        void show() {

            System.out.println("Inside Static Inner Class");

        }

    }


    public static void main(String[] args) {

        // Creating object of non-static inner class

        Outer outer = new Outer();

        Outer.Inner inner = outer.new Inner();

        inner.display();


        // Creating object of static inner class

        Outer.StaticInner s = new Outer.StaticInner();

        s.show();

    }

}




-----------

39. Describe the use of the synchronized keyword.

Answer : 

- synchronized ensures thread-safe access to shared resources by allowing only one thread to execute a block or method at a time.

- The synchronized keyword in Java is used to control access to shared resources in multithreaded environments.

- It ensures that only one thread at a time can execute a block of code or method, preventing race conditions and data inconsistency.


How it Works

1. When a thread enters a synchronized method/block, it acquires a lock (monitor) on the object or class.

2. Other threads trying to access the same synchronized resource wait until the lock is released.

3. After execution, the thread releases the lock, allowing other threads to proceed.



1. Synchronized Method

2. Synchronized Block

3. Synchronized Static Method


Note : There is No Synchronized Variable.


Real-Time Use Cases

- Bank account transactions

- Ticket booking systems



-----------

40. What is the difference between String, StringBuilder, and StringBuffer?

Answer : 

- String is immutable, StringBuilder is mutable and fast (single-threaded), StringBuffer is mutable and thread-safe (multi-threaded).



| Feature       | String                         | StringBuilder                       | StringBuffer                       |

| ------------- | ------------------------------ | ----------------------------------- | ---------------------------------- |

| Mutability    | Immutable                      | Mutable                             | Mutable                            |

| Thread-safety | No (immutable so safe)         | Not thread-safe                     | Thread-safe (synchronized)         |

| Performance   | Slow in repeated modifications | Fast                                | Slightly slower than StringBuilder |

| Use Case      | Fixed text, constants          | Single-threaded string manipulation | Multi-threaded string manipulation |

| Package       | java.lang                      | java.lang                           | java.lang                          |




-----------

41. Explain the concept of immutability in Java.

Answer : 

- Immutability means that once an object is created, its state (data) cannot be changed.

- Immutable objects are read-only and cannot be modified after creation.



** How to Create an Immutable Class

1. Declare the class as final → prevents inheritance.

2. Make all fields private and final → prevents direct modification.

3. Do not provide setter methods → only getters.

4. Initialize all fields via constructor → set values only once.

5. If a field is mutable (like Date or Array), return a copy in getter.



Example :


final class Employee {

    private final String name;

    private final int id;


    public Employee(String name, int id) {

        this.name = name;

        this.id = id;

    }


    public String getName() { return name; }

    public int getId() { return id; }

}


public class TestImmutable {

    public static void main(String[] args) {

        Employee e = new Employee("Datta", 101);

        System.out.println(e.getName() + " - " + e.getId());

        // Cannot modify name or id → immutable

    }

}




-----------

42. How does Java handle memory leaks?

Answer : 

- Java handles memory leaks primarily through Garbage Collection, but leaks can occur if unused objects are still referenced; developers must nullify references or use weak references to avoid leaks.


# Memory Leak in Java

- A memory leak occurs when objects are no longer used but still referenced, so they cannot be garbage collected, leading to memory wastage.

- Even though Java has automatic garbage collection, memory leaks can still happen if references are unintentionally maintained.


# How Java Handles Memory Leaks

1. Garbage Collector (GC) automatically frees memory of objects that are no longer reachable.

2. Nullifying references to objects that are no longer needed helps GC reclaim memory.

3. Weak references (WeakReference) can be used for objects that should be collected when memory is low.

4. Tools & Profilers like VisualVM, Eclipse MAT, or JConsole help detect memory leaks.

5. Avoid static references to objects unnecessarily, as they prevent GC from freeing memory.



-----------

43. What are functional interfaces? Provide examples.

Answer : 

- A Functional Interface in Java is an interface that contains exactly one abstract method.

- It can have default and static methods, but only one abstract method.

- Functional interfaces are mainly used in lambda expressions and method references to - provide a target type for lambda expressions.



-----------

44. Discuss the role of the default keyword in interfaces.

Answer : 

- The default keyword in Java allows interfaces to have concrete (method body) methods.

- Introduced in Java 8 to add new methods to interfaces without breaking existing implementations.

- It provides a default behavior that implementing classes can override if needed.


Why Default Methods Are Useful

- Backward Compatibility → Existing classes implementing the interface don’t need to implement new methods.

- Code Reusability → Common behavior can be defined in the interface itself.

- Multiple Inheritance Support → Helps avoid issues with multiple interfaces by providing default implementations.



Example :


interface Vehicle {

    void start();  // abstract method


    default void stop() {  // default method

        System.out.println("Vehicle stopped safely.");

    }

}


class Car implements Vehicle {

    @Override

    public void start() {

        System.out.println("Car started");

    }

}


public class TestDefault {

    public static void main(String[] args) {

        Car car = new Car();

        car.start(); // Car specific implementation

        car.stop();  // default implementation from interface

    }

}




-----------

45. What is the enum type in Java? How is it used?

Answer : 

- Enum is a special Java type that defines a fixed set of constants, providing type-safety, readability, and the ability to include fields and methods.


- Enum (short for enumeration) in Java is a special data type that represents a fixed set of constants.

- It is used when a variable can only have one value out of a predefined set (e.g., days of the week, directions, states).

- Enums are type-safe, improving readability and reducing errors compared to using integer constants or strings.



-----------

46. Explain the concept of reflection in Java.

Answer : 

- Reflection in Java is a powerful API that allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime, even if they are private.


Why Reflection is Useful

1. Inspect classes at runtime → get class name, methods, fields, and constructors.

2. Instantiate objects dynamically → without knowing the class at compile time.

3. Access private members → useful for testing or frameworks.

4. Used in frameworks → Spring, Hibernate, and JUnit heavily use reflection.



-----------

47. What are modules in Java? Discuss their significance ?

Answer : 

- Modules are a way to group packages together with explicit dependencies and exports, improving encapsulation, maintainability, and performance in large Java applications.




-----------

48. Data Hiding Method internally working ?

Answer : 

- Data hiding in Java restricts direct access to fields using private access, allowing controlled access via getters and setters to maintain data integrity.



-----------

49. Explain the Shallow and deep copy ?

Answer : 

- Shallow copy copies only object references, so changes may affect original; deep copy copies the object and its references recursively, keeping the original unchanged.


1. Meaning

- Shallow Copy: Copies the object itself, but references inside the object still point to the same original objects.

- Deep Copy: Copies the object and everything it refers to, so the new object is completely independent.


2. Effect of Changes

- Shallow Copy: Changing data in the copied object may affect the original object if it references other objects.

- Deep Copy: Changing data in the copied object does NOT affect the original object.


3. Memory Usage

- Shallow Copy: Uses less memory because it just copies references.

- Deep Copy: Uses more memory because it creates completely new copies of everything.



-----------

50. Why java is not pure  object ?

Answer : 

- Java is not pure object-oriented because it uses primitive data types and static methods, which are not objects.


- Why Primitives Exist

- Performance → Object creation is slower and consumes more memory.

- Ease of use → Simple operations on small data types without object overhead.




-----------

51. Which Object class Method  ?

Answer : 

1. toString() method

2. hashCode() method

3. equals(Object obj) method

4. finalize() method

5. getClass() method

6. clone() method

7. wait(), 

8. notify() 

9. notifyAll() methods




-----------

52. what is  Multithreading locks ? 

Answer : 

- Multithreading locks are mechanisms that allow only one thread at a time to access a shared resource, ensuring thread safety and avoiding data corruption.


Types of Locks in Java

1. Synchronized Block / Method (Intrinsic Lock)

- Every object in Java has an intrinsic lock (monitor).

- Use synchronized to lock a method or block.


2. Explicit Lock (ReentrantLock)

- Provided in java.util.concurrent.locks.

- More flexible than synchronized (can tryLock, interruptible, timed lock).



-----------

53. Can we create Object of Abstract class ? No bcoz it incomplete class

Answer : 

- No, we cannot create an object of an abstract class because it is incomplete; we must extend it and instantiate the subclass instead.

- No, we cannot create an object of an abstract class directly in Java.

- Reason: An abstract class is incomplete; it may have abstract methods without implementation, so it cannot be instantiated.




-----------

54. Can we override static Method ? No

Answer : 

- No, we cannot override a static method in Java.

- Reason: Static methods belong to the class, not to instances (objects), so they cannot be overridden at runtime like instance methods.


- If a subclass defines a static method with the same name as the parent class, it is called method hiding, not overriding.

- The method called depends on the reference type, not the object type.



-----------

55. Difference between Treemap & HashMap ? 

Answer : 

- HashMap stores key-value pairs with no order and offers fast access, while TreeMap stores keys in sorted order and is slower due to tree structure.


1. Ordering

- HashMap: Does not maintain any order of keys.

- TreeMap: Maintains keys in sorted order (natural order or using Comparator).


2. Implementation

- HashMap: Uses hash table internally.

- TreeMap: Uses Red-Black Tree internally.


3. Null Key & Value

- HashMap: Allows one null key and multiple null values.

- TreeMap: Does not allow null key, but allows multiple null values.


4. Performance

- HashMap: Faster – O(1) for get/put operations.

- TreeMap: Slower – O(log n) for get/put operations because of tree traversal.


5. Use Case

- HashMap: When you need fast insertion, deletion, and retrieval.

-  TreeMap: When you need sorted data.




-----------

56. What is  Custom Exception  & How we can implement ?

Answer : 

- A Custom Exception is a user-defined exception class that extends Exception (checked) or RuntimeException (unchecked), used to represent application-specific errors.


Why we need Custom Exception?

- Java provides many built-in exceptions, but sometimes in real-time applications, we need specific exception types to represent our own business logic errors.

- Custom exceptions make code more readable, maintainable, and meaningful.



Example :


class AgeException extends Exception {

    AgeException(String message) { super(message); }

}


public class TestCustomException {

    static void validateAge(int age) throws AgeException {

        if(age < 18) throw new AgeException("Age must be 18 or older");

        System.out.println("Age is valid");

    }


    public static void main(String[] args) {

        try { validateAge(15); }

        catch (AgeException e) { System.out.println(e.getMessage()); }

    }

}




-----------

57. Difference btw Stack and Heap  &  Use of it ?

Answer:

- Stack: use to store primitive local variables, method calls & method execution. its limited , smaller in size . Its fast in speed.

- Heap: Stores objects, instance variables and class instances, allows shared access, and is managed by GC. Its larger size & size depends on JVM too. Its slow in speed.


- We use Stack for temporary variables, method calls where use Heap for Objects, class instance , shared data.

Together: Ensures efficient memory management and thread-safe local execution.




-----------

58. Difference btw "==" operator and .equals() Method ?

Answer :

- == operation checks if two references point to the same object, whereas .equals() checks if two objects have the same content.


String s1 = new String("ABC");

String s2 = new String("ABC");


String s3 ="ABC";

String s4 ="ABC";


sop(s1 == s2);      // false   Both have two difference memory address so

sop(s1.equals(s2)); // true

sop(s1 == s3);      // false  // content same but address diff so 

sop(s1.equals(s3)); // true

sop(s3 == s4);     // true

sop(s3.equals(s4)); // true





-----------

59. Best practices to implement equals() & hashcode().

Answer :

- Why we need equals() & hashCode()?

1. We need both because Java uses hash-based collections like HashMap and HashSet to store and compare objects efficiently.

2. equals() checks logical equality of objects, while hashCode() helps determine the bucket location in hash-based collections.



1. Purpose

- equals(): Compares the content of two objects to see if they are logically equal.

- hashCode(): Returns an integer used to store objects in hash-based data structures efficiently.



2. Default Behavior

- equals(): In Object class, compares memory references (same as ==).

- hashCode(): In Object class, returns an integer derived from the memory address of the object.



3. Relationship

- If two objects are equal according to equals(), they must have the same hash code.

- If two objects have the same hash code, they may or may not be equal.



4. Overriding

- equals(): Can be overridden to compare object content (e.g., fields like name, age).

- hashCode(): Should be overridden whenever equals() is overridden to maintain the contract.



5. Use Case

- equals(): Used when we need to check if two objects are logically the same.

- hashCode(): Used when storing objects in HashMap, HashSet, Hashtable to find the bucket quickly.




- Both are equals() and hashcode() method override from Object class. 

- If two objects are equal according to the equals() method, then they must have the same hash code according to the hashCode() method.

- If two objects have the same hash code, it does not mean they are equal according to the equals() method.

1. The equals() method is used to compare the content of two objects.

1. The hashCode() method is used to generate a hash code value for an object.

2. It checks whether the values of the objects are equal or not.

2. It is used to store and retrieve objects from a hash-based collection like HashMap or HashSet.


3. It return Boolean value either true or false.

3. It takes no parameters and returns an int value.





-----------

60. How many ways we can create thread ?

Answer : 

- In Java, threads can be created by extending the Thread class, implementing Runnable, using Lambda expressions, or using Callable with ExecutorService.


1. Extending the Thread Class

- Create a class that extends Thread.

- Override the run() method.

- Call start() to begin execution.


Example : 


class MyThread extends Thread {

    public void run() {

        System.out.println("Thread is running");

    }

}


public class TestThread {

    public static void main(String[] args) {

        MyThread t = new MyThread();

        t.start();

    }

}



2. Implementing the Runnable Interface

- Create a class that implements Runnable.

-  Implement the run() method.

- Pass the object to a Thread and call start().


Example : 


class MyRunnable implements Runnable {

    public void run() {

        System.out.println("Runnable Thread running");

    }

}


public class TestRunnable {

    public static void main(String[] args) {

        Thread t = new Thread(new MyRunnable());

        t.start();

    }

}


3. Using Lambda Expression (Java 8+)

- Since Runnable is a functional interface, we can use lambda to create a thread.



Example : 


public class TestLambdaThread {

    public static void main(String[] args) {

        Thread t = new Thread(() -> System.out.println("Thread using Lambda"));

        t.start();

    }

}



4. Using Callable and Future (Optional, Advanced)

- For threads that return a result and throw checked exceptions, use Callable<V> with ExyeecutorService.




----------

61. Can we overload the run Method , and How we can call the run() generally.

Answer : 

- run() method is the entry point for thread execution. 

- Yes, we can overload run() method, but only the no-arg run() is executed by start(); overloaded run() must be called like a normal method.




----------

62. What is the difference between execute() & submit() method ?

Answer : 

- Both methods are used to run tasks via ExecutorService, but they behave differently in terms of return type and exception handling.

- execute() runs a Runnable and returns void, while submit() runs Runnable/Callable and returns a Future to retrieve result or exception.


1. Purpose

- execute(): Used to execute Runnable tasks only.

- submit(): Used to submit Runnable or Callable tasks and returns a Future object.


2. Return Type

- execute(): Returns void.

- submit(): Returns a Future object representing the pending result.





----------

63. What is fail-Safe & fail-Fast ?

Answer : 

- Why we need this distinction?

- While iterating over collections, we sometimes modify the collection.

- Java provides Fail-Fast and Fail-Safe iterators to handle or prevent concurrent modifications Exception.



1. Fail-Fast Iterator

- Definition: Iterator that immediately throws ConcurrentModificationException if the collection is modified during iteration.

- Collections: ArrayList, HashMap, HashSet (most from java.util).

- Mechanism: Works directly on the collection and checks a modCount to detect changes.

- Thread Safety: Not safe for concurrent modification.

- It is Faster than Fail-Safe Iterator.


Example:


import java.util.*;


public class FailFastExample {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));

        Iterator<Integer> it = list.iterator();

        while(it.hasNext()) {

            System.out.println(it.next());

            list.add(4); // ConcurrentModificationException

        }

    }

}



2. Fail-Safe Iterator

- Definition: Iterator that does not throw exception if the collection is modified while iterating.

- Collections: CopyOnWriteArrayList, ConcurrentHashMap (from java.util.concurrent).

- Mechanism: Works on a clone/copy of the collection internally.

- Thread Safety: Safe for concurrent modification.

- It is Slower than Faster-Safe Iterator.


Example:


import java.util.concurrent.*;

import java.util.*;


public class FailSafeExample {

    CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>(Arrays.asList(1,2,3));

    Iterator<Integer> it = list.iterator();

    while(it.hasNext()) {

        System.out.println(it.next());

        list.add(4); // No exception

    }

}




----------

64. Difference between HashTable & ConcurrentHashMap ?

Answer : 

Why we need both?

- Both are thread-safe Map implementations, but they handle concurrency differently.

- Using the right one improves performance in multi-threaded applications.


1. Thread Safety

- Hashtable: Synchronized at method level; whole object locked for each operation.

- ConcurrentHashMap: Synchronized at segment/portion level; locks only part of the map.



2. Null Key & Null Value

- Hashtable: Does not allow null key or null values.

- ConcurrentHashMap: Does not allow null key or null values.



3. Performance

- Hashtable: Slower in multi-threaded environment due to global locking.

- ConcurrentHashMap: Faster due to fine-grained locking.



4. Iterator Behavior

- Hashtable: Fail-Fast iterator; throws ConcurrentModificationException if modified during iteration.

- ConcurrentHashMap: Fail-Safe iterator; iterates over snapshot, allowing concurrent modifications.


- HashMap is the Class which is under Traditional Collection and ConcurrentHashMap is a Class which is under Concurrent Collections, apart from this there are various differences between them which are:


- HashMap is non-Synchronized in nature i.e. HashMap is not Thread-safe whereas ConcurrentHashMap is Thread-safe in nature.

- HashMap performance is relatively high because it is non-synchronized in nature and any number of threads can perform simultaneously. But ConcurrentHashMap performance is low sometimes because sometimes Threads are required to wait on ConcurrentHashMap.

- While one thread is Iterating the HashMap object, if other thread try to add/modify the contents of Object then we will get Run-time exception saying ConcurrentModificationException.Whereas In ConcurrentHashMap we wont get any exception while performing any modification at the time of Iteration.





----------

65. is Singleton threadSafe ?

Answer : 

- Singleton can be thread-safe if implemented using synchronized, double-checked locking, or eager initialization; otherwise, lazy initialization is not thread-safe.




----------

66. what is FileNotFoundException ?

Answer : 

- FileNotFoundException occurs when a file is not available at the specified path or the program does not have permission to access it.




----------

67. What is ClassNotFoundException and How to Solve that ?

Answer : 

- ClassNotFoundException occurs when a class is not found at runtime in the classpath, usually fixed by adding the missing class or dependency correctly.


Why does it occur? (Reasons)

1. Class missing from classpath

2. Wrong class name given in Class.forName()

3. JAR file not added or corrupted

4. Classloader unable to locate class

5. Version mismatch or deployment issue





----------

68. Which is Pure Abstraction ? Why interface 100 % and Abstract not purely 100% ?

Answer : 

- Interface is 100% abstract (pure abstraction) because it contains only abstract behavior, whereas an abstract class is not pure abstraction as it can include concrete methods and maintain state.

- where abstract has a constructor but interface does not allow constructor.




----------

69. Can we Convert ArrayList to Map ?

Answer : 

- Yes, we can convert an ArrayList to a Map using loops, Java 8 Streams, or Collectors.

It requires deciding how keys and values should be mapped.




----------

70. What is Constructor Overloading ?

Answer : 

- Constructor Overloading means creating multiple constructors in the same class with different parameter lists.

- It allows to created a objects in different ways, depending on the input values.




----------

71. if we want  finally block not executed if then exception occur or not then how would do that ? 

Answer : 

- finally block can be prevented from executing by calling System.exit(0) because it stops the JVM immediately.





----------

72. What is Difference between Runnable and Callable ?

Answer : 

- Why do we need Runnable & Callable?

- We need both because Java threads cannot directly return values.

- Runnable does not return a result, so Callable was introduced to support task results and exception handling in multithreading.



- Difference (Your Style Answer)

1. Runnable 

2. Callable 


1. Runnable cannot return a result, it just performs a task.

1. Callable can return a result after execution.


2. Runnable cannot throw checked exceptions.

2. Callable can throw checked exceptions.


3. Runnable provides run() method to define task logic.

3. Callable provides call() method which returns value.


4. Runnable introduced in Java 1.0

4. Callable introduced in Java 5 (with Executor framework).


5. Runnable used with Thread and ExecutorService

5. Callable used only with ExecutorService (submit method)


6. Runnable return type is void

6. Callable returns Future object



----------

73. What is Thread Local ?  

Answer : 

- ThreadLocal provides thread-specific variables so each thread has its own independent copy without using synchronization.


Why do we need ThreadLocal?

- To avoid synchronization when multiple threads use the same variable

- To store thread-specific data (like user session, request ID, DB connection) safely

- Each thread gets its own value, not shared with other threads


How it works internally

- ThreadLocal maintains a ThreadLocalMap inside each thread

- Each thread uses get() / set() to retrieve or assign its private value

- No two threads can see or change each other’s value



----------

74. What is Future Object ?

- Whatever the object that you want to return after thread logic is executed can be called as future object. 

- Future is an object in Java that represents the result of an asynchronous computation.

- It is returned when we submit a Callable task to an ExecutorService, and we can use it to check task status, wait for completion, and get the result.



Why do we need Future?

- To get result from a background thread

- To check whether a task is completed or still running

- To cancel a long-running task if required




-----------

75. What is Default value(Capacity) has HashMap and Load Factor ? 16 Bucket and 0.75 Load factor. 

- What is Load Factor : Load Factor which mean when it is storing the value if the first initial capacity reaches to its  75% of occupancy then it will generate one more with higher capacity and store all these values into that so the limit where it reaches to the 75% so that would be the load Factor. 




----------

76. What call by value ? 

Answer : 

- Call by value means that Java passes a copy of the variable value to a method.

Any changes made inside the method do not affect the original value outside the method.


Why?

- Java always passes copy of the variable, not the actual variable.

- So modification happens only on the local copy inside the method.



public class CallByValueExample {


    public static void modify(int x) {

        x = x + 10;   // modified local copy

    }


    public static void main(String[] args) {

        int num = 20;

        modify(num);

        System.out.println(num);   // Output: 20

    }

}


Explanation

- num = 20 is passed to the method

- Inside modify(), a copy of num (x = 20) is changed to 30

- The original num remains unchanged



----------

77. Is Java support  Pass By Reference ?

Answer : 

- Java does not support Pass By Reference. Java is always Pass By Value.

For objects, it passes the value of the reference, not the actual reference, so object data can change but reference itself cannot.





----------

78. Can we use HashMap in a multi-threaded environment ? No 

Answer : 

- No, HashMap is not safe to use directly in a multi-threaded environment.

Because HashMap is not synchronized → multiple threads modifying it simultaneously can cause:

- Data inconsistency

- Unexpected behavior

- Infinite loop / deadlock due to rehashing issue



- HashMap is not thread-safe, so we should not use it directly in multi-threaded environment.

- To use safely, we should use ConcurrentHashMap or Collections.synchronizedMap().



----------

79. Is there any difference in defining or creating a String by using String literal and by using the new() Operator ? 

Answer : 

- String literals are stored in the String Constant Pool and reused to save memory, while new String() creates a new object in heap memory even if the same value exists.


Differences

1. String Literal stored in String Constant Pool (SCP)

1. new String() stored in Heap Memory


2. JVM checks if object already exists in SCP, if yes then reference is reused

2. new String() always creates a new object, even if same value exists


3. String Literal is Memory Efficient

3. new String() is Not Memory Efficient


4. Using == with literals returns true because both reference same memory

4. Using == with new String() returns false because references are different


5. Example using literal:

String s1 = "Java";

String s2 = "Java";



5. Example using new():

String s3 = new String("Java");


s1 == s2 → true (same reference)

s1 == s3 → false (different objects)


s1.equals(s3) → true because checks content only



---------

80. When you use Thread Class and Runnable interface on the Specific condition which are main other requirement ?

Answer : 

- In industry, Runnable is preferred because it provides better scalability and reusability, while Thread class is used only for simple independent tasks.

- We use the Thread class when we need a separate independent thread and do not need to share the same task among multiple threads. It is useful for simple implementations but limits us because we cannot extend another class.

- We use the Runnable interface when we want to share the same task across multiple threads and also need multiple inheritance support. Runnable is lightweight, more flexible, and is recommended for real-time applications especially with ThreadPool / ExecutorService.


---------

81. Why we Cannot extends multiple classes in Java ?

Answer : 

- Java does not allow multiple inheritance (extending more than one class) to avoid ambiguity and diamond problem, where the compiler gets confused about which parent method to call if two parent classes have the same method. Allowing multiple inheritance also makes the code complex, error-prone, and difficult to maintain.

- To achieve similar behavior, Java provides interfaces, which support multiple inheritance safely without ambiguity.


---------

82. HashMap vs ConcurrentHashMap 

Answer : 

Why we need ConcurrentHashMap?

- Because HashMap is not thread-safe and can cause data inconsistency or infinite loop in a multi-threaded environment.

- ConcurrentHashMap is introduced to safely handle multiple threads without locking the entire map.


Differences

1. HashMap is NOT thread-safe

1. ConcurrentHashMap is thread-safe


2. HashMap allows multiple threads to modify data simultaneously → causes issues

2. ConcurrentHashMap allows only part-level locking using segment/bucket lock, so safe in multi-threading


3. HashMap can throw ConcurrentModificationException during iteration

3. ConcurrentHashMap never throws ConcurrentModificationException


4. HashMap performance is poor in multi-thread environment

4. ConcurrentHashMap gives high performance because it locks only required portion


5. HashMap allows null keys and null values

5. ConcurrentHashMap does NOT allow null key or null value


6. Fail-Fast Iterator (modification while iterating throws exception)

6. Fail-Safe Iterator (safe iteration even if structure is modified)


---------

83. volatile, transient, ThreadLocal ?

Answer : 

1. volatile : Used when multiple threads access the same shared variable.

2. transient : Used for sensitive data like passwords or temporary values.

3. ThreadLocal : Each thread gets its own variable value — not shared.



---------

84. Thread life cycle & ExecutorService ?

Answer : 

- A thread moves from New → Runnable → Running → Waiting/Blocked → Terminated.


ExecutorService

- ExecutorService is a framework that manages and controls thread execution instead of manually managing threads using start().

- It creates a thread pool to reuse threads, improves performance, and avoids creating too many threads.

- It provides methods like execute(), submit(), shutdown() for task handling.


Short Line:

ExecutorService is used for efficient thread management using Thread Pools.



--------

85. Different way to create object ?

Answer :

- Using new  keyword

- Using newInstance Method of Constructor.

- Using clone 

- deserialize 

- using anonymous inner class



---------

86. Internal Working of ConcurrentHashMap ?

Answer : 

Internal Working of ConcurrentHashMap (Simple Words)


1. ConcurrentHashMap is designed for multi-threading

- It allows multiple threads to read and write data without locking the entire map, providing thread safety + high performance.


2. Uses Segment / Bucket Level Locking (Partial Locking)

- Instead of locking the whole map like Hashtable, it locks only the specific bucket of data where modification happens.

- This concept is called Fine-grained locking.


3. Data Structure internally

- Internally it uses Array of Nodes similar to HashMap where each bucket contains a LinkedList or TreeNode (Red-Black Tree) when entries grow large.


4. Put operation working

- First calculates hash(key) to find bucket index.

- Locks only that specific bucket.

- Checks if key already exists → update value.

- Otherwise add a new node.

- Unlocks bucket after operation.


5. Get operation

- Non-blocking, no lock required.

- Reads directly from memory safely because volatile ensures visibility.


6. Avoids ConcurrentModificationException

- Provides Fail-Safe Iterator, meaning safe iteration even when data is being modified by other threads.


7. Does not allow null key/value

- Because null makes it difficult to detect missing values in multi-threading.


8. Tree-based structure

- When excessive collisions happen, bucket becomes Tree (Red-Black Tree) to improve performance from O(n) to O(log n).




---------

87. Differenect between TreeSet and TreeMap

Answer : 

1. TreeSet implements SortedSet in Java.

TreeMap implements Map Interface in Java


2. TreeSet stored a single object in java.

TreeMap stores two Object one Key and one value.


3. TreeSet does not allow duplication Object in java.

TreeMap in java allows duplication of values.


4. TreeSet implements NavigableSet in Java.

TreeMap implements NavigableMap in Java.


5. TreeSet is sorted based on objects.

TreeMap is sorted based on keys.



--------

88. Can we use a custom class as a key in HashMap?

Answer :

- Yes, we can use a custom class as a key in HashMap, but only if we properly override equals() and hashCode() methods. Without overriding them, HashMap cannot compare keys correctly, and duplicate keys may not be detected, causing unexpected behavior.

By overriding these methods, HashMap can correctly identify the bucket using hashCode() and check equality using equals(), ensuring accurate key lookup.





--------

89. How will you prevent the cloning of Singleton object?

Answer : 

- Prevent Singleton Pattern From Cloning

- To overcome the above issue, we need to implement/override the clone() method and throw an exception CloneNotSupportedException from the clone method. If anyone tries to create a clone object of Singleton , it will throw an exception.




--------





---------


============================  Notes =====================================


MULTITHREADING

1 : What is Thread  & its types?

- Thread  is smallest executable unit of process. thread in java simply represent a single independent path of execution of process(group of statement). It is the flow of execution, from beginning to end of a task.


Types of Thread :

There are 2 types of thread in java 

- The difference between two is that a user thread will continue to execute until its run() method ends while a daemon thread will be automatically ended when all user threads of a program have ended.

1. User Thread : User threades are threads which are created by user.they are high priority thread.These threads are foreground threads.

2. Daemon Thread : Daemon threads are threads which are mostly created by the JVM. these thread alway run in background. These threads are used to perform some background tasks like garbage collection. Thse threads are less priority. JVM will not wait for these threads to finish their execution. 




2.  How we can prevent thread Execution which methods we use ? 

- By Using 3 method we can 

1. Yield() 

- The yield() method pauses the execution of current thread and allows another thread of equal or higher priority that are waiting to execute. Currently executing thread give up the control of the CPU.  The general form of yield() method is as follows:

-  yield() method causes to pause current executing thread for giving the chance to remaining waiting threads of same priority.

- If there are no waiting thread or all waiting thread have low priority then the same thread will continue its execution once again.

- the Thread which is yieded when it will get chance once again for execution is decided by ThreadSchedular & we can't expect exactly.



2. join() :

- : The join() method is used to make a thread wait for another thread to terminate its process. 

- If a Thread want to wait until completing some other Thread then we should go for join() method.


3. sleep() :

- This method is used to stop the thread.

- If a thread dont want to perform any operation for perticular amount of time(Just pausing) then we should go for sleep() Method.

- When ever we are using sleep() method compulasory we should handle Intereupted Exception otherwise we will get compiletime Error.


3. How to Achieve Inter Thread Communication in Java ?

- Inter thread communication in Java can be achieved by using three methods provided by Object class of java.lang package. They are:

- we want called all below method then we need use synchronize method or block. 

- These methods can be called only from within a synchronized method or synchronized block of code otherwise, an exception named IllegalMonitorStateException is thrown.



1. wait() : wait() method in Java notifies the current thread to give up the monitor (lock) and to go into sleep state until another thread wakes it up by calling notify() method. This method throws InterruptedException.

2. notify() : The notify() method wakes up a single thread that called wait() method on the same object. If more than one thread is waiting, this method will awake one of them. 

3. notifyAll() :The notifyAll() method is used to wake up all threads that called wait() method on the same object. The thread having the highest priority will run first.


------------------



1. Why we Cannot extends multiple classes in Java ? Java  doesn't support Multiple Inheritance.

2. Can we use HashMap in a multi-threaded environment ? No 

3. What is Difference between Runnable and Callable ?

Q. What is fail-Safe & fail-Fast ?


4. What is Spring Boot Actuator ?

5. Does Hibernate Support Native SQL Queries ?

6. What is the difference between first Level cache & second level cache in Hibernate?

 


Q. Is Singleton class threadSafe ?

Answer : No, singleton classes are not inherently thread-safe. Multiple threads can access a singleton class at the same time, which can create multiple objects and violate the singleton pattern. 


- To make a singleton class thread-safe, you can: 

- Create the instance variable at class loading

- Synchronize the getInstance() method

- Use a synchronized block inside the if loop and volatile variable


--------

program

--------

class Singleton {

    private static Singleton instance;


    private Singleton() {}


    public static synchronized Singleton getInstance() {

        if (instance == null) {

            instance = new Singleton();

        }

        return instance;

    }

}






----------------------


Design Pattern  in Java 



link : https://medium.com/gitconnected/low-level-design-series-1-a2a818aeac36


Four Types 

1. Creational 

2. Behaviour 

3. Structural 

4. J2EE



Why these Design Patterns named as GoF?

It was 21 October 1994, when four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, with a foreword by Grady Booch, published a book titled as Design Patterns – Elements of Reusable Object-Oriented Software which launched the concept of Design Pattern in Software design. These four authors are altogether known as the Gang of Four (GoF). Since then, these are called GoF Design Patterns.



Design pattern: what is it and why use it?

- The design pattern is an essential element in object-oriented programming.

- It is a software infrastructure made up of a small number of classes that is used to solve a technical problem.




What are Design Patterns?

A design pattern is a generic repeatable solution to a frequently occurring problem in software design that is used in software engineering.

- The design pattern is a reusable solution to a common problem that occurs in software design.

- Design pattern represent and Idea.


Why use a design pattern?

- The usefulness of using a design pattern is obvious. The design pattern can accelerate the development process. It provides proven development paradigms, which helps save time without having to reinvent patterns every time a problem arises.

- Because the design pattern is created to fix known problems, they can be predicted before they become visible during the implementation process. Again, the design pattern speeds up the development process. Standardization related to the design pattern is also very useful to facilitate code readability.

- Design Patterns help us to solve a programming problem during project development. Moreover, Design Patterns will help us in fixing performance and memory related issues. 



- Java Design Pattern 


Java Design patterns are typically categorized into three main categories:


1. Creational Patterns: 

These patterns deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The main focus is on abstracting the object creation process and making the system independent of how objects are created, composed, and represented. Examples include Singleton, Factory Method, Abstract Factory, Builder, and Prototype patterns.


2. Structural Patterns: These patterns deal with object composition or structure and help to identify simple ways to realize relationships between different entities. They focus on class and object composition and typically involve inheritance to compose interfaces or implementations. Examples include Adapter, Bridge, Composite, Decorator, Facade, Flyweight, and Proxy patterns.


3. Behavioral Patterns: These patterns focus on communication between objects and the responsibilities that are shared between them. They describe not just patterns of objects or classes, but also the patterns of communication between them. Examples include Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor, and Null Object patterns.






What are the advantages/benefits of using Design Patterns?

1) Design Patterns help in finding the solution of a complex problem.

2) Using design patterns, we can make our code loosely-coupled.

3) Furthermore, it will have the option of reusable codes, which reduce the total development cost of the application.

4) Additionally, future developers feel the code more user-friendly.

5) It has all the standard approaches to find out solutions to the common problem of a software.

6) We can use the same pattern repeatedly in multiple projects.

7) Moreover, It helps in refactoring our code in a better way.






1. Singleton Constructor


/*

What is a Singleton Design Pattern?

There are only two points in the definition of a singleton design pattern,

1) There should be only one instance allowed for a class and

2) We should allow global point of access to that single instance.



- Singleton pattern will insure that only one instance of the class will be created by java virtual machine at any point of time. 

- It is used to provide global point of access to the object.Singleton patterns are used in logging, caches, thread pools,getting device driver objects etc.


// steps 


1. private constructors :  if it public then we can create multiple object (Constructor use to initialize of object)

2. Static Instance: - we create static instance varible for holds the instance of the class.

- Within the Singleton class, there is a static member variable that holds the single instance of the class.

3. public static method : this method allow to other classes to acccess the single instance of object. & according to condition object will create once & if we access to get object then we get same object everytime.

4. Lazy initialization :  in lazy initailizatio instance will be created when when we request for it or we can created  at class Loading (eager initialization). 

- Lazy initialization is more prefered to save the resource if the instance is not always needed.


- up to above 4 step is good work its work not single thread & but if we want to use multiple then it will not work its will be create 2 object so in singleton we don't want to more than one object.

5. Make the Access method Synchronized :

In multi-threaded environment it may happen that two or more threads enter the method getInstance() at the same time when Singleton instance is not created, resulting into simultaneous creation of two objects.Such problems can be avoided by defining getInstance() method synchronized.

-  we can use method synchronized Or we can use synchronized Block for Perticular block.



Here are some common use cases for the Singleton design pattern:

1. Database Connections

2. Thread Pools

3. Logging 





2. Factory Design Pattern 

- The Factory design pattern is used when we have a super class with multiple sub-classes and based on input, we need to return one of the sub-classes. This pattern takes out the responsibility of instantiation of a class from a client program to the factory class. 

- Super class in factory pattern can either be an interface, or an abstract class, or a normal Java class.


- The Factory Design Pattern is one of the creational design patterns and a powerful tool for managing object creation in a flexible and organized way, particularly when an application needs to support multiple variations or types of objects.

-  When there is superclass and multiple subclass and we want to get object of subclasses based on input and requirement.

-  Then we create factory class which takes reposibility of creating of class based on input.

Advantages of Factory Desing pattern

1. focus on creating object for interface rather than implementation.

2. Loose coupling more robust code.




3. Abstract Factory Pattern

- Almost similar to Factory Pattern, except the fact that it’s more like factory of factories. If you are familiar with factory design pattern in java, you will notice that we have a single Factory class that returns the different sub-classes based on the input provided. Generally,  factory class uses if-else or switch-case statement to achieve this. However, in Abstract Factory pattern, we get rid of if-else block and have a factory class for each sub-class and then an Abstract Factory class that will return the sub-class, based on the input factory class.


- In fact, An abstract factory is a factory that returns factories. Why is this layer of abstraction useful? A normal factory can be used to create sets of related objects. An abstract factory returns factories. Hence, an abstract factory is used to return factories that can be used to create sets of related objects.

-  The Abstract Factory Pattern is a way of organizing how you create groups of things that are related to each other. It provides a set of rules or instructions that let you create different types of things without knowing exactly what those things are. This helps you keep everything organized and lets you switch between different types easily.


Factory and Abstract Factory are both creational design patterns used in software engineering to handle the instantiation of objects. However, they differ in their implementation and use cases.


1. Factory Pattern:

   - The Factory Pattern is a creational pattern that provides an interface for creating objects but delegates the responsibility of which class to instantiate to its subclasses.

   - It encapsulates the object creation logic in a separate method (or class) rather than creating objects directly using the `new` keyword.

   - It promotes loose coupling by allowing the client code to interact with the factory interface rather than the concrete classes directly.

   - The Factory Pattern is typically used when you have a single factory class producing different types of objects based on a given input.


2. Abstract Factory Pattern:

   - The Abstract Factory Pattern is also a creational pattern, but it provides an interface for creating families of related or dependent objects without specifying their concrete classes.

   - It's an extension of the Factory Pattern and works around the concept of families of objects rather than just individual objects.

   - It defines an abstract factory interface that declares methods for creating the various objects. Each concrete implementation of this interface represents a different factory that produces objects of a particular family.

   - Abstract Factory Pattern is used when you need to create families of related or dependent objects, ensuring that the created objects are compatible.

   - It often involves multiple Factory Patterns working together, with each factory responsible for creating a different kind of object within a family.


Here's a simple analogy to differentiate the two:

- Factory Pattern: Think of a pizza restaurant where you have a single chef (factory) responsible for making different types of pizzas based on the customer's order.

- Abstract Factory Pattern: Now, consider a scenario where you have a pizza restaurant chain. Each branch of the chain has its own chef (factory) but follows a specific style of making pizzas (e.g., Italian, American). The Abstract Factory Pattern helps you manage these different styles of pizza-making across different branches of the chain.


In summary, while both Factory and Abstract Factory patterns deal with object creation, the Factory Pattern is focused on creating individual objects while the Abstract Factory Pattern is focused on creating families of related objects.




4. Builder Design Pattern

- The Builder Design Pattern is a creational pattern used in software design to construct a complex object step by step. 

- It allows the construction of a product in a step-by-step fashion, where the construction process can vary based on the type of product being built. 

- The pattern separates the construction of a complex object from its representation, allowing the same construction process to create different representations.


- while creating object when object contain may attributes there are many problm exists :

1. We have to pass many argument to create object.

2. some parameters might be optional.

3. factory class taked all responsibility for creating object. If the object is heavy then all then all complexity is the part of factory class.


So, in builder pattern be create object step by step and finally return final object with desired values of attributes.


- When to use Builder Design Pattern?

    The Builder design pattern is used when you need to create complex objects with a large number of optional components or configuration parameters. This pattern is particularly useful when an object needs to be constructed step by step, some of the scenarios where the Builder design pattern is beneficial are:

1. Complex Object Construction

2. Avoiding constructors with multiple parameters.

3. Immutable Objects

4. Common Interface for Multiple Representations


- When not to use Builder Design Pattern?

1. Simple Object Construction

2. Performance Concerns.

3. Immutable Objects with Final Fields.

4. Tight Coupling with Product


The intent of the Builder Pattern is to separate the construction of a complex object from its representation, so that the same construction process can create different representations. This type of separation reduces the object size. The design turns out to be more modular with each implementation contained in a different builder object. Therefore, Adding a new implementation (i.e., adding a new builder) becomes easier. Furthermore, the object construction process becomes independent of the components that make up the object. This provides more control over the object construction process.


Steps to create the Pattern

1. First of all, we need to create a static nested class and then copy all the arguments from the outer class to the Builder class. Additionally, we should follow the naming convention. For example, if the class name is Cake, then builder class should be named as CakeBuilder.

2. Next, the Builder class should have a public constructor with all the required attributes as parameters.

3. Builder class should have methods to set the optional parameters and it should return the same Builder object after setting the optional attribute.

4. Finally, we need to provide a build () method in the builder class that will return the Object needed by client program. In order to accomplish this, we need to have a private constructor in the Class with Builder class as argument.




5. Protypes Design Pattern

- Prototype pattern is one of the Creational Design patterns, so it provides a mechanism of object creation. However, Prototype pattern is used when the Object creation is a costly affair. Also, it requires a lot of time and resources and if you have a similar object already existing. Therefore, this pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. Moreover, this pattern uses java cloning to copy the object.


- The concept is to copy an existing object rather than creating a new instance from scratch.bcoz creating new object may be constly.

- This approach saves costly resource and time, especially when object creation is a heavy process.


- Imagine you have an object, let's call it "Prototype". This object is quite complex, and you want to make copies of it, but creating each copy from scratch would be inefficient and time-consuming. So, instead of creating copies by re-creating the whole object every time, you create a prototype, which is essentially a blueprint or template of the original object.


Here's how it works:


1. You start by creating your original object, the prototype.

2. When you need a copy, instead of creating a new object and setting all its properties again, you simply clone the prototype.

3. The clone operation creates a new object with the same properties as the prototype


Object Cloning

The Prototype Pattern works on the Cloning concept. However, in Java, if you’d like to use cloning, you can utilize the clone () method and the Cloneable interface. By default, clone () performs a shallow copy. Moreover, Serializable can be used to simplify deep copying.
















Comments

Popular posts from this blog

1. Collection Framework all in one

4. Real-Time Spring boot Interview Question (GenZ Career)