Advance Java MCQ Questions and Answers

71. What is Spring Boot’s @Value annotation and how is it used for configuration?

  1. @Value is used to assign a fixed hardcoded value to a field that cannot be changed after compilation
  2. @Value injects property values from application.properties/yml files, environment variables, or Spring expressions into Spring bean fields or constructor parameters — enabling externalized configuration
  3. @Value annotation is only for injecting numeric (int, double) values from external files
  4. @Value requires a separate configuration class — it cannot be used directly in @Service classes

Answer : B
Explanation: @Value injects externalized configuration into Spring beans: Basic usage: @Value(“${app.name}”) private String appName; — injects from application.properties: app.name=MyApplication. Default value: @Value(“${app.timeout:30}”) private int timeout; — uses 30 if property not found. Environment variables: @Value(“${JAVA_HOME}”) private String javaHome; — system environment variable. Spring Expression Language (SpEL): @Value(“#{systemProperties[‘user.name’]}”) private String username; — powerful dynamic expressions. @Value(“#{T(java.lang.Math).PI}”) private double pi; — static method call. Injecting lists: @Value(“${app.servers}”) private List<String> servers; — app.servers=server1,server2,server3. Type Conversion: @Value automatically converts String properties to int, boolean, List, etc. @ConfigurationProperties alternative: @ConfigurationProperties(prefix = “app”) class AppConfig { private String name; private int timeout; } — groups related properties, supports validation with @Validated, preferred for complex configuration objects. Spring Boot application.properties → application.yml: yaml format supports hierarchical structure natively. Profile-specific: application-dev.properties, application-prod.properties — activated by spring.profiles.active=dev. @Value with @ConfigurationProperties is the foundation of The Twelve-Factor App methodology’s “Store config in the environment” principle.

72. What is the Spring Boot @SpringBootApplication annotation?

  1. @SpringBootApplication is only needed for Spring applications deployed to cloud platforms
  2. @SpringBootApplication is a convenience annotation that combines @Configuration, @EnableAutoConfiguration, and @ComponentScan — marking the main class and triggering auto-configuration and component scanning from the package of the annotated class
  3. @SpringBootApplication replaces the entire Spring configuration and requires no other annotations
  4. @SpringBootApplication can only be placed on Spring configuration classes, not on the main class

Answer : B
Explanation: @SpringBootApplication is the cornerstone annotation of every Spring Boot application. It is composed of: @Configuration: marks the class as a source of Spring bean definitions. Methods annotated with @Bean define beans. @EnableAutoConfiguration: enables Spring Boot’s auto-configuration mechanism. Tells Spring Boot to automatically configure beans based on classpath. @ComponentScan: enables component scanning from the package of the annotated class and all sub-packages. Picks up @Component, @Service, @Repository, @Controller annotated classes automatically. The main method: @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }. SpringApplication.run() starts the embedded server, creates the Spring ApplicationContext, triggers auto-configuration. Customizing @SpringBootApplication: @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) — exclude specific auto-configurations. @SpringBootApplication(scanBasePackages = “com.example”) — customize scan base. Common mistake: placing @SpringBootApplication in the wrong package causes components to not be discovered. The annotated class’s package becomes the root of component scanning — all application code should be in sub-packages of this root package.

73. What is the purpose of the application.properties file in Spring Boot?

  1. application.properties stores the Java source code of the application in text format
  2. application.properties is the primary externalized configuration file in Spring Boot — storing database connections, server settings, logging levels, custom application properties, and any framework-specific configuration without modifying code
  3. application.properties is only for storing database schema definitions (DDL statements)
  4. application.properties is read-only and cannot be modified after the application is packaged

Answer : B
Explanation: application.properties (or application.yml) is the central configuration hub in Spring Boot. Common properties: Server: server.port=8080, server.servlet.context-path=/api. Database (JDBC): spring.datasource.url=jdbc:mysql://localhost:3306/mydb, spring.datasource.username=root, spring.datasource.password=secret, spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver. JPA/Hibernate: spring.jpa.hibernate.ddl-auto=update (create, create-drop, validate, update, none), spring.jpa.show-sql=true, spring.jpa.database-platform=org.hibernate.dialect.MySQL8Dialect. Logging: logging.level.org.springframework=INFO, logging.level.com.example=DEBUG, logging.file.name=app.log. Spring Boot specific: spring.application.name=my-service, spring.profiles.active=dev. Custom: app.jwt.secret=mySecret, app.jwt.expiration=86400. YAML alternative (application.yml): hierarchical format, same properties but with indentation. Profiles: application-dev.properties, application-prod.properties, application-test.properties — loaded based on active profile. Environment variable override: SPRING_DATASOURCE_URL=jdbc:mysql://prod-server/db — can override any property. The 12-Factor App: config should be in environment, not code — Spring Boot’s externalized configuration implements this principle.

