Java Other Interview Questions
496 questions with answers · Java Interview Guide
Miscellaneous Java topics including networking, I/O, annotations, and build tools.
What is the main advantage of resources
Resources (try-with-resources) automatically close AutoCloseable objects, ensuring proper cleanup of connections, streams, and other resources even on exceptions.
What commands do you know from SQL
SELECT, INSERT, UPDATE, DELETE, JOIN, WHERE, GROUP BY, ORDER BY, HAVING, AGGREGATE functions (COUNT, SUM, AVG, MAX, MIN).
What data structure lies in Arraylist
ArrayList's underlying data structure is a dynamic resizable array (Object[]) that grows exponentially; provides O(1) access and O(n) insertion/deletion.
What does the Componentscan annotation do
@ComponentScan tells Spring to scan specified packages for @Component, @Service, @Repository, @Controller annotated classes and auto-register them as beans in the application context.
That during assembly can be provided by Maven
Maven provides dependencies, plugins, and build configurations during assembly through the POM file and central repositories.
Against the background of which Spring Date is built
Spring Data is built on top of JPA (Java Persistence API) and Hibernate ORM framework.
What is caching
Caching stores frequently accessed data in memory to reduce latency and database load by serving from cache instead of recalculating.
What is the difficulty of searching for an element in Linkedlist
LinkedList has O(n) time complexity for searching an element since it requires sequential traversal from head or tail.
What are the types of stitches in JDBC
JDBC statement types are Statement (simple queries), PreparedStatement (parameterized queries), and CallableStatement (stored procedures).
What are the requirements for transaction
Transaction requirements are Atomicity, Consistency, Isolation, and Durability (ACID properties).
How the vertical and horizontal partners are different
Vertical scaling adds resources to existing servers (CPU, RAM), while horizontal scaling adds more servers to distribute load.
Are there any contraindications to the use of indexes
Index contraindications include write-heavy tables, low cardinality columns, and insufficient memory; they slow down INSERT/UPDATE/DELETE operations.
Is it possible to make private variables in the interface
No, interfaces cannot have private variables; all fields are implicitly public static final.
Will Stream API Randomacess provide
No, Stream API does not guarantee random access; it's designed for sequential processing and is often lazily evaluated.
Is there an iterator in Stream
Stream doesn't have an Iterator directly, but you can convert it using stream.iterator() or collect to a collection.
What do we use when we write for each
forEach uses the Iterable interface and calls iterator() under the hood to traverse collections.
What is the difference in replication and hearts
Replication copies data across nodes for availability; heartbeat is a periodic signal to detect node health/liveness.
What is the main problem of the cache
Cache coherency problem: multiple caches holding stale data, requiring invalidation strategies or write-through/write-back policies.
How to make a stream from the class
Make a class implement Iterable interface and override iterator() method to return an Iterator for that class.
Based on which data structure, Linked List is implemented
LinkedList is implemented using a doubly-linked list data structure with nodes containing data and references to next/previous nodes.
What is CAS
CAS (Compare-And-Swap) is an atomic operation that compares a memory location's current value with an expected value and atomically updates it if they match, enabling lock-free concurrent programming.
What is the difference between PUT and Compute in Map
PUT overwrites the value unconditionally, while Compute applies a function to compute the new value based on the existing entry, allowing conditional updates in a single atomic operation.
What does verified and unverified values mean
Verified values are those checked at compile-time (type-safe), while unverified values are unchecked at runtime, typically referring to raw types or unchecked casts in generics.
How to work on Spring
Spring is a lightweight framework providing dependency injection, aspect-oriented programming, and transaction management; configure beans via XML, annotations, or Java config, then autowire dependencies.
What is the difference between JPA and Hibernate
JPA is a specification for ORM, while Hibernate is an implementation of JPA; Hibernate offers additional features and can be used with or without following JPA standards.
What is Fetch Type
Fetch Type determines when associated entities are loaded: EAGER loads immediately, LAZY loads on access; default is LAZY for collections and EAGER for single relationships.
What are the mechanisms for complex requests with many parameters
Use query parameters, request bodies, or specialized query builders (QueryDSL, Specifications); Spring Data JPA and custom repositories handle complex queries with dynamic predicates.
What is the difference between JDBC species
JDBC drivers are categorized into Type 1-4: Type 1 (JDBC-ODBC bridge), Type 2 (native protocol), Type 3 (network protocol), Type 4 (direct database protocol); Type 4 is generally preferred.
What is the difference between atomicity and consistency
Atomicity ensures all-or-nothing transactions, while consistency ensures data integrity rules are maintained; both are essential but atomicity focuses on operation completeness, consistency on data validity.
Explain how indexes work
Indexes create sorted data structures mapping column values to row positions, enabling fast O(log n) lookups instead of O(n) full scans; trade storage for query speed.
There is experience with cloud services
Yes, extensive experience with AWS, Azure, GCP for containerized deployments, serverless functions, managed databases, and scaling across microservices architectures.
What are we working inside Stream
Streams are functional pipelines processing sequences of elements with intermediate (map, filter) and terminal (collect, reduce) operations, enabling declarative data transformations.
What essence in collections helps to access objects in the collection
Iterators and indexes provide access mechanisms; collections implement Iterable for foreach loops, while List supports index-based access and Set relies on iterators.
What classic functional interfaces you know
Function<T,R>, Predicate<T>, Consumer<T>, Supplier<T>, BiFunction<T,U,R>, UnaryOperator<T>, BinaryOperator<T> are commonly used functional interfaces in Stream and functional programming.
What task the chart solves
Graphs solve path-finding, connectivity, cycle detection, and topological sorting problems; they model relationships between entities with directed/undirected edges and weighted connections.
What data structure lies in Arraylist
ArrayList uses a dynamic resizable array (Object[]) as its underlying data structure, growing by 50% when capacity is exceeded.
What is a constructor for copying
Copy constructor creates a new object from an existing one: `public MyClass(MyClass original) { this.field = original.field; }`.
What is the idea of Builder
Builder pattern constructs complex objects step-by-step using method chaining: `new User.Builder().setName("John").setEmail("john@example.com").build()`.
What is unique applied to
@Unique annotation applied to fields/properties to enforce uniqueness constraint, typically in JPA entities mapping to database UNIQUE constraints.
Can there be a situation where Primary Key is repeated
No, PRIMARY KEY must be unique and not null; if a value repeats, it violates PRIMARY KEY constraint and the INSERT/UPDATE fails.
What is the basis of Spring Framework
Spring Framework is built on Inversion of Control (IoC) and Dependency Injection principles, using a container to manage object lifecycle and dependencies declaratively.
Is it possible to introduce dependence not only through the constructor
Yes, dependencies can be injected via setter methods, field injection, or method parameters; constructor injection is just one approach.
What is performed earlier: constructor, setter or implementation field
Field initialization happens first, then constructor execution; setters are called after construction if configured.
File specimen contains only a file path
A File object represents a file path (abstract pathname) but doesn't necessarily mean the file exists on disk.
What do the relationship "is" and "have" in the OOP
'Is-a' represents inheritance (IS-A relationship), while 'has-a' represents composition/association (HAS-A relationship).
Where it is better to use inheritance and association
Use inheritance for 'is-a' relationships with shared behavior; prefer composition/association for flexibility and loose coupling.
Why do you need Final for a static method
Final on static methods prevents overriding in subclasses, ensuring the method signature cannot be changed by inheritance.
Why Throws is bad in the signature of the method
Throws in method signatures exposes internal implementation details and forces checked exception handling on callers, breaking encapsulation.
How to throw exceptions correctly
Throw specific exceptions with meaningful messages; use unchecked exceptions for programming errors and checked exceptions for recoverable conditions.
Tell me about File class and its device
File class is an abstract representation of file/directory pathnames with platform-independent path handling and metadata methods like exists(), isFile(), delete().
How to avoid compulsory IOEXCEPTION processing
Use try-with-resources statements or wrapper libraries like Apache Commons IO to handle checked IOExceptions implicitly or convert to unchecked exceptions.
What is atomic and consistency
Atomicity means an operation completes fully without interruption; consistency means data transitions between valid states without violating constraints.
Why is Java Memory Model important when working with multi -thread
Java Memory Model defines visibility guarantees and ordering rules for shared variable access across threads, preventing unexpected behavior from compiler/CPU optimizations.
What is the difference between Synchronized and Lock
Synchronized is implicit mutual exclusion using built-in monitors; Lock (from java.util.concurrent) offers explicit control with tryLock(), conditions, and fairness policies.
What is callable
Callable is a functional interface similar to Runnable but returns a result and can throw checked exceptions; used with ExecutorService for async task execution.
Advantages of the implementation of Executorservice
ExecutorService provides thread pooling, task scheduling, and lifecycle management (shutdown), reducing overhead of creating threads and simplifying concurrent task handling.
Why Hashmap appeared
HashMap was introduced to provide O(1) average-case lookup time for key-value pairs, unlike the O(n) performance of Hashtable's linear search.
Why is it bad to make an array of bytes for hashmap
Using byte arrays as HashMap keys is bad because byte arrays use reference equality (hashCode/equals), not content equality, causing lookup failures even with identical content.
What is HashTable problem
HashTable is a legacy synchronized HashMap that uses hash codes to store key-value pairs; it's slower than HashMap due to synchronization and should be avoided in favor of ConcurrentHashMap.
What is automatic increment in different databases
AUTO_INCREMENT (MySQL), SERIAL (PostgreSQL), IDENTITY (SQL Server), and SEQUENCE (Oracle) are used to generate unique primary keys automatically.
What are the insulation levels in SQL
Four isolation levels: READ_UNCOMMITTED (dirty reads), READ_COMMITTED (non-repeatable reads), REPEATABLE_READ (phantom reads), SERIALIZABLE (full isolation).
Tell me about the idea of Framwar Hibernate
Hibernate is an ORM framework that maps Java objects to database tables, handling persistence, lazy loading, caching, and automatic SQL generation.
What types of communication in Hibernate are there
Hibernate communication includes unidirectional (one object references another), bidirectional (mutual references), and lazy/eager loading strategies.
What annotations are there to create bins
@Component, @Service, @Repository, @Controller, and @Bean annotations are used to define Spring-managed beans.
What is the value of the Bean annotation
@Bean is a method-level annotation that explicitly declares a bean definition, useful for configuring third-party libraries.
What is BeandEfinition and why is it needed
BeanDefinition is metadata describing how to instantiate a bean (class, scope, properties, initialization); Spring uses it internally for bean creation.
How to contact another service from a Spring application
Use RestTemplate, WebClient, or FeignClient to call other services; RestTemplate is synchronous, WebClient is reactive, FeignClient is declarative.
What is the value of Spring Boot
Spring Boot reduces boilerplate, provides auto-configuration, embedded servers, and production-ready metrics via conventions over configuration.
What starters do you know in Spring Boot
spring-boot-starter-web (web), spring-boot-starter-data-jpa (database), spring-boot-starter-security (auth), spring-boot-starter-actuator (monitoring).
Is it necessary to catch Throws
No, Java unchecked exceptions don't require catching; checked exceptions must be caught or declared with throws.
What is encapsulation for
Encapsulation hides internal implementation details, controls access through getters/setters, and protects object integrity.
Stack, is it a long -term storage
No, Stack is LIFO (Last-In-First-Out) short-term storage in memory; long-term storage is disk/database.
How can you compare with each other data types
Use .equals() for object comparison, == for reference equality; primitives compared with == check value equality.
As primitive data types can be compared to each other
Primitive types are compared with == operator directly by value (int, double, boolean, etc.).
Whether I heard something about static methods
Static methods belong to the class, not instances; called via ClassName.method(), shared across all objects, cannot access instance variables.
Why Equals need to be redistributed and why
Equals must be overridden to compare object contents properly; default implementation uses reference equality which is usually wrong for business logic.
What are the main implementations of leaf collections
Main implementations: ArrayList (dynamic array), LinkedList (doubly-linked), HashSet (hash table), TreeSet (Red-Black tree), HashMap, TreeMap.
What is the advantage of Hibernate over JBC
Hibernate provides ORM abstraction, automatic SQL generation, lazy loading, and caching, reducing boilerplate code compared to raw JDBC.
What is caching in Hibernate
Caching in Hibernate stores frequently accessed objects in memory (L1 session-level, L2 application-level) to reduce database queries and improve performance.
There is experience in writing tests
Describe your testing experience by framework and level: unit tests (JUnit 5, Mockito), integration tests (Spring Boot Test, Testcontainers), and any end-to-end or performance testing. Mention your approach to test coverage and whether you practice TDD.
Familiar with the principles of system scaling
I'm familiar with horizontal/vertical scaling, load balancing, database sharding, caching strategies, and microservices architecture for system scalability.
What is a dock
Docker is a containerization platform that packages applications with dependencies into isolated containers for consistent deployment across environments.
What he worked with from the point of view of security
Mention specific security practices you have applied: authentication and authorization (Spring Security, OAuth2, JWT), input validation and SQL injection prevention, HTTPS/TLS configuration, secrets management, OWASP Top 10 awareness. Give an example of a security issue you caught or fixed.
How many parts is JVTTOKEN
JWT tokens have 3 parts: header (algorithm/type), payload (claims/data), and signature (verification), separated by dots.
What is the feature of Spring Boot
Spring Boot key features include auto-configuration, embedded servers, production-ready metrics, simplified dependency management, and zero boilerplate setup.
What types of tests do you know
Unit tests (JUnit), integration tests (Spring Boot Test), functional tests, performance tests, and end-to-end tests.
What contains the task that came from analysts
Tasks from analysts contain requirements, acceptance criteria, business logic, user stories, and success conditions for implementation.
What is Main method
Main method is the program entry point: public static void main(String[] args) that JVM invokes to start execution.
What gives the word static
Static keyword makes members (variables/methods) belong to the class, not instances; shared across all objects and accessible without instantiation.
Why Main is considered static
Main is static because JVM needs to call it without creating an object instance; static methods can be invoked on the class itself.
What are arrays in Java
Arrays are fixed-size, ordered collections of elements of the same type; accessed by index with O(1) lookup time.
What class is realized by the dynamic array in Java
ArrayList class implements the dynamic array in Java, providing resizable arrays with automatic capacity management.
Due to which NIO provides non -insoluble access to resources
NIO (New I/O) provides non-blocking access through selectors that monitor multiple channels for I/O events without blocking threads.
What is the feature of CopyonWritearraylist
CopyOnWriteArrayList creates a copy of the internal array on modification, ensuring thread-safety and safe iteration without explicit synchronization.
What is Stream in the Stream API context
Stream in Stream API is a functional abstraction representing a sequence of elements supporting lazy evaluation and declarative transformations.
What is EXECUTORSERVICE for execution
ExecutorService is a framework for managing thread pools and asynchronous task execution, providing methods like submit(), invokeAll(), and shutdown().
What is meant by the letter O in Solid
O in SOLID stands for Open/Closed Principle: classes should be open for extension but closed for modification through inheritance/composition.
What are the differences between the strategy pattern and state pattern
Strategy pattern defines interchangeable algorithms at runtime, while State pattern changes object behavior based on internal state; strategy is selected externally, state transitions internally.
What is an adapter
Adapter pattern converts one interface to another that clients expect, allowing incompatible interfaces to work together without modifying existing code.
What is a group in the database
A database group (typically a user group or role) is a collection of permissions/privileges that can be assigned to multiple users at once for access control.
What are the main orm realization in Java
Main Java ORMs are Hibernate, JPA (Java Persistence API), MyBatis, EclipseLink, and TopLink; Hibernate is the most widely used.
What levels of caching are there in hibernate
Hibernate has three caching levels: L1 (Session-level, always enabled), L2 (SessionFactory-level, optional), and Query Cache (caches query results).
What is Docker
Docker is a containerization platform that packages applications with dependencies into lightweight, isolated containers for consistent deployment across environments.
What is the difference between a docker and a virtual machine
Docker containers share the host OS kernel and are lightweight (MB-sized), while VMs include full OS copies and are heavier (GB-sized) but provide stronger isolation.
How is JVM memory arranged
JVM memory is divided into Heap (objects, GC-managed), Stack (primitives, method calls, thread-local), Metaspace (class metadata), Code Cache (compiled code), and off-heap regions.
What are stacks
Stacks are LIFO (Last-In-First-Out) data structures used for JVM method execution frames, local variables, and return addresses; each thread has its own stack.
How the data between the glass and the hit pass
Data between cache layers and main memory pass through memory hierarchy: L1/L2/L3 CPU caches sync with RAM using cache coherence protocols, managed by CPU and JVM.
What is garbage assembly
Garbage collection is automatic memory deallocation removing unreachable objects; JVM uses algorithms like G1GC, CMS, or ZGC to identify and reclaim unused heap memory.
What is multi -fluidity, parallelism and asynchronism
Multithreading runs multiple threads in one process sharing memory; Parallelism executes truly simultaneous tasks on multi-core systems; Asynchronism performs non-blocking operations allowing other work during waits.
What are Future and Completablefuture classes for
Future represents an async computation result available later with blocking get(); CompletableFuture extends this with non-blocking callbacks, chaining, and manual completion.
What is under the letter L in the principles of Solid
L in SOLID stands for Liskov Substitution Principle: subtypes must be substitutable for parent types without breaking functionality; enforces proper inheritance contracts.
What is Result Set in JDBC
ResultSet is a JDBC interface that holds query results as a table; it maintains a cursor pointing to current row and provides methods to traverse and extract data.
Features of Result Set in JDBC and its configuration
ResultSet features include scrollability (TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE), updatability (CONCUR_READ_ONLY, CONCUR_UPDATABLE), and holding behavior (HOLD_CURSORS_OVER_COMMIT); configured via Statement.createStatement(int, int).
What is SessionFactory in Hibernate
SessionFactory is a thread-safe, immutable factory in Hibernate that creates Session instances; it's expensive to create (one per application) and manages dialects, connection pools, and mappings.
Tell me about the control levels of transaction insulation in Hibernate
Hibernate transaction isolation levels mirror SQL standards: READ_UNCOMMITTED (dirty reads), READ_COMMITTED (no dirty reads), REPEATABLE_READ (no phantom reads), SERIALIZABLE (full isolation); configured via hibernate.connection.isolation.
What is in the Collections Hiorarchies API
Collections API hierarchy includes Collection (Iterable, add, remove), with List (ordered, indexed), Set (unique elements), Queue (FIFO); Map is separate for key-value pairs.
TREMAP class, which data rod underly
TreeMap is a Red-Black Tree implementation providing O(log n) operations, sorted keys by Comparable/Comparator, and range operations; used when sorted map access is needed.
What is the complexity of the binary search
O(log n) - binary search halves the search space on each iteration by requiring a sorted array
Why do you need Future
Future represents an asynchronous computation result that may not be available immediately; you use it to retrieve results and check completion status
Why do you need Completablefuture
CompletableFuture extends Future with the ability to manually complete results, chain operations, and combine multiple async computations fluently
JDBC is the implementation or specification
JDBC is a specification (interface) defined by Java; vendors provide implementations as drivers for specific databases
Why load a database driver
Loading a database driver registers it with DriverManager so JDBC can establish connections to the specific database
What is Statement
Statement is a JDBC interface for executing SQL queries; it sends SQL to the database and returns results
What types of statement are there
Three types: Statement (simple queries), PreparedStatement (precompiled with parameters, prevents SQL injection), CallableStatement (stored procedures)
What is JPA
JPA is a specification for ORM (Object-Relational Mapping) that provides annotations and APIs to map Java objects to database tables
What is n+1 select problem
N+1 select problem occurs when fetching parent entities triggers N additional queries for child entities; solve with JOIN FETCH or eager loading
Final use options
Final prevents modification: final variables can't be reassigned, final methods can't be overridden, final classes can't be extended
What is the ITERABLE interface
Iterable is an interface with iterator() method that returns an Iterator; enables for-each loops and sequential element access
What is REST API
REST API is an architectural style using HTTP methods (GET, POST, PUT, DELETE) on resources identified by URLs to perform CRUD operations
What is the difference between a functional approach and object-oriented
Functional approach emphasizes immutability and function composition; OOP emphasizes objects, mutable state, and inheritance,Java supports both paradigms
What is the transmission of parameters in Java and how it happens
Java passes parameters by value: primitives pass the value itself, objects pass a copy of the reference pointing to the same object
What principle of OOP does the reduction of the methods belong
Encapsulation (reducing method visibility/access) is the OOP principle that hides internal implementation details and protects object state
What are Immutable objects
Immutable objects cannot be modified after creation; all fields are final and private, no setters,examples: String, Integer, LocalDate
With what functional interface do we work in the MAP () method
Function<T, R> functional interface,map() transforms each element of a stream using a function that takes one argument and returns a result
What is Named Query in Hibernate
Named Query is a predefined JDBC query in Hibernate defined via @NamedQuery annotation; reusable, validated at startup, improves performance
What is BeanpostProcessor
BeanPostProcessor is a Spring interface for custom bean initialization logic; postProcessBeforeInitialization() and postProcessAfterInitialization() intercept bean creation
What is Bean Scope
Bean Scope defines the lifecycle/visibility of a bean: singleton (one instance), prototype (new per request), request/session/application (web-scoped)
What types of scope exist
Java has four scopes: local (method/block), instance (object lifetime), static/class (class lifetime), and block scope for variables declared within braces.
What does the framework Spring do
Spring is a lightweight IoC container and framework that provides dependency injection, AOP, transaction management, and simplifies enterprise Java development.
What is oc and di
OC (Object Composition) is using objects as members; DI (Dependency Injection) is providing dependencies to objects rather than having them create their own.
What is the difference between an ordinary object from Bean
A Bean is a managed object created and controlled by a container (like Spring) with lifecycle hooks, while an ordinary object is manually instantiated and managed by the programmer.
What is Maven
Maven is a build automation and dependency management tool that uses a POM.xml file to define project structure, dependencies, and plugins.
Why do we use access modifiers
Access modifiers (public, protected, private, package-private) control visibility and encapsulation, protecting internal state and defining API boundaries.
Is it the correct statement that the String massif is the Char
No, a String is an immutable object composed of char arrays, not a char primitive; it's a reference type stored on the heap.
What are the key classes Exception
Key Exception classes are Throwable (root), Exception (checked), RuntimeException (unchecked), and Error; subclasses include IOException, NullPointerException, etc.
How can you process exceptions
Process exceptions using try-catch-finally blocks, try-with-resources for auto-closing resources, or throwing/propagating exceptions up the call stack.
What is a phantom reading
Phantom read is a transaction isolation issue where a query returns different rows in subsequent reads due to concurrent inserts/deletes, even without dirty/non-repeatable reads.
What does Fetchtype Lazy mean
FetchType.LAZY delays loading related entities until explicitly accessed, reducing memory and improving performance; opposite is EAGER which loads immediately.
What entities are involved in creating Bean
Creating a Bean involves BeanFactory/ApplicationContext reading configuration (XML/annotations), instantiating via constructor/factory method, setting properties, calling lifecycle callbacks (init/destroy).
What is asynchronism
Asynchronism means operations execute independently without blocking the caller; results are returned via callbacks, futures, or reactive streams.
What are the advantages of the composition in the OOP
Composition advantages: flexibility (change implementations without inheritance), loose coupling, no fragile base class problem, and better code reuse than inheritance.
What can lead to a violation of the principles of Solid
SOLID violations occur from tight coupling, god classes with multiple responsibilities, violating Liskov Substitution, ignoring dependency inversion, or interface segregation issues.
What are the immobilization of the LIST interface
Collections.unmodifiableList() returns an immutable wrapper that throws UnsupportedOperationException on modification attempts; useful for exposing read-only views.
When to use LinkedList
Use LinkedList for frequent insertions/deletions in the middle and when you need queue/deque operations; avoid for random access due to O(n) performance.
What determines the range of permissible values of "primitives"
Primitive ranges are determined by their bit size: byte (-128 to 127), short (-32K to 32K), int (-2B to 2B), long (-9E18 to 9E18), and float/double follow IEEE 754.
What does Peek () method do
peek() returns the first element without removing it in a Queue or Stream; if empty, returns null (Queue) or does nothing (Stream).
How CAS mechanism works
CAS (Compare-And-Swap) atomically compares a memory value with an expected value and swaps to a new value only if they match, providing lock-free thread-safe updates via Unsafe API.
Which gives the principle of incapsulation in real systems
Encapsulation in real systems is achieved by hiding internal state and exposing only necessary interfaces through access modifiers (private, protected, public) and getter/setter methods, controlling how data is accessed and modified.
Tell me about the third normal shape
Third Normal Form (3NF) requires that a relation be in 2NF and have no transitive dependencies; non-key attributes must depend only on the primary key, not on other non-key attributes.
What is the main task of caching in ORM
Caching in ORM reduces database queries by storing frequently accessed objects in memory, improving performance by avoiding repeated database round-trips for the same data.
What difficulties can arise when working with caching
Caching difficulties include cache invalidation complexity, stale data issues, memory overhead, consistency problems in distributed systems, and the challenge of determining optimal cache eviction policies.
What problem does Framework Spring solve
Spring Framework solves inversion of control (IoC), dependency injection, aspect-oriented programming, and provides unified abstractions for transaction management, data access, and web application development.
NAVOV DIFFERENT OF OOP and functional programming
OOP uses mutable state and imperative style with classes/inheritance; functional programming emphasizes immutability, pure functions, and composition, making it easier to reason about and parallelize code.
What is a composition
Composition means building complex objects by containing instances of other objects rather than inheriting from them, favoring 'has-a' relationships over 'is-a' relationships.
What are the advantages of the composition
Composition advantages include greater flexibility, easier testing through dependency injection, better encapsulation, avoiding fragile base class problems, and making code changes safer and more maintainable.
As you understand Interface Segregation
Interface Segregation Principle states clients should not depend on interfaces they don't use; create small, focused interfaces instead of fat interfaces, reducing coupling and improving modularity.
What is Dependency Inversion
Dependency Inversion means high-level modules shouldn't depend on low-level modules; both should depend on abstractions, achieved through interfaces and dependency injection to reduce coupling.
What is the covarian of types
Type covariance allows a subtype to be used where a supertype is expected in specific contexts (like return types), enabling more flexible and reusable code while maintaining type safety.
How can you make a class unchanged
Make a class immutable by declaring it final, making all fields private and final, initializing them in the constructor, and providing no setters or methods that modify state.
What is the difficulty of searching for a key method in the Treemap collection
TreeMap search difficulty is O(log n) because it maintains a Red-Black tree structure; each lookup requires traversing the tree height proportional to the number of elements.
What does Peek method do in Streamapi
Peek in Stream API is an intermediate operation that returns a stream after performing an action on each element without modifying the stream; useful for debugging and side effects.
What interface we get in the Foreach () method
The forEach() method accepts a Consumer interface (functional interface with void accept(T t) method) that defines the action to perform on each element.
Where static methods are stored in JVM memory
Static methods are stored in the method area (or code segment) of JVM memory, not in heap; they belong to the class, not instances, and are loaded when the class is loaded.
How to optimize the work of Hibernate
Optimize Hibernate by using lazy loading, batch fetching, query optimization with HQL/Criteria, proper indexing, connection pooling, caching (L1/L2), and selecting appropriate fetch strategies.
How to perfectly organize the CI/CD process
Organize CI/CD by automating builds and tests on every commit, using infrastructure-as-code, implementing automated deployments to staging/production, monitoring, and maintaining rollback capabilities.
Why is multiple inheritance prohibited
Multiple inheritance is prohibited to avoid the diamond problem where a class inherits conflicting method implementations from multiple parents; Java uses interfaces and composition instead.
When Hashcode conflict in Hashmap occurs
When a hash code conflict occurs in HashMap, the bucket uses a linked list (or red-black tree in Java 8+) to store multiple entries with the same hash code; lookup uses equals() to find the correct entry.
What is a functional paradigm
Functional paradigm treats computation as evaluation of mathematical functions, emphasizing immutability and avoiding state changes.
What is in the center of the paradigm
Functions are at the center of functional paradigm; everything revolves around pure functions and their composition.
What is callable
Callable is a functional interface that returns a result and can throw checked exceptions, unlike Runnable which returns void.
What is the meaning of multi -seating
Multi-tenancy means a single application instance serves multiple independent clients with isolated data and configurations.
What can lead to a violation of normalization
Normalization violations occur from data redundancy, improper foreign keys, or storing derived data instead of maintaining relationships.
How are bins initialized in Spring
Spring initializes beans through constructor injection, setter injection, or factory methods based on @Bean, @Component, or XML configuration.
What does Transactional annotation in Spring Data do
@Transactional in Spring manages transaction boundaries, ensuring ACID properties and automatic rollback on exceptions.
What is CAS mechanism
CAS (Compare-And-Swap) is an atomic operation that compares a memory value with an expected value and updates it if they match.
What is the difference between Optimistic and Pessimistic Lock in Hibernate
Optimistic locking assumes no conflicts and checks versions on commit; pessimistic locking acquires locks immediately to prevent conflicts.
What streamline collections in Java know
Stream collections include operations like filter(), map(), reduce(), and collect() for functional-style data processing in Java 8+.
What is LinkedHashmap.
LinkedHashMap maintains insertion order (or access order) while providing O(1) get/put operations like HashMap.
What lies "under the hood" Parallelstream ()
ParallelStream uses ForkJoinPool under the hood to divide work into subtasks and process them concurrently across multiple threads.
Tell me about the methods of optimizing requests in the database
Database query optimization includes indexing, query caching, lazy loading, batch processing, and using projections to fetch only needed columns.
What is the algorithmic complexity of searching for an element by index
Searching by index in an array/ArrayList is O(1) constant time; in LinkedList it's O(n) linear time.
What is Join differ from Union
JOIN combines rows from multiple tables based on relationships; UNION combines result sets from multiple queries and removes duplicates.
Tell me about Problem N+1 in Hibernate
N+1 problem occurs when loading a parent entity triggers N additional queries for children instead of using a single JOIN query.
What is ApplicationContext in Spring
ApplicationContext is Spring's central interface providing bean management, property resolution, event publishing, and resource loading.
As if implemented integration testing
Integration testing verifies component interactions using TestContainers, @SpringBootTest, or embedded servers to test database and service layers.
Where static methods and variables are stored
Static methods and variables are stored in the Metaspace (PermGen in older JVMs), not on the heap.
Where objects are stored
Objects are stored on the heap; reference variables are stored on the stack (for local variables) or in object fields.
What is "garbage" in terms of JVM
Garbage in JVM is unreachable objects that no longer have references, identified by garbage collectors using mark-sweep or generational algorithms to free heap memory.
What is CAS mechanism
CAS (Compare-And-Swap) is an atomic operation that compares a variable's current value with an expected value and swaps it only if they match, used for lock-free synchronization.
What groups of teams are there in SQL
SQL has four main groups: DDL (CREATE, ALTER, DROP), DML (INSERT, UPDATE, DELETE), DCL (GRANT, REVOKE), and TCL (COMMIT, ROLLBACK).
What are transaction insulation levels
Transaction isolation levels are READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, and SERIALIZABLE, controlling visibility of uncommitted data and preventing dirty/phantom reads.
How to process the request (httpservlet)
HttpServlet processes requests through doGet/doPost/doPut/doDelete methods called by the service() method, which routes based on HTTP method and calls the appropriate handler.
What is the difference between the composition and inheritance
Composition is HAS-A relationship where a class contains instances of other classes, offering better flexibility; inheritance is IS-A relationship with tight coupling and code reuse through parent-child hierarchy.
Mechanisms for the implementation of polymorphism
Polymorphism is implemented via method overriding (runtime/dynamic dispatch using vtable), method overloading (compile-time/static dispatch), and interface implementation.
What are unchanged classes
Immutable classes are instances where state cannot be changed after creation, typically declared final with final fields, private constructors, and defensive copying in getters.
What is the difficulty of inserting the element in Linkedlist
Inserting an element in LinkedList is O(1) if you have the node reference, O(n) if finding the position first, due to lack of random access requiring sequential traversal.
What is the difference between the volatility and atomicity
Volatile ensures visibility of changes across threads with happens-before semantics but not atomicity; atomicity guarantees indivisible operations, typically using CAS or locks.
N+1 Problem, solutions in Hibernate
N+1 problem occurs when fetching parent entities executes N additional queries for children; solutions include JOIN FETCH, @BatchSize, FetchType.EAGER, or explicit eager loading.
What are transactions promotion levels in Spring Data
Transaction propagation levels in Spring are REQUIRED, SUPPORTS, MANDATORY, REQUIRES_NEW, NOT_SUPPORTED, NEVER, and NESTED, controlling transaction scope and behavior.
What is a hypothetic method in Spring Data
Query methods in Spring Data (hypothetic/derived query methods) are automatically implemented by parsing method names like findByNameAndAge without explicit implementation code.
What is CAP theorem
CAP theorem states that distributed systems can guarantee only two of: Consistency (all nodes see same data), Availability (system operational), and Partition tolerance.
How the object differs from primitive
Objects are references to heap-allocated instances with identity and mutable state; primitives are stack-allocated values (int, long, boolean) with no identity and fixed size.
What algorithms for finding an element by array are known
Search algorithms for arrays include linear search O(n), binary search O(log n) on sorted arrays, hash-based lookup O(1), and interpolation search for uniform distributions.
Tell me about the concept of the Completablefuture class
CompletableFuture is a non-blocking, composable future allowing explicit completion, chaining operations via thenApply/thenCompose, and handling multiple async operations elegantly.
Why can the design template be useful to a chain of responsibility
Chain of Responsibility pattern is useful as a design template because it decouples senders from handlers by passing requests through a chain, allowing multiple handlers to process independently.
Bean is a class or object
A Bean is typically a class in code, but in the Spring context it refers to an object instance created and managed by the Spring container.
What are propagation levels in transactions
Transaction propagation levels control whether to create new transactions or use existing ones: REQUIRED creates if needed, REQUIRES_NEW always creates new, NESTED creates savepoints.
What is the ideality of the method
Method ideality refers to having a single, well-defined responsibility with minimal side effects and clear input/output contracts.
What is the ideality of the method
Method ideality refers to having a single, well-defined responsibility with minimal side effects and clear input/output contracts.
Tell about yourself what goals you set
My goals are delivering high-quality, maintainable code, mentoring junior developers, and staying current with Java ecosystem advancements while solving complex architectural problems.
What is the permissible range for the type of SHORT data
Short range is -32,768 to 32,767 (16-bit signed integer).
What is the difference between a primitive Short from Class Short
Primitive short is a 16-bit value type stored on stack, while Short is a boxed object wrapper class stored on heap with nullable semantics and utility methods.
How Java understands Generics
Java uses type erasure at compile-time; generics are checked during compilation but erased to Object at runtime, enforcing type safety without runtime overhead.
What idea does Arraylist realize
ArrayList implements the List interface using a dynamic array-based data structure that resizes automatically, supporting O(1) access and O(n) insertion/deletion.
What does transient in Java mean
Transient marks instance variables to be excluded from serialization, useful for sensitive data or non-serializable dependencies.
What does transient in Java mean
Transient marks instance variables to be excluded from serialization, useful for sensitive data or non-serializable dependencies.
What idea does LinkedList realize
LinkedList implements List and Deque using a doubly-linked node structure, supporting O(1) insertion/deletion at ends but O(n) for random access.
What is the difficulty of inserting the element in Linkedlist
LinkedList insertion is O(1) at known positions if you have the node reference, but O(n) for index-based insertion due to traversal overhead.
What is the Comparable interface for
Comparable defines natural ordering for objects via compareTo() method, enabling automatic sorting in collections and allowing single sort strategy per class.
What can lead to a violation of data normalization
Violations occur from data redundancy, inconsistent updates across duplicates, and denormalization allowing anomalies during insertion, deletion, or modification operations.
What can you reconcile Final
Final can be applied to classes (prevent extension), methods (prevent override), and variables (prevent reassignment), ensuring immutability or behavioral contracts.
What is LinkedHashset
LinkedHashSet maintains insertion order using a doubly-linked list while providing Set uniqueness semantics with O(1) average operations.
What is Hashset
HashSet is an unordered Set implementation using hash table, providing O(1) average add/remove/contains but no ordering guarantees.
What Phaser does
Phaser synchronizes multiple threads in waves using a reusable barrier pattern, supporting dynamic party registration unlike CountDownLatch.
What are scope bean for
Bean scopes (singleton, prototype, request, session, application) define object lifecycle and sharing within Spring containers.
What is Socket
Socket represents a network endpoint for TCP/IP communication, enabling bidirectional data exchange between client and server over IP networks.
Why is the strategy template is used
Strategy pattern decouples algorithm selection from usage context, while template method defines algorithm skeleton in base class with customizable steps in subclasses.
I studied something except Java
Mention other languages or technologies you have studied and how they complement your Java knowledge. Common strong answers: Python for scripting and data, JavaScript/TypeScript for frontend, Go or Rust for performance-critical services, SQL for databases. Explain what each taught you that made you a better Java developer.
As you understand the phrase java is OOP
Java is object-oriented,everything (except primitives) is an object; it supports encapsulation, inheritance, and polymorphism through classes.
Array is a primitive or object
Array is an object in Java; it's created at runtime and stored on the heap, though it can hold primitives as elements.
What is the difficulty of adding an element to Array List
Adding to ArrayList is O(1) amortized; when capacity is exceeded, it resizes by ~1.5x, requiring O(n) copy operation.
Which you know the most effective way to copy the array
For shallow copy use System.arraycopy() or Arrays.copyOf(); for deep copy iterate and clone elements or use Java Streams.
What is a collision of a hash codes from the point of view of Hashmap
Hash collision occurs when two different keys produce the same hash code; HashMap uses separate chaining (linked lists/trees) to resolve collisions.
What problem does Walatayl solve
Volatile ensures visibility of variable changes across threads; it prevents instruction reordering but doesn't provide atomicity.
What tasks are solved using Join
Thread.join() blocks the calling thread until the target thread completes; used for thread synchronization and waiting for task completion.
How to make a database with Java application
Use JDBC (DriverManager/DataSource) for direct database access or ORM frameworks like Hibernate/JPA for abstraction.
What is the name of the document in which I can see everything about JDBC
JDBC documentation is in the JavaDoc API docs (oracle.com) and the JDBC specification; check javax.sql package details.
What types of queries can I perform using hibernate
Hibernate supports HQL (object-oriented queries), Criteria API (type-safe), native SQL, and JPQL,all returning managed entity objects.
For complex requests where there are a lot of paraments that you need to use
Use Builder pattern or Parameter Object pattern; it improves readability and maintainability for methods with many parameters.
What happens from the start of the Spring of the application to the first request to Postman
Spring IoC container loads beans, applies properties via dependency injection, processes annotations, creates proxies for AOP, then handles first request.
What is the difference between Hashmap and Hashset
HashMap is unordered with O(1) lookup; HashSet is an unordered collection with no duplicates built on HashMap; both use hash codes.
What is Spring Data Repository
Spring Data Repository is an abstraction providing CRUD operations and query methods; you declare interfaces extending CrudRepository without implementation.
What is Spring Data Specification
Specification provides type-safe, reusable query criteria using Predicate; implement Specification<Entity> to build complex dynamic queries.
What are the differences in component annotations
@Component is generic; @Service, @Repository, @Controller are specialized stereotypes indicating the layer,Service for business logic, Repository for data access.
What is the difference between the configuration and the component
@Configuration declares a class producing bean definitions; @Component marks a class as a bean,@Configuration is for bean factories, @Component for simple beans.
What is @transactional annotation
@Transactional manages transactions automatically; Spring wraps the method in a transaction, committing on success or rolling back on exceptions.
What will happen if the method is caused by the @transactional annotation method
If a @Transactional method calls another @Transactional method in the same class, proxies are bypassed,use self-injection or separate class to apply transactional behavior.
What is the difference @Controller and @readController
@Controller handles HTTP requests and returns views; @RestController returns JSON/XML responses directly without view resolution.
How to effectively identify unproductive SQL - requests
Use database query logs, APM tools (New Relic, DataDog), EXPLAIN PLAN analysis, and slow query logs to identify N+1 queries and missing indexes.
How to deal with anomalies when performing transactions
Handle anomalies using try-catch blocks, @Transactional rollback, circuit breakers, and implement compensating transactions for distributed systems.
What is Message Broker
A message broker is middleware (RabbitMQ, Kafka) that decouples producers and consumers, enabling asynchronous message delivery between services.
What is asynchronous messages
Asynchronous messages are sent without waiting for immediate response; the sender continues execution while the broker delivers the message later.
What are non -blocking algorithms
Non-blocking algorithms use atomic operations and Compare-And-Swap (CAS) instead of locks, reducing contention and improving throughput in concurrent scenarios.
What is the difference between Mono and Flux
Mono returns 0 or 1 element; Flux returns 0 to N elements. Both are reactive types in Project Reactor for handling asynchronous data streams.
What will happen if you apply Volatile in objects
Volatile ensures visibility of variable changes across threads and prevents compiler reordering, but doesn't guarantee atomicity for compound operations.
How to ensure synchronization in a multi -thread environment
Use synchronized blocks/methods, ReentrantLock, volatile variables, atomic classes, concurrent collections, and proper happens-before relationships.
What is the Synchronized block in Java and what are the problems are there
Synchronized block acquires an object lock for critical sections; problems include deadlocks, performance overhead, and difficulty with fairness and timeouts.
What is the Database-Per-Service template
Database-Per-Service pattern assigns each microservice its own database to ensure loose coupling, but complicates distributed transactions and joins.
What is the EVEN Sourcing template
Event Sourcing stores all state changes as immutable events instead of current state, enabling audit trails, event replay, and temporal queries.
What tasks does Distributed Tracing solve
Distributed Tracing tracks requests across microservices, identifies latency bottlenecks, visualizes service dependencies, and aids debugging in distributed systems.
How to choose a strategy, template
Choose strategy pattern for runtime behavior selection based on conditions; use template method for fixed algorithm structure with customizable steps.
How will Prototype Bean behave in the framework of Singleton
Prototype beans are created fresh for each injection; if injected into a Singleton, the prototype instance is cached in the singleton and reused.
What you use as tracking your tasks
Use Jira, Azure DevOps, or GitHub Issues for task tracking; pair with Agile boards for sprint planning and progress visualization.
What FLO do you use when working with TASK
Use Kanban or Scrum workflow for task management; implement continuous deployment pipelines with stages like development, testing, and production.
Tell me the difference between the List and Set interface
List is ordered and allows duplicates with index-based access; Set is unordered, prevents duplicates, and provides faster contains() operations via hashing.
What is an executter-service
ExecutorService manages a thread pool for executing tasks asynchronously; provides lifecycle management, scheduled execution, and batch task handling capabilities.
That with the exception of Interrupted Exception
InterruptedException signals that a thread's blocking operation was interrupted; catch it to handle graceful shutdown or restore interrupt status with Thread.currentThread().interrupt().
What annotations you know to create bins
Common annotations include @Override, @Deprecated, @FunctionalInterface, @SuppressWarnings, and custom annotations created with @interface for marking, metadata, or compile-time processing.
What is the promotion and bias of the transaction
Transaction promotion refers to escalating isolation levels or lock scopes when conflicts occur; transaction bias involves preferring certain execution paths or lock holders in concurrency resolution.
Briefly tell me about your projects
Pick 1-2 projects most relevant to the job. For each, explain: what the system did, your specific role, the tech stack (Java version, frameworks, database), a technical challenge you faced, and the outcome. Quantify impact where possible (reduced latency by X%, handled Y requests/sec).
Why inheritance is needed
Inheritance enables code reuse, establishes hierarchical relationships, and allows polymorphic behavior through method overriding, promoting extensibility and contract-based design.
What alternatives are there inheritance
Composition, delegation, mixins, and interfaces are alternatives; composition uses object aggregation, interfaces define contracts without coupling implementations, and delegation delegates behavior to contained objects.
Why the composition is more often recommended to use than inheritance
Composition avoids fragile base class problem, prevents tight coupling, enables runtime flexibility by swapping implementations, and avoids deep inheritance hierarchies that become hard to maintain.
What is the main idea of the adapter
The adapter pattern converts an interface to another clients expect, allowing incompatible objects to work together; it's a wrapper that translates method calls between two incompatible interfaces.
What is the idea of Autoboxing and Unboxing
Autoboxing automatically wraps primitives into objects (int → Integer) during assignment or method calls; unboxing extracts primitive values from wrapper objects, both handled implicitly by the compiler.
What needs to be done in order to create a property class in Java
Extend a class, add a no-arg constructor, define private fields, provide getters/setters, and optionally implement Serializable and equals/hashCode for proper JavaBean compliance.
The basic differences between List and Linked List
List is ordered with indexed access (get/set O(1)) but insertion/deletion O(n); LinkedList is doubly-linked with O(1) insertion/deletion at ends but O(n) random access, less memory efficient.
What methods of processing are checked exceptions
Checked exceptions must be caught or declared; methods use try/catch blocks, throws clause in method signature, or wrap in unchecked exceptions to handle them.
What is Try/Catch
Try/catch is error handling: try block contains code that may throw exceptions, catch block handles specific exception types with recovery logic, preventing program crash.
Is it possible to write try without Catch
Yes, try can exist with finally alone (try/finally) for cleanup operations, or with multiple catch blocks; however, at least one of catch or finally must follow try.
What forms of writing Try/Catch know
Try/catch, try/catch/finally, try with resources (try-with-resources for AutoCloseable objects), multi-catch (catch multiple exceptions), and nested try blocks.
What is the importance of Stack Trace in exceptions
Stack trace shows the execution path when exception occurred, listing method calls in reverse order from throw to caller, enabling developers to identify where and why failure happened.
What is understood by the context of error
Error context includes the exception type, message, stack trace, thread information, and application state at failure point, essential for diagnosing root cause of failures.
What is constistence and chieftain
Question appears unclear/possibly translation issue; consistency refers to ACID properties ensuring data integrity; if referring to something else, please clarify the term.
Is it possible to manage a monitor
Yes, monitors in Java are managed implicitly via synchronized blocks/methods for mutual exclusion, and explicitly through Lock interface (ReentrantLock) for fine-grained control.
What is a steameterized type
Parametrized types (generics) like List<String> provide compile-time type safety, eliminate casting, enable better IDE support, and prevent ClassCastException at runtime.
Is there a constructor for a static class
No, static classes cannot have explicit constructors; the compiler generates an implicit no-arg constructor that's private, and static initialization blocks can initialize static fields.
How to create a static generical method
Use public static <T> ReturnType methodName(T param) { } syntax to declare a static generic method with type parameter T.
What does Java mean two types of exceptions
Java has checked exceptions (must be caught/declared) and unchecked exceptions (RuntimeException subclasses, optional handling).
What methods of processing in Java exist
Java supports sequential processing (single-threaded), parallel processing (multithreading), and concurrent processing (ExecutorService/ForkJoinPool).
Why is it necessary to close the resource
Resources must be closed to prevent memory leaks and free system handles; use try-with-resources or finally blocks.
Is it possible to launch a Java application with only jre
Yes, a Java application runs on JRE (Java Runtime Environment) only; JDK is needed only for compilation.
What is ODBC
ODBC (Open Database Connectivity) is a database API standard; in Java, JDBC is the equivalent for database connections.
What does a static in Java mean
Static in Java means a class-level member shared across all instances, not instance-specific; initialized once at class load time.
What is the difference between Exception and Error
Exception is a checked/unchecked recoverable error that extends Throwable; Error represents serious JVM problems (OutOfMemoryError) and shouldn't be caught.
Data transmission to Java is following the link or by value
Java passes all data by value; for objects, the reference (address) is passed by value, so modifications affect the original object.
What does the transmission mean by
Pass-by-value means a copy of the variable is passed to the method; changes inside the method don't affect the original primitive, but object state changes persist.
Why do I need property classes and their main characteristics
Properties classes (like java.util.Properties) store key-value pairs for configuration; main characteristics are persistence, string-based, and HashMap-backed.
What is the insulation or its absence
Encapsulation (insulation) hides internal implementation details using private/protected modifiers; absence means exposing internals, reducing maintainability and security.
Is it possible to lower the level of access modifier
No, you cannot lower access modifiers in overridden methods; only the same or less restrictive (e.g., package-private → public) are allowed.
What are the main three methods for Servlet and what is their task
Servlet's three main methods are doGet() (handle GET requests), doPost() (handle POST requests), and service() (handles all HTTP methods).
How Servlet works in multi -sided mode
Servlets are thread-safe at the servlet container level; each request gets its own thread, but shared instance variables require synchronization.
Arraylist, what is the speed of access to the last element
ArrayList access to the last element is O(1) constant time since it uses array indexing internally.
What is the difference between PrepareDstatement and Statement
PreparedStatement pre-compiles SQL with placeholders (?), improving performance and preventing SQL injection; Statement executes raw SQL strings.
What is the relationship in the database
A relationship in databases defines how tables connect; primary key in one table references foreign key in another.
What is One to One
One-to-One relationship means each record in Table A relates to exactly one record in Table B (e.g., User to Passport).
Give an example One to Many
One-to-Many relationship means one record in Table A relates to multiple records in Table B (e.g., Author to Books).
What two main types of data integrity do you know
Entity integrity ensures uniqueness of records via primary keys, while referential integrity maintains relationships between tables through foreign keys.
What types of constraints do you know
PRIMARY KEY (uniqueness & not null), FOREIGN KEY (referential integrity), UNIQUE (no duplicates), CHECK (column values), NOT NULL (mandatory fields), DEFAULT (default values).
What is DDL, DML, DCL
DDL (Data Definition Language) - CREATE/ALTER/DROP; DML (Data Manipulation Language) - INSERT/UPDATE/DELETE/SELECT; DCL (Data Control Language) - GRANT/REVOKE permissions.
How to fight the database from SQL Injection
Use parameterized queries/prepared statements instead of string concatenation, validate and sanitize input, apply principle of least privilege to database accounts.
What is the difference between Union and Union All
UNION removes duplicates (uses DISTINCT implicitly), UNION ALL keeps duplicates; UNION ALL is faster as it skips deduplication.
What are the main restrictions when working with Union operation
All SELECT statements must have same number of columns in same order and compatible data types; column names from first query are used in result set.
What is comit in SQL
COMMIT makes all changes in current transaction permanent and visible to other sessions; ends the transaction successfully.
What problem can the transaction set
Lost update, dirty read, non-repeatable read, phantom read - solved by transaction isolation levels (READ_UNCOMMITTED to SERIALIZABLE).
What is the principle of abstraction
Abstraction hides complex implementation details exposing only essential features through abstract classes or interfaces.
What is the difference between abstraction and polymorphism
Abstraction defines what something does (interface/contract), polymorphism defines how it's executed (method overriding/overloading providing different implementations).
What is the difference between Race Condition and Data Race
Race condition is unpredictable behavior from timing of concurrent execution; data race is specific unsynchronized concurrent access to shared mutable data causing corruption.
What methods of synchronization in Java do you know
synchronized keyword, ReentrantLock, ReadWriteLock, Semaphore, CountDownLatch, CyclicBarrier, atomic variables (AtomicInteger), concurrent collections.
What is the difference between Dependency Injection and Dependency Inversion
Dependency Injection provides dependencies to objects (IoC pattern), Dependency Inversion means depend on abstractions not concretions (SOLID principle).
What is Dispatchers Roulette
Not a standard Java term; likely confused with Double-Checked Locking pattern for lazy singleton initialization.
What is the difference between inheritance and polymorphism
Inheritance is IS-A relationship and code reuse through extending classes; polymorphism is ability to use objects of different types interchangeably via same interface.
What is contract programming
Contract programming uses pre-conditions, post-conditions, and invariants to formally specify expected behavior and validate assumptions before/after method execution.
Why is it so important to have a contract in Java
Contracts prevent bugs by documenting expected behavior explicitly, enable safe refactoring through documented guarantees, and improve code clarity and maintainability.
What are the main two types of Singletone implementation
Eager initialization (thread-safe from JVM loading) and lazy initialization (Double-Checked Locking or Bill Pugh Singleton with static inner class).
What is a decorator
Decorator pattern wraps object with same interface adding behavior dynamically without modifying original; uses composition over inheritance.
What is the decorator for
Decorator adds cross-cutting concerns (logging, caching, compression) to objects at runtime maintaining single responsibility while extending functionality flexibly.
What does reflection mean
Reflection is a Java mechanism that allows inspecting and manipulating classes, methods, fields, and constructors at runtime using the java.lang.reflect API.
What does symmetry mean
Symmetry in Java typically refers to the equals() and hashCode() contract,if two objects are equal, they must have the same hash code.
Why do objects fall into Stringpoll
Objects enter the String pool when String literals are created (e.g., String s = "hello") or when intern() is explicitly called on a String.
How objects fall into StringPoll
String objects are added to the pool through the compile-time constant folding process or by calling the intern() method, which places them in the pool if not already present.
What is the problem of concatenation of lines in Java
String concatenation using the + operator creates new String objects for each operation, causing performance issues and memory waste due to immutability.
How Stringbuilder solves the problem of concatenation
StringBuilder solves concatenation by using a mutable internal char array (buffer) and appending without creating intermediate String objects, then converting to String once at the end.
Are Stringbuilder faster than Stringbuffer if you remove synchronization
No, StringBuilder is not faster than StringBuffer without synchronization,they have identical performance; StringBuffer is slower due to synchronized method overhead.
What is the reason for the existence of MAP as a data structure and Collection in CollectionFramework
MAP stores key-value pairs for fast lookups by key, while Collection stores individual elements; MAP is ideal for associative data, Collection for element groups.
What is the main vocation of the MAP interface
The main purpose of the MAP interface is to provide a key-value mapping structure that enables efficient insertion, deletion, and retrieval of values by unique keys.
What are the basic implementations of InputoutPut Strem
Basic InputOutputStream implementations include FileInputStream/FileOutputStream for file I/O and ByteArrayInputStream/ByteArrayOutputStream for in-memory byte buffering.
What is the minimum unit for working with threads
The minimum unit for working with threads is the Runnable interface or a Thread object, which represents the smallest executable concurrent unit.
What is the progressiveness of NIO
NIO's progression involves moving from blocking I/O (streams) to non-blocking, multiplexed I/O using Channels, Buffers, and Selectors for handling multiple connections efficiently.
What is the meaning of buffering threads
Buffering in threads refers to using thread-safe buffer structures (like BlockingQueue) to exchange data between threads asynchronously without direct synchronization.
What is the advantage of buffering
Buffering advantages include decoupling producer-consumer threads, improving throughput by batching operations, and reducing context-switching overhead.
What is the advantage of buffering
Buffering advantages include decoupling producer-consumer threads, improving throughput by batching operations, and reducing context-switching overhead.
How Track.h works
Track.h is not a standard Java concept; if referring to a C++ header, it's outside Java scope; if you mean thread tracking, it would involve monitoring thread execution states.
What will happen if we try to change the value of a private variable
Attempting to change a private variable outside its class will result in a compile-time error because private restricts access to within the class definition only.
What is the difference in aspects between Advice and Point
Advice is the action taken at a join point (e.g., before, after, around), while a pointcut is the expression that selects which join points the advice applies to.
What is the difference in aspects between Advice and Point
Advice is the action taken at a join point (e.g., before, after, around), while a pointcut is the expression that selects which join points the advice applies to.
Why logging is very often associated with aspects
Logging is associated with aspects because cross-cutting concerns like logging naturally fit the AOP paradigm,you can inject logging at pointcuts without modifying core business logic.
Give an example of a relational database and a non
Relational: PostgreSQL/MySQL with structured tables and ACID properties. Non-relational: MongoDB/Cassandra with document/key-value storage and eventual consistency.
What is the meaning of restrictions
Restrictions are constraints that limit data values in a database, such as NOT NULL, UNIQUE, CHECK, and FOREIGN KEY to maintain data integrity.
What are the restrictions
Primary Key (unique, non-null), Foreign Key (references another table), UNIQUE (no duplicates), CHECK (condition validation), NOT NULL (mandatory values).
How is the access speed in SQL achieved
SQL achieves fast access through indexing on frequently queried columns, query optimization, and execution plans that minimize full table scans.
Primary Key is an index and why
Primary Key is automatically indexed because databases create a unique index to enforce uniqueness and speed up lookups by the primary key.
What restrictions do Primarykey have
Primary Key restrictions: must be unique, cannot be null, only one per table, and immutable once set to maintain referential integrity.
What is Asset principle
ACID principle: Atomicity (all-or-nothing), Consistency (valid state), Isolation (concurrent independence), Durability (persisted after commit).
What negative phenomena in SQL know
Negative phenomena: dirty reads (uncommitted data), non-repeatable reads (changed data mid-transaction), phantom reads (new rows inserted mid-transaction), deadlocks.
What is meant by Dirtyread
Dirty read is reading uncommitted data from another transaction that may be rolled back, violating isolation levels.
What types of configurations do you know
Isolation levels: READ_UNCOMMITTED (lowest), READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE (highest with strictest locking).
Why is it necessary to use the configuration through annotations, and you should not use the aanotation through the configuration
Annotations provide cleaner, more maintainable configuration; XML config is better for complex, environment-specific settings that shouldn't be in code.
In what cases would Java use configuration
Use configuration files for external properties (DB credentials, profiles), annotations for bean definitions and dependency injection within the application.
What annotations you know for the message of Spring, so that it creates on the basis of these Bean annotations
Spring Bean annotations: @Component, @Service, @Repository, @Controller, @Bean, @Autowired, @Qualifier, @Primary for component scanning and injection.
What is the feature of Dependency Injection
Dependency Injection inverts control by letting the framework manage object creation and injection of dependencies, improving testability and loose coupling.
What is Spring Data
Spring Data is an abstraction layer providing repositories and query methods to reduce boilerplate for data access across relational and non-relational databases.
What is the difference between Spring Data from Hibernate
Spring Data provides high-level repository abstractions and automatic query generation; Hibernate is a lower-level ORM for mapping objects to database tables.
How to fill the attributes in the class
Fill class attributes via constructor injection, setter injection, field injection (@Autowired), or using @ConfigurationProperties for externalized configuration mapping.
What is JSON data storage format
JSON is a lightweight text-based data format using key-value pairs with objects and arrays, human-readable and language-independent for data interchange.
What is characteristic of html
HTML characteristics: markup language for structure, uses tags for semantics, client-side rendering, stateless, combines with CSS for styling and JS for behavior.
What is SELECT from SQL
SELECT retrieves data from database tables with syntax: SELECT columns FROM table WHERE condition ORDER BY column, optionally with JOINs and aggregates.
How to make your first commit, add all files
git add . && git commit -m 'message' adds all files and creates initial commit.
How can you make a connection with a remote repository
git remote add origin <url> establishes connection to remote repository.
How to download changes from a remote repository
git pull fetches and merges changes from remote repository to local branch.
What is Spring
Spring is an enterprise Java framework providing dependency injection, AOP, and simplified application development.
What does the Spring Core module give
Spring Core provides IoC container, dependency injection, and bean lifecycle management.
Try Catch with Resources what is it
Try-with-resources (try-with-declaration) automatically closes resources implementing AutoCloseable in try block.
What is Git for
Git is a distributed version control system for tracking code changes and collaboration.
What kind of Git commands do you know
Common commands: git clone, git add, git commit, git push, git pull, git branch, git merge, git checkout.
What is MAP
Map is a key-value data structure where each key maps to a single value.
Can a primitive key be
No, Map keys must be Objects; primitives must be wrapped (Integer, Long, etc.).
Map keys can be repeated
No, Map keys are unique; duplicate keys overwrite previous values.
What are the data structures from Collection
Collection subinterfaces: List (ordered), Set (unique), Queue (FIFO), Deque (double-ended).
What is SET
Set is unordered, unique collection; duplicates are not allowed.
What is List
List is ordered, mutable collection allowing duplicate elements with index-based access.
What is the difference between List and SET
List maintains insertion order with index access; Set is unordered and contains only unique elements.
What is Q and DQ
Queue (FIFO) adds at tail, removes from head; Deque (double-ended) supports both ends.
Does LinkedList have Q/DQ interfaces
Yes, LinkedList implements both Queue and Deque interfaces.
What is a temporary complexity
Time complexity describes algorithm performance: O(1) constant, O(n) linear, O(log n) logarithmic, O(n²) quadratic.
What are Exception classes, what types of
Exception classes: Checked (IOException, SQLException) inherit Exception; Unchecked (RuntimeException) for runtime errors.
What is the EXCEPTION inherited
Exception class inherits from Throwable; RuntimeException and Error inherit from Throwable as well.
Why are Stream needed
Streams enable functional-style operations on collections, allowing declarative processing with lazy evaluation and composability of operations like filter, map, and reduce.
Stream API What paradigm uses
Streams use functional programming paradigm, treating data transformations as a pipeline of operations rather than imperative loops.
What are the types of Stream
Stream types include intermediate streams (filter, map, flatMap) that return Stream, and terminal operations (collect, forEach, reduce) that produce final results.
Can a private method be in the interface
Yes, private methods can exist in interfaces since Java 9, allowing code reuse among default methods without exposing implementation details.
What is the name of the functional interface that accepts the filter
The functional interface is Predicate<T>, which accepts a filter condition and returns a boolean for stream filtering operations.
What Collect does
Collect is a terminal operation that transforms stream elements into a collection (List, Set, Map) using a Collector strategy.
Is it possible to transform the collection into MAP
Yes, you can transform a collection into a Map using Collectors.toMap() with key and value mappers: stream.collect(Collectors.toMap(keyMapper, valueMapper)).
Can there be a constructor in the interface
No, interfaces cannot have constructors; they only define contracts. Objects are instantiated via implementing classes' constructors.
Overloading the method what it means
Method overloading means defining multiple methods with the same name but different parameter types/counts in the same class, resolved at compile-time.
What is a signature
A method signature consists of the method name and parameter types (not return type), used by compiler to identify and distinguish methods.
There is String, String Builder, String Buffer what is it
String is immutable and stored in string pool, StringBuilder is mutable and unsynchronized (fast), StringBuffer is mutable and synchronized (thread-safe but slower).
What is the living cycle Maven
Maven lifecycle phases: validate → compile → test → package → verify → install → deploy, executed sequentially for project build.
What is an oc container
An IoC (Inversion of Control) container manages object creation and dependency injection, removing manual instantiation and wiring responsibilities from application code.
What do you know about the annotation Predestroy
@PreDestroy annotation marks a method invoked before a bean is removed from container, used for cleanup operations like closing connections.
What gives an annotation of Service
@Service annotation marks a class as a service layer component in Spring, enabling auto-detection and dependency injection alongside stereotype annotations.
What is Spring Web
Spring Web (Spring MVC/WebFlux) provides web framework for building REST APIs and web applications with request handling, routing, and templating capabilities.
What is Mock, Stab, Spy
Mock replaces real objects entirely, Stub provides minimal responses without logic, Spy wraps real objects and records calls while allowing partial mocking.
How to connect a class with a database
Connect a class to database via JDBC drivers, ORM frameworks (Hibernate/JPA) for object mapping, or connection pooling (HikariCP) with proper transaction management.
Lazy vs eager loading, what is the difference
Eager loading loads related entities immediately when parent loads (JOIN), consuming memory upfront; Lazy loading defers loading until accessed (SELECT N+1 risk), optimizing initial query but risking performance.
Why did the division of data types into Int, Long
Integer types (int, long) provide different memory sizes and value ranges: int is 32-bit (-2B to 2B), long is 64-bit for larger numbers, allowing memory-efficient design choices.
What is the idea of primitive data types
Primitive data types (int, long, boolean, etc.) are predefined by Java and stored directly in stack memory, offering fixed size and fast access; they're not objects and have default values (0, false, null).
What are programming patterns for
Common programming patterns include Singleton, Factory, Observer, Strategy, and Decorator patterns,they solve recurring design problems and improve code maintainability and reusability.
What is a container
A container in Java (like Spring Container) manages object creation, lifecycle, and dependency injection; it instantiates beans, wires dependencies, and handles configuration without explicit client code.
What is the introduction of dependence
Dependency injection is a pattern where objects receive their dependencies from external sources rather than creating them internally, promoting loose coupling and testability.
What is the difference between Spring Boot and Spring Context
Spring Boot auto-configures ApplicationContext and provides embedded servers, production-ready features with minimal setup; Spring Context is the core IoC container that manages beans manually.
Which annotation allows you to understand that bins are raising
@Lazy, @PostConstruct, @PreDestroy, and @Bean annotations help understand bean lifecycle and initialization; @PostConstruct marks methods that run after bean construction.
How to connect your library in another project
Package your library as a JAR/Maven artifact, publish to a repository (Maven Central, Nexus, or local repo), then add it as a dependency in another project's pom.xml or build.gradle.
What should be the conditions for the database to be considered a relational
Relational databases must support ACID properties, enforce referential integrity via foreign keys, organize data in normalized tables with rows/columns, and support SQL queries.
How to prohibit leaving an empty column
Use NOT NULL constraint on columns in CREATE TABLE or ALTER TABLE statements; in JPA/Hibernate, use @NotNull or @Column(nullable=false) annotations.
Why do you need branches in Git
Git branches enable parallel development, feature isolation, and version management; they allow multiple developers to work independently and merge changes via pull requests.
How to see the version of the previous commune
Use 'git log' to view commit history or 'git show <commit-hash>' to see a specific commit; 'git reflog' shows all HEAD movements including previous states.
What are the types of branches of branches
Branch types include feature branches (for new features), hotfix branches (for urgent fixes), release branches (for versioning), and main/develop branches; naming conventions like git-flow are common.
How to find a mistake in the program
Use debuggers (IDE breakpoints), logging (SLF4J, Log4j), stack traces, code review, unit tests, and profiling tools; analyze logs and use 'git bisect' to locate regression commits.
How can you test the program and protect yourself from errors
Test using unit tests (JUnit, Mockito), integration tests, and end-to-end tests; use code coverage tools (JaCoCo), CI/CD pipelines (Jenkins, GitHub Actions), and static analysis (SonarQube).
What types of cycles do you know
Java has for loops, enhanced for-each loops, while loops, do-while loops, and streams/forEach(); for-each simplifies iteration, while streams enable functional composition.
How the cycles differ from each other
For loops offer index access and control; while/do-while suit unknown iteration counts; for-each is cleaner for collections; streams are functional and support parallel operations.
Tell me briefly with which frameworks you worked
List frameworks you have actually used in projects and briefly explain what each one does. Common Java frameworks: Spring Boot (application framework), Spring Data JPA / Hibernate (ORM), JUnit + Mockito (testing), Maven or Gradle (build tools), Kafka or RabbitMQ (messaging). Be prepared to go deep on any framework you name.
Which from the literature on Java read
Strong answers include "Effective Java" by Joshua Bloch, "Java Concurrency in Practice" by Brian Goetz, and "Clean Code" by Robert Martin. Only mention books you have actually read. Be ready for follow-up questions like "what was your key takeaway from that book?"
What literature I read not according to Java
Good answers: "The Pragmatic Programmer", "Designing Data-Intensive Applications" by Martin Kleppmann, "Design Patterns" (Gang of Four), "System Design Interview" by Alex Xu. Only mention books you can discuss. The interviewer may ask what you learned from them.
Did Java.util.concords use Java 5
Yes, java.util.concurrent was introduced in Java 5 and provides thread-safe utilities like ConcurrentHashMap, ExecutorService, and atomic variables for concurrent programming.
What in recent times I learned or read that you can advise
Recently studied virtual threads in Java 21 and reactive programming patterns with Project Reactor for handling high-concurrency systems efficiently.
Tell me briefly what you did in programming
Developed microservices using Spring Boot, implemented REST APIs, worked with JPA/Hibernate for ORM, and built distributed systems with message queues.
Tell me about your experience of translating the project to Java
Explain the motivation for the migration, your approach to mapping language-specific constructs (C# properties to Java getters/setters, LINQ to Streams, async/await to CompletableFuture), how you handled testing during the transition, and what you learned about both ecosystems.
What to do if there is no Right Join in the database, but there is Left Join
Simulate Right Join using Left Join with table positions reversed: `SELECT * FROM A LEFT JOIN B ON A.id = B.id` becomes `SELECT * FROM B LEFT JOIN A ON B.id = A.id`.
What are the merger strategies from the point of view of the database developer
Key strategies: proper indexing on search columns, partitioning for large tables, denormalization where read-heavy, and using materialized views for complex queries.
As if implemented a table in a database for 100 million records, with a search on the Int32 column
Create a clustered index on the Int32 column to enable O(log n) binary search; for 100M records, partition the table and use query optimization with execution plans.
How to make a quick search without sorting an integration of millions of values
Use database indexes (B-tree, hash indexes), implement pagination with LIMIT/OFFSET, leverage query result caching, and consider columnar databases for analytical queries.
What do you think about the test type of exceptions in Java
Checked exceptions in Java are often overused; prefer unchecked exceptions for programming errors and use checked only for recoverable conditions users can handle.
If I developed a library for working with http, I would use exceptions or something else
Use Result types or Optional combined with unchecked exceptions; they're more composable than checked exceptions and better suit functional error handling patterns.
Why are the pools of connections in the database are needed
Connection pools reduce overhead of creating new connections per request; they maintain reusable connections, improving performance and resource utilization significantly.
How the Close method works when working with the connection pulle to the database
Close() returns the connection to the pool rather than closing it; the pool manages actual closure based on idle timeout or shutdown, enabling connection reuse.
Used Kotlin
Used Kotlin for Android development and backend services; love null safety, extension functions, and coroutines, but Java's ecosystem remains more mature for enterprise.
What would I want to remove from Java
Remove checked exceptions (overly verbose), primitive types duplication (autoboxing overhead), and Java's verbose null handling compared to modern languages.
Whether it was spent with Content
Content negotiation not directly relevant to core Java development; assuming this refers to HTTP content negotiation which I handle via Spring ContentNegotiatingViewResolver.
Did you do any projects with many streams
Built high-throughput systems with thread pools using ExecutorService; implemented thread-safe concurrent collections and managed synchronization carefully for 1000+ concurrent threads.
What types of variables are in Java
Primitive types (int, long, boolean, etc.) and reference types (objects); primitives stored on stack, references on heap; autoboxing converts between them automatically.
What Java elements are responsible for inheritance
Inheritance uses `extends` for classes and `implements` for interfaces; supports single class inheritance and multiple interface implementation, enabled by `super` keyword access.
What is a reduction in the method
Method reduction (likely method reference) in streams: replace lambda with `::` operator like `list.forEach(System.out::println)` for cleaner, more readable code.
What is the class Pojo
POJO (Plain Old Java Object) is a simple class with private fields, public getters/setters, and no framework dependencies; foundation for entities, DTOs, and domain models.
How JPA differs from Hibernate
JPA is a specification/standard for ORM in Java, while Hibernate is a concrete implementation that also extends JPA with additional features like lazy loading proxies and HQL.
Can the entity class be abstract
Yes, entity classes can be abstract; they can contain shared mappings and logic inherited by concrete entity subclasses using @Inheritance annotation.
What is Exception
Exception is a checked exception class in Java that represents error conditions; unchecked exceptions (RuntimeException subclasses) don't require explicit handling, while checked exceptions must be caught or declared.
Tell me about your success in programming
Led migration of legacy monolith to microservices reducing deployment time by 60%, implemented caching strategy improving response times by 3x, and mentored junior developers on design patterns.
How can you optimize a highly loaded web service
Use connection pooling (HikariCP), implement caching (Redis), optimize queries (indexing, N+1 prevention), load balancing, async processing with message queues, and monitor with APM tools.
What tools used in addition to Java
Git for version control, Maven/Gradle for builds, Jenkins for CI/CD, Docker for containerization, Kubernetes for orchestration, SonarQube for code quality, and ELK stack for logging.
What is Branch in Git
A branch is a separate line of development in Git; it allows parallel work on features without affecting the main codebase, merged back when complete.
How to check that your program works correctly
Write unit tests with JUnit/Mockito for business logic, integration tests for database/API interactions, run test suites in CI/CD pipeline, use code coverage tools (JaCoCo), and perform manual testing.
We have a web service and in logs it is written "Record Not Found" - how to understand
Check application logs for detailed error context and stack trace, verify database connectivity and query correctness, check if the record exists in the database, review recent code changes.
The user came and says that the data is not displayed, your actions
Verify user permissions and data visibility, check browser cache/network tab, confirm data exists in database for that user, check application logs for errors, test with a known working dataset.
Need the "Delete Report from the System" button, your actions
Add UI delete button in the form, implement backend DELETE endpoint with proper authorization, add database cascade delete logic, implement confirmation dialog, add audit logging for deleted records.
What is the distance between the moon and the Earth
Approximately 384,400 km from Earth's center; irrelevant to Java development interview.
What are the principles of programming that help write a beautiful code you know
SOLID principles (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion), DRY, KISS, composition over inheritance, and proper naming conventions.
Tell me about the SEGREGATION interface
Interface Segregation Principle (ISP) states clients shouldn't depend on interfaces they don't use; design focused, specific interfaces rather than one bloated interface.
What are http methods
HTTP methods are verbs defining actions: GET (retrieve), POST (create), PUT (replace), PATCH (partial update), DELETE (remove), HEAD (like GET without body), OPTIONS (allowed methods).
What are the HTTP queries methods
HTTP request methods are GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, TRACE; they define what action to perform on the resource identified by the URL.
What is the difference between http requests
GET is idempotent and cacheable retrieving data, POST modifies server state creating new resources, PUT replaces entire resource, PATCH partially updates, DELETE removes; GET uses URL params, POST uses body.
What is strong and weakness in the understanding of the code
Strengths: deep understanding of Java internals, design patterns, clean code practices; weaknesses: may struggle with unfamiliar frameworks or legacy code without documentation.
What is atomic types and why they are needed
Atomic types (AtomicInteger, AtomicLong, AtomicReference) provide thread-safe operations without explicit synchronization using CAS (Compare-and-Swap); needed for lock-free concurrent programming.
What are interfaces-markers and why they are not created now
Marker interfaces (Serializable, Cloneable) use compile-time type information; modern Java uses annotations (@FunctionalInterface, @Deprecated) for metadata, providing better flexibility and IDE support.
What evolutionary development has received interfaces-markers and what replaced them
Marker interfaces were replaced by annotations (@interface) in Java 5+. Annotations provide metadata without affecting code semantics and are more flexible for compile-time and runtime processing.
For what purpose is serialization applied
Serialization converts objects into byte streams for storage, transmission over networks, or IPC. It enables object persistence and communication between JVMs.
What is PECS principle and how it is used
PECS (Producer Extends, Consumer Super) defines wildcard bounds: use <? extends T> when reading from a producer, <? super T> when writing to a consumer. It maximizes API flexibility while maintaining type safety.
Why can Immutable objects need in practice
Immutable objects are thread-safe without synchronization, can be safely shared, used as HashMap keys, and enable functional programming patterns with guaranteed state consistency.
What is error processing
Error processing is the mechanism to handle abnormal conditions via exceptions (checked/unchecked) or error codes, allowing graceful degradation and recovery.
What to do if Error flew out, can we catch it and somehow process it
Error (not Exception) indicates JVM-level problems (OutOfMemoryError, StackOverflowError) and shouldn't be caught; if unavoidable, catch conservatively without recovery expectations.
It is known that when the method A is called, the exception will be issued, your actions
Declare throws Exception in method signature, wrap in try-catch to handle gracefully, or let it propagate up the call stack depending on recovery capability.
How to get a Cant Convert Modification Exception when working with a collection
ConcurrentModificationException occurs when modifying a collection while iterating; use Iterator.remove(), Collections.synchronizedList(), or CopyOnWriteArrayList instead of direct modification.
Streams, what operations and types of operations are there
Streams have intermediate operations (map, filter, flatMap, sorted,lazy) and terminal operations (collect, forEach, reduce, findFirst,trigger evaluation). Distinguish between stateless and stateful operations.
What functional interfaces do you know
Functional interfaces: Function<T,R>, Consumer<T>, Supplier<T>, Predicate<T>, Comparator<T>, UnaryOperator<T>, BinaryOperator<T>. Each has a single abstract method for lambda compatibility.
What is the difference between Default Methods from Static Methods
Default methods have implementation in interface (can be overridden), static methods are utility functions not inherited by implementing classes. Both added in Java 8.
What are the types of databases
Types: Relational (SQL), NoSQL (document, key-value, graph, columnar), and NewSQL hybrids. Each designed for different consistency, scalability, and query patterns.
What are the advantages and disadvantages of database types
Relational: ACID compliance, normalization, joins (slower at scale). NoSQL: horizontal scaling, high availability, eventual consistency, weaker querying (choose based on requirements).
What is the normalization of data in a relational database
Normalization eliminates data redundancy through 1NF, 2NF, 3NF, BCNF by decomposing tables and removing partial/transitive dependencies while preserving functional dependencies.
Tell me about the syntax of the creation of the table in a relational database
CREATE TABLE syntax: CREATE TABLE name (column1 TYPE constraints, column2 TYPE constraints, PRIMARY KEY, FOREIGN KEY references). Add constraints like NOT NULL, UNIQUE, DEFAULT, CHECK.
How to change the table in a relational database
ALTER TABLE name ADD/DROP/MODIFY column definition; ADD/DROP PRIMARY KEY; ADD/DROP FOREIGN KEY; RENAME column/table. Use CONSTRAINT naming for complex changes.
You know what a request plan is in a relational database
Query plan (execution plan) shows how DB optimizer executes a query: join order, indexes used, scan types (sequential vs index), cost estimates. Analyze with EXPLAIN to optimize performance.
How Spring "under the hood" works
Spring uses dependency injection via annotations (@Autowired, @Component), AOP proxies for cross-cutting concerns, and BeanFactory/ApplicationContext to manage bean lifecycle and wiring.
Why do you need Hibernate
Hibernate provides ORM abstraction: maps classes to tables, handles CRUD via Session, manages relationships, lazy loading, caching, and HQL for database-agnostic queries.
Who calls the controller methods
Controller methods are called by the DispatcherServlet in Spring MVC after URL mapping and handler resolution based on HTTP requests and routing configurations.
Knowing the answers is half the battle
The other half is explaining them clearly under pressure.
Try a free mock interviewarrow_forward