JAVA

THIS IS NOTES FOR JAVA

























1. What is Java, and why is it popular?


Java is a high-level, object-oriented programming language known for its platform independence via the JVM. Its popularity stems from robust libraries, scalability, and widespread use in enterprise, web, and Android development.



2. What is the Java Virtual Machine (JVM)?


The JVM is an abstract machine that executes Java bytecode, enabling platform independence. It handles memory management, garbage collection, and runtime optimization for Java applications.



3. What is the Java Runtime Environment (JRE)?


The JRE includes the JVM, core libraries, and runtime components needed to run Java applications. It’s a subset of the JDK, sufficient for executing but not developing Java programs.



4. What is the Java Development Kit (JDK)?


The JDK is a software development kit containing the JRE, compiler (javac), and tools like javadoc for developing Java applications. It’s essential for coding, compiling, and running Java programs.



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


The JVM executes bytecode, the JRE provides runtime libraries and the JVM, and the JDK includes the JRE plus development tools. JDK is for development, JRE for running, and JVM for execution.



6. What is platform independence in Java?


Platform independence means Java code runs on any device with a JVM, as bytecode is platform-agnostic. Write once, run anywhere (WORA) is achieved through compilation to bytecode.



7. What is bytecode in Java?


Bytecode is an intermediate, platform-independent representation of a Java program generated by the compiler (javac). The JVM interprets or compiles it to machine code for execution.



8. What are the main features of Java?


Java features include object-oriented programming, platform independence, robust error handling, multithreading, and a rich API. Its simplicity, security, and scalability make it versatile for various applications.



9. What is the difference between C++ and Java?


Java is platform-independent and uses a JVM, while C++ is platform-dependent and compiles to native code. Java has automatic garbage collection, whereas C++ requires manual memory management.



10. What is object-oriented programming (OOP) in Java?


OOP in Java organizes code into objects with attributes and behaviors, using principles like encapsulation, inheritance, polymorphism, and abstraction. It promotes modularity and reusability in software design.



11. What is a class in Java?


A class is a blueprint for creating objects, defining properties (fields) and behaviors (methods). For example, `class Car { String model; void drive() { } }` defines a `Car` class.



12. What is an object in Java?


An object is an instance of a class, representing a specific entity with state and behavior. For example, `Car myCar



13. What is the difference between a class and an object?


A class is a template defining structure and behavior, while an object is a concrete instance of that class. Objects hold actual data and can invoke class methods.



14. What is the `main` method in Java?


The `main` method, `public static void main(String[] args)`, is the entry point for a Java program. It’s called by the JVM to start execution.



15. What is the significance of `public static void` in the `main` method?


`public` makes the method accessible to the JVM, `static` allows it to be called without an instance, and `void` indicates it returns nothing. This ensures the JVM can invoke it directly.



16. What is a constructor in Java?


A constructor is a special method called when an object is instantiated, initializing its state. It has the same name as the class and no return type.



17. What is the default constructor in Java?


The default constructor is a no-argument constructor automatically provided by Java if no constructors are defined. It initializes fields to default values (e.g., `null`, `0`).



18. What is constructor overloading in Java?


Constructor overloading allows multiple constructors with different parameter lists in a class. For example, `Car(String model)` and `Car(String model, int year)` cater to different initialization needs.



19. What is the `this` keyword in Java?


`this` refers to the current object, used to access instance variables or methods or to call other constructors. It resolves ambiguity between instance and local variables.



20. What is the `static` keyword in Java?


`static` indicates that a variable or method belongs to the class, not instances, shared across all objects. For example, `static int count` tracks total instances.



21. What is a static variable in Java?


A static variable is a class-level variable shared by all instances, initialized once at class loading. It’s accessed via the class name, like `ClassName.variable`.



22. What is a static method in Java?


A static method belongs to the class, not instances, and can be called without creating an object. It cannot access non-static fields or methods directly.



23. What is a static block in Java?


A static block, defined with `static { }`, runs once when the class is loaded, initializing static variables or performing setup. It’s useful for complex static initialization.



24. What is encapsulation in Java?


Encapsulation hides a class’s internal details, exposing only necessary parts via public methods. It’s achieved using private fields and public getters/setters for data protection.



25. What is inheritance in Java?


Inheritance allows a class to inherit fields and methods from another class using `extends`. It promotes code reuse, with the subclass inheriting the superclass’s functionality.







26. What is the `extends` keyword in Java?


`extends` specifies that a class inherits from another class, gaining its non-private members. For example, `class Dog extends Animal` makes `Dog` a subclass of `Animal`.



27. What is single inheritance in Java?


Single inheritance means a class can inherit from only one superclass, as Java doesn’t support multiple class inheritance. It simplifies the class hierarchy but allows interface inheritance.



28. What is multiple inheritance, and why doesn’t Java support it?


Multiple inheritance allows a class to inherit from multiple classes, but Java prohibits it to avoid complexity and ambiguity (e.g., diamond problem). Interfaces provide a workaround.



29. What is the diamond problem in Java?


The diamond problem occurs when a class inherits conflicting methods from multiple superclasses via multiple inheritance. Java avoids this by disallowing multiple class inheritance, using interfaces instead.



30. What is polymorphism in Java?


Polymorphism allows objects to be treated as instances of their superclass, with method overriding or overloading enabling different behaviors. It’s achieved via inheritance or interfaces.



31. What is method overloading in Java?


Method overloading allows multiple methods with the same name but different parameter lists (type, number, or order). For example, `add(int, int)` and `add(double, double)`.



32. What is method overriding in Java?


Method overriding allows a subclass to redefine a superclass method with the same signature. It’s used for runtime polymorphism, requiring the `@Override` annotation for clarity.



33. What is the `@Override` annotation in Java?


`@Override` indicates that a method overrides a superclass method, ensuring compile-time checks for correct signature matching. It improves code readability and prevents errors.



34. What is abstraction in Java?


Abstraction hides implementation details, exposing only essential features via abstract classes or interfaces. It simplifies complex systems, focusing on what an object does, not how.



35. What is an abstract class in Java?


An abstract class, declared with `abstract`, cannot be instantiated and may contain abstract methods or concrete methods. Subclasses must implement its abstract methods.



36. What is an abstract method in Java?


An abstract method, declared with `abstract` and no body, must be implemented by non-abstract subclasses. It defines a contract for subclasses in an abstract class.



37. What is an interface in Java?


An interface defines a contract of methods that implementing classes must provide, declared with `interface`. It supports multiple inheritance and abstraction, often used for loose coupling.



38. What is the difference between an abstract class and an interface?


An abstract class can have concrete methods and state, while an interface (pre-Java 8) has only abstract methods. A class can implement multiple interfaces but extend one abstract class.



39. What are default methods in Java interfaces?


Default methods, introduced in Java 8, provide a default implementation in interfaces using `default`. They allow interface evolution without breaking implementing classes.



40. What are static methods in Java interfaces?


Static methods in interfaces, introduced in Java 8, belong to the interface and are called via the interface name. They’re used for utility functions, not tied to instances.



41. What is the `implements` keyword in Java?


`implements` specifies that a class adheres to an interface, requiring it to provide implementations for all interface methods. For example, `class MyClass implements MyInterface`.



42. What is the `super` keyword in Java?


`super` accesses superclass members or calls its constructor from a subclass. For example, `super.method()` invokes the superclass’s method, resolving overridden names.



43. What is a final class in Java?


A final class, declared with `final`, cannot be subclassed, preventing inheritance. For example, `final class MyClass` ensures no class can extend it.



44. What is a final method in Java?


A final method, declared with `final`, cannot be overridden by subclasses. It ensures the method’s behavior remains unchanged in derived classes.



45. What is a final variable in Java?


A final variable, declared with `final`, can be assigned only once, acting as a constant. For example, `final int MAX