74. What is Microservices architecture in the context of Java and Spring?

  1. Microservices means running multiple small Spring Boot applications on a single server
  2. Microservices is an architectural style where an application is built as a suite of small, independently deployable services — each running its own process, communicating via HTTP APIs, with Spring Boot and Spring Cloud providing the ecosystem for building Java microservices
  3. Microservices require replacing Spring with a different framework specifically designed for small services
  4. Microservices in Java can only communicate through shared database tables, not through APIs

Answer : B
Explanation: Microservices decompose a monolithic application into independently deployable services. Spring Cloud provides the microservices ecosystem: Service Discovery: Spring Cloud Netflix Eureka — services register themselves and discover others by name. Load Balancing: Spring Cloud LoadBalancer (replaced Ribbon) — distributes requests across service instances. API Gateway: Spring Cloud Gateway — single entry point, routing, rate limiting, authentication. Config Server: Spring Cloud Config — centralized configuration for all services. Circuit Breaker: Resilience4j — prevents cascade failures when a service is down. Distributed Tracing: Spring Cloud Sleuth + Zipkin — trace requests across services. Feign Client: declarative HTTP client for calling other microservices: @FeignClient(name=”user-service”) interface UserClient { @GetMapping(“/users/{id}”) User getUser(@PathVariable Long id); }. Communication: Synchronous: REST (HTTP) using RestTemplate or WebClient. Asynchronous: Message queues (Apache Kafka, RabbitMQ via Spring AMQP). Each microservice: independent database, independent deployment, independent scaling, can use different technology stack. Docker + Kubernetes: containerize each Spring Boot microservice, Kubernetes manages deployment and scaling. Challenges: network latency, distributed transactions, service discovery, monitoring complexity. Use microservices when the monolith becomes unmanageable — don’t start with microservices.

75. What is the difference between @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping in Spring?

  1. These annotations all do the same thing — any can be used for any HTTP operation
  2. These are composed annotations that map HTTP GET, POST, PUT, and DELETE methods to handler methods respectively — shorthand for @RequestMapping(method=RequestMethod.GET/POST/PUT/DELETE)
  3. @PutMapping and @DeleteMapping only work with REST APIs — @GetMapping works with all Java web applications
  4. These annotations are only valid inside @RestController classes and not in regular @Controller classes

Answer : B
Explanation: HTTP method-specific mapping annotations (introduced Spring 4.3) are shorthand for @RequestMapping: @GetMapping(“/users”): retrieves resources. Safe, idempotent. Returns list of users or single user. No request body. @PostMapping(“/users”): creates a new resource. Not idempotent (calling twice creates two resources). Request body contains new resource data. Returns 201 Created + Location header. @PutMapping(“/users/{id}”): updates/replaces a resource completely. Idempotent (calling multiple times has same effect). Request body contains complete updated resource. @PatchMapping(“/users/{id}”): partial update of a resource. Only send changed fields in request body. @DeleteMapping(“/users/{id}”): deletes a resource. Idempotent. Returns 204 No Content. REST API conventions: GET /users — list all users. GET /users/1 — get user with id=1. POST /users — create new user. PUT /users/1 — update user 1. DELETE /users/1 — delete user 1. Additional options: consumes: @PostMapping(value=”/users”, consumes=”application/json”) — only accept JSON. produces: @GetMapping(value=”/users”, produces=”application/json”) — only return JSON. These annotations make REST controller code self-documenting and aligned with HTTP semantics.

76. What is ResponseEntity in Spring MVC and why is it used?

  1. ResponseEntity is a special data structure for storing response data in a Spring database
  2. ResponseEntity is a Spring MVC class that represents the complete HTTP response — including the status code, headers, and body — giving the controller full control over the HTTP response instead of just returning the body object
  3. ResponseEntity automatically converts Java objects to XML format for REST API responses
  4. ResponseEntity is only used for error responses — normal responses should return plain objects

