Advance Java MCQ Questions and Answers

61. What is JSP Expression Language (EL) and why is it used?

  1. JSP EL is a compiled language that replaces Java code entirely in JSP pages
  2. JSP Expression Language (EL) is a simplified syntax (${expression}) for accessing data in JSP pages — replacing verbose Java scriptlets by accessing scoped attributes, request parameters, and beans using dot and bracket notation
  3. JSP EL is a server-side JavaScript framework for creating dynamic web pages in Java
  4. EL only works with database query results and cannot access HTTP request parameters

Answer : B
Explanation: JSP Expression Language simplifies JSP pages by replacing scriptlets (<% %>) with clean expressions. Syntax: ${expression}. Accessing request attributes: ${user.name} instead of <%= ((User)request.getAttribute(“user”)).getName() %>. Accessing request parameters: ${param.username} — reads URL/form parameter. Accessing scoped variables (in order of lookup): pageScope, requestScope, sessionScope, applicationScope. Example: ${sessionScope.loggedInUser}. Arithmetic: ${price * quantity} — supports +, -, *, /, %, div, mod. Comparison: ${age gt 18} — supports gt, lt, ge, le, eq, ne. Logical: ${isActive and isAdmin}. Null handling: ${empty list} — returns true if null or empty. Implicit EL objects: param — request parameters. paramValues — multi-value parameters. header — HTTP headers. cookie — cookies. sessionScope — session attributes. requestScope, applicationScope, pageScope. JSTL (JSP Standard Tag Library): works with EL to provide tags for iteration, conditionals, formatting. <c:forEach items=”${users}” var=”user”> — loops through list. <c:if test=”${user.admin}”> — conditional display. Best practice in modern Java: Thymeleaf is the preferred alternative to JSP in Spring Boot applications — it is HTML5 compatible and more designer-friendly.

62. What is JSP session management and what are the different techniques?

  1. JSP session management is only possible using database storage with no other alternatives
  2. JSP session management maintains state across multiple HTTP requests using four techniques: Cookies, URL Rewriting, Hidden Form Fields, and HttpSession — since HTTP is stateless
  3. HTTP has built-in state management — JSP session management is only needed for mobile apps
  4. Session management in JSP is automatic and requires no developer intervention whatsoever

Answer : B
Explanation: HTTP is stateless — each request is independent. Session management maintains user state across requests: Cookies: small text files stored on the client browser. Server sends Set-Cookie header, browser sends Cookie header on subsequent requests. Used for: session ID, user preferences. Limitations: 4KB size limit, can be disabled by users, security concerns. HttpSession (most common in Java): server-side storage identified by JSESSIONID cookie. session.setAttribute(“user”, user), session.getAttribute(“user”). session.invalidate() — logout. Session timeout: session.setMaxInactiveInterval(1800) — 30 minutes. URL Rewriting: appends session ID to every URL. Used when cookies are disabled. response.encodeURL(“/products”) adds ;jsessionid=abc123. Less secure (session ID visible in browser history). Hidden Form Fields: embed session data in form’s hidden input fields. <input type=”hidden” name=”userId” value=”123″>. Only works across form submissions. No persistence between non-form pages. Modern approach: JWT (JSON Web Tokens) for REST APIs — stateless tokens containing user identity. Session stored in token itself (base64-encoded). No server-side session storage needed. Spring Security integrates with all these approaches.

63. What is the difference between forward() and sendRedirect() in Java servlets?

  1. forward() is for GET requests; sendRedirect() is only for POST requests
  2. forward() is a server-side forward (same request/response objects, URL doesn’t change in browser, one HTTP request); sendRedirect() sends a 302 response to the client causing the browser to make a NEW request to a different URL (URL changes, two HTTP requests)
  3. sendRedirect() is faster than forward() because it uses fewer server resources
  4. forward() sends data to an external server; sendRedirect() keeps the request within the same server

