How to use this revision
This page condenses every question from the Fresher to 2 Years course in these areas into a single line: the question, linked to its full answer, and the one-sentence answer you should be able to give instantly. Read down the list and answer each question aloud before reading the line. Wherever you hesitate, follow the link and revise the full answer — interviewers at your level expect these basics to be fluent, and they often open with them before going deeper.
Hibernate & Spring Data JPA
Hibernate & JPA Core Concepts — Interview Questions — open the lesson
- What is Hibernate? — Hibernate is the most widely used Java ORM (object-relational mapping) framework, and the default JPA implementation in Spring Boot.
- What are the core components of Hibernate? — -
Configuration/bootstrap: reads the settings and mappings. - SessionFactory: a thread-safe, expensive factory, one per database. - Session: the unit of work, holding the persistence context. - Transaction. - Query (HQL, native SQL, Criteria). - A connection…
- What is the role of the
SessionFactory? — It's built once at startup from the configuration and mappings. It holds the compiled metadata, the connection provider and the second-level cache, and it creates Sessions.
- What is a
Session? — A short-lived, single-threaded unit of work between the application and the database (JPA: EntityManager). It holds the persistence context, the first-level cache of the entities it has loaded, which tracks their changes.
- How does Hibernate manage transactions? — All writes happen inside a transaction. Plain Hibernate uses
session.beginTransaction() and commit()/rollback(), on top of either a JDBC connection's transaction or JTA (for distributed or container-managed transactions).
- What is HQL? — Hibernate Query Language, the superset of JPA's JPQL. It's an object-oriented query language that queries entities and their properties, not tables and columns.
- What is the Criteria API? — A programmatic, type-safe way to build queries in Java code instead of strings. It's ideal for dynamic queries whose filters depend on user input, such as search screens.
- What are the entity (object) states in Hibernate? — - Transient: new, not associated with a session, no database row. - Persistent (managed): attached to an open persistence context.
- What is the purpose of the
Configuration class? — In native Hibernate, Configuration (or the newer StandardServiceRegistryBuilder + MetadataSources) bootstraps Hibernate.
- What is the second-level cache? — An optional cache shared across sessions, at the
SessionFactory level, that stores entity data by ID. Repeat reads of the same entities from different transactions then skip the database.
- What's the difference between
get() and load()? — - session.get() (JPA: em.find()) hits the database immediately (unless the entity is already in the persistence context), and returns null if the row doesn't exist. - session.load() (JPA: em.getReference()) returns a lazy proxy without querying.
- How does Hibernate help ensure data integrity? — Through transactions (atomic commit or rollback), database constraints that it maps (primary keys, foreign keys, unique and not-null constraints), optimistic locking with
@Version to prevent lost updates, pessimistic locks (SELECT … FOR UPDATE) when needed, and Bean…
Hibernate Performance, Mapping & Scenarios — Interview Questions — open the lesson
- What is the N+1 SELECT problem, and how do you prevent it? — You run 1 query to load N parent rows. Then, as your code touches a lazy association on each parent, Hibernate runs N more queries, one per parent.
- What does
@Entity do? — It marks a class as a JPA entity, meaning its instances map to rows of a table and can be persisted. An entity needs: - an @Id; - a no-argument constructor (it can be protected); - a non-final class, so that proxies can extend it.
- What is cascading? — Cascading propagates entity operations from a parent to its associated children.
CascadeType.PERSIST, MERGE, REMOVE, REFRESH, DETACH, or ALL.
- What is a composite key, and how do you map it? — A primary key made of several columns, for example
(order_id, line_no). Map it with an @Embeddable key class used as an @EmbeddedId (preferred), or with @IdClass.
- How does Hibernate protect against SQL injection? — When you use parameter binding, values are sent as
PreparedStatement parameters, never concatenated into the SQL text.
- What is lazy loading? — Deferring the loading of an association until it's first accessed. Hibernate injects a proxy, or an uninitialised collection wrapper, and runs the query on first use.
- How do you handle concurrency in Hibernate? — With locking: - Optimistic locking (
@Version): no database locks. It detects conflicting updates at commit time. - Pessimistic locking (@Lock(LockModeType.PESSIMISTIC_WRITE) → SELECT … FOR UPDATE): locks the rows while you work, for heavily contended data such as stock…
- What is optimistic locking? — Each row carries a version column (
@Version). An update includes the version it read in its condition: `UPDATE … SET …, version = 6 WHERE id = ?
- Scenario: fetching entities with many relationships is slow. What would you do? — 1. Measure first: enable SQL logging or statistics, and count the queries. 2. Make associations LAZY by default, so unused data isn't loaded. 3.
- Scenario: how do you manage Hibernate sessions in a web application so they're always closed? — Let the framework own them. In Spring, the
EntityManager is bound to the transaction (@Transactional on the service layer), and it's opened and closed automatically, even when exceptions occur.
- Scenario: an error happens after several database operations in a transaction. How is integrity preserved? — Everything happened inside one transaction, so the failure triggers a rollback. The database discards every change made in that transaction, and no partial update remains.
- Scenario: you need to audit changes to entity data. What would you use? — Hibernate Envers. Annotate entities with
@Audited. For every change, Envers writes a revision into _AUD tables, recording the revision number, the type of change (add, modify or delete) and the entity's state.
- Scenario: map a legacy database whose table and column names don't follow your conventions. — Map the names explicitly, without changing the schema:
@Table(name = "TBL_CUST_MSTR") and @Column(name = "CUST_NM").
SQL
SQL Basics, Keys, Normalization & Transactions — Interview Questions — open the lesson
- What is SQL? — SQL (Structured Query Language) is the standard declarative language for working with relational databases. You describe what data you want (or want to change), and the database's query optimiser decides how to get it.
- Where is SQL used? — - In application backends, through JDBC, JPA or Spring Data, to store and query business data. - In reporting and business intelligence. - In data engineering and analytics (warehouses such as Snowflake and BigQuery, Spark SQL). - In database administration (users,…
- What are the types of SQL statements? — Compared side by side in the full answer (table) — know each row.
- What is a join? — A join combines rows from two or more tables, based on a related column (usually a foreign key matching a primary key), into a single result.
- What is the purpose of the
SELECT statement? — SELECT retrieves data. It lets you choose columns, filter rows (WHERE), join tables, aggregate (GROUP BY with COUNT, SUM, AVG), filter groups (HAVING), sort (ORDER BY), and limit results (LIMIT/OFFSET).
- What is normalization? — Normalization organises tables to remove redundancy and the update anomalies it causes, by splitting data into related tables so that each fact is stored once.
- What are the main data types in MySQL? — - Numeric:
TINYINT, INT, BIGINT, DECIMAL(p,s) (exact, use it for money), FLOAT/DOUBLE (approximate). - String: CHAR(n) (fixed length), VARCHAR(n) (variable length), TEXT/LONGTEXT, ENUM, BLOB (binary). - Date and time: DATE, TIME, DATETIME,…
- What's the difference between a primary key and a unique key? — Both enforce uniqueness. A primary key identifies each row. There's only one per table, it can't be NULL, and in InnoDB it's the clustered index that determines the physical row order.
- What is a foreign key constraint? — A foreign key makes a column's values reference the primary (or unique) key of another table. The database then enforces referential integrity: you can't insert a row pointing to a non-existent parent, or delete a parent that's still referenced, unless you define an `ON…
- What's the difference between NULL and zero? — Zero is a known numeric value. NULL means "unknown or missing". It isn't a value at all, and it behaves differently everywhere: - Arithmetic with NULL gives NULL (
NULL + 1 → NULL). - Comparisons with NULL give UNKNOWN, so WHERE amount = NULL matches nothing.
- What is a database transaction? — A transaction is a group of operations executed as one logical unit: either all of them take effect (commit) or none do (rollback).
SQL Joins, Triggers, Procedures, Functions & Indexes — Interview Questions — open the lesson
- What's the difference between an INNER JOIN and a NATURAL JOIN? — With an INNER JOIN you state the join condition explicitly (
ON e.department_id = d.id). A NATURAL JOIN joins automatically on every column with the same name in both tables.
- How do you perform a self-join? — Join a table to itself, using two different aliases. It's typically used for hierarchies (employee → manager), or for comparing rows within the same table.
- What is a trigger, and how do you create one in MySQL? — A trigger is code the database runs automatically
BEFORE or AFTER an INSERT, UPDATE or DELETE on a table, for each affected row.
- What is a stored procedure, and how do you create one? — A stored procedure is a named, precompiled block of SQL stored in the database. It can take
IN, OUT and INOUT parameters, contain control flow, and run multiple statements.
- What is a cursor, and how do you use one in MySQL? — A cursor lets a stored program iterate over a query result row by row: 1.
DECLARE it for a SELECT. 2. OPEN it. 3.
- What is a user-defined function, and how do you create one? — A stored function takes parameters and returns a single value. It can be used inside SQL expressions, unlike a procedure.
- What are aggregate functions? — Functions that compute one value from many rows:
COUNT, SUM, AVG, MIN, MAX, and MySQL's GROUP_CONCAT (or the standard STRING_AGG in other databases).
- What's the difference between
WHERE and HAVING? — WHERE filters individual rows before grouping, and can't use aggregates. HAVING filters groups after GROUP BY, and usually tests aggregates.
- What are indexes? — An index is a separate data structure, usually a B+ tree, that lets the database find rows by a column's value without scanning the whole table, much like a book's index.
- How do you find out which indexes a query uses? — Look at the execution plan: -
EXPLAIN SELECT … in MySQL. Check the type (ALL means a full scan; ref and range are good), key (the index chosen), rows (estimated rows examined) and Extra (Using index, Using filesort). - EXPLAIN ANALYZE (MySQL 8.0.18+,…
- Can you create an index on a view? — Only if the view's results are stored. A normal view is just a saved query, so there's nothing to index. The indexes on its base tables are used when the view is queried.
SQL "Difference Between" Questions — Interview Questions — open the lesson
- Two tables,
shop_1 and shop_2, have the same structure. How do you find customers who appear in both? — Use an INNER JOIN on the customer key, INTERSECT, or EXISTS.
- What's the difference between INNER JOIN and OUTER JOIN? — An INNER join returns only the rows that match in both tables. An OUTER join also keeps the non-matching rows, filling the missing side with NULLs: - LEFT: all rows from the left table. - RIGHT: all rows from the right table. - FULL: all rows from both tables.
WHERE vs HAVING? — WHERE filters rows before grouping, and can't contain aggregates. HAVING filters groups after GROUP BY, and typically uses aggregates.
UNION vs UNION ALL? — Both stack the results of two SELECTs, which must have the same number of columns with compatible types. UNION removes duplicates, which needs a sort or hash step, so it's slower.
DELETE vs TRUNCATE? — Compared side by side in the full answer (table) — know each row.
PRIMARY KEY vs UNIQUE? — A primary key is the row's identity. There's one per table, it's NOT NULL, and in InnoDB it's the clustered index.
DROP vs TRUNCATE? — DROP TABLE removes the table itself: its data, structure, indexes, constraints, triggers and privileges. TRUNCATE removes all rows but keeps the table definition, ready for reuse.
VARCHAR vs CHAR? — CHAR(n) is fixed length: values are right-padded with spaces to n characters (and trailing spaces are removed when read in MySQL).
IN vs EXISTS? — IN checks whether a value is in a list or a subquery's results. EXISTS checks whether a (usually correlated) subquery returns at least one row, and stops at the first match.
- JOIN vs subquery? — A JOIN combines columns from several tables into one result. A subquery is a query nested inside another: in
WHERE (filtering), FROM (a derived table) or SELECT (a scalar value).
SQL Query Writing (Part 1) — Interview Questions — open the lesson
- Find the Nth highest salary. — Use
DENSE_RANK() (MySQL 8+). It handles ties correctly, and N is a parameter.
- Find the 2nd highest salary in MySQL. — The classic answer is a subquery with
MAX — SELECT MAX(salary) AS second_highest FROM employees
- Find all employees with duplicate names. —
SELECT first_name, last_name, COUNT(*) AS occurrences FROM employees
- Find the second-highest salary (another common phrasing). — Any of the above works. The ORDER BY/LIMIT form is also common —
SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1 OFFSET 1;
- Create an empty table with the same structure as another table. — ```sql CREATE TABLE employees_archive LIKE employees; -- copies columns, indexes, PK, AUTO_INCREMENT (not FKs)
- Increase every employee's salary by 5%. —
UPDATE employees SET salary = ROUND(salary * 1.05, 2);
- Find employees whose name starts with "A". —
SELECT first_name, last_name FROM employees WHERE first_name LIKE 'A%';
- Count the employees in department 'ABC'. —
SELECT COUNT(*) AS employees_in_abc FROM employees WHERE department = 'ABC';
- Show employees whose first name ends with 'A' and has exactly 6 letters. —
SELECT * FROM employees WHERE first_name LIKE '_____a'; -- five underscores + 'a' = 6…
- Show employees whose salary is between 10,000 and 50,000. —
SELECT * FROM employees WHERE salary BETWEEN 10000 AND 50000; -- inclusive on both ends
- Fetch duplicate records from a table. — Group by the columns that define a duplicate, and keep the groups with more than one row —
SELECT first_name, last_name, department, COUNT(*) AS cnt FROM employees
SQL Query Writing (Part 2) — Interview Questions — open the lesson
- Fetch the top N records by salary. —
SELECT id, first_name, salary FROM employees
- Find all employees who report to a particular manager. —
SELECT id, first_name FROM employees WHERE manager_id = 17; SELECT e.id, e.first_name
- Extract only the first name from a full-name column. —
SELECT full_name, SUBSTRING_INDEX(TRIM(full_name), ' ', 1) AS first_name
- Get the employees hired in the last 8 months. —
SELECT id, first_name, hire_date FROM employees
- Retrieve the name of the employee with the maximum salary. —
SELECT first_name, salary FROM employees
- Find employees who have worked in more than one department. —
SELECT employee_id, COUNT(DISTINCT department_id) AS departments FROM employee_history
- Use
UNION to list employees who worked on Project A or Project B, without duplicates. — SELECT employee_name FROM project_a UNION -- removes duplicates (someone…
- Fetch the records common to two tables. —
SELECT * FROM table1 INTERSECT
- Show users who have placed fewer than 3 orders. — Use a LEFT JOIN, so that users with zero orders are included, and count a column from the orders table.
- Show employees with salary > 15,000 when the salary is stored in a separate table. —
SELECT e.id, e.first_name, s.salary FROM employees e
Microservices Basics
Microservices, API Gateway & Communication — Interview Questions — open the lesson
- What are microservices? — An architectural style in which an application is built as a set of small, independently deployable services. Each one is organised around a business capability (orders, payments, inventory), owns its data, and communicates with the others over the network (HTTP/REST, gRPC or…
- How do microservices differ from a monolith? — A monolith is built, deployed and scaled as one unit, usually with a single shared database. Microservices split the system into many independently deployed services, each with its own database.
- What are the benefits of microservices? — - Independent deployment: faster, lower-risk releases. - Independent scaling: scale the checkout service for a sale without scaling user profiles. - Team autonomy: a team owns a service end to end. - Technology freedom: the right tool per service. - Fault isolation: a failing…
- What challenges do microservices bring? — - Distributed-system complexity: network latency and partial failures. - Data consistency across services: no single ACID transaction. - Harder debugging: one request touches many services. - Operational overhead: deployment pipelines, monitoring and logging for every…
- What is the role of an API gateway? — It's the single entry point for external clients. It routes each request to the right service, and centralises cross-cutting concerns: authentication and token validation, rate limiting, TLS termination, CORS, request and response transformation, caching, and logging and metrics.
- How does an API gateway manage traffic? — - Routing by path, host or header. - Load balancing across service instances. - Rate limiting and throttling per client or API key (for example token buckets stored in Redis). - Response caching. - Timeouts, retries and circuit breaking towards the backends. - Request size…
- What security measures can be implemented at the API gateway? — - Authentication: validate JWTs or OAuth2 access tokens, or API keys. - Coarse-grained authorisation (scopes and roles per route). - TLS termination. - Rate limiting, against abuse and denial of service. - IP allow and deny lists. - CORS policy. - Request validation and size…
- How can an API gateway handle load balancing? — It looks up the healthy instances of a service (from a service registry such as Eureka, or from Kubernetes Services and DNS), and spreads requests across them using an algorithm: - round robin; - least connections; - weighted (for canary releases); - latency-aware routing.
- How do microservices communicate with each other? — In two styles: - Synchronous request/response: REST over HTTP (with
RestClient, WebClient or OpenFeign), or gRPC, for queries that need an immediate answer. - Asynchronous messaging: events or commands through a message broker (Kafka, RabbitMQ, SQS), for decoupled…
- What's the difference between synchronous and asynchronous communication? — Synchronous: the caller sends a request and waits for the response, so both services must be up at the same time (HTTP or gRPC).
- What role do message brokers play? — A broker receives, stores and delivers messages between producers and consumers. It decouples services, buffers load spikes, enables publish/subscribe fan-out (one event, many consumers), and supports retries and dead-letter queues, with delivery guarantees (at-least-once is…
- What are the risks of inter-service communication? — - Network failures and latency. - Cascading failures: one slow service exhausts its callers' threads. - Retry storms. - Partial failures, which leave data inconsistent. - Chatty designs: many fine-grained calls per request. - Contract drift: breaking API changes. - Security:…
Service Discovery, Data Consistency & Deployment — Interview Questions — open the lesson
- What is a service registry? — A service registry is a database of available service instances and their network locations (host, port, health, metadata).
- How does service discovery work? — 1. A service instance starts, and registers its address with the registry. It keeps sending heartbeats. 2. A caller asks for "order-service", and gets the list of healthy instances. 3.
- What happens if the service registry fails? — It depends on the design, but it shouldn't cause an immediate outage: - Clients cache the registry contents. Eureka clients keep their last-known list of instances, and continue calling services, although they won't see new or removed instances until the registry recovers. -…
- How do services keep their registration up to date? — They register on startup, send periodic heartbeats (Eureka's default is every 30 seconds), and deregister on graceful shutdown.
- How do you handle data consistency in microservices? — Each service owns its data, so there's no single database transaction across services. Consistency is achieved with: - Sagas: a chain of local transactions, each with a compensating action. - Domain events, published reliably with the transactional outbox pattern. -…
- What is eventual consistency? — A consistency model in which, after an update, the different copies or services may disagree temporarily. If no new updates arrive, they all converge to the same state.
- How would you implement a transaction that spans multiple services? — With the Saga pattern. The business transaction is split into a sequence of local transactions, one per service.
- What are the trade-offs between eventual and strong consistency? — Compared side by side in the full answer (table) — know each row.
- What strategies are used to deploy microservices? — Each service is packaged as a container image, deployed through a CI/CD pipeline, and run on an orchestrator (Kubernetes, or ECS).
- What is blue-green deployment? — You run two identical production environments. Blue serves live traffic while green gets the new version. After green passes its checks, you switch all traffic to green (at the load balancer or router).
- How does a canary release differ from blue-green? — A canary sends a small percentage of real traffic (say 5%) to the new version, watches the error rate and latency, then increases the share step by step.
- What tools would you use to automate microservices deployment? — - Docker (or buildpacks and Jib) to build images. - CI pipelines: GitHub Actions, GitLab CI, Jenkins. - Kubernetes, with Helm or Kustomize for manifests. - GitOps with Argo CD or Flux. - Terraform for the infrastructure. - Argo Rollouts or Flagger for progressive delivery.
Microservices Monitoring, Security & Resilience — Interview Questions — open the lesson
- How do you monitor and manage microservices? — With the three pillars of observability, plus automation: - Metrics: Micrometer → Prometheus → Grafana dashboards and alerts. - Logs: structured JSON logs shipped to ELK/OpenSearch or Loki, with a correlation or trace ID in every line. - Traces: OpenTelemetry or Micrometer…
- Which metrics are important in a microservices architecture? — Start with the golden signals for every service: - Latency: p50, p95, p99. Averages hide slow requests. - Traffic: requests per second. - Errors: rate of 5xx responses and failed operations. - Saturation: CPU, memory, thread and connection pool usage, queue depth.
- How does distributed tracing help? — A trace follows one request across every service it touches. Each hop is recorded as a span, with timing and metadata, all linked by a shared trace ID that's propagated in headers (W3C
traceparent).
- Which tools are used for logging and monitoring microservices? — - Metrics: Prometheus, Grafana, Micrometer. Commercial options: Datadog, New Relic. - Logs: ELK (Elasticsearch, Logstash or Fluent Bit, Kibana), OpenSearch, Grafana Loki. - Tracing: Jaeger, Zipkin, Grafana Tempo, with OpenTelemetry as the vendor-neutral instrumentation…
- How do you ensure security in microservices? — Defence in depth: - Identity: OAuth2/OIDC with JWT access tokens, validated by each service as an OAuth2 resource server. - Authorisation: coarse-grained at the gateway, fine-grained in each service. - Encryption: TLS everywhere (mTLS internally), and encryption at rest. -…
- What are common security patterns in microservices? — - API gateway as the edge: authentication, rate limiting, TLS. - Access-token propagation, or token exchange, so downstream services know who the end user is. - Service-to-service authentication with mTLS or client-credentials tokens. - Sidecar / service mesh (Istio,…
- How can services communicate with each other securely? — mTLS encrypts the traffic, and lets each side verify the other's certificate. A service mesh can manage the certificates automatically.
- What does a database per service mean for security? — It limits the blast radius. A compromised service can reach only its own data, with its own credentials. Each database gets permissions and encryption suited to its sensitivity (for example, a stricter setup for payments data), and access is easier to audit.
- What patterns handle failures in microservices? — - Timeouts: never wait forever. - Retries with exponential backoff and jitter: for transient errors, on idempotent operations only. - Circuit breaker: stop calling a service that keeps failing. - Bulkhead: isolate resources, so one dependency can't exhaust them all. -…
- What is the Circuit Breaker pattern? — A circuit breaker wraps calls to a dependency, and tracks their failures. It has three states: - CLOSED: calls flow normally, and failures are counted. - OPEN: after the failure rate crosses a threshold, calls fail fast, or go to a fallback, without touching the dependency.
- How does the Bulkhead pattern improve resilience? — Like the watertight compartments in a ship's hull, a bulkhead isolates resources per dependency or per workload.
- What are the Retry and Backoff patterns? — Retry re-attempts an operation that failed with a transient error (a timeout, a 503, a connection reset). Backoff waits longer between attempts (for example 200 ms, 400 ms, 800 ms: exponential), with random jitter, so thousands of clients don't retry in lockstep and overload…
Maven & Git
Maven — Interview Questions — open the lesson
- What is Maven, and what problem does it solve? — Maven is a build automation and dependency management tool for Java. It solves three problems: - Dependency hell: it downloads libraries, and their transitive dependencies, from repositories, instead of you copying JARs by hand. - Inconsistent builds: there's a standard…
- What is a POM file? —
pom.xml is the Project Object Model, the XML file that describes the project for Maven: - its coordinates (groupId:artifactId:version) and packaging (jar, war, pom); - its dependencies, and dependencyManagement; - its plugins and build settings; - properties,…
- What's the difference between compile and runtime dependencies? What scopes exist? — A compile-scope dependency (the default) is needed to compile and run the code, and it's on every classpath. A runtime dependency isn't needed to compile, only to run and test.
- Explain Maven's lifecycles and phases. — Maven has three built-in lifecycles: -
clean: removes the previous build output. - default (build): from validation through to deployment. - site: generates project documentation.
- What is a Maven repository? — A repository stores artifacts (JARs, POMs, plugins), identified by their coordinates. There are three kinds: - Local:
~/.m2/repository.
- How do you exclude a dependency? — Use
<exclusions> inside the dependency that pulls in the unwanted transitive dependency.
- How can you speed up the Maven build of a large project? — - Build in parallel:
mvn -T 1C install (one thread per core). - Build only what changed: -pl module-a -am builds a module plus the modules it depends on. - Skip what you don't need locally: -DskipTests (tests are still compiled), -Dmaven.test.skip=true (skips even…
- How do you run a Maven build? — From the directory containing
pom.xml, run a phase, for example mvn package (compile, test and create the JAR or WAR in target/), or mvn verify in CI.
- What's the difference between
mvn clean and mvn install? — mvn clean runs the clean lifecycle, and deletes the target/ directory, meaning all previous build output. mvn install runs the default lifecycle up to install: it compiles, tests, packages, verifies, and then copies the artifact into your local repository (~/.m2),…
- How do you manage dependencies in a Maven project? — - Declare the dependencies in
<dependencies>, and let Maven resolve the transitive ones. - Centralise versions in <dependencyManagement>, or import a BOM (spring-boot-dependencies), so all modules agree on versions. - Keep versions in <properties>. - Inspect the…
- Explain the Maven lifecycle once more: what exactly runs when you type
mvn install? — Maven executes, in order, every phase of the default lifecycle up to install: validate, initialize, the source-generation phases, compile, process-classes, test-compile, test (Surefire runs the unit tests), package (builds the JAR),…
Git — Interview Questions — open the lesson
- What is Git, and how does it differ from other version control systems? — Git is a distributed version control system. Every clone holds the full history, so commits, branches, diffs and log searches all work locally and quickly, even offline.
- What's the difference between
git clone, git fetch and git pull? — - clone: copies a remote repository to your machine, once. It includes the full history, and sets up origin. - fetch: downloads new commits and branches from the remote into the remote-tracking branches (origin/main), without touching your working branch. - pull:…
- What is a Git repository? — The
.git directory and its contents: the object database (commits, trees, blobs, tags), refs (branches and tags pointing to commits), the index (staging area) and the configuration.
- What is a commit? — A commit is an immutable snapshot of the whole project. It records a tree of files, parent commit(s), author and committer, timestamps and a message, all identified by a SHA hash.
- What is a branch? — A branch is just a movable pointer (ref) to a commit. Creating one is almost free. As you commit on a branch, the pointer moves forward.
- What is a merge? — A merge integrates the history of one branch into another: - If the target hasn't moved, Git just moves the pointer forward (a fast-forward).
- What is a merge conflict? — A conflict happens when both branches changed the same lines of a file (or one side edited a file the other deleted), so Git can't decide which change wins.
- What is a Git remote? — A remote is a named reference to another copy of the repository, usually on a server, such as
origin → https://github.com/shop/order-service.git.
- Explain branching strategies such as Gitflow and GitHub Flow. — - Gitflow uses long-lived branches:
main (releases), develop (integration), and short-lived feature/*, release/* and hotfix/* branches.
- How do you revert a commit? — Use
git revert <sha>. It creates a new commit that applies the inverse of the given commit, so history is preserved, and it's safe on shared branches.
- Scenario: you're on branch
feature-x, and priorities change. How do you put your work on hold and start a new task? — Save the uncommitted work, branch from an up-to-date main, and come back later.
- Scenario: merging
feature-y into main gives a conflict in Abc.java. How do you resolve it? — ```bash git switch main git merge feature-y # CONFLICT (content): Merge conflict in Abc.java git status # lists the conflicted files # edit Abc.java: combine both intentions, delete the <<<<<<< ======= >>>>>>> markers ./mvnw test # make sure the combined code still compiles…
- Scenario: your feature branch is several commits behind
main. How do you use rebase to update it? — Replay your branch's commits on top of the latest main — git fetch origin git switch feature-z
- Scenario: an urgent bug fix comes in, but you have uncommitted changes. How do you set them aside and restore them afterwards? — Stash them, fix the bug on its own branch, then restore them —
git stash push -m "wip before hotfix" git switch -c hotfix/null-price main
- Scenario: a just-deployed commit caused a serious issue. How do you undo it, and when may you remove it from history? — On a shared branch such as
main, use git revert. It creates a new commit that undoes the change, deploys like any other commit, and doesn't disturb anyone else's history.
Follow-up questions this topic invites — and their answers
Q: How should I use this list in the last week before an interview?
A: Do one pass per day. Cover the answer text, say your answer out loud, then check it. Mark every question you could not answer crisply, and spend your study time only on the marked ones by opening the linked full answer. By the third pass the marked list should be short.
Q: The interviewer asks one of these basics — should I give only the one-liner?
A: Lead with the one-liner, then add one concrete detail or example from your own work. At this level the follow-up usually probes the mechanism behind the basic answer, so be ready to go one layer deeper using the key points in the full lesson.
Q: Some answers here were corrected compared with common prep sheets — why?
A: Several widely shared answers are outdated or wrong (for example, Java version details, removed Spring APIs, or SQL queries that miss edge cases). The full lessons call these out under "Common trap" — reading those is the fastest way to stand out from candidates who memorised the same sheets.