Answer : B
Explanation: ResponseEntity<T> wraps the full HTTP response: return value, status code, and headers. Without ResponseEntity: return user; — Spring returns 200 OK with user as JSON (fine for simple cases). With ResponseEntity: return ResponseEntity.ok(user); — explicitly returns 200 OK with user. return ResponseEntity.created(location).body(savedUser); — 201 Created with Location header. return ResponseEntity.noContent().build(); — 204 No Content (successful delete). return ResponseEntity.notFound().build(); — 404 Not Found. return ResponseEntity.badRequest().body(errorDetails); — 400 with error body. return ResponseEntity.status(HttpStatus.CONFLICT).body(message); — any custom status. Custom headers: return ResponseEntity.ok().header(“X-Custom-Header”, “value”).body(data); Why use ResponseEntity: precise HTTP status codes (201 vs 200 for creation). Add response headers. Return different body types based on success/failure. Build RESTful APIs that follow HTTP conventions. Common patterns: @GetMapping(“/{id}”) public ResponseEntity<User> getUser(@PathVariable Long id) { return userService.findById(id).map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build()); }. @ControllerAdvice with @ExceptionHandler is the alternative for centralized exception-to-response mapping — keeps controllers clean.

77. What is the role of Tomcat in Java web applications?

  1. Tomcat is a Java IDE for developing web applications, similar to Eclipse or IntelliJ IDEA
  2. Apache Tomcat is an open-source Java Servlet Container and Web Server that implements the Jakarta Servlet, JSP, WebSocket, and Expression Language specifications — providing the runtime environment for Java web applications
  3. Tomcat is a Java build tool that compiles and packages web applications for deployment
  4. Tomcat is a database server specifically designed for use with Java web applications

Answer : B
Explanation: Apache Tomcat is the most widely used Java web server/servlet container. Key roles: Servlet Container: manages servlet lifecycle (init/service/destroy). Processes HTTP requests and dispatches to the correct servlet. Web Server: serves static content (HTML, CSS, JS, images). JSP Engine: compiles JSP files to servlets. HTTP Connector: listens on port 8080 (default), handles TCP connections. Tomcat components: Catalina — servlet container core. Coyote — HTTP connector (processes HTTP/1.1 and HTTP/2). Jasper — JSP engine. Deployment: Traditional: deploy WAR file to Tomcat’s webapps directory. Spring Boot: embeds Tomcat inside the JAR. No external Tomcat installation needed! java -jar myapp.jar — Tomcat starts automatically on port 8080. Changing embedded server port: server.port=9090 in application.properties. Switching embedded servers: replace spring-boot-starter-web (Tomcat) with spring-boot-starter-jetty or spring-boot-starter-undertow. Tomcat architecture: one JVM process handles all requests using thread pool. Each request runs in a separate thread (from the thread pool). Thread pool settings: server.tomcat.threads.max=200 (default). Compared to web servers: Tomcat handles Java web apps. Nginx/Apache used as reverse proxies in production, handling SSL termination, load balancing, serving static files, proxying requests to Tomcat.

78. What is Lombok in Java and what problems does it solve?

  1. Lombok is a Spring Boot dependency that manages application configuration and security
  2. Project Lombok is a Java library that eliminates boilerplate code using annotations — automatically generating getters, setters, constructors, equals(), hashCode(), toString(), and builder patterns at compile time via annotation processing
  3. Lombok is a Java profiling tool that analyzes application performance at runtime
  4. Lombok is a JavaScript library mistakenly included in Java projects for frontend development