Answer : B
Explanation: forward() vs sendRedirect() is a classic Java web interview question: forward() (RequestDispatcher.forward()): request.getRequestDispatcher(“/success.jsp”).forward(request, response). Server-side — the same request and response objects are passed to the target. URL in the browser does NOT change (user still sees the original URL). Request attributes (request.setAttribute()) are preserved and accessible in the target. Faster — only one HTTP request. Cannot forward to resources on a different server. Use: displaying a result page after processing (user already sent the data). sendRedirect(): response.sendRedirect(“/home”); Sends HTTP 302 status code with Location header to client. Browser makes a NEW request to the redirected URL. URL in the browser CHANGES to the new URL. Request attributes are LOST (new request). Two HTTP round trips — slower. Can redirect to any URL (different server, different application). Use: After form submission (Post-Redirect-Get pattern — prevents duplicate form submission on browser refresh), After logout, After successful login to redirect to dashboard. The POST-Redirect-GET pattern is the most important use case: submit form (POST) → process → sendRedirect() → GET → display result. Prevents browser asking “do you want to resubmit?” on refresh.

64. What is the Post-Redirect-Get (PRG) pattern in web development?

  1. PRG is a database design pattern for POST queries that are then redirected to a GET query
  2. Post-Redirect-Get is a web design pattern where form submission (POST) is followed by a server-side redirect to prevent duplicate form submissions when the user refreshes the confirmation page — the GET request fetches a results page that can be safely refreshed
  3. PRG is an API design pattern for converting POST endpoints to GET endpoints automatically
  4. PRG is a caching strategy where POST responses are cached and served as GET responses

Answer : B
Explanation: The Post-Redirect-Get (PRG) pattern solves the “duplicate form submission” problem. Without PRG: User fills form, clicks Submit → POST request. Server processes (saves order), shows confirmation page. User presses F5 (refresh). Browser resends the POST request. Order is duplicated! With PRG: User submits form → POST request. Server processes (saves order). Server calls response.sendRedirect(“/order-confirmation?id=123”) → HTTP 302. Browser makes a NEW GET request to /order-confirmation?id=123. Server returns confirmation page. User presses F5 → browser re-sends the GET request (harmless — just fetches the page again). No duplicate processing! This pattern is: the standard solution for all form submissions. Used in Spring MVC with RedirectAttributes. Common in e-commerce (prevent duplicate purchases), banking (prevent duplicate transfers), any form with side effects. Spring MVC implementation: return “redirect:/order/” + savedOrder.getId(); in @PostMapping method. RedirectAttributes: adds flash attributes accessible after redirect. PRG prevents data corruption and user confusion — every web developer must understand it.

65. What are Java Annotations and how are they used in frameworks?

  1. Java Annotations are comments that only serve as documentation with no runtime effect
  2. Java Annotations are metadata markers that can be attached to code elements (classes, methods, fields) — read by the compiler, IDE, or frameworks at runtime via reflection to modify behavior without changing logic
  3. Java Annotations are executable code blocks that run automatically when a class is loaded
  4. Annotations can only be placed on class declarations and cannot annotate methods or fields

Answer : B
Explanation: Java Annotations (introduced Java 5) are metadata attached to code. Built-in Java annotations: @Override — compiler checks you’re actually overriding a superclass method. @Deprecated — marks API as obsolete, triggers compiler warning. @SuppressWarnings — suppresses specific compiler warnings. @FunctionalInterface — marks interface as functional. Meta-annotations (annotations on annotations): @Target — where can annotation be used (METHOD, FIELD, CLASS, PARAMETER). @Retention — when is annotation available: SOURCE (compile only), CLASS (class file, default), RUNTIME (available via reflection at runtime). @Documented — include in Javadoc. @Inherited — subclasses inherit annotation. Custom annotation: @interface MyAnnotation { String value(); int priority() default 1; }. Framework annotations (most searched): Spring: @Component, @Autowired, @RequestMapping, @Transactional, @Bean, @Value. JPA/Hibernate: @Entity, @Table, @Column, @Id, @GeneratedValue, @OneToMany, @ManyToMany. JUnit: @Test, @BeforeEach, @AfterEach, @Mock, @SpringBootTest. Jackson: @JsonProperty, @JsonIgnore, @JsonSerialize. Lombok: @Data, @Getter, @Setter, @Builder, @Slf4j. Reading annotations at runtime: Class.getAnnotation(MyAnnotation.class). Spring uses reflection heavily to process its annotations and wire the application context.