46. What is the `Object` class in Java?


The `Object` class is the root of Java’s class hierarchy, with every class implicitly extending it. It provides methods like `toString()`, `equals()`, and `hashCode()`.



47. What is the `toString()` method in Java?


`toString()` returns a string representation of an object, typically overridden to provide meaningful details. By default, `Object`’s `toString()` returns the class name and hash code.



48. What is the `equals()` method in Java?


`equals()` compares two objects for equality, typically overridden to compare content, not just references. `Object`’s default `equals()` checks reference equality (`



49. What is the `hashCode()` method in Java?


`hashCode()` returns an integer hash code for an object, used in hash-based collections like `HashMap`. It must be consistent with `equals()` for correct behavior.



50. What is the contract between `equals()` and `hashCode()`?


If two objects are equal by `equals()`, they must have the same `hashCode()`. This ensures consistent behavior in hash-based collections, though equal hash codes don’t imply equality.







51. What is the `clone()` method in Java?


`clone()` creates a copy of an object, defined in `Object` but requires implementing the `Cloneable` interface. It’s overridden for deep or shallow copying as needed.



52. What is the `Cloneable` interface in Java?


`Cloneable` is a marker interface indicating a class supports cloning via `clone()`. Without implementing it, `clone()` throws `CloneNotSupportedException`.



53. What is the difference between shallow and deep copying in Java?


Shallow copying copies an object’s fields, but references point to the same objects, while deep copying creates new copies of referenced objects. Deep copying requires custom logic or serialization.



54. What is garbage collection in Java?


Garbage collection automatically reclaims memory by freeing objects no longer referenced, managed by the JVM. It uses algorithms like mark-and-sweep to identify unreachable objects.



55. What is the `finalize()` method in Java?


`finalize()`, deprecated since Java 9, was called by the garbage collector before reclaiming an object, allowing cleanup. It’s unreliable, and `try-with-resources` is preferred for resource management.



56. What is the `System.gc()` method in Java?


`System.gc()` requests garbage collection, but it’s only a hint to the JVM, not guaranteed to run immediately. It’s rarely used, as the JVM manages memory automatically.



57. What are the types of garbage collectors in Java?


Java’s garbage collectors include Serial, Parallel, CMS (Concurrent Mark-Sweep), and G1 (Garbage First). Each balances throughput, latency, and pause times for different workloads.



58. What is the G1 garbage collector in Java?


G1 (Garbage First) is a low-pause, region-based garbage collector, prioritizing areas with the most garbage. It’s the default since Java 9, suitable for large heaps.



59. What is a memory leak in Java?


A memory leak occurs when objects remain in memory despite no longer being needed, often due to unclosed resources or static references. Tools like profilers help detect leaks.



60. What is the Java Memory Model (JMM)?


The JMM defines how threads interact with memory, ensuring visibility and ordering of operations. It governs synchronization, volatile variables, and atomicity in multithreaded programs.



61. What is a Java package?


A package is a namespace for organizing classes and interfaces, like `java.util`, preventing name conflicts. It’s declared with `package` and corresponds to a directory structure.



62. What is the `import` statement in Java?


`import` makes classes or packages available in a Java file, like `import java.util.List`. It simplifies referencing classes without fully qualified names.



63. What is a fully qualified name in Java?


A fully qualified name includes the package and class name, like `java.util.ArrayList`. It’s used to avoid ambiguity when classes have the same name in different packages.



64. What is the `classpath` in Java?


The classpath is a parameter specifying where the JVM looks for class files and resources, set via `-cp` or the `CLASSPATH` environment variable. It includes directories and JARs.



65. What is a JAR file in Java?


A JAR (Java Archive) file bundles Java classes, resources, and metadata into a compressed file, typically with a `.jar` extension. It’s used for distribution and execution.



66. What is a WAR file in Java?


A WAR (Web Archive) file packages a web application, including servlets, JSPs, and resources, for deployment on a web server like Tomcat. It’s a specialized JAR file.



67. What is an EAR file in Java?


An EAR (Enterprise Archive) file packages multiple modules, like WARs and EJB JARs, for deployment on a Java EE application server. It organizes enterprise applications.



68. What is the `public` access modifier in Java?


`public` makes a class, method, or field accessible from anywhere. For example, `public class MyClass` allows instantiation from any package.



69. What is the `private` access modifier in Java?


`private` restricts access to a method or field to within its own class. For example, `private int x` is only accessible inside the class.



70. What is the `protected` access modifier in Java?


`protected` allows access within the same package and in subclasses, even in different packages. It’s used for controlled inheritance, like `protected void method()`.



71. What is the default access modifier in Java?


The default access modifier (package-private) applies when no modifier is specified, restricting access to the same package. For example, `void method()` is package-private.



72. What is a Java exception?


An exception is an event disrupting normal program flow, like `NullPointerException`. Java handles exceptions using `try-catch` blocks to prevent crashes.



73. What is the difference between checked and unchecked exceptions?


Checked exceptions (e.g., `IOException`) must be declared or handled, enforced at compile-time, while unchecked exceptions (e.g., `RuntimeException`) don’t require explicit handling. Unchecked are typically programming errors.



74. What is the `try-catch` block in Java?


A `try-catch` block handles exceptions, with `try` enclosing risky code and `catch` handling specific exceptions. For example, `catch (IOException e)` manages file errors.



75. What is the `finally` block in Java?


`finally` executes code after `try-catch`, regardless of whether an exception occurs, often for cleanup like closing resources. It’s guaranteed to run unless the JVM exits.







76. What is the `try-with-resources` statement in Java?


`try-with-resources`, introduced in Java 7, automatically closes resources implementing `AutoCloseable`, like files. For example, `try (FileReader fr



77. What is the `throws` keyword in Java?


`throws` declares checked exceptions a method might throw, like `void read() throws IOException`. It informs callers to handle or propagate the exception.



78. What is the `throw` keyword in Java?


`throw` manually triggers an exception, like `throw new IllegalArgumentException(\"Invalid input\")`. It’s used to signal errors explicitly in code logic.



79. What is a custom exception in Java?


A custom exception is a user-defined exception class extending `Exception` or `RuntimeException`, like `class MyException extends Exception`. It’s used for application-specific errors.



80. What is the `Exception` class in Java?


`Exception` is the base class for all checked and unchecked exceptions, except errors. It’s extended for custom exceptions and caught in `try-catch` blocks.



81. What is the `RuntimeException` class in Java?


`RuntimeException` is the base class for unchecked exceptions, like `NullPointerException`, not requiring explicit handling. It’s typically used for programming errors.



82. What is the `Error` class in Java?


`Error` represents serious issues, like `OutOfMemoryError`, that applications shouldn’t catch. It’s distinct from `Exception`, indicating unrecoverable JVM problems.



83. What is a `NullPointerException` in Java?


`NullPointerException` is an unchecked exception thrown when accessing a method or field on a `null` reference. It’s a common error requiring null checks.



84. What is an `ArrayIndexOutOfBoundsException` in Java?


`ArrayIndexOutOfBoundsException` is thrown when accessing an array with an invalid index, like `array[10]` for a 5-element array. It’s an unchecked exception.



85. What is a `ClassCastException` in Java?


`ClassCastException` is thrown when casting an object to an incompatible type, like `(String) obj` when `obj` isn’t a `String`. It’s unchecked and indicates type errors.



86. What is a `IllegalArgumentException` in Java?


`IllegalArgumentException` is an unchecked exception thrown when a method receives an invalid argument, like negative values where positive is expected. It’s used for input validation.



87. What is multithreading in Java?


Multithreading allows concurrent execution of multiple threads within a program, improving performance for I/O or parallel tasks. Java supports it via `Thread` or `Runnable`.



88. What is a thread in Java?


A thread is a lightweight unit of execution within a process, sharing the same memory. Java creates threads by extending `Thread` or implementing `Runnable`.



89. What is the difference between `Thread` and `Runnable` in Java?


`Thread` is a class for creating threads, while `Runnable` is an interface with a `run()` method. `Runnable` is preferred for flexibility, allowing classes to extend other classes.



90. How do you create a thread in Java?


Create a thread by extending `Thread` and overriding `run()`, or implementing `Runnable` and passing it to a `Thread` object. Call `start()` to begin execution.



91. What is the `start()` method in Java threads?


`start()` initiates a thread’s execution, calling its `run()` method in a separate stack. Directly calling `run()` executes it in the current thread, not concurrently.



92. What is the `run()` method in Java threads?


`run()` contains the thread’s logic, defined in a `Thread` subclass or `Runnable`. It’s executed when `start()` is called, running in a separate thread.



93. What is the `sleep()` method in Java?


`Thread.sleep(millis)` pauses the current thread for a specified time, allowing others to run. It throws `InterruptedException` and doesn’t release locks.



94. What is the `join()` method in Java?


`join()` makes the calling thread wait for the target thread to complete, ensuring sequential execution. For example, `thread.join()` waits until `thread` finishes.



95. What is the `yield()` method in Java?


`Thread.yield()` hints the scheduler to pause the current thread, giving others a chance to run. Its effect depends on the JVM and is rarely used.



96. What is thread priority in Java?


Thread priority, set via `setPriority()`, influences scheduling, with values from `MIN_PRIORITY` (1) to `MAX_PRIORITY` (10). Higher priority threads may run before lower ones, but it’s not guaranteed.



97. What is a daemon thread in Java?


A daemon thread runs in the background (e.g., garbage collector), set via `setDaemon(true)` before starting. The JVM exits when only daemon threads remain.



98. What is synchronization in Java?


Synchronization ensures thread-safe access to shared resources using `synchronized` blocks or methods. It prevents race conditions by allowing only one thread to execute critical sections.



99. What is a `synchronized` block in Java?


A `synchronized` block restricts access to a code section, locking on an object, like `synchronized(obj) { }`. It’s more granular than synchronizing an entire method.



100. What is a `synchronized` method in Java?


A `synchronized` method locks the entire method, using the object’s monitor (or class for static methods). It ensures only one thread executes it at a time.







101. What is the `volatile` keyword in Java?


`volatile` ensures a variable’s value is always read from and written to main memory, preventing thread-local caching. It’s used for visibility in multithreaded programs.



102. What is a `Lock` interface in Java?


The `Lock` interface, in `java.util.concurrent.locks`, provides flexible locking mechanisms, like `ReentrantLock`, over `synchronized`. It supports try-locks and interruptible locks.



103. What is a `ReentrantLock` in Java?


`ReentrantLock` is a concrete `Lock` implementation allowing a thread to reacquire the same lock multiple times. It offers features like fairness and try-locking.



104. What is the `Condition` interface in Java?


`Condition`, used with `Lock`, enables precise thread coordination, like `await()` and `signal()`, similar to `wait()` and `notify()`. It’s created via `Lock.newCondition()`.



105. What is the difference between `wait()` and `sleep()` in Java?


`wait()` releases the monitor and pauses a thread, requiring `notify()`, while `sleep()` pauses without releasing locks. `wait()` is for synchronization, `sleep()` for delays.



106. What is the `notify()` method in Java?


`notify()` wakes one thread waiting on an object’s monitor, typically used with `wait()` in synchronized blocks. It’s non-deterministic about which thread resumes.



107. What is the `notifyAll()` method in Java?


`notifyAll()` wakes all threads waiting on an object’s monitor, allowing them to compete for the lock. It’s used when multiple threads need to resume.



108. What is a deadlock in Java?


A deadlock occurs when multiple threads hold locks and wait for each other’s locks, causing a permanent stall. It’s prevented by lock ordering or timeouts.



109. What is a race condition in Java?


A race condition occurs when multiple threads access shared resources concurrently, leading to unpredictable results. Synchronization or atomic operations prevent it.



110. What is the `java.util.concurrent` package?


`java.util.concurrent` provides utilities for concurrent programming, including thread pools (`ExecutorService`), locks (`ReentrantLock`), and concurrent collections (`ConcurrentHashMap`). It simplifies multithreading.



111. What is an `ExecutorService` in Java?


`ExecutorService` manages a pool of threads for executing tasks, like `Executors.newFixedThreadPool()`. It abstracts thread creation and supports task submission via `submit()` or `execute()`.



112. What is a `Callable` interface in Java?


`Callable` is similar to `Runnable` but can return a result and throw checked exceptions, used with `ExecutorService`. Its `call()` method returns a value.



113. What is a `Future` in Java?


`Future` represents the result of an asynchronous task, like a `Callable` submitted to `ExecutorService`. It allows checking status or retrieving results via `get()`.



114. What is a `ThreadPool` in Java?


A thread pool, managed by `ExecutorService`, reuses a fixed number of threads to execute tasks, reducing overhead. It’s created via `Executors.newFixedThreadPool(n)`.



115. What is the `ForkJoinPool` in Java?


`ForkJoinPool`, introduced in Java 7, is a thread pool for parallel tasks, using work-stealing to balance workloads. It’s ideal for recursive divide-and-conquer algorithms.



116. What is the `CompletableFuture` in Java?


`CompletableFuture`, introduced in Java 8, supports asynchronous programming with chaining and composition, like `thenApply()`. It simplifies non-blocking task coordination.



117. What is a `ConcurrentHashMap` in Java?


`ConcurrentHashMap` is a thread-safe `Map` allowing concurrent reads and writes without full locking, using segmentation. It’s used in multithreaded applications for high performance.



118. What is a `CopyOnWriteArrayList` in Java?


`CopyOnWriteArrayList` is a thread-safe `List` that creates a new copy on each write, ideal for read-heavy scenarios. Writes are expensive but reads are lock-free.



119. What is a `BlockingQueue` in Java?


`BlockingQueue` is a thread-safe queue where producers block if full and consumers block if empty, like `ArrayBlockingQueue`. It’s used for producer-consumer patterns.



120. What is the `Collections` class in Java?


`Collections` provides static utility methods for manipulating collections, like `Collections.sort()`, `Collections.synchronizedList()`, or `Collections.unmodifiableList()`. It complements the `Collection` interface.



121. What is the `Collection` interface in Java?


`Collection` is the root interface for collections like `List`, `Set`, and `Queue`, defining methods like `add()`, `remove()`, and `size()`. It’s extended by specific collection types.



122. What is the `List` interface in Java?


`List` is an ordered collection allowing duplicates, with implementations like `ArrayList` and `LinkedList`. It supports positional access and iteration via indices.



123. What is the `Set` interface in Java?


`Set` is a collection without duplicates, with implementations like `HashSet` and `TreeSet`. It’s used for unique elements, with `TreeSet` maintaining order.



124. What is the `Map` interface in Java?


`Map` stores key-value pairs with unique keys, like `HashMap` or `TreeMap`. It supports fast lookups but isn’t part of the `Collection` hierarchy.



125. What is the difference between `ArrayList` and `LinkedList`?


`ArrayList` uses a dynamic array, offering fast random access but slow insertions/deletions, while `LinkedList` uses a doubly-linked list, better for frequent modifications but slower access.







126. What is a `HashMap` in Java?


`HashMap` is a `Map` implementation using a hash table for key-value pairs, allowing `null` keys/values. It offers constant-time performance for basic operations, assuming good hashing.



127. What is a `TreeMap` in Java?


`TreeMap` is a `Map` implementation using a red-black tree, maintaining keys in sorted order. It’s slower than `HashMap` but supports ordered traversal.



128. What is a `HashSet` in Java?


`HashSet` is a `Set` implementation using a hash table, ensuring unique elements with no order. It offers constant-time performance for add/remove operations.



129. What is a `TreeSet` in Java?


`TreeSet` is a `Set` implementation using a red-black tree, maintaining elements in sorted order. It’s slower than `HashSet` but supports ordered operations.



130. What is the difference between `HashMap` and `Hashtable`?


`HashMap` is non-synchronized, allows `null` keys/values, and is faster, while `Hashtable` is synchronized, thread-safe, and doesn’t allow `nulls`. `ConcurrentHashMap` is preferred for modern concurrency.



131. What is the `Iterator` interface in Java?


`Iterator` allows iterating over collections, providing `hasNext()`, `next()`, and `remove()` methods. It’s obtained via `collection.iterator()` for safe traversal.



132. What is the `ListIterator` interface in Java?


`ListIterator` extends `Iterator` for `List` collections, adding bidirectional traversal (`previous()`) and modification (`set()`, `add()`). It’s obtained via `list.listIterator()`.



133. What is the `Comparable` interface in Java?


`Comparable` defines a natural ordering for objects via `compareTo()`, used by `TreeSet` or `Collections.sort()`. Classes like `String` implement it for sorting.



134. What is the `Comparator` interface in Java?


`Comparator` defines custom ordering via `compare()`, used for sorting when `Comparable` isn’t suitable. It’s passed to `Collections.sort()` or `TreeMap`.



135. What is the difference between `Comparable` and `Comparator`?


136. `Comparable` is implemented by a class for natural ordering (`compareTo()`), while `Comparator` is a separate class for custom ordering (`compare()`). `Comparator` is more flexible.


137. What is a `PriorityQueue` in Java?


`PriorityQueue` is a queue where elements are ordered by natural ordering or a `Comparator`, with the smallest element dequeued first. It’s used for priority-based tasks.



138. What is a `Deque` in Java?


`Deque` (double-ended queue) allows adding/removing elements from both ends, implemented by `ArrayDeque` or `LinkedList`. It’s used for stacks or queues.



139. What is a `Stack` class in Java?


`Stack` is a legacy class extending `Vector`, implementing a last-in, first-out (LIFO) structure. `ArrayDeque` is preferred for modern stack implementations due to performance.



140. What is the `Arrays` class in Java?


`Arrays` provides static utility methods for arrays, like `Arrays.sort()`, `Arrays.binarySearch()`, or `Arrays.asList()`. It simplifies array manipulation and conversion.



141. What is a Java array?


A Java array is a fixed-size, homogeneous collection of elements, like `int[] arr



142. What is the difference between an array and an `ArrayList`?


An array has a fixed size and primitive support, while `ArrayList` is dynamic, resizable, and works with objects. `ArrayList` offers methods like `add()` or `remove()`.



143. What is a `String` in Java?


`String` is an immutable class representing a sequence of characters, like `String s



144. What is the string pool in Java?


The string pool is a special memory area in the heap for storing unique `String` literals, like `\"hello\"`. It reduces memory usage by reusing identical strings.



145. What is the `StringBuilder` class in Java?


`StringBuilder` is a mutable class for building strings efficiently, unlike immutable `String`. It’s used for frequent concatenations, like `builder.append(\"text\")`.



146. What is the `StringBuffer` class in Java?


`StringBuffer` is a thread-safe, mutable class for string manipulation, similar to `StringBuilder`. It’s slower due to synchronization, used in multithreaded contexts.



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


`String` is immutable, `StringBuilder` is mutable and non-thread-safe, and `StringBuffer` is mutable and thread-safe. Use `StringBuilder` for single-threaded string operations.



148. What is the `toString()` method in `String`?


`String`’s `toString()` returns the string itself, as it’s already a string representation. It’s rarely overridden, unlike in custom classes where it’s customized.



149. What is the `intern()` method in `String`?


`intern()` adds a string to the string pool or returns an existing pooled string, ensuring a single copy. It’s used for memory optimization, like `str.intern()`.



150. What is a Java enum?


An enum, declared with `enum`, is a type-safe set of named constants, like `enum Color {RED, BLUE}`. It can have fields, methods, and constructors.







151. What is the `EnumSet` class in Java?


`EnumSet` is a specialized `Set` for enums, offering high performance with bit vectors. It’s used for efficient enum collections, like `EnumSet.of(Color.RED)`.



152. What is the `EnumMap` class in Java?


`EnumMap` is a specialized `Map` with enum keys, offering compact, efficient storage. It’s faster than `HashMap` for enums, like `EnumMap`.



153. What is a Java annotation?


An annotation, like `@Override`, provides metadata about code, processed at compile-time or runtime. It’s used for configuration, validation, or framework integration.



154. What are built-in annotations in Java?


Built-in annotations include `@Override`, `@Deprecated`, and `@SuppressWarnings`, affecting compilation or runtime behavior. They’re defined in `java.lang` for common tasks.



155. What is a custom annotation in Java?


A custom annotation is user-defined using `@interface`, like `@interface MyAnnotation`. It’s used with reflection for frameworks or custom processing.



156. What is the `@Retention` annotation in Java?


`@Retention` specifies how long a custom annotation is retained: `SOURCE`, `CLASS`, or `RUNTIME`. For example, `@Retention(RetentionPolicy.RUNTIME)` allows runtime reflection.



157. What is the `@Target` annotation in Java?


`@Target` restricts where a custom annotation can be applied, like `METHOD` or `TYPE`. For example, `@Target(ElementType.METHOD)` limits it to methods.



158. What is reflection in Java?


Reflection allows inspecting and modifying classes, methods, or fields at runtime, using `java.lang.reflect`. It’s used in frameworks like Spring but can be slow.



159. What is the `Class` class in Java?


`Class` represents a class or interface at runtime, obtained via `.class` or `Class.forName()`. It’s used in reflection to access metadata or instantiate objects.



160. What is the `getClass()` method in Java?


`getClass()`, defined in `Object`, returns the runtime class of an object, like `obj.getClass()`. It’s used for type checking or reflection.



161. What is a Java generic?


Generics enable type-safe collections, like `List`, ensuring compile-time type checking. They eliminate casting and improve code reusability.



162. What is a type parameter in Java generics?


A type parameter, like ``, is a placeholder for a type in generic classes or methods, like `class Box`. It’s specified when instantiating, like `Box`.



163. What is a bounded type parameter in Java?


A bounded type parameter restricts a generic type, like ``, ensuring `T` is a `Number` or its subclass. It allows access to superclass methods.



164. What is a wildcard in Java generics?


A wildcard, like `List`, represents an unknown type, used for flexibility. Bounded wildcards, like `List`, restrict types to subclasses.



165. What is the difference between `List` and `List`?


`List` accepts any type but is read-only for safety, while `List` accepts any object but allows modifications. `List` is more restrictive for type safety.



166. What is type erasure in Java?


Type erasure removes generic type information at runtime, replacing type parameters with `Object` or bounds. It ensures backward compatibility but limits runtime reflection.



167. What is a raw type in Java?


A raw type is a generic class used without type parameters, like `List` instead of `List`. It’s unsafe, causing warnings, and should be avoided.



168. What is the `Serializable` interface in Java?


`Serializable` is a marker interface enabling objects to be serialized into a byte stream for storage or transmission. Classes must implement it for serialization.



169. What is serialization in Java?


Serialization converts an object into a byte stream for saving or sending, using `ObjectOutputStream`. It requires the object to implement `Serializable`.



170. What is deserialization in Java?


Deserialization reconstructs an object from a byte stream, using `ObjectInputStream`. It reverses serialization, restoring the object’s state if `Serializable` is implemented.



171. What is the `transient` keyword in Java?


`transient` prevents a field from being serialized, like `transient int password`. It’s used to exclude sensitive or non-serializable data during serialization.



172. What is the `Externalizable` interface in Java?


`Externalizable` extends `Serializable`, allowing custom serialization via `writeExternal()` and `readExternal()`. It gives finer control but requires manual implementation.



173. What is a Java stream?


Java streams, introduced in Java 8, process sequences of elements, like collections, using functional operations (`map`, `filter`). They support lazy evaluation and parallel processing.



174. What is the `Stream` interface in Java?


`Stream` represents a sequence of elements supporting functional-style operations, like `stream().map()`. It’s created from collections or arrays, used for data processing.



175. What is the difference between intermediate and terminal stream operations?


Intermediate operations, like `map()` or `filter()`, transform a stream and are lazy, while terminal operations, like `collect()` or `forEach()`, produce a result and trigger execution.







176. What is a `Collector` in Java streams?


A `Collector` defines how to collect stream elements into a result, like `Collectors.toList()`. It’s used in `collect()` for aggregating or grouping data.



177. What is the `Optional` class in Java?


`Optional`, introduced in Java 8, wraps a value that may be `null`, encouraging safe handling via `orElse()` or `ifPresent()`. It reduces `NullPointerException` risks.



178. What is a lambda expression in Java?


A lambda expression, like `(x, y) -> x + y`, is a concise way to represent a functional interface’s method. Introduced in Java 8, it enables functional programming.



179. What is a functional interface in Java?


A functional interface has exactly one abstract method, like `Runnable` or `Predicate`, often annotated with `@FunctionalInterface`. It’s used with lambda expressions.



180. What is the `Function` interface in Java?


`Function` represents a function transforming input `T` to output `R`, via `apply()`. It’s used in streams or functional programming, like `Function`.



181. What is the `Predicate` interface in Java?


`Predicate` tests a condition on input `T`, returning a boolean via `test()`. It’s used in stream filtering, like `Predicate isEven



182. What is the `Consumer` interface in Java?


`Consumer` performs an action on input `T` without returning a result, via `accept()`. It’s used in `forEach()`, like `Consumer print



183. What is the `Supplier` interface in Java?


`Supplier` provides a value of type `T` via `get()`, with no input. It’s used for lazy initialization, like `Supplier getName



184. What is method reference in Java?


Method reference, like `Class::method`, is a shorthand for lambda expressions, introduced in Java 8. It simplifies code, like `System.out::println` for `Consumer`.



185. What is the `java.time` package in Java?


`java.time`, introduced in Java 8, provides modern date and time APIs, like `LocalDate` and `ZonedDateTime`. It’s immutable and replaces `java.util.Date`.



186. What is `LocalDate` in Java?


`LocalDate` represents a date without time or timezone, like `LocalDate.now()`. It’s used for date operations, like `plusDays()` or formatting.



187. What is `LocalTime` in Java?


`LocalTime` represents a time without date or timezone, like `LocalTime.of(14, 30)`. It’s used for time-specific operations, like `plusHours()`.



188. What is `LocalDateTime` in Java?


`LocalDateTime` combines date and time without timezone, like `LocalDateTime.now()`. It’s used for general date-time operations, like scheduling or logging.



189. What is `ZonedDateTime` in Java?


`ZonedDateTime` represents a date-time with a timezone, like `ZonedDateTime.now(ZoneId.of(\"UTC\"))`. It’s used for global applications handling timezone conversions.



190. What is the `DateTimeFormatter` in Java?


`DateTimeFormatter` formats and parses date-time objects, like `DateTimeFormatter.ofPattern(\"yyyy-MM-dd\")`. It’s used with `java.time` classes for custom string representations.



191. What is the `Files` class in Java?


`Files` provides static methods for file operations, like `Files.readAllLines()` or `Files.createDirectory()`. Introduced in Java 7, it simplifies NIO file handling.



192. What is Java NIO?


Java NIO (New I/O), in `java.nio`, provides non-blocking I/O, channels, buffers, and file system APIs. It’s more scalable than `java.io` for high-performance applications.



193. What is a `Path` in Java NIO?


`Path` represents a file system path, like `Paths.get(\"file.txt\")`, used with `Files` for operations. It’s platform-independent, replacing `File` in modern code.



194. What is a `Channel` in Java NIO?


A `Channel` is a conduit for I/O operations, like reading or writing, used with buffers. For example, `FileChannel` handles file I/O efficiently.



195. What is a `Buffer` in Java NIO?


A `Buffer` is a container for data in NIO, like `ByteBuffer`, used with channels for I/O. It manages position, limit, and capacity for efficient data transfer.



196. What is the `Selector` in Java NIO?


`Selector` enables non-blocking I/O by monitoring multiple channels for events, like `Selector.open()`. It’s used in scalable servers handling many connections.



197. What is the `Servlet` in Java?


A `Servlet` is a Java class handling HTTP requests and responses in a web application, extending `HttpServlet`. It’s deployed in a servlet container like Tomcat.



198. What is a `JSP` in Java?


JavaServer Pages (JSP) is a technology for dynamic web content, combining HTML and Java code. It’s compiled into servlets for server-side processing.



199. What is the `Spring` framework in Java?


Spring is a modular framework for enterprise Java, providing dependency injection, MVC, and data access. It simplifies development with annotations like `@Autowired`.



200. What is dependency injection in Spring?


Dependency injection in Spring automatically provides dependencies to objects, typically via `@Autowired`. It reduces coupling, managed by the Spring IoC container.







201. What is the Spring IoC container?


The Spring IoC (Inversion of Control) container manages bean creation, wiring, and lifecycle. It uses configuration (XML, annotations, or Java) to inject dependencies.



202. What is a Spring Bean?


A Spring Bean is an object managed by the Spring IoC container, defined via `@Bean`, `@Component`, or XML. It’s instantiated, configured, and wired automatically.



203. What is the `@Autowired` annotation in Spring?


`@Autowired` injects dependencies automatically, like a service into a controller, by type or name. It’s used on fields, constructors, or setters in Spring beans.



204. What is Spring Boot?


Spring Boot is a framework simplifying Spring application setup with auto-configuration, embedded servers, and starters. It enables rapid development of production-ready applications.



205. What is a Spring Boot starter?


A Spring Boot starter is a dependency aggregating libraries for specific functionality, like `spring-boot-starter-web` for web apps. It simplifies dependency management.



206. What is the `@SpringBootApplication` annotation?


`@SpringBootApplication` combines `@EnableAutoConfiguration`, `@ComponentScan`, and `@Configuration`, marking the main class of a Spring Boot application. It triggers auto-configuration and scanning.



207. What is Hibernate in Java?


Hibernate is an ORM (Object-Relational Mapping) framework mapping Java objects to database tables, simplifying data access. It uses annotations like `@Entity` for configuration.



208. What is an `@Entity` in Hibernate?


`@Entity` marks a Java class as a database entity, mapping it to a table. It’s used with Hibernate to persist objects, requiring a primary key (`@Id`).



209. What is the `SessionFactory` in Hibernate?


`SessionFactory` is a thread-safe, immutable factory creating `Session` objects for database operations in Hibernate. It’s configured once and reused across the application.



210. What is a `Session` in Hibernate?


`Session` is a lightweight object for database operations, like saving or querying entities, obtained from `SessionFactory`. It represents a single unit of work.



211. What is the `Criteria` API in Hibernate?


The Criteria API builds type-safe, programmatic queries for Hibernate, like `CriteriaBuilder` for dynamic queries. It’s an alternative to HQL for complex searches.



212. What is HQL in Hibernate?


HQL (Hibernate Query Language) is an object-oriented query language, similar to SQL, for querying entities. For example, `from User where id



213. What is the `JPA` in Java?


Java Persistence API (JPA) is a specification for ORM, defining standards for mapping and querying databases. Hibernate is a popular JPA implementation.



214. What is the `EntityManager` in JPA?


`EntityManager` manages entity persistence in JPA, providing methods like `persist()` or `find()`. It’s similar to Hibernate’s `Session`, used in JPA applications.



215. What is the `Persistence.xml` file in JPA?


`Persistence.xml` configures JPA persistence units, specifying database connections, providers (e.g., Hibernate), and entity classes. It’s used in Java EE or standalone apps.



216. What is a design pattern in Java?


A design pattern is a reusable solution to common software design problems, like Singleton or Factory. It improves code structure, maintainability, and scalability.



217. What is the Singleton pattern in Java?


The Singleton pattern ensures a class has one instance, accessed globally, often via a static method. It’s implemented with a private constructor and lazy initialization.



218. What is the Factory pattern in Java?


The Factory pattern creates objects without exposing instantiation logic, using a factory method or class. It’s used for flexible object creation, like `ShapeFactory`.



219. What is the Observer pattern in Java?


The Observer pattern defines a one-to-many dependency where objects (observers) are notified of state changes in a subject. Java’s `Observable` and `Observer` support it.



220. What is the MVC pattern in Java?


MVC (Model-View-Controller) separates data (Model), presentation (View), and logic (Controller). In Java, frameworks like Spring MVC implement it for web applications.



221. What is the `Comparable` interface used for in sorting?


`Comparable` enables custom sorting by implementing `compareTo()`, used by `Collections.sort()` or `TreeSet`. It defines a natural order, like sorting `Person` by age.



222. What is the `Comparator` interface used for in sorting?


`Comparator` provides custom sorting via `compare()`, used when `Comparable` isn’t suitable or multiple orders are needed. It’s passed to `Collections.sort()` or `TreeMap`.



223. What is a Java module?


A Java module, introduced in Java 9, is a named, encapsulated group of packages defined in `module-info.java`. It enhances modularity with `exports` and `requires` directives.



224. What is the `module-info.java` file?


`module-info.java` defines a Java module, specifying its name, dependencies (`requires`), and exported packages (`exports`). It’s used in the Java Platform Module System (JPMS).



225. What is the `exports` directive in a Java module?


`exports` in `module-info.java` makes a package’s public types accessible to other modules, like `exports com.example`. It controls encapsulation in modular Java.







226. What is the `requires` directive in a Java module?


`requires` in `module-info.java` declares a module’s dependency on another module, like `requires java.sql`. It ensures the dependent module is available at runtime.



227. What is the `jdeps` tool in Java?


`jdeps` analyzes class or JAR dependencies, identifying used modules or packages, like `jdeps myapp.jar`. It’s used for migration to Java modules or dependency auditing.



228. What is the `jlink` tool in Java?


`jlink` creates a custom runtime image with only required modules, like `jlink --module-path mods --add-modules myapp`. It reduces Java application size for deployment.



229. What is the `var` keyword in Java?


`var`, introduced in Java 10, infers local variable types, like `var list



230. What is a record in Java?


A record, introduced in Java 14, is a concise class for immutable data, like `record Point(int x, int y)`. It auto-generates constructors, getters, and `equals()`.



231. What is a sealed class in Java?


A sealed class, introduced in Java 17, restricts which classes can extend or implement it, using `sealed` and `permits`. It enhances control over inheritance hierarchies.



232. What is a switch expression in Java?


A switch expression, introduced in Java 14, returns a value using `yield` or arrow syntax (`->`). It simplifies code compared to traditional switch statements.



233. What is a text block in Java?


A text block, introduced in Java 15, simplifies multiline strings using `\"\"\"`, preserving formatting. It’s used for JSON, SQL, or HTML without escape sequences.



234. What is pattern matching in Java?


Pattern matching, evolving in Java (e.g., `instanceof` in Java 16), simplifies type checking and casting, like `if (obj instanceof String s)`. It reduces boilerplate.



235. What is the `instanceof` pattern matching in Java?


`instanceof` pattern matching, introduced in Java 16, combines type checking and casting, like `if (obj instanceof String s)`. It eliminates explicit casts, improving readability.



236. What is the `JDBC` API in Java?


Java Database Connectivity (JDBC) is an API for connecting Java applications to databases, executing SQL queries via `Connection` and `Statement`. It’s vendor-agnostic.



237. What is a `PreparedStatement` in JDBC?


`PreparedStatement` precompiles SQL queries, allowing parameter binding, like `setString(1, \"name\")`. It prevents SQL injection and improves performance for repeated queries.



238. What is a `ResultSet` in JDBC?


`ResultSet` represents the results of a database query, providing methods like `next()` and `getString()`. It’s used to iterate and retrieve data from SQL queries.



239. What is the `Maven` build tool in Java?


Maven is a build automation tool using `pom.xml` to manage dependencies, builds, and plugins. It standardizes project structure and simplifies dependency resolution.



240. What is the `pom.xml` file in Maven?


`pom.xml` (Project Object Model) defines a Maven project’s dependencies, plugins, and build settings. It’s the central configuration file for Maven builds.



241. What is the `Gradle` build tool in Java?


Gradle is a flexible build tool using Groovy or Kotlin scripts (e.g., `build.gradle`) for dependency management and builds. It’s faster and more customizable than Maven.



242. What is a `JUnit` in Java?


JUnit is a testing framework for writing and running unit tests, using annotations like `@Test` and assertions like `assertEquals()`. It ensures code reliability.



243. What is the `@Test` annotation in JUnit?


`@Test` marks a method as a test case in JUnit, executed by the test runner. It can include attributes like `timeout` or `expected` for specific behaviors.



244. What is `TestNG` in Java?


TestNG is a testing framework inspired by JUnit, offering advanced features like parallel testing, data-driven tests, and flexible configuration via XML or annotations.



245. What is the difference between JUnit and TestNG?


JUnit is simpler, focused on unit testing, while TestNG supports advanced features like parallel execution, dependency testing, and parameterization. TestNG is preferred for complex test suites.



246. What is `Log4j` in Java?


Log4j is a logging framework for recording application events, supporting levels like DEBUG or ERROR. It’s configured via `log4j.properties` or XML for flexible output.



247. What is `SLF4J` in Java?


SLF4J (Simple Logging Facade for Java) is a logging facade providing a unified API for logging frameworks like Log4j or JUL. It simplifies switching logging implementations.



248. What is the `Apache Commons` library in Java?


Apache Commons provides reusable Java components, like `Commons Lang` for utilities or `Commons Collections` for enhanced collections. It extends the standard library.



249. What is the `Jackson` library in Java?


Jackson is a JSON processing library for serializing Java objects to JSON and deserializing JSON to objects. It’s used in REST APIs with annotations like `@JsonProperty`.



250. What is the `Gson` library in Java?


Gson, from Google, is a library for JSON serialization and deserialization, converting Java objects to/from JSON. It’s simpler than Jackson but less feature-rich.







251. What is a REST API in Java?


A REST API is a web service using HTTP methods (GET, POST) to expose resources, often implemented in Java with Spring or JAX-RS. It’s stateless and JSON-based.



252. What is JAX-RS in Java?


JAX-RS (Java API for RESTful Web Services) is a specification for building REST APIs, with implementations like Jersey. It uses annotations like `@Path` and `@GET`.



253. What is the `@Path` annotation in JAX-RS?


`@Path` in JAX-RS maps a method or class to a URL path, like `@Path(\"/users\")` for a resource endpoint. It defines the REST API’s URL structure.



254. What is a SOAP web service in Java?


SOAP is a protocol for structured web services using XML, often implemented in Java with JAX-WS. It’s more rigid than REST, used in enterprise systems.



255. What is JAX-WS in Java?


JAX-WS (Java API for XML Web Services) is a specification for building SOAP web services, with implementations like Metro. It uses annotations like `@WebService`.



256. What is the difference between REST and SOAP in Java?


REST is lightweight, using HTTP and JSON, while SOAP is protocol-based, using XML and stricter standards. REST is simpler, but SOAP offers advanced security features.



257. What is the `HttpServlet` class in Java?


`HttpServlet` is a base class for handling HTTP requests, with methods like `doGet()` and `doPost()`. It’s extended to create servlets in web applications.



258. What is the `ServletContext` in Java?


`ServletContext` represents the web application’s environment, providing access to resources, attributes, or initialization parameters. It’s shared across all servlets in the app.



259. What is a `Filter` in Java web applications?


A `Filter` intercepts requests and responses, performing tasks like logging or authentication, using `doFilter()`. It’s configured via `@WebFilter` or web.xml.



260. What is the `Tomcat` server in Java?


Tomcat is an open-source servlet container and web server for running Java web applications, like servlets and JSPs. It’s lightweight and widely used.



261. What is the `Jetty` server in Java?


Jetty is a lightweight, embeddable web server and servlet container for Java applications. It’s used for development, testing, or production with minimal overhead.



262. What is a `WAR` file deployment in Java?


Deploying a WAR file involves placing it in a web server’s (e.g., Tomcat) `webapps` directory, where it’s unpacked and run. It contains the web application’s resources.



263. What is the `Apache Kafka` in Java?


Apache Kafka is a distributed streaming platform for high-throughput, fault-tolerant data pipelines, used with Java via its client APIs. It handles real-time data feeds.



264. What is the `Spring Kafka` library?


Spring Kafka simplifies Kafka integration in Java, providing abstractions like `@KafkaListener` and `KafkaTemplate`. It integrates with Spring’s ecosystem for messaging.



265. What is a `Docker` container in Java?


A Docker container packages a Java application and its dependencies (e.g., JDK, JAR) into a portable unit. It ensures consistent execution across environments.



266. What is a `Kubernetes` in Java?


Kubernetes is a platform for orchestrating Docker containers, managing Java applications’ deployment, scaling, and availability. It’s used for microservices in cloud environments.



267. What is the `Jenkins` tool in Java?


Jenkins is a CI/CD server for automating Java application builds, tests, and deployments, configured via pipelines or plugins. It integrates with Maven or Gradle.



268. What is a `pipeline` in Jenkins?


A Jenkins pipeline is a scripted or declarative workflow defining build, test, and deploy stages for a Java project. It’s written in Groovy, often in a `Jenkinsfile`.



269. What is the `Git` version control in Java?


Git is a distributed version control system used for Java projects, managing code versions via commits, branches, and repositories. Tools like JGit integrate Git in Java.



270. What is the `JGit` library in Java?


JGit is a Java library for Git operations, like cloning or committing, without needing the Git command-line tool. It’s used in Java-based DevOps tools.



271. What is the `SLF4J` vs `Log4j` in Java?


SLF4J is a logging facade providing a unified API, while Log4j is a concrete logging framework. SLF4J with Log4j as a backend is a common setup.



272. What is the `Mockito` framework in Java?


Mockito is a mocking framework for unit testing, creating mock objects to simulate dependencies, like `mock(MyService.class)`. It’s used with JUnit or TestNG.



273. What is the `PowerMock` framework in Java?


PowerMock extends Mockito to mock static methods, final classes, or private methods, which Mockito can’t handle. It’s used for testing legacy or complex code.



274. What is the `AssertJ` library in Java?


AssertJ provides fluent assertions for testing, like `assertThat(actual).isEqualTo(expected)`. It’s more readable than JUnit’s assertions, used in unit tests.



275. What is the `WireMock` library in Java?


WireMock mocks HTTP services, simulating APIs for testing, like stubbing responses for `/api/users`. It’s used to test Java applications interacting with external APIs.







276. What is the `Spring Security` framework?


Spring Security provides authentication, authorization, and protection against attacks, like CSRF or XSS, for Java applications. It integrates with Spring via annotations like `@Secured`.



277. What is the `@Secured` annotation in Spring Security?


`@Secured` restricts method access to users with specific roles, like `@Secured(\"ROLE_ADMIN\")`. It’s used for role-based authorization in Spring applications.



278. What is OAuth2 in Spring Security?


OAuth2 in Spring Security implements an authorization framework, enabling secure token-based access for APIs. It supports flows like authorization code or client credentials.



279. What is the `Spring Data` project?


Spring Data simplifies database access, providing repositories for JPA, MongoDB, or Redis, with auto-implemented CRUD methods. It reduces boilerplate via `@Repository`.



280. What is the `@Repository` annotation in Spring?


`@Repository` marks a class as a data access component, enabling exception translation and component scanning. It’s used for DAOs or Spring Data repositories.



281. What is the `Spring Cloud` project?


Spring Cloud provides tools for distributed systems, like service discovery, configuration management, and circuit breakers. It’s used for microservices in Java.



282. What is a circuit breaker in Spring Cloud?


A circuit breaker, like Resilience4j in Spring Cloud, prevents cascading failures in microservices by halting calls to failing services. It improves system reliability.



283. What is the `Eureka` server in Spring Cloud?


Eureka is a service registry in Spring Cloud, allowing microservices to register and discover each other dynamically. It’s used for load balancing and failover.



284. What is the `Spring Actuator` in Spring Boot?


Spring Actuator provides production-ready endpoints, like `/health` or `/metrics`, for monitoring and managing Spring Boot applications. It’s enabled via dependencies.



285. What is the `Micrometer` library in Spring Boot?


Micrometer provide



List Memory Pages
Share Via Whastapp/Facebook
Share to Your Friends

Share this protal to share friends and complete unlimited tests here. You can also make friends on our protal also start mutual competition tests with your firends easily.

Share to Facebook Share to WhatsApp Promote & Earn