0% found this document useful (0 votes)
3 views7 pages

Java Interview Qa

The document is a quick answer guide for Java backend interviews, compiling the top 30 most-repeated questions and essential concepts. It covers topics such as microservices architecture, design patterns, Spring Boot annotations, and testing frameworks like JUnit and Mockito. Each section provides concise explanations and code examples to illustrate key points relevant for interview preparation.

Uploaded by

imran12beit17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Java Interview Qa

The document is a quick answer guide for Java backend interviews, compiling the top 30 most-repeated questions and essential concepts. It covers topics such as microservices architecture, design patterns, Spring Boot annotations, and testing frameworks like JUnit and Mockito. Each section provides concise explanations and code examples to illustrate key points relevant for interview preparation.

Uploaded by

imran12beit17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Backend Interview - Quick

Answer Guide
Top 30 Most-Repeated Questions + Testing Essentials

Java Backend Interview - Quick


Answer Guide
Compiled from repeated questions across e&, COMS, DPW, Visionet,
Careem, UAE Pass, e& Money, Rak Bank, Big Data, Etisalat and SCB
interview sheets. Each answer is kept to 2-3 lines with a short
example where useful.

1. Microservices Architecture &


Communication
Microservices split one application into small, independently
deployable services, each owning its own data and business capability.
They communicate synchronously via REST/gRPC or asynchronously
via message queues (Kafka, RabbitMQ). Each service can be scaled,
deployed, and upgraded independently.

Order-Service --REST--> Payment-Service


Order-Service --Kafka event--> Notification-Service

2. API Gateway
A single entry point that routes client requests to the correct
microservice, handling cross-cutting concerns like authentication, rate
limiting, and request aggregation. It hides internal service topology
from clients (e.g., Spring Cloud Gateway, Kong).

3. Design Patterns (Singleton, Factory,


Strategy, Builder)
Singleton: one instance per JVM (e.g., Spring beans by default).
Factory: centralizes object creation logic, hiding new calls.
Strategy: swap algorithms at runtime via a common interface.
Builder: constructs complex objects step by step.

public class Car {


private final String engine;
private Car(Builder b) { [Link] = [Link]; }
public static class Builder {
private String engine;
public Builder engine(String e) { [Link] = e; return
this; }
public Car build() { return new Car(this); }
}
}
4. Spring Boot Annotations (@Controller,
@Service, @Repository, @Autowired)
@Controller/@RestController handle HTTP requests, @Service holds
business logic, @Repository handles persistence and translates DB
exceptions, and @Autowired injects a dependency by type. All are
specializations of @Component, so Spring’s classpath scanning picks
them up as beans.

5. JWT (Structure, Refresh Token)


A JWT has three Base64Url parts - header, payload (claims), and
signature - separated by dots. The server verifies the signature to
trust the claims without a DB lookup. A short-lived access token is
paired with a longer-lived refresh token used to obtain a new access
token without re-login.

6. HashMap Internals / HashMap vs


TreeMap vs HashSet
HashMap stores key-value pairs in buckets indexed by hashCode();
collisions form a linked list that converts to a red-black tree past a
threshold (8) for O(1) average lookup. TreeMap keeps keys sorted
(Red-Black tree, O(log n)); HashSet is really a HashMap internally,
storing only keys.

Map<String,String> m = new HashMap<>();


[Link]("name","A");
[Link]("name","B"); // overwrites -> value becomes "B", no exception

7. CI/CD Pipelines
Continuous Integration automatically builds and tests every commit
(Jenkins/GitHub Actions); Continuous Delivery/Deployment automates
packaging and releasing that build to environments. A typical
pipeline: build → unit test → SonarQube scan → package (Docker
image) → deploy to staging/prod.

8. Java 8 Features (Streams, Lambda,


Functional Interface, Optional)
Lambdas allow passing behavior as data; Streams enable declarative,
pipeline-style collection processing (filter/map/reduce); Functional
Interfaces (one abstract method, e.g., Runnable, Comparator) are lambda
targets; Optional avoids null checks by wrapping a possibly-absent
value.

List<String> names = [Link]("Ann","Bob","Al");


long count = [Link]().filter(n -> [Link]("A")).count();

9. Bean Scopes - Singleton vs Prototype