Answer : B
Explanation: Lombok reduces Java’s notorious verbosity. Key Lombok annotations: @Getter / @Setter: generates getter/setter for all or specific fields. @ToString: generates toString() method including all/specified fields. @EqualsAndHashCode: generates equals() and hashCode() based on fields. @NoArgsConstructor: generates no-argument constructor. @AllArgsConstructor: generates constructor with all fields. @RequiredArgsConstructor: generates constructor for final fields and @NonNull fields. @Data: combines @Getter, @Setter, @ToString, @EqualsAndHashCode, @RequiredArgsConstructor. @Builder: generates builder pattern — User.builder().name(“John”).age(30).build(). @Slf4j: injects a Logger field — private static final Logger log = LoggerFactory.getLogger(this.getClass()). @Value: immutable class (all fields private final, no setters). @NonNull: generates null check in constructor/setter. Before Lombok: 50+ lines of boilerplate for a simple entity class. With @Data: 5 lines. Caution with JPA entities: @Data generates hashCode() based on all fields — problematic for JPA entities with collections or lazy-loaded fields. Use @Getter, @Setter, @ToString separately for JPA entities. Controversy: some teams avoid Lombok because generated code is invisible in IDE — can make debugging harder. Alternatives: Java 14+ Records for immutable data classes (no setters but clean syntax).

79. What is Jackson in the context of Spring Boot REST APIs?

  1. Jackson is a Java logging framework similar to Log4j for structured JSON logging
  2. Jackson is the most widely used Java JSON library — automatically used by Spring Boot to serialize Java objects to JSON (for responses) and deserialize JSON to Java objects (for request bodies) via ObjectMapper
  3. Jackson is a Spring Boot database connection library for managing JSON document storage
  4. Jackson is only needed for reading JSON files from disk — not for HTTP API communication

Answer : B
Explanation: Jackson (com.fasterxml.jackson) is the JSON processing library automatically included via spring-boot-starter-web. Two directions: Serialization: Java Object → JSON String. User object with name=”John”, age=30 → {“name”:”John”,”age”:30}. Deserialization: JSON String → Java Object. {“name”:”John”,”age”:30} → User object. Key Jackson annotations: @JsonProperty(“user_name”): map Java field to different JSON key. @JsonIgnore: exclude field from JSON. @JsonInclude(Include.NON_NULL): don’t include null fields. @JsonSerialize/@JsonDeserialize: custom serialization logic. @JsonFormat(pattern=”yyyy-MM-dd”): format dates. @JsonAlias: accept multiple input JSON key names. ObjectMapper: Spring Boot auto-configures a shared ObjectMapper bean. Customization: @Bean public ObjectMapper objectMapper() { return new ObjectMapper().configure(…); } or via spring.jackson.* properties. Date handling: spring.jackson.serialization.write-dates-as-timestamps=false — output dates as ISO strings. spring.jackson.date-format=yyyy-MM-dd. DTOs (Data Transfer Objects): best practice — expose DTOs (not entities) in APIs. Avoids exposing internal data model, enables API versioning, prevents lazy loading issues. Jackson with @RestController: Spring Boot automatically applies Jackson serialization to all @ResponseBody return values. Content negotiation: produces=”application/json” ensures JSON output.

80. What is the difference between @Bean and @Component in Spring?

  1. @Bean creates database entities; @Component creates business logic components only
  2. @Component (and its stereotypes) is placed on the class itself — Spring detects and creates the bean via component scanning; @Bean is placed on a method inside a @Configuration class — the method explicitly creates and returns the bean object, used for third-party classes you cannot annotate
  3. @Bean creates singleton beans; @Component creates prototype beans by default
  4. @Bean is for Spring Boot only; @Component works in both Spring and Spring Boot applications

Answer : B
Explanation: Two ways to register Spring beans: @Component (and @Service, @Repository, @Controller): you annotate YOUR class. Spring discovers it via classpath scanning (@ComponentScan). Works only when you own/can modify the class. Example: @Service public class EmailService { … }. @Bean inside @Configuration: you write a method that creates and returns thebean. Used for third-party library classes you cannot annotate (e.g., Jackson’s ObjectMapper, RestTemplate, DataSource). Also used when you need conditional logic during bean creation. Example: @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @Bean public ObjectMapper objectMapper() { return new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true); } }. When to use @Bean: configuring third-party libraries, applying conditional logic during instantiation, creating multiple instances of the same class with different configurations. Bean scope: @Scope(“singleton”) — default, one instance per context. @Scope(“prototype”) — new instance every time. @Scope(“request”) — one per HTTP request. @Scope(“session”) — one per HTTP session. Naming: @Component class name becomes bean name (camelCase). @Bean method name becomes bean name. Both are registered in the same ApplicationContext and can be @Autowired anywhere.