Advance Java MCQ Questions and Answers

41. What are RESTful web services and how are they implemented in Spring Boot?

  1. RESTful web services are a specific Java technology requiring special server licenses
  2. REST (Representational State Transfer) is an architectural style for building web services using HTTP methods — Spring Boot implements REST APIs using @RestController with @GetMapping, @PostMapping, @PutMapping, @DeleteMapping annotations mapping HTTP methods to Java methods
  3. RESTful services can only return XML — JSON support requires a separate framework
  4. REST is exclusively for inter-database communication and cannot serve web or mobile clients

Answer : B
Explanation: REST (Representational State Transfer) uses HTTP methods to perform CRUD operations on resources: GET — Read (retrieve resource), POST — Create (new resource), PUT — Update (replace resource), PATCH — Update (partial update), DELETE — Remove resource. REST principles: Stateless (each request is self-contained), Client-Server, Uniform Interface, Cacheable. Spring Boot REST implementation: @RestController combines @Controller + @ResponseBody — all method return values are automatically serialized to JSON (using Jackson). Example: @GetMapping(“/users/{id}”) returns a User object → Jackson serializes to JSON automatically. HTTP status codes: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 500 Internal Server Error. ResponseEntity<T> provides fine-grained control over status code and headers. @RequestBody deserializes incoming JSON to Java objects. Spring Boot auto-configures Jackson (JSON library) when spring-boot-starter-web is on the classpath. REST APIs are the dominant pattern for modern web application backend development.

42. What is Spring Data JPA and how does it simplify data access?

  1. Spring Data JPA is a replacement for SQL that allows Java developers to avoid writing database queries
  2. Spring Data JPA is a Spring module that simplifies JPA-based data access by providing repository interfaces with built-in CRUD operations, query derivation from method names, and pagination support — eliminating most boilerplate DAO code
  3. Spring Data JPA is a standalone database that replaces MySQL and PostgreSQL for Spring applications
  4. Spring Data JPA only works with NoSQL databases like MongoDB and Cassandra

Answer : B
Explanation: Spring Data JPA eliminates the need to write implementation code for common data access operations. Core interface: JpaRepository<T, ID> provides: save(), findById(), findAll(), deleteById(), count(), existsById(). Query derivation: Spring generates queries from method names automatically. findByEmailAndActive(String email, boolean active) → generates SELECT * FROM users WHERE email=? AND active=?. findByAgeGreaterThan(int age) → SELECT * FROM users WHERE age > ?. Custom JPQL queries: @Query(“SELECT u FROM User u WHERE u.status = :status”) List<User> findByStatus(@Param(“status”) String status). Pagination: PagingAndSortingRepository — findAll(Pageable pageable) returns Page<T> with content, total pages, current page info. Sorting: findAll(Sort.by(“lastName”).ascending()). Transactions: @Transactional annotation at service layer. Spring Data repositories are interfaces — no implementation needed. Spring generates the implementation at runtime. This reduces hundreds of lines of DAO boilerplate to just a few method declarations. Used with Hibernate as the JPA provider.

43. What is Hibernate and what are its advantages over plain JDBC?

  1. Hibernate is a Java web server alternative to Apache Tomcat for hosting web applications
  2. Hibernate is a Java ORM framework that maps Java objects to relational database tables automatically — advantages over JDBC include no SQL boilerplate, automatic mapping, caching, lazy loading, database portability, and transaction management
  3. Hibernate is a Java bytecode optimization library that improves application performance
  4. Hibernate provides only connection pooling benefits over JDBC with no additional functionality