Singleton (default) creates one shared bean instance per Spring
container; Prototype creates a new instance every time it’s requested.
A Singleton bean cannot directly @Autowired a Prototype bean and get
a fresh instance each call - use ObjectFactory or @Lookup to get a new
instance on demand.
10. Multithreading - Thread, Runnable,
Callable, volatile
Thread/Runnable run code without returning a result; Callable runs
code and returns a value (used with ExecutorService, can throw
checked exceptions). volatile ensures a variable’s writes are
immediately visible to all threads, preventing caching in CPU
registers, but doesn’t guarantee atomicity.

Callable<Integer> task = () -> 10 + 20;


Future<Integer> result =
[Link]().submit(task);

11. Docker & Kubernetes


Docker packages an app with its dependencies into a portable
container image, ensuring consistent behavior across environments.
Kubernetes orchestrates many containers across nodes - handling
scheduling, scaling, self-healing (restarting failed Pods), and rolling
deployments.

12. IoC and Dependency Injection


Inversion of Control means the framework (Spring container), not
your code, creates and manages object lifecycles. Dependency
Injection is the mechanism IoC uses to supply a bean’s required
collaborators (via constructor, setter, or field injection) instead of the
bean creating them itself.

13. Query Optimization / Slow Query


Resolution
Start by running EXPLAIN/EXPLAIN ANALYZE to see the execution plan,
then add indexes on filter/join/order-by columns, avoid SELECT *, and
rewrite correlated subqueries as joins. Also check for missing
pagination and N+1 query patterns from the ORM.

14. Circuit Breaker Pattern


Wraps a remote call and stops calling a failing dependency after a
failure threshold, “opening” the circuit and failing fast (optionally
returning a fallback) instead of piling up timeouts. After a cooldown it
goes “half-open” to test if the dependency recovered (Resilience4j,
Hystrix).

15. Hibernate - Session, N+1,


evict/detach, Caching
A Session is a single-threaded unit-of-work object used to
persist/retrieve entities within a transaction. The N+1 problem
happens when fetching a parent triggers a separate query per child
(fixed with JOIN FETCH or batch fetching). evict()/detach() remove an
entity from the session’s first-level cache; second-level cache (e.g.,
Ehcache) shares data across sessions.
16. Collections Framework (List, Set,
Map)
List is an ordered, index-based, duplicate-allowing collection
(ArrayList, LinkedList); Set holds unique elements (HashSet, TreeSet);
Map stores key-value pairs and is not a Collection (separate interface).
ConcurrentHashMap allows safe concurrent access via lock striping,
unlike synchronized HashMap.

17. OOP Pillars (Inheritance,


Polymorphism, Encapsulation,
Abstraction)
Encapsulation hides internal state behind methods (getters/setters);
Inheritance lets a class reuse/extend another’s behavior;
Polymorphism allows one interface to behave differently per
implementing class (overriding = runtime, overloading = compile-
time); Abstraction exposes only essential details via
interfaces/abstract classes.

abstract class Shape { abstract double area(); }


class Circle extends Shape {
double r;
Circle(double r){ this.r = r; }
double area(){ return [Link] * r * r; } // overriding
}

18. Spring Security - Roles, Authorities,


JWT Integration
Spring Security intercepts requests via a filter chain, authenticates
the user (username/password, JWT, OAuth2), and authorizes access
based on roles/authorities using @PreAuthorize or URL rules. For JWT,
a custom filter validates the token and populates the SecurityContext
before the request reaches the controller.

19. Caching in Spring Boot (Redis, Levels)


@EnableCaching plus @Cacheable/@CacheEvict lets Spring cache method
results transparently, backed by Redis, Caffeine, or Ehcache.
Application-level caching sits alongside DB-level caching (Hibernate
1st/2nd level) and CDN/browser caching for full-stack performance.

@Cacheable("products")
public Product getProduct(Long id) { return
[Link](id).orElseThrow(); }

20. Database Indexing & Partitioning


An index is a separate sorted structure (usually B-tree) pointing to
rows, speeding up lookups at the cost of slower writes and extra
storage. Partitioning splits one large table into smaller physical pieces
(by range/hash) to improve query and maintenance performance,
while indexing speeds up lookups within data.

21. Immutable Class Implementation


Make the class final, all fields private final, no setters, initialize
everything via constructor, and defensively copy any mutable fields
(like Date or collections) on the way in and out.

public final class Student {


private final String name;
private final int age;
public Student(String name, int age) { [Link] = name;
[Link] = age; }
public String getName(){ return name; }
public int getAge(){ return age; }
}

22. SAGA Pattern (Orchestration vs


Choreography)
SAGA manages distributed transactions across microservices as a
sequence of local transactions, each with a compensating action to
undo it on failure. Orchestration uses a central coordinator to direct
the steps; choreography has each service publish events that trigger
the next service, with no central controller.

