31. What is JDBC and what is its full form?
- Java Database Container — a framework for managing Java application containers
- Java Database Connectivity — a Java API that provides a standard interface for connecting Java applications to relational databases, enabling execution of SQL queries, updates, and stored procedures
- Java Dynamic Configuration — a tool for dynamically configuring Java applications at runtime
- Java Direct Connection — a protocol for direct peer-to-peer Java application communication
Answer : B Explanation: JDBC (Java Database Connectivity) is a Java API introduced in JDK 1.1 that provides a standard way for Java applications to interact with relational databases. It is part of the Java SE platform (java.sql package). JDBC enables: connecting to databases (MySQL, Oracle, PostgreSQL, SQL Server), executing SQL statements (SELECT, INSERT, UPDATE, DELETE), calling stored procedures, handling transactions, and processing result sets. JDBC works through a driver model — vendors provide JDBC drivers for their specific database, while Java code remains database-independent. The four types of JDBC drivers are: Type-1 (JDBC-ODBC Bridge), Type-2 (Native API), Type-3 (Network Protocol), and Type-4 (Pure Java/Thin Driver — most commonly used today).
32. What is the difference between Statement, PreparedStatement, and CallableStatement in JDBC?
- All three are identical — they can be used interchangeably for any SQL operation
- Statement executes static SQL; PreparedStatement pre-compiles parameterized SQL for reuse and prevents SQL injection; CallableStatement executes stored procedures in the database
- PreparedStatement is slower than Statement because it adds extra compilation overhead
- CallableStatement can only be used with Oracle databases, not other RDBMS systems
Answer : B Explanation: Statement: used for simple, static SQL queries without parameters. Creates a new execution plan every time. Vulnerable to SQL injection. Example: stmt.executeQuery(“SELECT * FROM users”). PreparedStatement: pre-compiled SQL with ? placeholders for parameters. Compiled once, executed many times with different parameters — better performance. Prevents SQL injection by separating SQL from data. Example: pstmt = conn.prepareStatement(“SELECT * FROM users WHERE id=?”); pstmt.setInt(1, userId). Always preferred over Statement for parameterized queries. CallableStatement: extends PreparedStatement for executing stored procedures. Supports IN, OUT, and INOUT parameters. Example: cstmt = conn.prepareCall(“{call getEmployee(?)}”). Used for complex business logic encapsulated in database stored procedures. PreparedStatement is the most important of the three — it is the correct and safe way to execute parameterized queries.
33. What is SQL injection and how does PreparedStatement prevent it?
- SQL injection is a performance issue where poorly written SQL queries inject delays into execution
- SQL injection is a security attack where malicious SQL code is inserted into input fields to manipulate database queries — PreparedStatement prevents it by treating user input as literal data (parameter values) rather than executable SQL code
- PreparedStatement prevents SQL injection by encrypting all SQL queries before sending to the database
- SQL injection only affects Oracle databases — MySQL and PostgreSQL are automatically immune
Answer : B Explanation: SQL Injection is one of the most critical web application security vulnerabilities (OWASP Top 10). Attack example: if a login query is built by concatenation: “SELECT * FROM users WHERE username='” + username + “‘ AND password='” + password + “‘”, an attacker can enter username as: admin’– (comments out the password check) — granting unauthorized access. With PreparedStatement: the query structure is fixed at compile time. User input is sent separately as a parameter. The database treats it as a literal value, not executable SQL. Even if input contains ‘ or –; DROP TABLE users–, it is treated as a string literal, not SQL. Prevention best practices: Always use PreparedStatement or ORM frameworks (Hibernate/JPA). Use stored procedures. Validate and sanitize all inputs. Apply principle of least privilege to database accounts. Input validation alone is NOT sufficient — parameterized queries are mandatory.
34. What is the servlet life cycle and what are its key methods?
- Servlets have a two-phase lifecycle: creation and deletion — handled automatically by the JVM
- The servlet life cycle has three key phases managed by the servlet container: init() called once when servlet is first loaded, service() called for each HTTP request, and destroy() called once when servlet is unloaded
- Servlets restart their lifecycle for every new HTTP request from each unique client
- The servlet lifecycle is identical to a regular Java class lifecycle with no container involvement
Answer : B Explanation: The Servlet Life Cycle is managed by the servlet container (Tomcat, Jetty, GlassFish): Loading and Instantiation: the container loads the servlet class and creates an instance (only one instance handles all requests — not one per request). init(ServletConfig config): called exactly ONCE when the servlet is first loaded. Used for one-time initialization (loading configuration, establishing DB connections). Overriding this method is optional but recommended for setup. service(HttpServletRequest req, HttpServletResponse resp): called for EVERY HTTP request. Dispatches to doGet(), doPost(), doPut(), doDelete() etc. based on the HTTP method. This is where the request processing logic lives. destroy(): called exactly ONCE before the servlet is taken out of service. Used for cleanup (closing connections, saving state). Garbage Collection: after destroy(), the servlet is eligible for GC. Key insight: one servlet instance serves many concurrent requests via multiple threads — servlets must be thread-safe.
35. What is JSP (JavaServer Pages) and how does it differ from a Servlet?
- JSP is a Java programming language; Servlet is a Java framework for web applications
- JSP is a server-side technology that allows embedding Java code directly in HTML pages, making it easier to create dynamic web content; Servlets are pure Java classes that generate HTML programmatically — JSP is internally converted to a Servlet by the container
- JSP runs on the client browser; Servlet runs on the server — they are complementary client-server technologies
- JSP is faster than Servlets because it uses a different compilation model with no overhead
Answer : B Explanation: JSP (JavaServer Pages) allows mixing HTML markup with Java code using special tags. JSP Advantages over plain Servlets: Easier to write presentation logic (no out.println(“<html>”) nightmare), separation of business logic from presentation, custom tags (JSTL), expression language (${expression}). How JSP works: the container translates .jsp file into a Servlet class the first time it is accessed, then compiles and loads it. Subsequent requests use the compiled class (fast). JSP elements: Scriptlets (<% code %>), Expressions (<%= value %>), Declarations (<%! method %>), Directives (<%@ page/include/taglib %>). Modern pattern: use Servlets for controller logic (receiving requests, business logic) and JSP for view (presentation). This is the MVC pattern applied to Java web development. In modern applications, JSP has been largely replaced by template engines (Thymeleaf, FreeMarker) and frontend frameworks (React, Angular) with REST APIs.
36. What is Spring Framework and why is it widely used in Java development?
- Spring Framework is a Java game development library for building 2D and 3D games
- Spring Framework is a comprehensive Java application framework that provides Dependency Injection (IoC container), Aspect-Oriented Programming, MVC web framework, data access, security, and integration capabilities — simplifying enterprise Java development
- Spring Framework is a compiler optimization tool that speeds up Java application startup time
- Spring Framework is Oracle’s official enterprise Java framework replacing Java EE entirely
Answer : B Explanation: Spring Framework, created by Rod Johnson and released in 2003, revolutionized Java enterprise development by addressing the complexity of Java EE. Core features: IoC Container — manages object creation and lifecycle (ApplicationContext, BeanFactory). Dependency Injection — objects receive their dependencies through constructor, setter, or field injection. AOP — Aspect-Oriented Programming for cross-cutting concerns (logging, security, transactions). Spring MVC — Model-View-Controller for web applications. Spring Data — simplifies data access (JPA repositories, CRUD operations). Spring Security — comprehensive authentication and authorization. Spring Testing — first-class testing support with MockMvc. Why developers love Spring: reduces boilerplate code, promotes testable code (easy to mock dependencies), massive ecosystem (Spring Boot, Spring Cloud, Spring Batch, Spring Integration), huge community and documentation. Spring is the most widely used Java framework in the enterprise world — proficiency in Spring is essentially mandatory for Java backend developers.
37. What is Spring Boot and how does it differ from Spring Framework?
- Spring Boot replaces Spring Framework — applications must use either one or the other, not both
- Spring Boot is an opinionated, convention-over-configuration extension of Spring Framework that provides auto-configuration, embedded servers, starter dependencies, and production-ready features — enabling creation of standalone Spring applications with minimal setup
- Spring Boot is a lightweight version of Spring Framework designed for mobile applications only
- Spring Boot is a cloud platform service similar to AWS that hosts Spring applications automatically
Answer : B Explanation: Spring Boot, released in 2014, dramatically simplifies Spring application development. Key Spring Boot features: Auto-configuration — automatically configures Spring beans based on classpath dependencies (detects H2 database → configures H2 DataSource automatically). Starter Dependencies — curated dependency bundles: spring-boot-starter-web (Spring MVC + Tomcat + Jackson), spring-boot-starter-data-jpa, spring-boot-starter-security. Embedded Servers — packages Tomcat, Jetty, or Undertow inside the JAR — no external server deployment needed. spring-boot-starter-parent — manages dependency versions. Production-ready features — Actuator: /health, /metrics, /info endpoints. application.properties/yaml — centralized configuration. Spring Boot vs Spring: Spring requires extensive XML or Java configuration. Spring Boot provides defaults and auto-configures almost everything. The same Spring modules run underneath — Spring Boot is NOT a replacement but an enhancement. A Spring Boot application is typically a regular JAR with a main() method calling SpringApplication.run() — completely self-contained and deployable anywhere Java runs.
38. What is Dependency Injection (DI) in Spring Framework?
- Dependency Injection is a technique for injecting code into a database dependency directly
- Dependency Injection is a design pattern where objects receive their dependencies from an external container rather than creating them themselves — Spring’s IoC container injects required objects, promoting loose coupling and testability
- Dependency Injection is the process of adding new dependencies (libraries) to a Maven or Gradle project
- Dependency Injection means one Java class depends on another class for its initialization code
Answer : B Explanation: Dependency Injection (DI) is the most important Spring concept. Without DI: class A creates its own dependency B (new B()) — tight coupling, hard to test, hard to change implementation. With DI: class A declares it needs B, Spring’s IoC container creates B and provides it to A. Types of injection: Constructor Injection (recommended): @Autowired public Service(Repository repo) { this.repo = repo; }. Ensures required dependencies are always present, enables immutability, ideal for unit testing. Setter Injection: @Autowired public void setRepository(Repository repo) {}. For optional dependencies. Field Injection (avoid): @Autowired private Repository repo; — harder to test, hides dependencies. Spring annotations: @Component, @Service, @Repository, @Controller — mark classes as Spring beans. @Autowired — marks injection points. @Bean — manually define beans in @Configuration classes. Benefits: Loose coupling (can swap implementations), Testability (inject mock dependencies in tests), Single Responsibility (class focused on its task, not creating dependencies). DI is the foundation of Spring — everything else builds on it.
39. What is the difference between @Component, @Service, @Repository, and @Controller in Spring?
- These four annotations are completely identical — they are just aliases for each other with no functional difference
- All four are Spring stereotype annotations that mark classes as Spring-managed beans, but @Service, @Repository, and @Controller are specializations of @Component for specific layers — @Repository also adds exception translation for persistence exceptions
- @Controller creates REST endpoints; the others create regular Java objects without HTTP handling
- These annotations are only used for documentation purposes and have no effect on Spring bean creation
Answer : B Explanation: All four are stereotype annotations that make a class a Spring bean (component scanning picks them up): @Component: generic stereotype for any Spring-managed component. Use when no more specific annotation fits. @Service: marks business logic/service layer classes. Functionally same as @Component but semantically indicates service role. Example: UserService, OrderService. @Repository: marks data access layer (DAO) classes. Additionally enables Spring’s PersistenceExceptionTranslationPostProcessor — converts database-specific exceptions to Spring’s DataAccessException hierarchy. Example: UserRepository, ProductDAO. @Controller: marks web layer classes in Spring MVC. Works with @RequestMapping to handle HTTP requests. Returns views. @RestController = @Controller + @ResponseBody — returns data (JSON/XML) directly. Recommendation: Use the most specific annotation that fits. This communicates intent to other developers and enables framework-specific features. Layer assignment: Controller → Service → Repository is the standard three-layer architecture in Spring applications. @Autowired works with all four to inject dependencies.
40. What is Spring MVC and how does an HTTP request flow through it?
- Spring MVC is a Java library for building desktop applications using Model-View-Controller pattern
- Spring MVC is a web framework built on the Servlet API that implements the MVC pattern — HTTP requests flow through the DispatcherServlet (front controller) which routes to appropriate controllers, which populate a Model, select a View, and the view renders the response
- Spring MVC replaces HTTP with its own proprietary protocol for faster web communication
- In Spring MVC, the Model handles HTTP requests directly, bypassing the Controller layer
Answer : B Explanation: Spring MVC request flow: Client sends HTTP request. DispatcherServlet (front controller — single entry point) receives all requests. DispatcherServlet consults HandlerMapping to find the appropriate @Controller method for this URL. HandlerAdapter invokes the controller method. @Controller method: processes business logic (via @Service), populates the Model, returns a View name (or uses @ResponseBody for REST). ViewResolver translates the view name to an actual view (JSP, Thymeleaf template). View renders the model data as HTML/JSON response. DispatcherServlet sends response to client. Key annotations: @Controller or @RestController — marks controller class. @RequestMapping(“/path”) or @GetMapping, @PostMapping, @PutMapping, @DeleteMapping — maps URL patterns to methods. @PathVariable — extracts URL path parameters. @RequestParam — extracts query string parameters. @RequestBody — deserializes request body to Java object. @ResponseBody — serializes return value to response body. ModelAndView — return type that holds both model data and view name. Spring MVC with @RestController and JSON is the foundation of REST API development in Java.