Answer : B
Explanation: Hibernate (ORM Framework) advantages over plain JDBC: No manual SQL: instead of writing INSERT INTO users VALUES(?,?,?), just session.save(user). Object-Relational Mapping: @Entity, @Table, @Column annotations map classes to tables automatically. HQL (Hibernate Query Language): object-oriented query language — “FROM User WHERE age > 18” instead of table-name SQL. Automatic DDL: hibernate.hbm2ddl.auto=update creates/updates tables from entity classes. Caching: First-level cache (Session level — automatic), Second-level cache (SessionFactory level — optional, using EHCache, Redis). Lazy Loading: @OneToMany(fetch=FetchType.LAZY) — related objects loaded only when accessed. Connection Pooling: built-in via C3P0, HikariCP. Transaction Management: session.beginTransaction() / transaction.commit(). Portability: change database just by changing the dialect (MySQL5Dialect → PostgreSQLDialect). When to use plain JDBC: complex, highly optimized queries, batch processing with millions of rows, scenarios where Hibernate’s overhead is unacceptable. In practice: Hibernate via Spring Data JPA is the default choice for most enterprise Java applications.

44. What are the different states of a Hibernate entity object?

  1. Hibernate entities have two states: saved and unsaved
  2. Hibernate entity objects have four states: Transient (not associated with Session, not in database), Persistent (associated with Session, in database), Detached (was persistent but Session closed), and Removed (marked for deletion)
  3. Hibernate entities have three states: new, existing, and deleted — matching database CRUD operations
  4. Hibernate entity states are the same as Java object lifecycle states defined by the JVM

Answer : B
Explanation: Understanding Hibernate entity states is crucial for effective ORM usage: Transient: object created with new but not associated with any Hibernate Session and not in the database. Example: User user = new User(“John”). No ID assigned by Hibernate. Not tracked for changes. Persistent: object is associated with an open Hibernate Session and has a database record. Hibernate tracks all changes (dirty checking) — any modifications are automatically saved on session.flush() or transaction.commit(). Obtained via: session.save(), session.get(), session.load(), Query results. Detached: was previously persistent but the Session was closed or the object was evicted. Has a database record and an ID but Hibernate is NOT tracking changes. Can be reattached using session.update() or session.merge(). Removed (Deleted): object scheduled for deletion from the database. session.delete(entity) transitions to Removed. Deleted on flush/commit. State transitions: Transient → Persistent (save/persist), Persistent → Detached (session close), Detached → Persistent (update/merge), Persistent → Removed (delete). Understanding these states prevents common bugs like updating a detached entity without reattaching it.

45. What is the difference between session.get() and session.load() in Hibernate?

  1. get() and load() are identical — they always return the same result from the database
  2. session.get() hits the database immediately and returns null if not found; session.load() returns a proxy object immediately without hitting the database until properties are accessed, and throws ObjectNotFoundException if not found when accessed
  3. session.load() is for loading collections; session.get() is for loading single entities only
  4. get() uses first-level cache; load() uses second-level cache exclusively

Answer : B
Explanation: This is a commonly tested Hibernate distinction: session.get(): immediately hits the database (or first-level cache). Returns the actual entity object. Returns null if the entity with the given ID does not exist. Safe to use when you are not sure the entity exists. Example: User user = session.get(User.class, 1L); // null if not found. session.load(): returns a proxy object immediately (lazy loading) — does NOT hit the database right away. The proxy is a subclass of the entity class generated by Hibernate. Database is only hit when you access a property of the proxy. If the entity does not exist in the database, throws ObjectNotFoundException when the proxy is initialized. Use when you are sure the entity exists (e.g., setting a foreign key reference). Example: User user = session.load(User.class, 1L); // returns proxy. When to use each: get() — when you need the entity’s data immediately and it may not exist. load() — when you need a reference for setting a foreign key and you know the entity exists (saves a database round trip if you never access the data). In Spring Data JPA: findById() corresponds to get() behavior; getById()/getOne() corresponds to load() behavior.

46. What is the N+1 query problem in Hibernate and how is it solved?

  1. The N+1 problem means Hibernate requires N+1 database connections for N concurrent users
  2. The N+1 query problem occurs when fetching N parent entities causes N additional queries to load their lazy-loaded child collections — solved using JOIN FETCH in JPQL, @BatchSize annotation, or EntityGraph to eagerly load associations in a single query
  3. N+1 is a mathematical property of Hibernate caching that requires N+1 cache invalidations per update
  4. The N+1 problem only affects applications with more than 1000 records in the database

