| 1 |
Object |
An Object is a runtime instance of a class that contains state (fields) and behavior (methods). It is the fundamental building block of object-oriented programming in Java. Every object occupies memory and has its own identity, state, and behavior. |
Real-world entities need to be represented in software with data and operations bundled together. |
Objects and references are the same thing. |
Model business entities and encapsulate related data and behavior. |
Customer, Account, Employee, Order objects in enterprise applications. |
What is the difference between an object and a reference? How is an object represented in memory? |
Class, Heap, Object Header |
| 2 |
Class |
A Class is a blueprint or template that defines the structure and behavior of objects. It specifies fields, methods, constructors, and nested types. Objects are created based on class definitions. |
Developers need a reusable way to define object structure and behavior. |
Classes occupy memory only when objects are created. |
Define reusable object templates. |
Employee class used to create thousands of employee objects. |
What metadata does JVM store for a class? Where is class metadata stored? |
Object, Metaspace |
| 3 |
Encapsulation |
Encapsulation is the practice of bundling data and behavior together while controlling access to internal implementation details. Fields are typically hidden using access modifiers and exposed through methods. |
Direct access to internal state can lead to invalid object states and maintenance problems. |
Encapsulation means only making fields private. |
Protect object integrity and reduce coupling. |
BankAccount exposing deposit() and withdraw() rather than allowing direct balance modification. |
Why is encapsulation considered a foundation of maintainable software? |
Access Modifiers, Abstraction |
| 4 |
Abstraction |
Abstraction is the process of exposing only essential behavior while hiding implementation details. Consumers focus on what an object does rather than how it does it. |
Complex systems require simplified interfaces to reduce cognitive load. |
Abstraction and Encapsulation are identical concepts. |
Reduce complexity and improve maintainability. |
JDBC API hides database-specific implementation details. |
How does abstraction differ from encapsulation? |
Interface, Abstract Class |
| 5 |
Inheritance |
Inheritance allows one class to acquire the properties and behaviors of another class. The derived class extends the base class and may add or modify functionality. |
Many domain models contain hierarchical relationships with shared behavior. |
Inheritance is always the best way to reuse code. |
Promote reuse and specialization. |
SavingsAccount extending Account. |
Why is composition often preferred over inheritance? |
Polymorphism, Composition |
| 6 |
Polymorphism |
Polymorphism allows the same interface or method call to exhibit different behavior depending on the actual object involved. The caller interacts with a common contract while the runtime selects the appropriate implementation. |
Applications often need to work with multiple implementations through a common abstraction. |
Polymorphism only means method overriding. |
Increase flexibility and reduce coupling. |
PaymentService working with CreditCardPayment, UpiPayment, and NetBankingPayment implementations. |
Explain compile-time and runtime polymorphism. |
Interface, Method Overriding |
| 7 |
Association |
Association represents a relationship between two independent objects where one object uses or interacts with another. Neither object necessarily owns the other's lifecycle. |
Real-world entities often interact without strict ownership relationships. |
Association always implies ownership. |
Model relationships between business entities. |
Customer placing Orders. |
How does association differ from aggregation and composition? |
Aggregation, Composition |
| 8 |
Aggregation |
Aggregation is a special form of association where one object contains references to other objects, but the contained objects can exist independently. It represents a "has-a" relationship with weak ownership. |
Some relationships require grouping objects without controlling their lifecycle. |
Aggregation and composition are identical. |
Model logical ownership without lifecycle dependency. |
Department containing Employees who can exist independently. |
What happens to child objects when the parent is destroyed? |
Association, Composition |
| 9 |
Composition |
Composition is a strong form of aggregation where the parent object owns the lifecycle of child objects. If the parent is destroyed, the child objects typically cease to exist as well. |
Certain relationships require strict ownership and lifecycle control. |
Composition is simply aggregation with different naming. |
Model strong ownership relationships. |
House containing Rooms. |
Why is composition often preferred over inheritance? |
Aggregation, Inheritance |
| 10 |
Method Overloading |
Method Overloading allows multiple methods with the same name but different parameter lists within the same class. The compiler determines which method to invoke based on argument types and counts. |
Similar operations often need to support multiple input variations. |
Return type alone can differentiate overloaded methods. |
Improve API usability and readability. |
String.valueOf() providing overloads for many data types. |
How does the compiler resolve overloaded methods? |
Method Overriding, Polymorphism |
| 11 |
Method Overriding |
Method Overriding occurs when a subclass provides its own implementation of a method already defined in its superclass. The method signature must remain compatible, and the JVM selects the implementation based on the actual object type at runtime. |
Subclasses often need specialized behavior while preserving a common contract. |
Overriding and overloading are the same concept. |
Enable runtime polymorphism and specialization. |
A SavingsAccount overriding calculateInterest() from Account. |
How does dynamic method dispatch work internally? |
Polymorphism, Inheritance |
| 12 |
Static |
The static keyword indicates that a member belongs to the class itself rather than individual object instances. Static members are loaded once per class and shared across all objects. |
Some data and behavior are common to all instances and should not be duplicated. |
Static variables are global variables. Static methods improve performance. |
Share data and behavior at the class level. |
Math.max(), Collections.sort(), application-wide counters. |
When should static be avoided in object-oriented design? |
Class Loading, Memory Model |
| 13 |
Final |
The final keyword restricts modification. A final variable cannot be reassigned, a final method cannot be overridden, and a final class cannot be extended. The exact meaning depends on where it is applied. |
Certain behaviors and data should remain stable to ensure correctness and predictability. |
Final makes objects immutable. |
Prevent unintended modifications and enforce design constraints. |
String is a final class to preserve immutability and security. |
Difference between final reference and immutable object. |
Immutability, Inheritance |
| 14 |
this |
The this keyword refers to the current object instance. It is used to access instance members, resolve naming conflicts, and invoke constructors within the same class. |
Methods and constructors often need an explicit way to reference the current object. |
this creates a new object. |
Provide access to the current instance context. |
Using this.name = name inside a constructor. |
What exactly does this reference point to at runtime? |
Object, Constructor |
| 15 |
super |
The super keyword refers to the immediate parent class. It is used to access superclass members and invoke superclass constructors. |
Child classes often need to reuse or extend parent behavior. |
super refers to any ancestor in the hierarchy. |
Provide controlled access to parent implementations. |
Calling super() inside a subclass constructor. |
Why must super() often be the first statement in a constructor? |
Inheritance, Constructor Chaining |
| 16 |
Constructor |
A Constructor is a special member used to initialize objects when they are created. Constructors establish the initial state of an object and execute automatically during object creation. |
Objects often require valid initial state before they can be used safely. |
Constructors create objects. |
Initialize newly allocated objects. |
Creating an Employee with id, name, and department information. |
What happens internally during object creation before and after constructor execution? |
Object, Initialization |
| 17 |
Constructor Chaining |
Constructor Chaining is the process where one constructor invokes another constructor either within the same class using this() or in the parent class using super(). It promotes code reuse and consistent initialization. |
Multiple constructors often share common initialization logic. |
Constructor chaining is optional for inheritance. |
Avoid duplication and ensure complete initialization. |
Default constructor calling a parameterized constructor. |
Explain the execution order of constructor chains. |
Constructor, super, this |
| 18 |
Initialization Block |
An Initialization Block is a block of code executed during object creation before the constructor body. Instance initialization blocks run for every object, while static initialization blocks run once during class loading. |
Some initialization logic is common across multiple constructors. |
Initialization blocks replace constructors. |
Centralize common initialization logic. |
Loading configuration values during class initialization. |
What is the execution order of static blocks, instance blocks, and constructors? |
Static, Constructor |
| 19 |
Access Modifier |
Access Modifiers control the visibility of classes, methods, fields, and constructors. Java provides private, default (package-private), protected, and public access levels. |
Software systems require controlled access to internal implementation details. |
Access modifiers provide security. |
Enforce encapsulation and API boundaries. |
Public service APIs with private implementation details. |
Explain accessibility rules across packages and inheritance hierarchies. |
Encapsulation, Package |
| 20 |
Package |
A Package is a namespace mechanism used to organize related classes and interfaces. Packages help prevent naming conflicts and provide modular structure for applications. |
Large applications require logical organization and namespace separation. |
Packages are physical folders only. |
Improve maintainability and modularity. |
com.company.payment.service and com.company.payment.repository packages. |
How do packages influence access control and class loading? |
Access Modifier, ClassLoader |
| 21 |
Interface |
An Interface is a contract that defines behavior without prescribing implementation details. Classes implement interfaces to provide concrete behavior. Interfaces promote abstraction, loose coupling, and polymorphism. Modern Java interfaces can also contain default, static, and private methods. |
Applications often need to depend on capabilities rather than concrete implementations. |
Interfaces cannot contain methods with implementation. Interfaces are only used for multiple inheritance. |
Define contracts and enable interchangeable implementations. |
PaymentService interface implemented by CreditCardPaymentService and UpiPaymentService. |
Why should code depend on interfaces rather than implementations? |
Abstraction, Polymorphism |
| 22 |
Abstract Class |
An Abstract Class is a partially implemented class that cannot be instantiated directly. It can contain both abstract methods and concrete methods. Abstract classes provide a common foundation for related subclasses. |
Some classes represent incomplete concepts that require specialization. |
Abstract classes and interfaces are interchangeable. |
Share common behavior while enforcing specialization. |
Abstract Employee class extended by PermanentEmployee and ContractEmployee. |
When should Abstract Classes be preferred over Interfaces? |
Inheritance, Interface |
| 23 |
Functional Interface |
A Functional Interface is an interface containing exactly one abstract method. It serves as the foundation for Lambda Expressions and Method References in Java. |
Functional programming features require a target type representing executable behavior. |
Functional Interfaces cannot contain default methods. |
Enable concise representation of behavior as data. |
Runnable, Callable, Comparator, Predicate. |
Why does Lambda require a Functional Interface? |
Lambda, Method Reference |
| 24 |
Lambda Expression |
A Lambda Expression is a concise way of representing anonymous functions. It allows behavior to be passed as data without creating explicit classes or anonymous inner classes. |
Anonymous classes often introduce excessive boilerplate code. |
Lambda creates a new thread automatically. |
Simplify functional programming and behavior passing. |
Sorting collections using custom comparators. |
How are Lambda Expressions implemented internally by the JVM? |
Functional Interface, Stream API |
| 25 |
Method Reference |
A Method Reference is a shorthand notation for a Lambda Expression that directly invokes an existing method. It improves readability when a Lambda simply delegates to another method. |
Many Lambda expressions merely call existing methods. |
Method References are different from Lambda Expressions. |
Improve code clarity and reduce boilerplate. |
list.forEach(System.out::println). |
What types of Method References exist in Java? |
Lambda Expression, Functional Interface |
| 26 |
Anonymous Inner Class |
An Anonymous Inner Class is a class without a name that is declared and instantiated in a single expression. It is commonly used when a one-time implementation is required. |
Some behaviors are needed only once and do not justify creating separate classes. |
Anonymous classes are identical to Lambda Expressions. |
Provide inline implementation of interfaces or classes. |
Event listeners and callback implementations. |
How do Anonymous Classes differ from Lambda Expressions? |
Inner Class, Functional Interface |
| 27 |
Inner Class |
An Inner Class is a class defined within another class. It has access to members of the enclosing class, including private members. |
Some helper classes are tightly coupled to a specific outer class. |
Inner Classes are primarily used for inheritance. |
Improve encapsulation and logical grouping. |
Iterator implementations inside collection classes. |
What are the different types of Inner Classes? |
Nested Class, Anonymous Class |
| 28 |
Static Nested Class |
A Static Nested Class is a nested class declared with the static keyword. Unlike inner classes, it does not maintain a reference to an enclosing instance. |
Some nested classes logically belong to an outer class but do not require access to object state. |
Static Nested Classes behave like Inner Classes. |
Improve organization while avoiding unnecessary references. |
Builder classes inside domain objects. |
When should Static Nested Classes be preferred over Inner Classes? |
Inner Class, Static |
| 29 |
Enum |
An Enum is a special type representing a fixed set of constants. Unlike traditional constants, enums are full-fledged classes capable of containing fields, methods, and constructors. |
Many domains contain predefined finite sets of values. |
Enums are merely named integer constants. |
Improve type safety and readability. |
OrderStatus, PaymentType, UserRole. |
Why are Enums considered superior to integer constants? |
Static, Class |
| 30 |
Record |
A Record is a special Java class designed for immutable data carriers. The compiler automatically generates constructors, accessors, equals(), hashCode(), and toString() methods. |
Many classes exist solely to hold data and require repetitive boilerplate code. |
Records are equivalent to normal classes. |
Simplify immutable data modeling. |
CustomerDTO, AddressDTO, API response objects. |
What restrictions distinguish Records from traditional classes? |
Immutability, Object |
| 31 |
Sealed Class |
A Sealed Class is a class that restricts which other classes or interfaces can extend or implement it. The permitted subclasses must be explicitly declared. This provides controlled inheritance and makes class hierarchies more predictable. |
Unrestricted inheritance can lead to unintended extensions and maintenance challenges. |
Sealed Classes completely replace final classes. |
Control inheritance while still allowing limited extensibility. |
Shape permitting only Circle, Rectangle, and Triangle subclasses. |
When should Sealed Classes be preferred over final and abstract classes? |
Inheritance, Polymorphism |
| 32 |
Generic |
Generics provide type parameterization, allowing classes, interfaces, and methods to operate on different data types while maintaining compile-time type safety. |
Prior to Generics, collections stored Objects, requiring manual casting and increasing runtime errors. |
Generics exist only for collections. |
Improve type safety and eliminate unnecessary casts. |
List, Map<Long, Employee>. |
How do Generics improve compile-time safety? |
Type Erasure, Collections |
| 33 |
Type Erasure |
Type Erasure is the process by which generic type information is removed during compilation. The JVM executes generic code using ordinary classes and casts inserted by the compiler. |
Java introduced Generics without breaking backward compatibility with older JVMs. |
Generic type information exists completely at runtime. |
Maintain backward compatibility while providing compile-time safety. |
List and List become similar bytecode structures after compilation. |
Why can't you create new T() or use instanceof with generic types? |
Generics, Reflection |
| 34 |
Wildcard Generic |
Wildcards provide flexibility when working with generic types. The symbols ?, ? extends T, and ? super T allow controlled variance while maintaining type safety. |
Strict generic typing can sometimes be too restrictive. |
Wildcards make generic code less type-safe. |
Enable flexible APIs without sacrificing compile-time validation. |
Methods accepting List<? extends Number>. |
Explain PECS (Producer Extends, Consumer Super). |
Generics, Collections |
| 35 |
Comparable |
Comparable defines a natural ordering for objects. Classes implement Comparable to specify how instances should be compared and sorted. |
Sorting requires a consistent comparison strategy. |
Comparable and Comparator are interchangeable. |
Provide default ordering semantics. |
Sorting employees by employeeId. |
Why should compareTo() remain consistent with equals()? |
Comparator, Collections |
| 36 |
Comparator |
Comparator provides an external comparison strategy independent of the object's class definition. Multiple comparators can exist for the same class. |
Objects often need multiple sorting criteria. |
Comparator replaces Comparable. |
Enable flexible sorting behavior. |
Sorting employees by salary, age, or department. |
When should Comparator be preferred over Comparable? |
Comparable, Lambda |
| 37 |
equals() |
equals() defines logical equality between objects. By default, Object.equals() compares references, but classes often override it to compare business-relevant fields. |
Object identity and business equality are often different concepts. |
equals() compares memory addresses. |
Determine whether two objects represent the same logical entity. |
Comparing Customer objects using customerId. |
Why must equals() satisfy reflexive, symmetric, and transitive properties? |
hashCode(), Object |
| 38 |
hashCode() |
hashCode() returns an integer representation used by hash-based collections to locate objects efficiently. Objects that are equal according to equals() must return the same hash code. |
Linear searches become inefficient as collections grow. |
Unique hash codes are required for every object. |
Improve lookup performance in hash-based structures. |
HashMap and HashSet operations. |
Why must equals() and hashCode() be implemented together? |
equals(), HashMap |
| 39 |
Object Identity |
Object Identity refers to the unique existence of an object instance in memory. Two objects may contain identical data yet still possess different identities. |
Runtime systems need a way to distinguish object instances. |
Equal objects are always the same object. |
Represent unique runtime instances. |
Two Customer objects with identical fields but separate allocations. |
Difference between == and equals(). |
Object, Reference |
| 40 |
Object Equality |
Object Equality represents logical equivalence between objects based on business rules rather than memory location. |
Business systems often care about logical identity rather than physical memory identity. |
Equality and identity are the same concept. |
Support meaningful object comparisons. |
Two Employee objects representing the same employee record. |
How should equality be defined for entities versus value objects? |
equals(), hashCode() |
| 41 |
Exception |
An Exception is an object representing an abnormal condition that disrupts normal program execution. Exceptions provide structured error handling separate from business logic. |
Error handling through return codes leads to cluttered and error-prone code. |
Exceptions are only for unexpected crashes. |
Separate error handling from normal application flow. |
Database connectivity failures and validation errors. |
How does exception propagation work through the call stack? |
Throwable, Try-Catch |
| 42 |
Throwable |
Throwable is the root class of Java's error handling hierarchy. Both Exception and Error inherit from Throwable. Only Throwable objects can be thrown by the JVM or application code. |
A common hierarchy is required for error handling mechanisms. |
Throwable and Exception are identical. |
Provide a unified error representation model. |
RuntimeException, IOException, OutOfMemoryError. |
Why can only subclasses of Throwable be thrown? |
Exception, Error |
| 43 |
Checked Exception |
A Checked Exception is an exception that the compiler requires developers to handle or declare. These exceptions typically represent recoverable conditions. |
Some failures require explicit consideration by developers. |
Checked Exceptions are always recoverable. |
Encourage explicit error handling. |
IOException, SQLException. |
Why are Checked Exceptions controversial in large systems? |
Exception, Throws |
| 44 |
Unchecked Exception |
An Unchecked Exception is an exception that does not require explicit handling by the compiler. These exceptions typically indicate programming errors or invalid assumptions. |
Some failures are best addressed by fixing code rather than recovering at runtime. |
Unchecked Exceptions are less severe. |
Represent programming defects and invalid states. |
NullPointerException, IllegalArgumentException. |
When should custom exceptions extend RuntimeException? |
RuntimeException, Exception |
| 45 |
Error |
Error represents serious JVM-level problems that applications generally should not attempt to recover from. Errors indicate failures in the runtime environment itself. |
Certain failures are beyond application control. |
Errors are simply severe exceptions. |
Signal critical runtime failures. |
OutOfMemoryError, StackOverflowError. |
Why should applications rarely catch Errors? |
Throwable, JVM |
| 46 |
try-catch-finally |
try-catch-finally is Java's structured exception handling construct. The try block contains risky operations, catch handles exceptions, and finally executes cleanup code regardless of success or failure. |
Resources often require cleanup even when failures occur. |
finally always executes under every circumstance. |
Manage exceptions and resource cleanup reliably. |
Closing database connections after operations. |
What situations can prevent finally from executing? |
Exception Handling, Resources |
| 47 |
try-with-resources |
try-with-resources automatically closes resources that implement AutoCloseable after execution completes. It simplifies resource management and prevents leaks. |
Manual resource cleanup is error-prone and often forgotten. |
try-with-resources only works with files. |
Ensure deterministic resource cleanup. |
Managing database connections, streams, and readers. |
How does AutoCloseable integrate with try-with-resources? |
AutoCloseable, Exception Handling |
| 48 |
Custom Exception |
A Custom Exception is a user-defined exception type representing domain-specific failure conditions. Custom exceptions improve readability and error categorization. |
Generic exceptions often fail to communicate business context. |
Every application requires hundreds of custom exceptions. |
Model domain-specific error scenarios. |
InsufficientBalanceException in banking applications. |
When should custom exceptions be checked versus unchecked? |
Exception Hierarchy |
| 49 |
Serialization |
Serialization is the process of converting an object's state into a byte stream so it can be stored or transmitted and later reconstructed. |
Objects often need persistence or network transmission. |
Serialization stores methods and runtime behavior. |
Enable object persistence and communication. |
Session replication and distributed caching. |
Why is Java native serialization often discouraged today? |
Deserialization, Object Streams |
| 50 |
Deserialization |
Deserialization is the process of reconstructing an object from serialized data. The JVM recreates the object's state from the byte stream. |
Serialized objects must be restored into usable runtime objects. |
Deserialization simply copies memory. |
Reconstruct objects from persistent or transmitted data. |
Reading objects from files, caches, or message queues. |
Why can deserialization introduce security vulnerabilities? |
Serialization, Security |
| 51 |
Cloneable |
Cloneable is a marker interface indicating that an object supports cloning through the clone() method. It allows creation of object copies without invoking constructors. |
Some applications require duplication of object state. |
Cloneable automatically performs deep copies. |
Provide a mechanism for object duplication. |
Copying configuration objects or prototypes. |
Why is Cloneable considered flawed by many Java developers? |
clone(), Deep Copy |
| 52 |
clone() |
clone() is a method inherited from Object that creates a copy of an existing object. By default, it performs a field-by-field copy. |
Creating copies manually can be repetitive and error-prone. |
clone() always creates an independent object graph. |
Duplicate object state efficiently. |
Creating copies of DTOs and configuration objects. |
What are the limitations of Object.clone()? |
Cloneable, Shallow Copy |
| 53 |
Shallow Copy |
A Shallow Copy duplicates the object's fields but does not recursively copy referenced objects. Primitive values are copied, while object references are shared. |
Deep copying entire object graphs can be expensive. |
Shallow Copy creates a fully independent duplicate. |
Create lightweight copies quickly. |
Copying an Employee object while sharing the same Address object. |
Why can modifying nested objects affect both copies? |
Deep Copy, clone() |
| 54 |
Deep Copy |
A Deep Copy duplicates an object and all objects reachable from it, producing a completely independent object graph. |
Shared references can create unintended side effects. |
Deep Copy simply means copying more fields. |
Ensure complete independence between object copies. |
Copying a Customer with Address, Orders, and PaymentDetails. |
What techniques can be used to implement Deep Copy? |
Shallow Copy, Serialization |
| 55 |
Immutable Object |
An Immutable Object cannot change its state after creation. Any modification results in a new object rather than altering the existing one. |
Shared mutable state is a major source of bugs and concurrency issues. |
final fields automatically make an object immutable. |
Improve thread safety and predictability. |
String, LocalDate, BigDecimal. |
What conditions must be satisfied for true immutability? |
Final, Thread Safety |
| 56 |
String |
String is an immutable sequence of characters representing textual data. Strings are heavily optimized and receive special treatment from the JVM. |
Text manipulation is fundamental to nearly every application. |
String is simply a character array. |
Provide efficient, secure, and immutable text handling. |
User names, JSON payloads, SQL queries. |
Why is String immutable and how does the String Pool work? |
String Pool, Immutability |
| 57 |
String Pool |
The String Pool is a JVM-managed cache that stores string literals and interned strings. Identical string literals share the same memory instance. |
String duplication can consume significant memory. |
Every String automatically resides in the pool. |
Reduce memory consumption and improve performance. |
Multiple occurrences of "SUCCESS" sharing one pooled object. |
Difference between new String() and string literals. |
String, Heap |
| 58 |
StringBuilder |
StringBuilder is a mutable character sequence optimized for single-threaded string manipulation. It avoids repeated object creation associated with String concatenation. |
Strings are immutable, making repeated concatenation inefficient. |
StringBuilder is always faster than String. |
Improve performance during intensive string modifications. |
Building SQL queries and report content. |
Why does StringBuilder outperform repeated String concatenation? |
String, StringBuffer |
| 59 |
StringBuffer |
StringBuffer is a thread-safe mutable character sequence. Its methods are synchronized, making it safe for concurrent access but generally slower than StringBuilder. |
Some applications require mutable strings shared across threads. |
StringBuffer should always be preferred because it is thread-safe. |
Provide synchronized string manipulation. |
Legacy multi-threaded text processing systems. |
When is StringBuffer preferable to StringBuilder? |
StringBuilder, Synchronization |
| 60 |
Wrapper Class |
Wrapper Classes provide object representations of primitive types. Examples include Integer, Long, Double, and Boolean. They enable primitives to participate in object-oriented APIs. |
Collections and generics operate on objects rather than primitive values. |
Wrapper Classes are identical to primitives. |
Bridge primitive values and object-oriented APIs. |
List and Map<Long, String>. |
What are the memory and performance implications of wrappers? |
Autoboxing, Primitive Types |
| 61 |
Autoboxing |
Autoboxing is the automatic conversion of primitive values into their corresponding wrapper objects performed by the compiler. |
Manual wrapper creation introduces boilerplate code. |
Autoboxing has no performance cost. |
Simplify interoperability between primitives and objects. |
Adding an int value into a List. |
What hidden object allocations can Autoboxing create? |
Wrapper Class, Collections |
| 62 |
Unboxing |
Unboxing is the automatic conversion of wrapper objects into primitive values. The compiler inserts the necessary conversion code. |
APIs often return wrapper objects while business logic requires primitives. |
Unboxing cannot cause runtime errors. |
Simplify interaction between wrappers and primitives. |
Retrieving Integer values from collections. |
Why can Unboxing cause NullPointerException? |
Wrapper Class, Autoboxing |
| 63 |
var |
var allows local variable type inference where the compiler determines the variable type from the assigned expression. The actual type remains strongly typed. |
Some variable declarations contain redundant type information. |
var creates dynamically typed variables. |
Improve readability by reducing verbosity. |
var employee = new Employee(); |
How does var differ from dynamic typing languages? |
Type Inference, Compiler |
| 64 |
Annotation |
An Annotation is metadata attached to program elements such as classes, methods, and fields. Annotations provide information to the compiler, runtime, or frameworks. |
Applications often require metadata separate from business logic. |
Annotations directly execute code. |
Supply declarative configuration and metadata. |
@Override, @Service, @Transactional. |
How are annotations processed at compile time and runtime? |
Reflection, Frameworks |
| 65 |
Reflection |
Reflection is the ability of a program to inspect and manipulate classes, methods, fields, constructors, and annotations at runtime. It enables dynamic behavior. |
Frameworks often need runtime access to application metadata. |
Reflection modifies source code. |
Enable dynamic inspection and framework automation. |
Spring Dependency Injection and Hibernate entity mapping. |
Why is Reflection powerful but potentially expensive? |
Annotation, ClassLoader |
| 66 |
Dynamic Proxy |
A Dynamic Proxy is a runtime-generated object that intercepts method calls and delegates behavior dynamically. It allows cross-cutting concerns without modifying business code. |
Many frameworks require behavior injection around existing methods. |
Dynamic Proxies are only used for remote communication. |
Implement interception and aspect-oriented programming. |
Spring AOP and transaction management. |
How does Java's Proxy API work internally? |
Reflection, AOP |
| 67 |
Class Object |
A Class Object is the runtime representation of a Java class. Every loaded class has exactly one corresponding Class instance accessible through reflection APIs. |
The JVM requires metadata structures describing loaded classes. |
Class and Class Object are the same concept. |
Provide runtime access to type information. |
Employee.class and employee.getClass(). |
How are Class objects loaded and cached? |
Reflection, ClassLoader |
| 68 |
instanceof |
instanceof determines whether an object is compatible with a specified type. It checks inheritance and interface relationships at runtime. |
Applications often need safe type verification before casting. |
instanceof compares exact class equality. |
Prevent invalid type conversions. |
Verifying whether a Payment object is a CreditCardPayment. |
How does instanceof interact with inheritance hierarchies? |
Casting, Polymorphism |
| 69 |
Type Casting |
Type Casting converts references between compatible types within an inheritance hierarchy. Upcasting is generally safe, while downcasting requires runtime validation. |
Polymorphism often requires viewing objects through different abstractions. |
Casting changes the actual object type. |
Enable flexible interaction with inheritance structures. |
Converting Employee references to Manager references. |
Why can ClassCastException occur? |
instanceof, Polymorphism |
| 70 |
Covariant Return Type |
Covariant Return Type allows an overriding method to return a more specific type than the method defined in the superclass. |
Subclasses often know more specific return information than parent contracts. |
Overriding methods must always return identical types. |
Improve type safety while preserving polymorphism. |
Factory methods returning specialized implementations. |
How do covariant return types support cleaner APIs? |
Method Overriding, Polymorphism |
| 71 |
Object Class |
Object is the root class of the Java class hierarchy. Every class directly or indirectly inherits from Object, gaining access to methods such as equals(), hashCode(), toString(), clone(), and wait(). |
The JVM requires a common ancestor to support universal object operations. |
Only custom classes inherit from Object. |
Provide common behavior shared by all objects. |
Employee, Customer, Order, and every Java object inherit from Object. |
Why is Object considered the foundation of Java's type system? |
Class, Inheritance |
| 72 |
toString() |
toString() returns a string representation of an object. By default, it returns the class name and hash code, but it is commonly overridden to provide meaningful information. |
Developers need a readable representation of objects for debugging and logging. |
toString() is used only for printing objects. |
Improve observability and debugging. |
Logging Employee details in application logs. |
Why should business entities override toString()? |
Object, Logging |
| 73 |
finalize() |
finalize() is a method that the Garbage Collector may invoke before reclaiming an object. It was intended for cleanup operations but is deprecated due to unpredictability and performance concerns. |
Early Java versions lacked modern resource management mechanisms. |
finalize() always executes before object destruction. |
Historically provided cleanup hooks. |
Legacy code releasing native resources. |
Why was finalize() deprecated and what replaces it? |
Garbage Collection, AutoCloseable |
| 74 |
AutoCloseable |
AutoCloseable is an interface whose implementation allows resources to be automatically closed when used with try-with-resources. |
Resource leaks can occur when developers forget cleanup operations. |
AutoCloseable is only for file handling. |
Standardize resource management. |
Database connections, streams, sockets. |
How does AutoCloseable improve reliability? |
try-with-resources, Exception Handling |
| 75 |
Dependency Injection |
Dependency Injection is a design technique where required dependencies are provided from outside rather than created internally. This reduces coupling and improves testability. |
Hardcoded dependencies make systems rigid and difficult to test. |
Dependency Injection is a Spring-only concept. |
Promote loose coupling and modular design. |
Injecting a PaymentRepository into PaymentService. |
Why is Dependency Injection considered a core enterprise design principle? |
IoC, Spring |
| 76 |
Inversion of Control (IoC) |
Inversion of Control is a design principle where the responsibility for object creation and lifecycle management is transferred to a framework or container. |
Applications become easier to manage when object creation is centralized. |
IoC and Dependency Injection are identical. |
Improve flexibility and manageability. |
Spring Container managing application beans. |
How does IoC differ from Dependency Injection? |
Dependency Injection, Spring Container |
| 77 |
Cohesion |
Cohesion measures how closely related the responsibilities of a class or module are. High cohesion means a component focuses on a single purpose. |
Components with mixed responsibilities are harder to maintain and test. |
High cohesion means many classes working together. |
Improve maintainability and clarity. |
UserService handling only user-related operations. |
Why is high cohesion desirable in software design? |
SOLID, Single Responsibility Principle |
| 78 |
Coupling |
Coupling measures the degree of dependency between components. Lower coupling improves flexibility and reduces the impact of changes. |
Highly dependent components become difficult to modify independently. |
Coupling should always be eliminated completely. |
Improve modularity and adaptability. |
Service depending on an interface instead of a concrete implementation. |
How can dependency injection reduce coupling? |
Abstraction, Interface |
| 79 |
SOLID Principles |
SOLID is a collection of five object-oriented design principles that improve maintainability, scalability, and flexibility. They include SRP, OCP, LSP, ISP, and DIP. |
Large systems become difficult to evolve without design guidelines. |
SOLID applies only to enterprise applications. |
Promote robust and maintainable software architecture. |
Well-structured Spring applications following layered architecture. |
Which SOLID principle is most frequently violated in real-world systems? |
OOP, Design Patterns |
| 80 |
Single Responsibility Principle (SRP) |
SRP states that a class should have only one reason to change. A class should focus on a single responsibility or concern. |
Classes with multiple responsibilities become fragile and difficult to maintain. |
SRP means a class should contain only one method. |
Improve maintainability and testability. |
Separating UserValidationService from UserPersistenceService. |
How can you identify SRP violations in existing code? |
SOLID, Cohesion |
| 81 |
Open Closed Principle (OCP) |
OCP states that software entities should be open for extension but closed for modification. New behavior should be added without altering existing code. |
Frequent modification of stable code increases regression risk. |
OCP prevents any code changes. |
Support extensibility while minimizing risk. |
Adding a new payment method through a new implementation class. |
How do interfaces help achieve OCP? |
Polymorphism, SOLID |
| 82 |
Liskov Substitution Principle (LSP) |
LSP states that subclasses should be replaceable for their base classes without altering program correctness. |
Incorrect inheritance hierarchies break polymorphism. |
Any subclass automatically satisfies LSP. |
Preserve behavioral consistency. |
Square and Rectangle inheritance often violating LSP. |
What are common examples of LSP violations? |
Inheritance, Polymorphism |
| 83 |
Interface Segregation Principle (ISP) |
ISP states that clients should not be forced to depend on methods they do not use. Large interfaces should be split into focused contracts. |
Fat interfaces create unnecessary dependencies. |
More methods always make interfaces better. |
Improve modularity and maintainability. |
Separate Printable and Scannable interfaces. |
Why are large interfaces considered a design smell? |
Interface, SOLID |
| 84 |
Dependency Inversion Principle (DIP) |
DIP states that high-level modules should depend on abstractions rather than concrete implementations. |
Direct dependencies create rigid architectures. |
DIP means removing all dependencies. |
Promote loose coupling and extensibility. |
Service depending on UserRepository interface instead of JpaUserRepository. |
How does Spring implement DIP extensively? |
Interface, Dependency Injection |
| 85 |
Design Pattern |
A Design Pattern is a proven reusable solution to a recurring software design problem. Patterns provide guidance rather than complete implementations. |
Developers frequently encounter similar design challenges. |
Design Patterns are framework-specific. |
Improve software structure and communication. |
Factory, Singleton, Builder, Strategy. |
Why are patterns considered templates rather than finished solutions? |
SOLID, OOP |
| 86 |
Singleton Pattern |
Singleton ensures that only one instance of a class exists within an application and provides a global access point to it. |
Certain resources should be shared globally. |
Singleton is always an anti-pattern. |
Control instance creation and lifecycle. |
Configuration managers and cache managers. |
How can Singleton implementations fail in concurrent environments? |
Design Patterns, Thread Safety |
| 87 |
Factory Pattern |
Factory Pattern encapsulates object creation logic and returns appropriate object instances without exposing construction details to clients. |
Direct object creation increases coupling. |
Factory Pattern only uses static methods. |
Decouple object creation from object usage. |
PaymentFactory returning different payment processors. |
How does Factory support Open Closed Principle? |
Polymorphism, OCP |
| 88 |
Builder Pattern |
Builder Pattern separates object construction from representation, allowing complex objects to be created step-by-step. |
Constructors with many parameters become difficult to manage. |
Builder is useful only for immutable classes. |
Improve readability and object creation flexibility. |
Creating Employee objects with many optional attributes. |
Why is Builder widely used in modern Java APIs? |
Immutability, Object Creation |
| 89 |
Strategy Pattern |
Strategy Pattern defines a family of interchangeable algorithms and allows behavior to be selected at runtime. |
Applications often require multiple implementations of the same operation. |
Strategy Pattern is only for sorting algorithms. |
Enable runtime behavior variation. |
Different discount calculation strategies. |
How does Strategy reduce conditional complexity? |
Interface, Polymorphism |
| 90 |
Observer Pattern |
Observer Pattern establishes a one-to-many dependency where changes in one object automatically notify dependent objects. |
Event-driven communication requires loose coupling between producers and consumers. |
Observer Pattern requires direct object references. |
Support event-driven architectures. |
GUI event handling, application event publishing. |
How does Observer Pattern influence modern reactive systems? |
Event Driven Architecture, Reactive Programming |
| 101 |
Generic Method |
A Generic Method is a method that declares its own type parameters independent of the class's generic parameters. The method can operate on different data types while maintaining compile-time type safety. |
Some operations require type flexibility without making the entire class generic. |
Generic Methods can only exist inside Generic Classes. |
Enable reusable and type-safe algorithms. |
Utility methods such as Collections.emptyList(). |
How does the compiler infer generic method type parameters? |
Generics, Type Inference |
| 102 |
Generic Class |
A Generic Class is a class parameterized with one or more type variables, allowing the same class definition to work with different data types. |
Creating separate classes for every data type leads to code duplication. |
Generic Classes store type information at runtime. |
Promote code reuse and type safety. |
List, Map<K,V>, Optional. |
How does the compiler enforce type safety in Generic Classes? |
Generics, Type Erasure |
| 103 |
Generic Interface |
A Generic Interface is an interface that defines one or more type parameters, allowing implementations to operate on various data types while preserving type safety. |
Interfaces often need flexibility across multiple data models. |
Generic Interfaces behave differently from Generic Classes. |
Create reusable contracts across different types. |
Comparable, Comparator. |
How do implementations specify generic types? |
Interface, Generics |
| 104 |
Bounded Type Parameter |
A Bounded Type Parameter restricts the types that can be used as generic arguments. The extends keyword specifies upper bounds. |
Some generic algorithms require capabilities available only in specific type hierarchies. |
Bounds are used only with classes. |
Enforce constraints on generic type usage. |
. |
Why are bounds important in generic programming? |
Generics, Inheritance |
| 105 |
Multiple Bounds |
Multiple Bounds allow a generic type parameter to satisfy multiple constraints simultaneously. A type parameter may extend one class and implement multiple interfaces. |
Complex generic algorithms may require multiple capabilities. |
A type parameter can extend multiple classes. |
Combine multiple type requirements safely. |
<T extends Number & Comparable>. |
Why must the class bound appear before interface bounds? |
Generics, Type Constraints |
| 106 |
Recursive Type Bound |
A Recursive Type Bound defines a type parameter in terms of itself. It is commonly used to express self-referential relationships in generic APIs. |
Certain abstractions require knowledge of their own subtype. |
Recursive bounds create recursive objects. |
Enable strongly typed fluent APIs and comparisons. |
Comparable, Enum<E extends Enum>. |
Why is Comparable implemented using recursive bounds? |
Generics, Comparable |
| 107 |
Bridge Method |
A Bridge Method is a synthetic method generated by the compiler to preserve polymorphism after type erasure. It ensures overridden generic methods behave correctly at runtime. |
Type Erasure can create signature mismatches between parent and child classes. |
Developers explicitly write Bridge Methods. |
Maintain compatibility between generics and polymorphism. |
Overriding methods in generic inheritance hierarchies. |
Why does the compiler generate Bridge Methods automatically? |
Type Erasure, Polymorphism |
| 108 |
Heap Pollution |
Heap Pollution occurs when a variable of a parameterized type refers to an object that is not of that parameterized type. This can lead to runtime ClassCastException despite successful compilation. |
Type Erasure removes generic information at runtime. |
Generics completely eliminate type-related runtime errors. |
Highlight limitations of Java's generic implementation. |
Unsafe casts involving raw types. |
How can raw types introduce Heap Pollution? |
Generics, Type Erasure |
| 109 |
Reifiable Type |
A Reifiable Type is a type whose complete information is available at runtime. Primitive types, non-generic classes, and raw types are reifiable. |
Certain runtime operations require full type information. |
All Java types are reifiable. |
Identify types accessible through reflection and runtime checks. |
String.class and Integer.class. |
Why are generic parameter types usually not reifiable? |
Reflection, Type Erasure |
| 110 |
Non-Reifiable Type |
A Non-Reifiable Type is a type whose complete information is not available at runtime due to type erasure. Most generic parameterized types fall into this category. |
Generics were implemented without changing JVM bytecode compatibility. |
Non-Reifiable Types are invalid Java types. |
Explain limitations of runtime generic operations. |
List, Map<Long, String>. |
Why does instanceof not work with most parameterized types? |
Type Erasure, Generics |
| 111 |
Predicate |
Predicate is a functional interface representing a boolean-valued function that evaluates a condition against an input value. |
Applications frequently need reusable filtering logic. |
Predicate is only used in Stream API. |
Encapsulate conditions and validation rules. |
Filtering active users from a collection. |
Why is Predicate considered a first-class function? |
Functional Interface, Stream API |
| 112 |
Function |
Function is a functional interface representing a transformation from one value to another. It accepts an input and produces an output. |
Data transformation is a common programming operation. |
Function modifies the original object. |
Encapsulate reusable transformation logic. |
Converting Employee entities into EmployeeDTO objects. |
How does Function differ from Consumer? |
Lambda, Stream API |
| 113 |
Consumer |
Consumer is a functional interface that accepts an input and performs an operation without returning a result. |
Many operations involve side effects rather than value production. |
Consumer always modifies data. |
Represent executable actions. |
Logging, auditing, and notification operations. |
Why does Consumer return void? |
Lambda, Functional Interface |
| 114 |
Supplier |
Supplier is a functional interface that provides values without accepting input parameters. It acts as a value generator. |
Some operations need deferred or lazy value creation. |
Supplier stores values permanently. |
Support lazy evaluation and object creation. |
Creating objects only when needed. |
How is Supplier used in lazy initialization? |
Functional Programming, Lazy Evaluation |
| 115 |
UnaryOperator |
UnaryOperator is a specialization of Function where input and output types are identical. |
Many transformations modify values without changing their type. |
UnaryOperator is unrelated to Function. |
Simplify same-type transformations. |
Converting strings to uppercase. |
Why does UnaryOperator extend Function? |
Function, Functional Interface |
| 116 |
BinaryOperator |
BinaryOperator is a specialization of BiFunction where both inputs and the result share the same type. |
Many operations combine two values into one value of the same type. |
BinaryOperator always performs arithmetic operations. |
Model reduction and aggregation logic. |
Summing integers in a stream reduction. |
Why is BinaryOperator heavily used by reduce() operations? |
Stream API, Functional Programming |
| 117 |
Stream Pipeline |
A Stream Pipeline is the sequence of operations applied to a stream, consisting of a source, intermediate operations, and a terminal operation. Execution occurs only when a terminal operation is invoked. |
Data processing often involves multiple transformation stages. |
Each stream operation executes immediately. |
Enable declarative and optimized data processing. |
Filtering, mapping, and collecting employee records. |
How does the JVM optimize Stream Pipelines? |
Stream API, Lazy Evaluation |
| 118 |
Intermediate Operation |
An Intermediate Operation transforms a stream and returns another stream, allowing multiple operations to be chained together. Intermediate operations are lazy. |
Complex data processing requires staged transformations. |
Intermediate Operations immediately process data. |
Build processing pipelines incrementally. |
filter(), map(), sorted(). |
Why are Intermediate Operations considered lazy? |
Stream Pipeline, Stream API |
| 119 |
Terminal Operation |
A Terminal Operation triggers execution of the entire stream pipeline and produces a final result or side effect. |
Stream processing must eventually produce usable outcomes. |
Terminal Operations can be executed repeatedly on the same stream. |
Materialize results from stream computations. |
collect(), count(), forEach(). |
Why does a stream become unusable after a Terminal Operation? |
Stream Pipeline, Stream API |
| 120 |
Lazy Evaluation |
Lazy Evaluation postpones computation until the result is actually required. Stream operations leverage this principle to avoid unnecessary work. |
Eager computation may waste resources on unused results. |
Lazy Evaluation always improves performance. |
Optimize execution by processing only necessary data. |
Filtering millions of records while stopping after the first match. |
How does Lazy Evaluation reduce processing overhead? |
Stream API, Supplier |
| 121 |
Spliterator |
Spliterator is a specialized iterator designed for traversing and partitioning data sources efficiently. It supports both sequential and parallel processing by allowing collections to split their elements into smaller chunks. |
Parallel processing requires efficient work distribution across multiple threads. |
Spliterator is simply a faster Iterator. |
Enable scalable parallel stream processing. |
Parallel Stream dividing a large collection among multiple worker threads. |
How does Spliterator support parallelism better than Iterator? |
Stream API, Parallel Streams |
| 122 |
Collector |
Collector is a mutable reduction mechanism used to accumulate stream elements into a final result. It defines how elements are supplied, accumulated, combined, and finished. |
Stream processing often requires aggregation into collections or computed results. |
Collector only works with collections. |
Convert stream elements into meaningful outputs. |
Collecting Employee objects into a Map grouped by department. |
What are the components of a Collector? |
Stream API, Collectors |
| 123 |
Collectors Utility |
Collectors is a utility class providing predefined Collector implementations for common aggregation operations. |
Many collection and aggregation operations are repetitive. |
Collectors stores stream data permanently. |
Simplify stream result aggregation. |
Collectors.toList(), Collectors.toSet(), Collectors.toMap(). |
Why does Collectors improve stream readability? |
Collector, Stream API |
| 124 |
GroupingBy |
groupingBy is a Collector that groups stream elements based on a classification function and returns a Map of grouped results. |
Business data often needs categorization. |
groupingBy performs sorting. |
Organize data into logical groups. |
Grouping employees by department. |
How does groupingBy differ from partitioningBy? |
Collector, Stream API |
| 125 |
PartitioningBy |
partitioningBy is a Collector that divides stream elements into exactly two groups based on a boolean condition. |
Many business rules result in binary classifications. |
partitioningBy supports unlimited groups. |
Efficiently separate data into true and false categories. |
Partitioning customers into active and inactive groups. |
When should partitioningBy be preferred over groupingBy? |
Collector, Predicate |
| 126 |
FlatMap |
flatMap transforms each element into a stream and then flattens all resulting streams into a single stream. |
Nested collections are common in real-world data models. |
flatMap is identical to map. |
Eliminate nested structures and simplify processing. |
Converting List<List> into Stream. |
Why is flatMap essential for processing nested collections? |
Stream API, Map |
| 127 |
Reduce |
reduce combines stream elements into a single result using an associative accumulation function. It is a fundamental reduction operation. |
Many computations involve aggregating values into a summary result. |
reduce only performs mathematical calculations. |
Perform generalized aggregation. |
Calculating total salary of all employees. |
Why must reduce operations be associative for parallel execution? |
BinaryOperator, Stream API |
| 129 |
Stream Characteristics |
Stream Characteristics describe properties of stream sources such as ORDERED, DISTINCT, SORTED, SIZED, NONNULL, IMMUTABLE, and CONCURRENT. These characteristics help optimize execution. |
Stream implementations need metadata for optimization decisions. |
Characteristics affect only output formatting. |
Improve execution efficiency and correctness. |
ArrayList streams marked as ORDERED and SIZED. |
How do characteristics influence parallel stream performance? |
Spliterator, Stream API |
| 130 |
Short Circuit Operation |
A Short Circuit Operation terminates stream processing as soon as the result is known, avoiding unnecessary computation. |
Processing entire datasets is often wasteful when an early answer exists. |
Every terminal operation short-circuits. |
Improve efficiency by stopping early. |
anyMatch(), findFirst(), findAny(). |
Why can short-circuit operations significantly improve performance? |
Lazy Evaluation, Stream API |
| 141 |
NIO |
NIO (New I/O) is a Java I/O framework introduced to support high-performance, non-blocking, and scalable input/output operations. Unlike traditional stream-based I/O, NIO uses Buffers, Channels, and Selectors. |
Traditional I/O becomes inefficient when handling large numbers of concurrent connections. |
NIO is simply a faster version of java.io. |
Support scalable network and file operations. |
High-concurrency servers and messaging systems. |
How does NIO differ fundamentally from traditional stream-based I/O? |
Channel, Buffer |
| 142 |
Buffer |
A Buffer is a memory container used by NIO to temporarily hold data during input and output operations. All NIO data transfers occur through buffers. |
Efficient I/O requires intermediate storage between applications and operating systems. |
Buffers store unlimited data. |
Provide controlled memory regions for data exchange. |
Reading data from files into memory before processing. |
Why is data always transferred through Buffers in NIO? |
NIO, ByteBuffer |
| 143 |
ByteBuffer |
ByteBuffer is the most commonly used NIO buffer implementation. It stores binary data and provides methods for reading and writing primitive values. |
Most I/O operations ultimately operate on bytes. |
ByteBuffer is only used for files. |
Facilitate efficient binary data manipulation. |
Network packet processing and file reading. |
What is the purpose of position, limit, and capacity in ByteBuffer? |
Buffer, Channel |
| 144 |
Channel |
A Channel is a bidirectional communication path between an application and an I/O source or destination. Unlike streams, channels support both reading and writing. |
Modern applications require more flexible I/O mechanisms. |
Channels replace all stream APIs. |
Enable efficient data transfer operations. |
FileChannel, SocketChannel, DatagramChannel. |
Why are Channels considered more flexible than Streams? |
NIO, Buffer |
| 145 |
Selector |
A Selector allows a single thread to monitor multiple channels and react when one or more channels become ready for I/O operations. |
Creating one thread per connection does not scale well. |
Selectors eliminate the need for threads. |
Enable event-driven non-blocking architectures. |
High-performance web servers handling thousands of connections. |
How does Selector support scalable networking? |
NIO, Non-Blocking I/O |
| 146 |
Direct Buffer |
A Direct Buffer is a buffer allocated outside the JVM heap in native memory. It reduces copying between JVM memory and operating system memory during I/O operations. |
Heap-to-kernel memory copies introduce overhead. |
Direct Buffers are always faster. |
Improve large-scale I/O performance. |
Database drivers and high-performance networking frameworks. |
What are the trade-offs of using Direct Buffers? |
ByteBuffer, Native Memory |
| 147 |
Memory Mapped File |
A Memory Mapped File maps file contents directly into memory, allowing file access as if it were ordinary memory operations. |
Large file operations often involve excessive copying and system calls. |
Entire files must be loaded into RAM. |
Improve performance for large file processing. |
Log analysis and database storage engines. |
Why can Memory Mapped Files outperform traditional file I/O? |
FileChannel, NIO |
| 148 |
Scatter Gather I/O |
Scatter/Gather I/O allows reading data into multiple buffers (scatter) and writing data from multiple buffers (gather) using a single I/O operation. |
Complex protocols often contain multiple logical data sections. |
Scatter/Gather requires multiple system calls. |
Improve efficiency when handling structured data. |
Network protocols containing headers and payloads. |
What advantages does Scatter/Gather provide over standard reads and writes? |
Channel, ByteBuffer |
| 149 |
Asynchronous Channel |
An Asynchronous Channel performs I/O operations without blocking the calling thread. Completion is reported through callbacks or futures. |
Blocking threads during I/O reduces scalability. |
Asynchronous means parallel execution. |
Improve responsiveness and scalability. |
Asynchronous file servers and network applications. |
How do asynchronous channels differ from non-blocking channels? |
Future, NIO |
| 150 |
Zero Copy |
Zero Copy is a technique that transfers data between devices without unnecessary copying through user-space memory. The operating system moves data directly between buffers. |
Memory copying consumes CPU cycles and reduces throughput. |
Zero Copy means no memory is used. |
Maximize I/O performance and reduce CPU overhead. |
High-speed file transfer servers. |
How does FileChannel.transferTo() implement Zero Copy? |
NIO, Operating System |
| 151 |
Pattern Matching |
Pattern Matching is a language feature that combines type checking and data extraction into a single operation. It simplifies conditional logic and reduces boilerplate code. |
Traditional type checking often requires repetitive casting code. |
Pattern Matching replaces polymorphism. |
Improve readability and safety. |
Processing different types of events in business applications. |
How does Pattern Matching reduce explicit casting? |
instanceof, Switch Expression |
| 152 |
Switch Expression |
Switch Expression is an enhanced form of switch that returns values directly and eliminates many fall-through issues associated with traditional switch statements. |
Traditional switch statements are verbose and error-prone. |
Switch Expressions replace all if statements. |
Improve readability and reduce bugs. |
Determining order status messages. |
How do Switch Expressions differ from classic switch statements? |
Pattern Matching, Enum |
| 153 |
Text Block |
Text Block is a multi-line string literal introduced to simplify representation of structured text such as JSON, XML, and SQL. |
Escaping large text blocks is difficult and reduces readability. |
Text Blocks create mutable strings. |
Improve readability of multiline content. |
Embedding SQL queries and JSON payloads. |
What advantages do Text Blocks provide over traditional string literals? |
String, Compiler |
| 154 |
Local Record |
A Local Record is a Record declared within a method. Its scope is limited to that method, making it useful for temporary immutable data structures. |
Some data models are relevant only within a specific method. |
Local Records are accessible globally. |
Improve locality and reduce class clutter. |
Intermediate result representations inside stream operations. |
When should Local Records be preferred over local classes? |
Record, Immutability |
| 155 |
Record Pattern |
Record Pattern allows deconstruction of record components directly within pattern matching constructs. |
Extracting record fields often requires repetitive accessor calls. |
Record Patterns modify record values. |
Simplify data extraction. |
Processing API response records. |
How do Record Patterns improve readability? |
Record, Pattern Matching |
| 156 |
Pattern Matching instanceof |
Pattern Matching for instanceof combines type checking and variable declaration into a single construct. |
Traditional instanceof checks require explicit casting afterward. |
It changes runtime type behavior. |
Reduce boilerplate and improve safety. |
Processing different message types. |
Why is Pattern Matching instanceof safer than manual casting? |
Pattern Matching, instanceof |
| 157 |
Sealed Interface |
A Sealed Interface restricts which classes or interfaces may implement it. The permitted implementations are explicitly declared. |
Large inheritance hierarchies often require stricter control. |
Sealed Interfaces behave like final interfaces. |
Create predictable and controlled type hierarchies. |
PaymentMethod permitting only approved implementations. |
When should Sealed Interfaces be used instead of ordinary interfaces? |
Sealed Class, Polymorphism |
| 158 |
Permitted Class |
A Permitted Class is a class explicitly listed in the permits clause of a sealed class or interface. Only permitted classes may participate in the hierarchy. |
Sealed hierarchies require explicit membership control. |
Any subclass can become a permitted class. |
Enforce inheritance restrictions. |
Circle and Rectangle as permitted subclasses of Shape. |
How does the JVM enforce permitted class restrictions? |
Sealed Class, Sealed Interface |
| 163 |
MethodHandle |
MethodHandle is a typed, direct reference to methods, constructors, or fields that can be invoked dynamically. It is more efficient than reflection for repeated dynamic invocations. |
Reflection introduces overhead for dynamic method invocation. |
MethodHandle is another form of reflection. |
Enable high-performance dynamic invocation. |
Lambda implementation and dynamic language support. |
Why is MethodHandle faster than Reflection? |
Reflection, Invokedynamic |
| 167 |
Annotation Processor |
Annotation Processor is a compile-time tool that analyzes annotations and generates additional code, metadata, or validation results before application execution. |
Certain repetitive tasks can be automated during compilation. |
Annotations execute business logic directly. |
Automate code generation and validation. |
Lombok, MapStruct, Dagger. |
How does compile-time annotation processing differ from runtime reflection? |
Annotation, Compiler |
| 168 |
Java Platform Module System (JPMS) |
JPMS is the module system introduced in Java 9 that allows applications to define explicit module boundaries, dependencies, and encapsulation rules. |
Large applications require stronger modularity than packages alone provide. |
JPMS replaces packages. |
Improve maintainability, security, and deployment. |
Modular enterprise applications. |
How does JPMS improve encapsulation compared to packages? |
Module, ClassLoader |
| 169 |
ServiceLoader |
ServiceLoader is a built-in Java mechanism for discovering and loading service implementations dynamically at runtime. It supports pluggable architectures. |
Applications often require extension points without hardcoded implementations. |
ServiceLoader performs dependency injection. |
Enable runtime extensibility. |
JDBC driver discovery mechanism. |
How does ServiceLoader locate implementations? |
SPI, ClassLoader |
| 170 |
Service Provider Interface (SPI) |
SPI is a design pattern where a framework defines a contract and external providers supply implementations. ServiceLoader is commonly used to discover SPI implementations. |
Frameworks need extensibility without direct knowledge of implementations. |
SPI and API are the same concept. |
Support plugin-based architectures. |
JDBC drivers, logging providers, authentication providers. |
What is the difference between an API and an SPI? |
ServiceLoader, Framework Design |