66. What is the difference between checked and unchecked exceptions in Java?

  1. Checked exceptions are more severe than unchecked exceptions and always crash the application
  2. Checked exceptions (extend Exception) must be declared in method signatures or handled with try-catch — enforced by the compiler; unchecked exceptions (extend RuntimeException) do not require explicit handling and indicate programming errors
  3. Unchecked exceptions can only occur in multithreaded code; checked exceptions in single-threaded code
  4. Checked exceptions are created by developers; unchecked exceptions are created by the JVM only

Answer : B
Explanation: Java Exception Hierarchy: Throwable → Error (JVM errors — OutOfMemoryError, StackOverflowError — don’t catch). Throwable → Exception → checked exceptions. Throwable → Exception → RuntimeException → unchecked exceptions. Checked Exceptions: must be handled (try-catch) or declared (throws clause) — compiler enforces this. Represent recoverable conditions outside the program’s control. Examples: IOException, SQLException, FileNotFoundException, ClassNotFoundException. Example: public void readFile(String path) throws IOException { … }. Caller must handle IOException. Unchecked Exceptions (RuntimeException): NOT required to be caught or declared. Represent programming bugs — fix the code, don’t catch the exception. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, IllegalArgumentException, IllegalStateException. Never catch NullPointerException — fix the code that caused it. Spring/Hibernate best practice: wrap checked exceptions in custom RuntimeExceptions. Why Spring prefers unchecked: DataAccessException (Spring) wraps SQLExceptions — callers aren’t forced to handle DB exceptions they can’t recover from. @Transactional rolls back on RuntimeException by default. Custom exceptions: extend RuntimeException for application errors, extend Exception for recoverable errors requiring explicit handling.

67. What is connection pooling in JDBC and which libraries provide it?

  1. Connection pooling in JDBC means pooling (grouping) all SQL queries before sending them to the database
  2. Connection pooling maintains a pool of pre-established database connections that are reused across requests — dramatically improving performance by avoiding the expensive overhead of creating and closing a new connection for every database operation
  3. Connection pooling is only needed for applications with more than 10,000 concurrent users
  4. Connection pooling stores SQL query results in memory to avoid repeated database round trips

Answer : B
Explanation: JDBC Connection Pool: creating a new database connection involves network socket creation, authentication, session setup — typically takes 50-100ms. For a web application handling 1000 requests/second, creating a new connection per request is disastrous. Connection Pool solution: Create a fixed pool of connections at application startup. When a request needs a connection: get one from the pool (instantly). After the request: return the connection to the pool (not closed, ready for reuse). Pool manages idle connections, validates connections, removes stale connections. Key settings: minimum/maximum pool size, connection timeout, idle timeout, max lifetime. Popular connection pool libraries: HikariCP (most popular in Spring Boot — default since Spring Boot 2.0). Ultra-fast, lightweight. hikari.maximum-pool-size=10 in application.properties. Apache DBCP2 — mature, stable. C3P0 — older, less popular. Tomcat JDBC Pool — Tomcat-bundled. Configuration in Spring Boot application.properties: spring.datasource.hikari.maximum-pool-size=10. spring.datasource.hikari.minimum-idle=5. spring.datasource.hikari.idle-timeout=600000. Without pooling: 50ms × 1000 requests = 50 seconds connection overhead per second (unusable). With pooling: ~0ms connection overhead — connections instantly available.

68. What is JPA (Java Persistence API) and how does it relate to Hibernate?

  1. JPA and Hibernate are competing technologies — using one means you cannot use the other
  2. JPA is a Java specification (interface/standard) for ORM; Hibernate is the most popular JPA implementation — code written against JPA interfaces can theoretically switch between Hibernate, EclipseLink, or OpenJPA without changing application code
  3. JPA is a newer version of Hibernate that replaces all Hibernate-specific features
  4. JPA only works with Oracle databases; Hibernate is the universal ORM for all databases