Answer : B
Explanation: The N+1 Problem is the most common Hibernate performance issue. Example: fetching 10 Orders, each with lazy-loaded OrderItems. 1 query: SELECT * FROM orders (returns 10 orders). 10 queries: SELECT * FROM order_items WHERE order_id = ? (one for each order). Total: 11 queries (1+N) instead of the optimal 1-2. Solutions: JOIN FETCH in JPQL: @Query(“SELECT o FROM Order o JOIN FETCH o.orderItems”). Fetches orders and items in one SQL JOIN query. @EntityGraph: @EntityGraph(attributePaths = {“orderItems”}) on repository method — tells JPA to eagerly load specified associations. @BatchSize: @OneToMany @BatchSize(size=10) — loads child collections in batches of 10 using IN clause (10 queries → 2 queries for 10 orders). @Fetch(FetchMode.SUBSELECT): loads all children in one subselect query. DTO Projections: select only needed fields using JPQL constructor expressions or Spring Data Projections — avoids loading full entity graphs. Best practice: use LAZY loading as default, apply JOIN FETCH or EntityGraph only when you know you’ll need the association. Tools like Hibernate Statistics or p6spy help detect N+1 issues.

47. What is Spring Security and what are its core concepts?

  1. Spring Security is a network security tool for protecting the servers running Spring applications
  2. Spring Security is a powerful, customizable authentication and access control framework for Java applications — providing authentication (who are you?), authorization (what are you allowed to do?), protection against common attacks (CSRF, session fixation, XSS headers), and OAuth2/JWT support
  3. Spring Security is a testing library that verifies the security of Spring application source code
  4. Spring Security only supports username/password authentication and cannot be extended