23. Horizontal vs Vertical Scaling


Vertical scaling adds more CPU/RAM to a single machine (simple but
has a hardware ceiling); horizontal scaling adds more
machines/instances behind a load balancer (better fault tolerance and
near-limitless scale, but needs stateless services).

24. Event-Driven Architecture / Kafka


Services communicate by publishing/subscribing to events rather than
calling each other directly, decoupling producers from consumers.
Kafka stores events in partitioned, ordered logs (topics); producers
append, consumer groups read at their own pace, and offsets track
progress for replay/fault-tolerance.

25. Rate Limiting


Rate limiting caps how many requests a client can make in a time
window (e.g., token bucket or sliding window algorithm) to protect the
system from overload or abuse. It’s typically implemented at the API
Gateway or with Redis-backed counters (e.g., Bucket4j).

26. Singleton Design Pattern (Thread-


Safe)
A thread-safe singleton ensures only one instance is created even
under concurrent access, commonly via double-checked locking or an
enum (simplest, JVM-guaranteed).

public class Singleton {


private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized ([Link]) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}

27. Exception Handling - Error vs


Exception, finally
Error represents unrecoverable JVM-level problems
(OutOfMemoryError) that apps shouldn’t catch; Exception represents
recoverable conditions, split into checked (must be declared/caught,
e.g., IOException) and unchecked (RuntimeException). finally always
runs (even after a return or an exception in catch), so it’s used for
guaranteed cleanup like closing non-try-with-resources connections.

28. Find Pair in Array with Given Sum -


O(n)
Use a HashSet: for each element, check if (target - element) was
already seen; if yes, that’s your pair, else add the current element and
continue.

static void findPair(int[] arr, int sum) {


Set<Integer> seen = new HashSet<>();
for (int n : arr) {
if ([Link](sum - n)) { [Link](n + "," +
(sum-n)); return; }
[Link](n);
}
}

29. Count Vowels in a String


Iterate the string once, incrementing a counter whenever the
lowercase character is in "aeiou".

static long countVowels(String s) {


return [Link]().chars().filter(c -> "aeiou".indexOf(c) >=
0).count();
}

30. @Transactional in Microservices


@Transactional wraps a method in a local ACID database transaction,
rolling back all changes if a RuntimeException is thrown. Across
microservices there’s no single DB transaction, so distributed
consistency is instead handled with the SAGA pattern or eventual
consistency via events.

Added: Core JVM & Testing Topics


(commonly missed)

31. JVM Memory Model (Heap, Stack,


Metaspace)
The Stack is per-thread and holds method call frames, local variables,
and object references (fast, LIFO, auto-cleaned when a method
returns). The Heap is shared across all threads and stores all objects,
split into Young Generation (Eden + Survivor, for new objects) and Old
Generation (long-lived objects), managed by the Garbage Collector.
Metaspace (replacing PermGen since Java 8) holds class metadata
and lives in native memory rather than the heap.

Heap: [ Young Gen (Eden|S0|S1) ] -- promotion --> [ Old Gen ]


Stack: per-thread frames (local vars, method calls)
Metaspace: class definitions, method bytecode (native memory)

32. JUnit - Writing a Simple Test Case


JUnit 5 uses @Test to mark a test method and assertion methods
(assertEquals, assertTrue, etc.) to verify expected behavior;
@BeforeEach/@AfterEach set up and tear down state around each test.

class CalculatorTest {
private final Calculator calc = new Calculator();

@Test
void addsTwoNumbers() {
int result = [Link](2, 3);
assertEquals(5, result, "2 + 3 should equal 5");
}

@Test
void throwsOnDivideByZero() {
assertThrows([Link], () ->
[Link](10, 0));
}
}

33. Mockito - Writing a Simple Test with


Mocks
Mockito creates fake implementations of dependencies (mock() or
@Mock) so you can test a class in isolation, defining fake return values
with when(...).thenReturn(...) and verifying interactions with
verify(...).

@ExtendWith([Link])
class OrderServiceTest {
@Mock
private PaymentRepository paymentRepo;

@InjectMocks
private OrderService orderService;

@Test
void confirmsOrderWhenPaymentSucceeds() {
when([Link](anyDouble())).thenReturn(true);

boolean confirmed = [Link](100.0);

assertTrue(confirmed);
verify(paymentRepo, times(1)).charge(100.0);
}
}

You might also like