Answer : B
Explanation: JPA (Jakarta Persistence API, formerly Java Persistence API) is a specification — a set of interfaces, annotations, and rules defining how Java ORM should work. JPA doesn’t provide implementation — it defines the contract. Hibernate is the most widely used JPA provider (implementation). Relationship: similar to JDBC (specification) and MySQL Driver (implementation). Or Servlet API (specification) and Tomcat (implementation). Key JPA concepts: @Entity, @Table, @Id, @GeneratedValue, @Column — entity mapping. @OneToOne, @OneToMany, @ManyToOne, @ManyToMany — relationship mapping. EntityManager — JPA’s equivalent of Hibernate’s Session. createQuery(), find(), persist(), remove(), merge(). JPQL (Java Persistence Query Language) — JPA’s equivalent of HQL. EntityManagerFactory — creates EntityManagers (equivalent of SessionFactory). Persistence Context — unit of work, tracks entity state changes. Spring Data JPA: uses JPA API (EntityManager) with Hibernate underneath. You write repository interfaces, Spring + Hibernate does the work. When to use Hibernate-specific features: Session, Criteria API, @Filter — when you need Hibernate features not in JPA spec. Best practice: use JPA annotations and APIs wherever possible, use Hibernate-specific features only when necessary, making future provider swaps easier.

69. What is Spring Boot Auto-Configuration and how does it work?

  1. Auto-configuration automatically writes all application business logic without any developer input
  2. Spring Boot Auto-Configuration automatically creates and configures Spring beans based on the classpath dependencies and existing beans — using @Conditional annotations to apply configurations only when specific conditions are met
  3. Auto-configuration is a paid feature requiring a Spring Boot commercial license
  4. Auto-configuration only works for database-related beans and has no effect on web configurations

Answer : B
Explanation: Spring Boot Auto-Configuration is the key reason Spring Boot dramatically reduces configuration. How it works: @SpringBootApplication includes @EnableAutoConfiguration. At startup, Spring Boot scans META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (or spring.factories in older versions). Each auto-configuration class is marked with @Configuration and @Conditional* annotations. @ConditionalOnClass(DataSource.class) — configure only if DataSource class is on classpath. @ConditionalOnMissingBean(DataSource.class) — configure only if no DataSource bean exists already. @ConditionalOnProperty(prefix=”spring.datasource”, name=”url”) — configure only if property exists. Examples: Add spring-boot-starter-data-jpa → Spring Boot automatically creates: DataSource (from spring.datasource.* properties), EntityManagerFactory, JpaTransactionManager, JPA repositories. Add spring-boot-starter-web → Creates: DispatcherServlet, Jackson ObjectMapper, ContentNegotiationManager. Override auto-configuration: define your own bean → auto-configuration backs off (@ConditionalOnMissingBean). Debug auto-configuration: –debug flag or logging.level.org.springframework.boot.autoconfigure=DEBUG shows why each auto-configuration was applied or skipped. @SpringBootTest loads complete application context for integration testing.

70. What is Thymeleaf in Spring Boot and how does it compare to JSP?

  1. Thymeleaf is a Java testing library for testing HTML template rendering logic
  2. Thymeleaf is a modern server-side Java template engine that processes HTML templates — it is HTML5-valid (templates can be opened directly in browsers), integrates naturally with Spring MVC, and is the default template engine in Spring Boot applications
  3. Thymeleaf is only for email template rendering and cannot create web page views
  4. Thymeleaf completely replaces the MVC pattern — controllers are not needed with Thymeleaf

Answer : B
Explanation: Thymeleaf is the recommended template engine in Spring Boot (replacing JSP). Key Thymeleaf features: Natural Templates: HTML files with Thymeleaf attributes are valid HTML — can be opened directly in a browser for static mockups (prototyping without server). JSP cannot do this (has Java code and tags making it invalid HTML). Spring Integration: seamless access to model attributes, Spring Security, messages. Thymeleaf syntax: th:text — display value: <p th:text=”${user.name}”>Default Name</p>. th:each — iteration: <tr th:each=”product : ${products}”>. th:if / th:unless — conditionals: <div th:if=”${user.isAdmin}”>. th:href, th:src — for URLs: <a th:href=”@{/users/{id}(id=${user.id})}”>. th:action — form action: <form th:action=”@{/submit}” method=”post”>. Spring Boot configuration: add spring-boot-starter-thymeleaf to pom.xml. Templates in src/main/resources/templates/. Thymeleaf vs JSP: Thymeleaf is valid HTML (designer-friendly), JSP has Java code embedded (developer-only). Thymeleaf has better Spring Boot integration. JSP requires servlet container support; Thymeleaf works in embedded containers. Modern Spring Boot applications: for server-side rendering, Thymeleaf is standard. For full separation, use React/Angular frontend with REST API backend.