Answer : B
Explanation: Spring Security is the de-facto standard for securing Spring applications. Core concepts: Authentication: verifying identity. Supports: form login, HTTP Basic, OAuth2, SAML, LDAP, JWT. AuthenticationManager — processes authentication requests. UserDetailsService — loads user details from database. Authorization: controlling access. Method-level: @PreAuthorize(“hasRole(‘ADMIN’)”), @Secured(“ROLE_ADMIN”). URL-based: http.authorizeRequests().antMatchers(“/admin/**”).hasRole(“ADMIN”). Security Filter Chain: Spring Security is implemented as a chain of servlet filters. Every request passes through these filters (authentication, authorization, CSRF check). Common filters: UsernamePasswordAuthenticationFilter, JwtAuthenticationFilter (custom), BasicAuthenticationFilter. SecurityContext: stores the current authenticated user (Authentication object) — accessible via SecurityContextHolder.getContext().getAuthentication(). CSRF Protection: prevents cross-site request forgery — enabled by default for state-changing requests. Stateless REST APIs typically disable CSRF (using JWT tokens instead). JWT (JSON Web Token): for stateless REST authentication — validate token on each request without server-side session. Spring Boot auto-configures basic security when spring-boot-starter-security is on the classpath.

48. What is AOP (Aspect-Oriented Programming) in Spring?

  1. AOP is the process of designing algorithms and operators for Spring mathematical operations
  2. AOP is a programming paradigm that separates cross-cutting concerns (logging, security, transactions, caching) from the main business logic — Spring AOP applies behavior (aspects) to methods without modifying the actual method code
  3. AOP stands for Application Object Programming — a Spring-specific design pattern
  4. AOP in Spring is a performance monitoring tool that traces API response times automatically

Answer : B
Explanation: AOP addresses the “cross-cutting concerns” problem — functionality needed across many components (logging every service method, applying @Transactional, checking security). Without AOP: you’d add the same logging/transaction code to every method. With AOP: define the behavior once, Spring applies it automatically. Key AOP concepts: Aspect: a class containing cross-cutting logic. @Aspect annotation. Advice: the action to take. Types: @Before (runs before method), @After (runs after), @AfterReturning (after successful return), @AfterThrowing (after exception), @Around (wraps method, most powerful). Join Point: the point in program execution where an aspect can be applied (method call). Pointcut: expression defining WHICH join points to apply advice to. Example: @Pointcut(“execution(* com.example.service.*.*(..))” — all methods in service package. Weaving: applying aspects to target objects — Spring AOP uses runtime proxies (JDK dynamic proxy or CGLIB). Example use: @Transactional works through Spring AOP — the transaction advice wraps the method. @Around for logging: log method name, parameters, execution time, return value. Custom security checks: verify user has correct role before method executes. AOP reduces code duplication and keeps business methods clean.

49. What is the difference between @Transactional in Spring and database transactions?

  1. @Transactional is only for annotating database migration scripts and has no runtime effect
  2. @Transactional is a Spring annotation that declaratively manages database transactions — when applied to a method, Spring wraps it in a transaction that commits on successful completion or rolls back if a RuntimeException is thrown, without requiring explicit transaction management code
  3. @Transactional in Spring is unrelated to database transactions — it only manages bean scopes
  4. @Transactional only works with Hibernate and not with other persistence technologies

Answer : B
Explanation: @Transactional replaces manual transaction management (session.beginTransaction() / transaction.commit() / transaction.rollback()). How it works (Spring AOP): when a @Transactional method is called, Spring’s proxy intercepts the call, begins a transaction, calls the actual method, and commits (success) or rolls back (RuntimeException). Important behaviors: Rollback rules: by default, rolls back on RuntimeException and Error, but NOT on checked exceptions. Override: @Transactional(rollbackFor = Exception.class). Propagation: @Transactional(propagation = Propagation.REQUIRED) — default: joins existing transaction or creates new one. Propagation.REQUIRES_NEW — always creates a new transaction. Propagation.NESTED — nested transaction. Read-Only: @Transactional(readOnly = true) — optimizes read-only operations. Timeout: @Transactional(timeout = 30). Isolation levels: controls concurrent access. Self-invocation problem: calling a @Transactional method from within the same class bypasses the proxy — the transaction doesn’t apply. Solution: inject the bean and call through the proxy, or use AopContext.currentProxy(). Best practice: put @Transactional on service methods, not repository methods or controller methods.

50. What is the difference between @PathVariable and @RequestParam in Spring MVC?

  1. @PathVariable is for POST requests; @RequestParam is for GET requests exclusively
  2. @PathVariable extracts values from URI path segments (e.g., /users/123 where 123 is extracted); @RequestParam extracts values from query string parameters (e.g., /users?page=1&size=10)
  3. Both annotations do the same thing — they are interchangeable in all Spring MVC scenarios
  4. @RequestParam is deprecated in Spring Boot — @PathVariable should always be used instead

Answer : B
Explanation: Both extract request data but from different parts of the URL: @PathVariable: extracts values from URI template variables enclosed in {}. The value is part of the URL path itself. Example: @GetMapping(“/users/{id}”) + @PathVariable Long id — URL: /users/123 → id = 123. REST API convention: use for resource identifiers (e.g., /products/456, /orders/789). Multiple path variables: /users/{userId}/orders/{orderId}. @RequestParam: extracts query string parameters (after ? in URL). Example: @GetMapping(“/users”) + @RequestParam String name — URL: /users?name=John → name = “John”. Required by default — missing parameter causes 400 Bad Request. Make optional: @RequestParam(required = false) or @RequestParam Optional<String> name. Default values: @RequestParam(defaultValue = “0”) int page. Multiple values: /search?tags=java&tags=spring → @RequestParam List<String> tags. REST conventions: @PathVariable for resource identification (/users/{id}), @RequestParam for filtering/pagination (/users?status=active&page=0&size=20). @RequestBody is a third option — for JSON in request body (POST/PUT requests).