Programming in Java III Practice Exam Quiz

Get solved practice exam answers for your midterm and final examinations

Programming in Java III Practice Exam Quiz

 

Which of the following annotations is used in the Spring framework to define a controller?

@Service
B. @RestController
C. @Entity
D. @Repository

Answer: B

What is the primary purpose of the @RequestMapping annotation in Spring?

To define a database connection
B. To map HTTP requests to handler methods
C. To manage transaction boundaries
D. To inject dependencies into classes

Answer: B

Which of the following best describes the use of dependency injection in Spring?

To handle multi-threading in Java applications
B. To manage class dependencies at runtime
C. To improve database query performance
D. To simplify exception handling

Answer: B

In the Spring framework, which of the following is used to connect to a database?

JdbcTemplate
B. RestTemplate
C. DataTemplate
D. ServiceTemplate

Answer: A

Which Spring module is specifically designed for building web applications?

Spring Batch
B. Spring Web
C. Spring Security
D. Spring ORM

Answer: B

Which of the following design patterns is most commonly associated with Spring MVC?

Singleton Pattern
B. Observer Pattern
C. Model-View-Controller (MVC)
D. Factory Pattern

Answer: C

What is the role of @Transactional in Spring?

To define the structure of a table in the database
B. To ensure thread safety in controller classes
C. To manage transactions in the application
D. To configure beans in the application context

Answer: C

Which of the following methods is used to handle GET requests in Spring MVC?

@PostMapping
B. @GetMapping
C. @PutMapping
D. @PatchMapping

Answer: B

In a Spring Boot application, which file is commonly used to define the database configuration?

application.properties
B. dbconfig.yml
C. config.xml
D. server.yml

Answer: A

Which annotation in Spring Boot is used to enable auto-configuration?

@EnableAutoConfig
B. @EnableConfiguration
C. @SpringBootApplication
D. @ConfigurationProperties

Answer: C

In Spring Security, which component is used to define user roles and permissions?

SecurityConfig
B. AuthenticationManager
C. WebSecurityConfigurerAdapter
D. RoleManager

Answer: C

What is the main advantage of using Spring Data JPA?

It reduces the need for manual SQL query writing.
B. It simplifies REST API development.
C. It eliminates the need for an application server.
D. It improves front-end development performance.

Answer: A

Which of the following is a feature of Spring Boot?

Manual XML-based configuration
B. Simplified dependency management
C. Advanced GUI design tools
D. Native support for frontend frameworks

Answer: B

Which Java class is commonly used to establish a connection pool in Spring?

DataSource
B. ConnectionPoolManager
C. PoolConnection
D. DataDriver

Answer: A

In Spring MVC, what is the purpose of the ModelAndView class?

To handle exceptions globally
B. To define the application’s model
C. To combine model data with a view
D. To manage database queries

Answer: C

Which of the following is a common method used to fetch data from a database using Spring JPA?

fetch()
B. queryForData()
C. findById()
D. get()

Answer: C

In Spring Boot, how can you exclude a specific auto-configuration class?

By setting @ConfigurationExclude
B. Using @SpringBootExclude
C. Adding @EnableAutoConfiguration(exclude = …)
D. By creating a custom auto-config class

Answer: C

What is the function of the @PathVariable annotation in Spring MVC?

To inject dependencies into a class
B. To pass dynamic values in the URI to controller methods
C. To secure controller methods with roles
D. To map the database schema

Answer: B

Which of the following is the correct order of Spring Bean lifecycle methods?

constructor > destroy > init
B. constructor > init > destroy
C. init > destroy > constructor
D. destroy > constructor > init

Answer: B

Which HTTP status code is returned by default for a successful @PostMapping request in Spring MVC?

200
B. 201
C. 204
D. 404

Answer: B

 

Which annotation is used in Spring to specify a bean explicitly?

@Autowired
B. @Bean
C. @Component
D. @Service

Answer: B

What does the @RestController annotation in Spring implicitly combine?

@Controller and @RequestMapping
B. @Controller and @ResponseBody
C. @Service and @Transactional
D. @Entity and @Table

Answer: B

What is the default scope of a Spring Bean?

prototype
B. singleton
C. request
D. session

Answer: B

Which class in Spring handles exception mapping to HTTP response codes?

ResponseEntityExceptionHandler
B. ErrorResponseHandler
C. ExceptionMapper
D. HttpExceptionHandler

Answer: A

Which annotation is used to map a form parameter to a method parameter in Spring MVC?

@RequestParam
B. @PathVariable
C. @ModelAttribute
D. @RequestBody

Answer: A

What is the role of @EnableJpaRepositories in Spring?

To enable database transactions
B. To scan for JPA repositories in the application
C. To configure the persistence context
D. To map Java objects to database tables

Answer: B

Which of the following tools is commonly used for dependency management in Spring applications?

Maven
B. Docker
C. Jenkins
D. Kubernetes

Answer: A

What is the purpose of the EntityManager in JPA?

To handle HTTP requests
B. To manage database transactions and persistence operations
C. To define entity relationships
D. To execute native SQL queries

Answer: B

Which Spring annotation is used to manage CORS (Cross-Origin Resource Sharing) settings?

@CrossOrigin
B. @AllowOrigins
C. @EnableCORS
D. @RequestMapping

Answer: A

In a Spring Boot application, how is the server port typically changed?

By modifying server.xml
B. By setting server.port in application.properties
C. By changing the port in config.yml
D. By updating the Spring Boot Starter dependency

Answer: B

Which of the following is a valid way to load an external property file in Spring?

Using @LoadProperties
B. Using @PropertySource
C. Using @ConfigProperties
D. Using @ExternalFile

Answer: B

What is the default HTTP status code for a successful @GetMapping request in Spring?

200
B. 201
C. 202
D. 404

Answer: A

In Spring, which annotation is used to secure a method or class?

@Secured
B. @Security
C. @Authorize
D. @EnableSecurity

Answer: A

What is the purpose of the @Scheduled annotation in Spring?

To define scheduled tasks
B. To manage transactions
C. To configure application properties
D. To create beans at runtime

Answer: A

Which annotation is used to validate input data in Spring?

@Validate
B. @Valid
C. @DataValidator
D. @InputCheck

Answer: B

What does the @Repository annotation signify in Spring?

That a class is responsible for database access logic
B. That a class manages application properties
C. That a class handles HTTP requests
D. That a class performs validation tasks

Answer: A

Which of the following methods is used to configure a Spring application context programmatically?

ApplicationContextRunner
B. AnnotationConfigApplicationContext
C. XmlApplicationContext
D. ProgrammaticApplicationContext

Answer: B

In Spring Boot, which starter dependency is required for using Spring Data JPA?

spring-boot-starter-data-jpa
B. spring-boot-starter-data-sql
C. spring-boot-starter-jdbc
D. spring-boot-starter-db

Answer: A

What is the purpose of @ComponentScan in Spring?

To specify which packages to scan for components, services, and controllers
B. To enable auto-configuration in the application
C. To define entity mappings
D. To manage database connections

Answer: A

Which of the following is NOT a valid Spring Bean scope?

singleton
B. prototype
C. application
D. thread

Answer: D

Which annotation is used to specify an endpoint for a REST API in Spring?

@RestEndpoint
B. @PathMapping
C. @RequestMapping
D. @Service

Answer: C

In Spring, which annotation is used to bind form data to a model object?

@ModelAttribute
B. @FormObject
C. @BindData
D. @RequestData

Answer: A

What is the role of DispatcherServlet in Spring MVC?

To handle database transactions
B. To manage views and templates
C. To act as the front controller in the MVC architecture
D. To process background jobs

Answer: C

Which dependency is required to include Spring Security in a Spring Boot project?

spring-boot-starter-security
B. spring-boot-starter-auth
C. spring-boot-starter-login
D. spring-boot-starter-access

Answer: A

What is the main purpose of the RestTemplate in Spring?

To build HTML templates
B. To make HTTP requests to external APIs
C. To manage database entities
D. To serve web pages

Answer: B

What does the @RequestBody annotation do in Spring MVC?

Maps a method parameter to the body of an HTTP request
B. Validates incoming HTTP requests
C. Defines a new REST endpoint
D. Processes HTTP headers

Answer: A

In Spring, which interface is used to manage transactions programmatically?

TransactionManager
B. EntityTransaction
C. PlatformTransactionManager
D. TransactionHandler

Answer: C

Which annotation in Spring Data JPA is used to create a custom query?

@NamedQuery
B. @Query
C. @CustomQuery
D. @NativeQuery

Answer: B

What is the main purpose of @ControllerAdvice in Spring MVC?

To manage exceptions globally across all controllers
B. To define a REST controller
C. To enable scheduling tasks
D. To manage security configurations

Answer: A

Which of the following is used in Spring Boot to run the application as a standalone application?

SpringApplication.run()
B. SpringBootApplication.start()
C. ApplicationRunner.run()
D. SpringContext.start()

Answer: A

 

Which annotation is used to map a specific HTTP method to a method in Spring MVC?

@RequestMethod
B. @GetMapping
C. @RequestMapping
D. @HttpMethod

Answer: B

In the Spring framework, what is the primary role of the @Transactional annotation?

To handle HTTP requests
B. To manage database transactions
C. To define application properties
D. To create a bean at runtime

Answer: B

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

To configure dependencies
B. To define bean lifecycles
C. To manage application-level configurations
D. To specify Java runtime properties

Answer: C

Which dependency is needed to use Thymeleaf with Spring Boot?

spring-boot-starter-thymeleaf
B. spring-boot-starter-web
C. spring-boot-starter-ui
D. spring-boot-starter-template

Answer: A

In Spring, what is the function of the @Qualifier annotation?

To manage session scope
B. To resolve bean ambiguity
C. To inject dependencies by type
D. To define custom bean scopes

Answer: B

Which annotation in Spring Boot enables auto-configuration?

@EnableAutoConfiguration
B. @Configuration
C. @Component
D. @RestController

Answer: A

What is the primary purpose of JpaRepository in Spring Data JPA?

To execute native SQL queries
B. To provide CRUD operations for entities
C. To map relationships between entities
D. To validate user input

Answer: B

Which of the following annotations is used to enable scheduling in a Spring application?

@EnableScheduling
B. @ScheduledTask
C. @Schedule
D. @EnableTasks

Answer: A

Which of the following is an advantage of using Spring Boot?

Manual configuration of dependencies
B. Reduced boilerplate code
C. Lack of integration with other frameworks
D. Complex project setup

Answer: B

What does the @PathVariable annotation do in Spring MVC?

Maps a method parameter to a URL segment
B. Maps a method parameter to a query parameter
C. Maps a method parameter to a request header
D. Maps a method parameter to the request body

Answer: A

Which of the following can be used to access the environment-specific properties in a Spring application?

@EnvironmentProperties
B. Environment interface
C. @AppConfig
D. @EnvironmentConfig

Answer: B

Which scope ensures a new bean instance is created for each HTTP request in Spring?

prototype
B. request
C. session
D. application

Answer: B

What does the SpringApplication.run() method return?

ConfigurableApplicationContext
B. ApplicationRunner
C. SpringContext
D. Environment

Answer: A

What is the primary purpose of the @EnableCaching annotation?

To enable bean lifecycle management
B. To manage caching in the application
C. To secure the application
D. To handle exception mappings

Answer: B

Which component in Spring MVC is responsible for handling user input and returning appropriate views?

Controller
B. Model
C. ViewResolver
D. DispatcherServlet

Answer: A

What is the default fetch type for @OneToMany in JPA?

Lazy
B. Eager
C. Cascade
D. Immediate

Answer: A

In Spring, which annotation is used to configure a REST client?

@RestClient
B. @EnableWebClient
C. @FeignClient
D. @ClientConfig

Answer: C

What is the purpose of the CommandLineRunner interface in Spring Boot?

To execute code after application startup
B. To manage HTTP requests
C. To handle database migrations
D. To run scheduled tasks

Answer: A

Which annotation is used to initialize mock objects in Spring Boot test classes?

@Mock
B. @MockBean
C. @InitMock
D. @EnableMocks

Answer: B

What does the @ResponseEntity class provide in a Spring REST API?

Standard error codes
B. Customizable HTTP responses
C. Automatic transaction handling
D. Request mapping flexibility

Answer: B

What is the role of the @Primary annotation in Spring?

To define a bean as a singleton
B. To specify the default bean for autowiring
C. To mark a bean for lazy initialization
D. To indicate the main class in Spring Boot

Answer: B

Which annotation in Spring is used for unit testing with Spring context?

@RunWith(SpringRunner.class)
B. @SpringBootTest
C. @ContextTest
D. @UnitTest

Answer: B

Which interface is responsible for handling HTTP sessions in Spring?

HttpSessionListener
B. SessionHandler
C. SessionRepository
D. SessionManager

Answer: C

In Spring MVC, which annotation is used to specify HTTP headers in a response?

@ResponseHeaders
B. @Header
C. @ResponseHeader
D. @RequestHeader

Answer: D

What is the role of @Data in Lombok within a Spring application?

To generate getters, setters, and other utility methods
B. To validate form data
C. To create entity mappings
D. To manage transactional data

Answer: A

Which annotation ensures that a bean is initialized only when it is needed?

@Lazy
B. @InitBean
C. @Eager
D. @Conditional

Answer: A

Which annotation in Spring Boot disables specific auto-configuration classes?

@DisableAutoConfig
B. @ExcludeAutoConfiguration
C. @SpringBootExclude
D. @EnableAutoConfig

Answer: B

What is the role of Spring Security in a Spring application?

To manage database transactions
B. To secure endpoints and handle authentication/authorization
C. To handle input validation
D. To schedule tasks

Answer: B

What does the @RequestHeader annotation do?

Extracts HTTP headers from requests
B. Maps HTTP headers to a view
C. Handles response headers
D. Configures headers in REST clients

Answer: A

Which annotation is used in Spring Boot to define a batch job?

@JobConfiguration
B. @EnableBatchProcessing
C. @BatchJob
D. @ProcessBatch

Answer: B

 

What is the primary role of the @RestController annotation in Spring?

To handle database connections
B. To create RESTful web services
C. To configure application properties
D. To manage session state

Answer: B

Which annotation is used to inject dependencies in Spring?

@Bean
B. @Inject
C. @Autowired
D. @Component

Answer: C

What does the @Bean annotation do in a Spring application?

It marks a class as a configuration class.
B. It defines a method that returns a Spring-managed bean.
C. It specifies the entry point of the application.
D. It configures the application’s database connection.

Answer: B

Which of the following is NOT a valid scope for a Spring bean?

singleton
B. prototype
C. application
D. static

Answer: D

In Spring, what is the purpose of the @ComponentScan annotation?

To scan for Spring-managed components in specified packages.
B. To define a component’s lifecycle.
C. To create a new application context.
D. To configure a database connection.

Answer: A

What is the default scope of a Spring bean?

prototype
B. session
C. singleton
D. request

Answer: C

Which of the following annotations is used to validate form data in Spring?

@Valid
B. @Validate
C. @FormValidator
D. @ValidateData

Answer: A

Which of the following is a valid HTTP status code for a successful request in REST APIs?

200
B. 400
C. 500
D. 404

Answer: A

In Spring Boot, which annotation is used to mark the main class of the application?

@SpringBootMain
B. @SpringBootApplication
C. @EnableApplication
D. @ApplicationStart

Answer: B

Which dependency is required for Spring Security?

spring-boot-starter-security
B. spring-boot-starter-web
C. spring-boot-starter-data
D. spring-security-core

Answer: A

What is the function of the @RequestParam annotation in Spring MVC?

To map query parameters to method arguments.
B. To bind form data to objects.
C. To handle HTTP request headers.
D. To bind request bodies to objects.

Answer: A

Which annotation is used to enable Cross-Origin Resource Sharing (CORS) in Spring Boot?

@CrossOrigin
B. @AllowOrigin
C. @EnableCORS
D. @CORSConfig

Answer: A

What is the primary purpose of the EntityManager in JPA?

To manage database transactions
B. To execute SQL queries directly
C. To manage the lifecycle of entities
D. To handle caching in the application

Answer: C

Which property is used to define the server port in a Spring Boot application?

server.port
B. application.port
C. server.connection.port
D. server.start.port

Answer: A

What does the @GetMapping annotation do in Spring MVC?

Maps GET requests to a method.
B. Maps all HTTP methods to a method.
C. Maps HTTP headers to a method.
D. Maps request parameters to a method.

Answer: A

Which of the following is a default exception handler provided by Spring?

GlobalExceptionHandler
B. ResponseStatusException
C. SpringExceptionResolver
D. ErrorController

Answer: B

Which of the following is used to customize error messages in Spring Boot?

messages.properties
B. application-errors.properties
C. error-messages.properties
D. custom-errors.yml

Answer: A

Which feature in Spring Boot allows real-time monitoring of application metrics?

Spring AOP
B. Spring Boot Actuator
C. Spring Data JPA
D. Spring DevTools

Answer: B

What is the role of the DispatcherServlet in Spring MVC?

To handle all incoming HTTP requests.
B. To manage transactions.
C. To handle database queries.
D. To provide dependency injection.

Answer: A

What is the default database embedded in Spring Boot?

MySQL
B. H2
C. PostgreSQL
D. MongoDB

Answer: B

Which annotation is used to handle exceptions in Spring controllers?

@ExceptionHandler
B. @ErrorHandler
C. @ControllerError
D. @HandleException

Answer: A

What is the purpose of the @Scope annotation in Spring?

To specify the lifecycle of a bean.
B. To enable aspect-oriented programming.
C. To define application properties.
D. To map HTTP requests.

Answer: A

Which annotation is used in Spring Boot to test a web layer?

@WebMvcTest
B. @SpringBootWebTest
C. @WebLayerTest
D. @TestWeb

Answer: A

In Spring Security, which filter is used to manage authentication?

AuthenticationFilter
B. UsernamePasswordAuthenticationFilter
C. SessionFilter
D. SecurityFilter

Answer: B

What is the default view technology used by Spring MVC?

JSP
B. Thymeleaf
C. Velocity
D. Freemarker

Answer: A

Which of the following is NOT a valid HTTP method?

POST
B. PUT
C. SEND
D. DELETE

Answer: C

What is the purpose of the @Profile annotation in Spring?

To specify the active bean profiles.
B. To manage the lifecycle of controllers.
C. To define database queries.
D. To handle HTTP sessions.

Answer: A

What is the function of the @Scheduled annotation in Spring?

To execute tasks at fixed intervals.
B. To initialize database schemas.
C. To manage user authentication.
D. To bind request parameters.

Answer: A

Which dependency is required for using Spring Data JPA?

spring-boot-starter-data-jpa
B. spring-data-core
C. spring-jpa-library
D. spring-boot-starter-data

Answer: A

What is the purpose of @EnableAspectJAutoProxy in Spring?

To enable aspect-oriented programming.
B. To configure HTTP proxies.
C. To enable database transactions.
D. To manage application profiles.

Answer: A

 

Which annotation is used to specify that a class is a Spring configuration class?

@Configuration
B. @Config
C. @SpringConfig
D. @AppConfig

Answer: A

What does the @Transactional annotation in Spring indicate?

A method or class should be executed in a transactional context.
B. A method should handle exceptions automatically.
C. A method is scheduled for execution.
D. A method is used for authentication.

Answer: A

In Spring, what is the purpose of the @PathVariable annotation?

To bind a URL template variable to a method parameter.
B. To retrieve HTTP request headers.
C. To map a form input field to a method parameter.
D. To validate a query parameter.

Answer: A

What is the role of the SpringApplication.run() method in a Spring Boot application?

It starts the application.
B. It scans for Spring components.
C. It initializes the database.
D. It creates the application context.

Answer: A

Which annotation is used in Spring Boot to exclude specific auto-configurations?

@ExcludeAutoConfiguration
B. @SpringExclude
C. @EnableAutoConfiguration
D. @SpringBootApplication(exclude=…)

Answer: D

What does the @Entity annotation in JPA signify?

A class represents a table in the database.
B. A class is a configuration class.
C. A class handles HTTP requests.
D. A class provides utility functions.

Answer: A

Which of the following is a common HTTP method for updating resources in REST?

POST
B. PUT
C. GET
D. DELETE

Answer: B

Which annotation in Spring MVC is used to handle a specific exception globally?

@ControllerAdvice
B. @ExceptionResolver
C. @GlobalExceptionHandler
D. @HandleException

Answer: A

What is the main purpose of Spring Boot Starter dependencies?

To provide a simplified way to manage dependencies.
B. To configure application security.
C. To enable database transactions.
D. To handle HTTP sessions.

Answer: A

What is the default HTTP response format for a Spring Boot REST API?

JSON
B. XML
C. YAML
D. Plain text

Answer: A

Which annotation in Spring Boot maps form data to a Java object?

@ModelAttribute
B. @RequestParam
C. @RequestBody
D. @BindForm

Answer: A

In Spring, what is the purpose of the @PostMapping annotation?

To map HTTP POST requests to a method.
B. To initialize database connections.
C. To validate user sessions.
D. To perform authentication.

Answer: A

What is the default port for a Spring Boot application?

8080
B. 3000
C. 9090
D. 80

Answer: A

What does the @SessionAttributes annotation in Spring MVC do?

Stores attributes in the HTTP session.
B. Validates session cookies.
C. Configures session timeouts.
D. Manages database transactions.

Answer: A

Which of the following is NOT a feature of Spring Boot Actuator?

Monitoring application metrics
B. Exposing application health checks
C. Managing application security
D. Generating REST endpoints automatically

Answer: D

Which database transaction isolation level prevents dirty reads?

READ_UNCOMMITTED
B. READ_COMMITTED
C. REPEATABLE_READ
D. SERIALIZABLE

Answer: B

Which of the following annotations is used for creating a service in Spring?

@Service
B. @Controller
C. @Component
D. @RestService

Answer: A

What is the purpose of the @Primary annotation in Spring?

To define the default bean when multiple beans exist.
B. To specify a class is a primary entity.
C. To handle primary keys in a database.
D. To specify the main configuration class.

Answer: A

Which annotation is used to enable scheduling in Spring?

@EnableScheduling
B. @Schedule
C. @SpringScheduler
D. @TaskScheduler

Answer: A

Which tool is commonly used to package Spring Boot applications into JARs?

Maven
B. Gradle
C. Ant
D. Both A and B

Answer: D

What is the purpose of the @ConditionalOnProperty annotation in Spring Boot?

To conditionally enable a bean based on a property.
B. To configure database properties.
C. To manage user-defined properties.
D. To handle request headers.

Answer: A

Which of the following is a valid Spring Boot property for setting the application context path?

server.servlet.context-path
B. application.context-path
C. server.context-path
D. app.servlet.context-path

Answer: A

Which Spring component is responsible for managing HTTP sessions?

SessionRegistry
B. HttpSessionManager
C. SessionHandler
D. SpringSessionManager

Answer: A

Which annotation is used to enable caching in a Spring application?

@EnableCaching
B. @Cacheable
C. @EnableCache
D. @SpringCache

Answer: A

Which of the following is a Spring Boot Starter for testing?

spring-boot-starter-test
B. spring-test-starter
C. spring-boot-starter-web-test
D. spring-starter-test

Answer: A

What is the purpose of the @MappedSuperclass annotation in JPA?

To define a base class for entities.
B. To manage database transactions.
C. To enable mapping for embedded objects.
D. To create view components.

Answer: A

In Spring Security, which class is used for encoding passwords?

PasswordEncoder
B. PasswordHasher
C. Encoder
D. HashManager

Answer: A

Which of the following annotations is used for dependency injection in Spring?

@Autowired
B. @Inject
C. @Resource
D. All of the above

Answer: D

What is the purpose of the @EntityListeners annotation in JPA?

To specify lifecycle callbacks for entities.
B. To configure database listeners.
C. To handle SQL exceptions.
D. To log database queries.

Answer: A

Which of the following annotations is used to enable a Spring Boot application to register with a discovery service like Eureka?

@EnableDiscoveryClient
B. @EnableEurekaClient
C. @EnableServiceDiscovery
D. @EnableRegistry

Answer: A

 

Which annotation in Spring MVC is used to handle HTTP DELETE requests?

@DeleteMapping
B. @RequestMapping
C. @DeleteRequest
D. @DeletePath

Answer: A

In Spring, which class is used to perform JDBC operations?

JdbcTemplate
B. JdbcManager
C. JdbcHandler
D. JdbcController

Answer: A

What is the default scope of a Spring bean?

Singleton
B. Prototype
C. Session
D. Request

Answer: A

Which of the following is NOT a feature of Spring Boot?

Embedded web server
B. Automatic configuration
C. Manual dependency management
D. Microservice-ready architecture

Answer: C

What is the purpose of the @RequestHeader annotation in Spring MVC?

To bind HTTP request headers to method parameters
B. To define headers for HTTP responses
C. To log HTTP headers
D. To manage HTTP sessions

Answer: A

Which of the following is true about @ComponentScan in Spring?

It scans for components in the specified packages.
B. It scans for database configurations.
C. It handles application security.
D. It starts the Spring application.

Answer: A

In Spring Security, what does the @PreAuthorize annotation do?

Ensures a method is executed only if the specified security expression is true.
B. Configures authorization for a controller.
C. Handles password encoding.
D. Configures user roles in the database.

Answer: A

Which of the following is a valid return type for a Spring MVC controller method?

ModelAndView
B. String
C. ResponseEntity
D. All of the above

Answer: D

What is the purpose of the @Controller annotation in Spring?

To define a class as a Spring MVC controller.
B. To define a service class.
C. To create REST endpoints.
D. To handle database operations.

Answer: A

Which annotation is used to enable asynchronous methods in Spring?

@EnableAsync
B. @AsyncMethod
C. @AsyncConfig
D. @EnableThreads

Answer: A

In Spring Boot, which property file is used by default to configure the application?

application.properties
B. app.config
C. boot.config
D. spring.properties

Answer: A

Which of the following is NOT a scope of a Spring bean?

Singleton
B. Prototype
C. Temporary
D. Request

Answer: C

What does the @Bean annotation in Spring signify?

It defines a method that produces a bean to be managed by the Spring container.
B. It defines a service layer class.
C. It maps a controller to a URL.
D. It validates HTTP requests.

Answer: A

Which annotation is used in Spring Boot to mark the main class of the application?

@SpringBootApplication
B. @EnableAutoConfiguration
C. @BootApplication
D. @ApplicationStarter

Answer: A

In JPA, what is the purpose of the @OneToMany annotation?

To map a one-to-many relationship.
B. To map a many-to-one relationship.
C. To define a join table.
D. To define a composite key.

Answer: A

Which Spring Boot Starter dependency is used for web development?

spring-boot-starter-web
B. spring-boot-starter-data
C. spring-boot-starter-security
D. spring-boot-starter-jpa

Answer: A

What does the @CrossOrigin annotation in Spring do?

Enables CORS support for a specific method or class.
B. Configures SSL certificates.
C. Manages cross-database connections.
D. Handles cross-server requests automatically.

Answer: A

In Spring, what is the purpose of the RestTemplate class?

To make RESTful HTTP requests from the application.
B. To configure REST endpoints.
C. To handle session management.
D. To validate REST requests.

Answer: A

Which annotation is used in Spring Boot to run unit tests for the application?

@SpringBootTest
B. @UnitTest
C. @BootTest
D. @TestConfig

Answer: A

What is the purpose of the @Lazy annotation in Spring?

To delay the initialization of a bean until it is needed.
B. To reduce application startup time.
C. To enable lazy loading of database records.
D. To handle background tasks.

Answer: A

Which HTTP status code is returned by default for a successful Spring REST API response?

200
B. 201
C. 204
D. 500

Answer: A

In JPA, which annotation is used to define a primary key?

@Id
B. @Key
C. @Primary
D. @PK

Answer: A

What is the purpose of the @RequestMapping annotation in Spring MVC?

To map HTTP requests to handler methods.
B. To manage database transactions.
C. To configure application properties.
D. To handle HTTP sessions.

Answer: A

What is a key feature of the Spring Framework?

Dependency Injection
B. Aspect-Oriented Programming
C. Transaction Management
D. All of the above

Answer: D

Which annotation is used in Spring to create a RESTful web service?

@RestController
B. @Controller
C. @WebService
D. @Service

Answer: A

In Spring Security, what does the HttpSecurity object configure?

Security policies for HTTP requests.
B. Database security policies.
C. SSL certificate management.
D. User authentication in the database.

Answer: A

Which of the following is NOT a feature of Hibernate?

Object-Relational Mapping (ORM)
B. Lazy Loading
C. Session Management
D. Server Monitoring

Answer: D

What does the @PropertySource annotation in Spring do?

It loads properties from an external file into the application context.
B. It configures security settings.
C. It validates request headers.
D. It manages application logs.

Answer: A

In Spring MVC, what is the purpose of a ViewResolver?

To resolve logical view names to actual views.
B. To handle HTTP requests.
C. To configure request mappings.
D. To validate form inputs.

Answer: A

Which annotation in JPA is used to specify a generated value for the primary key?

@GeneratedValue
B. @PrimaryKeyGenerated
C. @AutoGenerateKey
D. @AutoIncrement

Answer: A

 

What is polymorphism in Java?

A class having multiple constructors
B. The ability of a method to perform different tasks based on the object
C. Hiding the implementation details of a class
D. Sharing common functionality between classes

Answer: B

Which type of polymorphism is achieved at compile time in Java?

Dynamic polymorphism
B. Runtime polymorphism
C. Static polymorphism
D. None of the above

Answer: C

Which of the following is NOT a principle of Object-Oriented Programming?

Encapsulation
B. Inheritance
C. Abstraction
D. Modularization

Answer: D

In Java, what is the purpose of the final keyword when applied to a class?

It prevents the class from being instantiated.
B. It prevents the class from being extended.
C. It prevents variables in the class from being modified.
D. It makes the class abstract.

Answer: B

Which of the following best describes encapsulation?

Using interfaces to define methods
B. Bundling data and methods within a class while restricting access
C. Allowing classes to inherit from a base class
D. Writing classes in separate packages

Answer: B

 

Which concept of OOP is demonstrated when two classes share the same interface?

Abstraction
B. Inheritance
C. Polymorphism
D. Encapsulation

Answer: A

Which modifier is used to prevent a method from being overridden?

private
B. protected
C. final
D. static

Answer: C

Which of the following is NOT a characteristic of inheritance?

Code reuse
B. Hierarchical relationship
C. Multiple parent classes
D. Extensibility

Answer: C

Which of the following statements is true about abstract classes in Java?

Abstract classes can be instantiated.
B. Abstract classes can have both abstract and concrete methods.
C. Abstract classes must be declared final.
D. Abstract classes cannot have a constructor.

Answer: B

What is the difference between an abstract class and an interface in Java?

Interfaces can have fields, while abstract classes cannot.
B. Abstract classes support multiple inheritance, while interfaces do not.
C. An abstract class can have constructors, while an interface cannot.
D. Interfaces are slower than abstract classes.

Answer: C

What does the super keyword in Java do?

Refers to the parent class constructor
B. Refers to the parent class method or variable
C. Calls the parent class constructor
D. All of the above

Answer: D

What is method overloading?

Defining multiple methods in a class with the same name but different parameter lists
B. Overriding a parent class method in a subclass
C. Defining a method in multiple classes with the same signature
D. A method that calls itself recursively

Answer: A

Which of the following is NOT true about Java interfaces?

They can contain static methods.
B. They can contain private methods.
C. They can have constructors.
D. They can have default methods.

Answer: C

Which OOP concept does the private access modifier in Java enforce?

Polymorphism
B. Encapsulation
C. Abstraction
D. Inheritance

Answer: B

What is dynamic method dispatch?

Invoking a method at compile time
B. Overloading methods within a single class
C. Resolving a method call to the actual implementation at runtime
D. Using the static keyword to create a method

Answer: C

Which of the following is NOT a valid use of the this keyword?

Accessing the current object’s methods
B. Calling the constructor of the current class
C. Referring to the superclass
D. Passing the current object as an argument

Answer: C

How is multiple inheritance achieved in Java?

By extending multiple classes
B. By implementing multiple interfaces
C. By using the final keyword
D. By using abstract classes

Answer: B

What happens when a subclass does not override an abstract method in the superclass?

A runtime error occurs.
B. The subclass becomes abstract.
C. The program executes normally.
D. The method is treated as a concrete method.

Answer: B

Which statement is true about Java enums?

Enums can inherit from another class.
B. Enums are implicitly final.
C. Enums cannot implement interfaces.
D. Enums can have methods and fields.

Answer: D

What is the difference between HashMap and HashTable in Java?

HashTable allows null keys, while HashMap does not.
B. HashMap is synchronized, while HashTable is not.
C. HashTable is synchronized, while HashMap is not.
D. Both are identical in functionality.

Answer: C

Which method in Java is used to clone an object?

cloneObject()
B. copy()
C. clone()
D. duplicate()

Answer: C

What is the purpose of the equals() method in Java?

To compare memory addresses of two objects
B. To compare the contents of two objects
C. To compare class types of objects
D. To compare the size of two objects

Answer: B

Which keyword is used to declare a class as immutable?

final
B. static
C. immutable
D. None of the above

Answer: A

What is the main advantage of using interfaces?

Improved code readability
B. Enforcing multiple inheritance
C. Allowing loose coupling between components
D. Simplified debugging

Answer: C

What is method overriding?

Writing a method with the same name and parameters in a child class as in the parent class
B. Writing multiple methods with the same name but different parameters in a class
C. Writing a static method with the same name in a child class
D. Writing multiple methods in unrelated classes

Answer: A

Which access modifier ensures maximum accessibility?

private
B. protected
C. public
D. default

Answer: C

How can you create a shallow copy of an object in Java?

Using the clone() method
B. Using a constructor
C. Using the deepClone() method
D. Using the shallowCopy() method

Answer: A

Which Java feature allows the creation of an anonymous inner class?

Inheritance
B. Encapsulation
C. Polymorphism
D. Abstraction

Answer: C

What is a functional interface in Java?

An interface with at least one abstract method
B. An interface with exactly one abstract method
C. An interface with only default methods
D. An interface with a single method and no fields

Answer: B

 

What is the difference between abstract classes and interfaces in Java?

Interfaces can have private methods, but abstract classes cannot.
B. Abstract classes can have constructors, but interfaces cannot.
C. Interfaces support fields with default values, but abstract classes do not.
D. Abstract classes can only have static methods.

Answer: B

In the context of OOP, which design pattern relies heavily on polymorphism?

Singleton
B. Factory Method
C. Observer
D. Builder

Answer: B

Which of the following is true for constructor chaining in Java?

Only superclass constructors are called.
B. It involves calling one constructor from another in the same or parent class.
C. It is used only for abstract classes.
D. It is not allowed in Java.

Answer: B

What is the purpose of the @Override annotation in Java?

To suppress warnings in the code
B. To indicate that a method overrides a superclass method
C. To define a new method in a subclass
D. To enforce method overloading

Answer: B

Which feature in Java allows multiple methods in a class with the same name but different parameters?

Method overriding
B. Method overloading
C. Polymorphism
D. Inheritance

Answer: B

What happens if an abstract class has no abstract methods?

It cannot be instantiated.
B. It can still be extended by other classes.
C. It must be declared as final.
D. Both A and B.

Answer: D

How does Java achieve runtime polymorphism?

Through static binding
B. Using method overloading
C. Through method overriding
D. Using interfaces

Answer: C

Which of the following best defines composition in Java?

A “has-a” relationship between classes
B. An “is-a” relationship between classes
C. Overriding methods of a superclass
D. Combining multiple interfaces

Answer: A

What is the Liskov Substitution Principle in OOP?

Objects of a superclass should be replaceable with objects of a subclass without affecting functionality.
B. Every class should have only one responsibility.
C. Objects should be created using constructors only.
D. No two classes should have the same method names.

Answer: A

Which method in the Object class is used for object comparison?

hashCode()
B. equals()
C. compareTo()
D. compare()

Answer: B

What is a nested class in Java?

A class inside a method
B. A class defined within another class
C. A subclass of the parent class
D. A class with static methods only

Answer: B

Which of the following is an advantage of encapsulation?

Increases code readability
B. Reduces code complexity
C. Protects data from unauthorized access
D. All of the above

Answer: D

 

Which Java keyword is used to inherit from a class?

this
B. implements
C. extends
D. inherits

Answer: C

What is the purpose of the default method in Java interfaces?

To provide optional methods that implementing classes can override
B. To ensure all methods in an interface have implementations
C. To replace abstract methods in interfaces
D. To define static methods in interfaces

Answer: A

What is downcasting in Java?

Converting a parent object to a child type
B. Converting a child object to a parent type
C. Converting a primitive to an object
D. None of the above

Answer: A

What does the protected access modifier allow?

Access within the same package only
B. Access from the same package and subclasses
C. Access from all classes in all packages
D. Access from private methods only

Answer: B

 

Which of the following ensures data hiding?

Interfaces
B. Abstract classes
C. Private fields and methods
D. Static methods

Answer: C

What is the Single Responsibility Principle in OOP?

A class should have only one reason to change.
B. A class can extend only one parent class.
C. A method should perform only one task.
D. None of the above.

Answer: A

Which of the following is an example of IS-A relationship?

A class implementing an interface
B. A class extending another class
C. A class containing another class
D. Both A and B

Answer: D

What is the use of the instanceof operator?

To check if an object belongs to a particular class or subclass
B. To create a new instance of a class
C. To initialize objects
D. To compare two objects

Answer: A

What is a functional interface in Java?

An interface with one or more abstract methods
B. An interface with exactly one abstract method
C. An interface with no methods
D. An interface with only default methods

Answer: B

What is aggregation in OOP?

A strong form of association where one object owns another
B. A weak form of association where one object can exist independently of another
C. A form of multiple inheritance
D. None of the above

Answer: B

Which method cannot be overridden in Java?

toString()
B. equals()
C. main()
D. final methods

Answer: D

Which of these can be used to implement interfaces with default methods?

Abstract classes
B. Static methods
C. Concrete classes
D. Abstract methods

Answer: C

What is the use of the super() keyword?

To access superclass methods
B. To call the parent class constructor
C. To access superclass variables
D. All of the above

Answer: D

In method overriding, which method is called when a parent object references a child instance?

Parent class method
B. Child class method
C. Compilation error
D. Runtime error

Answer: B

What is the default access modifier for methods and variables in Java?

public
B. private
C. protected
D. Package-private

Answer: D

Which of these design principles focuses on programming to an interface, not an implementation?

Open-Closed Principle
B. Dependency Inversion Principle
C. Single Responsibility Principle
D. Encapsulation

Answer: B

 

What is an exception in Java?

A syntax error in the code
B. A runtime error that disrupts the normal flow of the program
C. A feature of the JVM to optimize performance
D. A warning during compilation

Answer: B

Which Java keyword is used to throw an exception?

throws
B. throw
C. exception
D. catch

Answer: B

What is the purpose of the throws keyword in a method declaration?

To handle exceptions in the method
B. To specify the exceptions a method can throw
C. To terminate the program when an exception occurs
D. To define custom exceptions

Answer: B

What type of exception is FileNotFoundException in Java?

Checked exception
B. Unchecked exception
C. Runtime exception
D. Error

Answer: A

What happens when an exception is not caught in a Java program?

The program will continue running normally.
B. The program terminates abruptly.
C. The exception is ignored.
D. The JVM automatically catches and handles the exception.

Answer: B

Which of the following is NOT a built-in exception class in Java?

ArithmeticException
B. IOException
C. StringIndexOutOfBoundsException
D. CustomException

Answer: D

What is the correct order of the blocks in exception handling?

try, finally, catch
B. catch, finally, try
C. try, catch, finally
D. finally, try, catch

Answer: C

What does the finally block do in exception handling?

It executes only when an exception occurs.
B. It executes only when no exception occurs.
C. It executes always, whether or not an exception occurs.
D. It prevents exceptions from being thrown.

Answer: C

Can a try block exist without a catch block?

Yes, but only if it has a finally block.
B. No, it must always have a catch block.
C. Yes, and it can also exist without a finally block.
D. No, exceptions will not be handled without catch.

Answer: A

Which of these is a superclass of all exceptions in Java?

Object
B. Throwable
C. Exception
D. RuntimeException

Answer: B

What is the purpose of the catch block in Java?

To define the exception
B. To execute cleanup code
C. To handle the exception
D. To rethrow the exception

Answer: C

 

What is the difference between checked and unchecked exceptions?

Checked exceptions are handled automatically, unchecked are not.
B. Checked exceptions are checked at runtime, unchecked at compile-time.
C. Checked exceptions are checked at compile-time, unchecked at runtime.
D. There is no difference.

Answer: C

Can you have multiple catch blocks for a single try block?

Yes, but only one catch block will execute.
B. Yes, and all catch blocks will execute.
C. No, only one catch block is allowed per try block.
D. No, a try block must have exactly one catch block.

Answer: A

What is the purpose of the throw keyword?

To specify exceptions in the method signature
B. To handle exceptions
C. To create and throw an exception manually
D. To execute a finally block

Answer: C

Which of the following statements is true about custom exceptions in Java?

Custom exceptions must extend the Throwable class.
B. Custom exceptions must extend the Exception or RuntimeException class.
C. Custom exceptions must be checked exceptions.
D. Custom exceptions must be defined as abstract classes.

Answer: B

What happens if a finally block contains a return statement?

It overrides any exception thrown.
B. It executes after the catch block but before returning to the caller.
C. It causes a compilation error.
D. The catch block will not execute.

Answer: B

Can the main method throw exceptions in Java?

Yes, but only runtime exceptions.
B. Yes, any exception can be declared using throws.
C. No, it cannot throw exceptions.
D. Yes, but only checked exceptions.

Answer: B

What is the correct way to create a custom exception?

Define a class that extends Throwable.
B. Define a class that extends Exception or RuntimeException.
C. Define a class with the @Exception annotation.
D. Define a class that implements the ExceptionHandler interface.

Answer: B

What is the default behavior of the JVM when an exception occurs?

It ignores the exception.
B. It executes the catch block automatically.
C. It prints the exception stack trace and terminates the program.
D. It executes the finally block directly.

Answer: C

What will happen if an exception is thrown in the catch block?

The program will terminate immediately.
B. The exception will be rethrown to the next catch block or caller.
C. The exception is ignored.
D. The finally block will not execute.

Answer: B

Which exception is thrown when a null object is accessed?

NullPointerException
B. IllegalArgumentException
C. ClassCastException
D. RuntimeException

Answer: A

Which of the following is NOT an unchecked exception?

ArrayIndexOutOfBoundsException
B. NullPointerException
C. FileNotFoundException
D. ArithmeticException

Answer: C

What is the purpose of try-with-resources in Java?

To avoid writing catch blocks
B. To automatically close resources after use
C. To handle runtime exceptions
D. To allow multiple exceptions to be thrown

Answer: B

Can you nest try-catch blocks in Java?

Yes, nesting is allowed and commonly used.
B. No, only one try block is allowed per method.
C. Yes, but only with runtime exceptions.
D. No, it causes a compilation error.

Answer: A

Which class is used to define errors in Java?

Throwable
B. Exception
C. Error
D. RuntimeException

Answer: C

What does the getMessage() method of the Throwable class return?

The stack trace of the exception
B. The exception’s detailed message
C. The exception type
D. The cause of the exception

Answer: B

Which exception is thrown when an invalid cast is attempted?

IllegalArgumentException
B. ClassCastException
C. NumberFormatException
D. InvalidCastException

Answer: B

Can a finally block execute after a System.exit() call?

Yes, always.
B. No, the program terminates immediately.
C. Yes, but only if no exceptions occur.
D. No, but the catch block will execute instead.

Answer: B

 

Which of the following is part of the Java Collections Framework?

Map
B. Set
C. List
D. All of the above

Answer: D

Which collection class implements the List interface?

HashSet
B. ArrayList
C. TreeMap
D. LinkedHashMap

Answer: B

Which of the following methods is used to add an element to a list in Java?

add()
B. insert()
C. push()
D. append()

Answer: A

What is the default capacity of an ArrayList in Java when it is created without specifying an initial size?

5
B. 10
C. 15
D. 20

Answer: B

Which of the following collection interfaces does not allow duplicate elements?

Set
B. List
C. Queue
D. Deque

Answer: A

Which of the following classes implements the Set interface?

HashSet
B. ArrayList
C. LinkedList
D. PriorityQueue

Answer: A

Which of the following collections maintains the insertion order of elements?

HashSet
B. TreeSet
C. LinkedHashSet
D. PriorityQueue

Answer: C

Which method is used to remove an element from a list at a specific index?

remove()
B. delete()
C. pop()
D. discard()

Answer: A

 

Which of the following collections does not implement the Collection interface?

Set
B. Map
C. List
D. Queue

Answer: B

Which method is used to check if a Set contains a specific element?

has()
B. contains()
C. find()
D. search()

Answer: B

Which of the following collection classes implements the SortedSet interface?

HashSet
B. TreeSet
C. ArrayList
D. LinkedList

Answer: B

Which of the following is true about a HashMap?

It maintains the order of insertion.
B. It allows only unique values.
C. It does not allow duplicate keys.
D. It does not allow null values.

Answer: C

What is the purpose of the Iterator in the Collections Framework?

To provide a way to traverse through elements of a collection
B. To remove elements from a collection
C. To modify elements in a collection
D. To sort elements in a collection

Answer: A

Which of the following is the correct syntax to create a Map in Java?

Map<String, Integer> map = new HashMap<>();
B. Map map = new HashMap();
C. Map<String> map = new HashMap<>();
D. Map<String, Integer> map = new TreeMap<>();

Answer: A

What will happen if you try to add a duplicate key to a Map?

The new value will replace the old one.
B. The program will throw an exception.
C. The duplicate entry will be ignored.
D. The program will terminate.

Answer: A

Which of the following collections is sorted based on natural ordering of elements?

HashSet
B. TreeSet
C. ArrayList
D. PriorityQueue

Answer: B

What is the function of the Comparator interface?

To allow sorting of objects in a collection
B. To allow elements to be added to a collection
C. To iterate over elements of a collection
D. To perform operations on elements of a collection

Answer: A

What is the difference between HashMap and TreeMap?

HashMap stores elements in sorted order, while TreeMap does not.
B. HashMap allows null keys and values, while TreeMap does not.
C. TreeMap allows duplicate keys, while HashMap does not.
D. There is no difference.

Answer: B

Which of the following collection classes implements the Queue interface?

ArrayList
B. LinkedList
C. TreeSet
D. PriorityQueue

Answer: B

Which method is used to remove and return the first element of a Queue?

poll()
B. pop()
C. removeFirst()
D. dequeue()

Answer: A

Which of the following collection classes is thread-safe?

HashMap
B. LinkedList
C. Vector
D. TreeMap

Answer: C

Which collection interface allows insertion of duplicate elements?

Set
B. List
C. Queue
D. Map

Answer: B

What is the advantage of using LinkedList over ArrayList in Java?

LinkedList provides faster access to elements by index.
B. LinkedList consumes less memory.
C. LinkedList is better for frequent insertions and deletions.
D. LinkedList maintains the order of insertion.

Answer: C

 

Which method of List interface allows you to remove an element at a specified index?

remove()
B. delete()
C. removeAt()
D. clear()

Answer: A

What does the clear() method do in a Map?

Removes all entries from the map.
B. Removes all keys from the map.
C. Clears the values of the map.
D. Clears the entire map and reinitializes it.

Answer: A

Which of the following collections does not allow null elements?

HashSet
B. TreeSet
C. ArrayList
D. HashMap

Answer: B

 

30. Which method is used to obtain a set view of the keys in a Map?

keySet()
B. entrySet()
C. values()
D. getKeys()

Answer: A

 

Which class in Java is used to create a thread?

Thread
B. Runnable
C. Executor
D. ThreadPoolExecutor

Answer: A

How do you start a thread in Java?

By calling start() method of the Thread class
B. By calling run() method of the Thread class
C. By calling execute() method of the Runnable class
D. By creating an instance of Thread

Answer: A

What is the purpose of the run() method in a Thread class?

To initialize a thread
B. To execute the task in a separate thread
C. To terminate a thread
D. To pause a thread

Answer: B

Which of the following interfaces is implemented to create a task for a thread?

Runnable
B. Callable
C. Thread
D. ExecutorService

Answer: A

What is the method signature of the run() method in the Thread class?

public void run()
B. public void execute()
C. public static void run()
D. public void threadRun()

Answer: A

Which method is used to pause the execution of a thread for a specific time in Java?

sleep()
B. wait()
C. sleepFor()
D. pause()

Answer: A

How do you ensure that one thread waits until another thread has completed its execution?

By using sleep() method
B. By using join() method
C. By using wait() method
D. By using yield() method

Answer: B

What does the yield() method do in Java threads?

Pauses the execution of a thread
B. Resumes the execution of a thread
C. Suggests that the current thread should pause and allow other threads to run
D. Terminates the current thread

Answer: C

Which of the following methods are part of the Thread class to check the current state of the thread?

isAlive()
B. isRunning()
C. getState()
D. Both A and C

Answer: D

Which of the following is a correct way to create a thread in Java?

By extending Thread class and overriding the run() method
B. By implementing Runnable interface and passing it to a Thread object
C. By implementing Callable interface and passing it to a ExecutorService
D. All of the above

Answer: D

What is the main difference between the Runnable and Callable interfaces in Java?

Callable can return a result, while Runnable cannot
B. Runnable can return a result, while Callable cannot
C. Runnable executes in a new thread, while Callable executes in the current thread
D. Runnable is part of the java.lang package, while Callable is part of the java.util.concurrent package

Answer: A

Which of the following classes provides a thread pool for managing multiple threads?

ExecutorService
B. ThreadPoolExecutor
C. Executor
D. All of the above

Answer: D

What does the wait() method do in Java threads?

Pauses the current thread for a specified time
B. Resumes a paused thread
C. Releases the lock and allows other threads to access the object
D. Checks if a thread is alive

Answer: C

What is the default priority of a thread in Java?

Thread.MIN_PRIORITY
B. Thread.MAX_PRIORITY
C. Thread.NORM_PRIORITY
D. Thread.DEFAULT_PRIORITY

Answer: C

What is a race condition in multi-threading?

When multiple threads compete to access the same resource
B. When a thread is blocked indefinitely
C. When a thread is paused for too long
D. When threads are executed sequentially

Answer: A

Which of the following can be used to synchronize threads in Java?

synchronized keyword
B. lock() method
C. wait() method
D. All of the above

Answer: A

What does the synchronized keyword do in Java?

Ensures that a block of code is executed by only one thread at a time
B. Pauses the thread for a specified period
C. Runs the method in a new thread
D. Makes the method non-blocking

Answer: A

Which of the following classes are part of the java.util.concurrent package for managing concurrency?

CountDownLatch
B. Semaphore
C. CyclicBarrier
D. All of the above

Answer: D

Which class is used to implement a thread-safe counter in Java?

AtomicInteger
B. Integer
C. Counter
D. ThreadSafeCounter

Answer: A

What is the volatile keyword used for in Java?

To make a variable visible to all threads
B. To prevent a thread from modifying a variable
C. To execute a method concurrently
D. To make a thread execute only once

Answer: A

Which of the following is true about thread synchronization in Java?

Only one thread can access the synchronized method at a time
B. All threads can access synchronized methods concurrently
C. synchronized methods do not block threads
D. Synchronization is not necessary for multi-threaded applications

Answer: A

What is the purpose of the ExecutorService interface?

To provide a way to execute tasks asynchronously
B. To manage thread pools
C. To submit tasks for execution
D. All of the above

Answer: D

Which of the following is a type of thread pool in Java?

FixedThreadPool
B. CachedThreadPool
C. SingleThreadExecutor
D. All of the above

Answer: D

How do you stop a thread in Java?

By calling stop() method
B. By calling interrupt() method
C. By calling exit() method
D. Java threads cannot be stopped manually

Answer: B

What is the ForkJoinPool used for in Java?

To manage a large number of tasks by dividing them into smaller sub-tasks
B. To manage a fixed number of threads
C. To manage tasks that need to be executed sequentially
D. To execute tasks in a random order

Answer: A

What is deadlock in Java?

When two threads are blocked, waiting for each other’s resources
B. When a thread is executing indefinitely
C. When a thread is paused by another thread
D. When threads complete execution without any errors

Answer: A

Which of the following methods can be used to check if a thread is currently executing?

isAlive()
B. isRunning()
C. isActive()
D. isExecuting()

Answer: A

What is the purpose of the Callable interface in Java?

To represent a task that can be executed by a thread
B. To return a result from a task executed by a thread
C. To define a thread-safe method
D. To execute a task without returning a result

Answer: B

What is the significance of the join() method in Java threads?

It suspends the execution of the current thread until the specified thread terminates
B. It terminates the execution of the current thread
C. It pauses the execution of the current thread for a specified time
D. It resumes the execution of a suspended thread

Answer: A

Which of the following is a key benefit of using multi-threading in Java?

Reducing CPU utilization
B. Enabling parallel execution for improved performance
C. Simplifying the development process
D. Making the program single-threaded

Answer: B

 

What is the purpose of the Thread.sleep(long millis) method in Java?

It pauses the current thread for the specified time in milliseconds.
B. It makes the thread go into a waiting state indefinitely.
C. It starts a new thread after the specified time.
D. It wakes up a sleeping thread immediately.

Answer: A

Which of the following interfaces should be used for executing tasks asynchronously in Java?

Runnable
B. Executor
C. Callable
D. Both A and B

Answer: D

How does the ExecutorService.submit() method differ from ExecutorService.execute()?

submit() can return a result, while execute() does not.
B. execute() can return a result, while submit() does not.
C. submit() executes tasks sequentially, while execute() runs tasks in parallel.
D. There is no difference between the two.

Answer: A

Which of the following methods is used to wake up a thread that is in the wait() state?

notify()
B. resume()
C. wake()
D. signal()

Answer: A

Which method is used to pause the execution of a thread temporarily, yielding control to other threads?

wait()
B. yield()
C. sleep()
D. pause()

Answer: B

What is the CountDownLatch used for in Java?

To allow threads to synchronize execution at a certain point
B. To block a thread until a specified condition is met
C. To count the number of threads in execution
D. To allow a thread to wait for a specific period

Answer: A

Which of the following classes is used for thread synchronization in Java?

Lock
B. Semaphore
C. CyclicBarrier
D. All of the above

Answer: D

What is the purpose of the ExecutorService interface?

It allows executing tasks in separate threads.
B. It provides a framework for managing thread pools.
C. It handles task scheduling.
D. All of the above.

Answer: D

Which of the following is true about the ThreadPoolExecutor in Java?

It manages a fixed number of threads.
B. It can automatically adjust the number of threads in the pool based on demand.
C. It executes a task only after all tasks in the queue are completed.
D. It cannot be used with other classes in the java.util.concurrent package.

Answer: B

What is the function of the AtomicInteger class in Java?

It is used to make integers immutable.
B. It provides a way to perform thread-safe operations on integer values.
C. It provides basic synchronization for integer operations.
D. It performs arithmetic operations on integers.

Answer: B

Which of the following methods can be used to get the number of active threads in a thread group in Java?

getThreadCount()
B. activeCount()
C. getThreadGroupSize()
D. threadCount()

Answer: B

How does the CyclicBarrier class help with synchronization in multi-threaded applications?

It allows multiple threads to wait until a certain number of threads have reached a specific point in execution.
B. It allows threads to communicate with each other.
C. It blocks threads for a fixed period.
D. It ensures that threads execute in sequential order.

Answer: A

What does the Thread.interrupt() method do in Java?

Terminates the execution of a thread.
B. Pauses the execution of a thread for a certain period.
C. Signals that a thread should stop its execution.
D. None of the above.

Answer: C

What is a deadlock in the context of Java multi-threading?

When two threads are unable to access a common resource due to conflicting priorities.
B. When a thread cannot continue execution because it is waiting for a resource that is held by another thread.
C. When a thread executes faster than other threads.
D. When a thread is created and then never starts.

Answer: B

Which of the following thread states is not possible in Java?

New
B. Runnable
C. Sleeping
D. Active

Answer: D

What is the purpose of the ExecutorService.shutdown() method?

It terminates all running threads immediately.
B. It blocks the main thread until all tasks are completed.
C. It prevents new tasks from being submitted while allowing currently executing tasks to finish.
D. It cancels all running tasks.

Answer: C

Which class implements the Runnable interface in Java?

Thread
B. RunnableTask
C. ExecutorService
D. ThreadPoolExecutor

Answer: A

What is the main benefit of using synchronized blocks over synchronized methods in Java?

synchronized blocks allow for finer-grained control over which parts of the method are synchronized.
B. synchronized blocks are faster than synchronized methods.
C. synchronized blocks do not lock objects.
D. There is no difference between synchronized blocks and methods.

Answer: A

Which method in Java is used to check whether a thread is alive?

isAlive()
B. isRunning()
C. checkAlive()
D. checkRunning()

Answer: A

What is the role of the Semaphore class in Java?

It controls access to a shared resource by limiting the number of threads that can access it simultaneously.
B. It synchronizes the execution of threads.
C. It pauses the execution of all threads until a signal is received.
D. It manages the execution of multiple tasks in parallel.

Answer: A

Which of the following is used for achieving mutual exclusion in Java?

ReentrantLock
B. CyclicBarrier
C. CountDownLatch
D. AtomicInteger

Answer: A

What is the purpose of the ReentrantLock class in Java?

It provides a simple mechanism for locking a block of code to allow only one thread at a time to execute it.
B. It locks a thread indefinitely until a condition is met.
C. It allows multiple threads to execute the same code concurrently.
D. It prevents thread starvation.

Answer: A

Which of the following methods is used to acquire a lock in ReentrantLock?

lock()
B. acquire()
C. enter()
D. getLock()

Answer: A

What is the purpose of ExecutorCompletionService in Java?

To manage tasks in a thread pool and retrieve the results as soon as they are completed.
B. To execute tasks in sequence rather than concurrently.
C. To control the execution priority of tasks.
D. To ensure tasks are executed in the order they are submitted.

Answer: A

How does the ForkJoinPool improve parallel processing in Java?

It divides tasks into smaller sub-tasks and processes them in parallel.
B. It forces tasks to execute sequentially.
C. It provides a fixed number of threads for all tasks.
D. It allows only one thread to execute tasks at a time.

Answer: A

Which of the following classes can be used for managing concurrent access to a shared resource in Java?

ConcurrentHashMap
B. Vector
C. Hashtable
D. All of the above

Answer: D

What is the difference between synchronized methods and synchronized blocks?

synchronized methods lock the entire method, while synchronized blocks allow locking only a portion of the method.
B. synchronized blocks are more efficient than synchronized methods.
C. synchronized methods cannot be used for static methods.
D. There is no difference.

Answer: A

What is the purpose of the join() method in multi-threading?

To make a thread wait for another thread to finish execution.
B. To resume the execution of a blocked thread.
C. To pause the execution of a thread.
D. To terminate a thread.

Answer: A

What happens if a thread calls the sleep() method with a negative value?

It throws an IllegalArgumentException.
B. It results in an infinite sleep.
C. It causes an immediate return from the sleep() method.
D. It has no effect on the thread.

Answer: A

Which of the following is a thread-safe collection class in Java?

ArrayList
B. LinkedList
C. HashMap
D. CopyOnWriteArrayList

Answer: D

 

Which of the following classes is used to write bytes to a file in Java?

FileReader
B. FileWriter
C. BufferedWriter
D. FileOutputStream

Answer: D

Which method of the ObjectOutputStream class is used to serialize an object?

writeObject(Object obj)
B. serialize(Object obj)
C. writeFile(Object obj)
D. objectToStream(Object obj)

Answer: A

Which of the following is true about serialization in Java?

Only primitive types can be serialized.
B. The class must implement the Serializable interface to allow serialization.
C. Serialized objects can only be written to a file, not transmitted over a network.
D. The Serializable interface must contain the readObject() and writeObject() methods.

Answer: B

What is the role of the transient keyword in Java serialization?

It prevents a field from being serialized.
B. It forces a field to be serialized.
C. It indicates that a field can be serialized only once.
D. It marks a class as not serializable.

Answer: A

What happens if a non-serializable object is referenced within a serializable object?

A NotSerializableException will be thrown at runtime.
B. The non-serializable object will be skipped during serialization.
C. The program will not compile.
D. The non-serializable object will be serialized but with a null value.

Answer: A

Which of the following is the correct method for deserializing an object in Java?

readObject()
B. deserialize()
C. objectToStream()
D. readFromFile()

Answer: A

Which class in Java is used to read bytes from a file?

FileReader
B. BufferedReader
C. FileInputStream
D. ObjectInputStream

Answer: C

What does the ObjectInputStream class do in Java?

It is used to read primitive data types.
B. It is used to read serialized objects.
C. It is used to write serialized objects.
D. It is used to read text files.

Answer: B

Which of the following can be used to read data from the console in Java?

System.in.read()
B. BufferedReader.read()
C. Scanner.nextLine()
D. All of the above

Answer: D

What is the purpose of the flush() method in Java I/O operations?

It writes all buffered data to the output stream.
B. It reads data from the input stream.
C. It clears the buffer.
D. It closes the stream.

Answer: A

Which of the following classes is used for buffered output in Java?

BufferedInputStream
B. BufferedWriter
C. FileOutputStream
D. FileReader

Answer: B

Which method of the FileInputStream class is used to read a byte of data?

readByte()
B. read()
C. nextByte()
D. getByte()

Answer: B

In Java, what does the Serializable interface mark a class as?

It marks the class for compression.
B. It indicates the class can be serialized and deserialized.
C. It marks the class for secure transmission.
D. It marks the class as immutable.

Answer: B

Which of the following classes cannot be serialized in Java?

String
B. ArrayList
C. Thread
D. HashMap

Answer: C

Which stream class is used to read and write primitive data types in Java?

FileInputStream
B. DataInputStream
C. ObjectInputStream
D. BufferedReader

Answer: B

Which of the following statements is correct about the ObjectOutputStream class in Java?

It is used for reading serialized objects.
B. It is used for writing primitive data types.
C. It writes objects to an output stream in a format that can be read later.
D. It is used for reading text data.

Answer: C

Which method in the ObjectInputStream class is used to read a serialized object from an input stream?

readObject()
B. deserialize()
C. objectToStream()
D. readSerializedObject()

Answer: A

What is the default behavior of the readObject() method in ObjectInputStream?

It automatically closes the input stream.
B. It throws a ClassNotFoundException if the class is not found.
C. It returns a serialized object that is fully initialized.
D. It skips non-serializable objects.

Answer: B

What is the effect of the close() method in Java I/O operations?

It writes all remaining data to the stream and then closes it.
B. It stops the program from running.
C. It flushes the buffer but does not close the stream.
D. It resets the file pointer to the beginning of the file.

Answer: A

Which of the following statements is true about BufferedReader in Java?

It reads one byte at a time from the file.
B. It reads characters from an input stream.
C. It writes bytes to an output stream.
D. It is used to read binary data from a file.

Answer: B

Which of the following is true about the RandomAccessFile class?

It allows both reading and writing of a file.
B. It only allows reading from a file.
C. It is used to write binary data only.
D. It cannot read files sequentially.

Answer: A

What is the function of the FileOutputStream class?

It is used to read files from the disk.
B. It is used to write primitive data types to a file.
C. It is used to write bytes to a file.
D. It is used for buffered output operations.

Answer: C

Which of the following methods is used to write a string to a file in Java?

write()
B. print()
C. println()
D. Both A and C

Answer: D

Which of the following classes can be used for object serialization in Java?

ObjectInputStream
B. ObjectOutputStream
C. Serializable
D. All of the above

Answer: D

Which of the following is a method of the DataOutputStream class?

writeData()
B. writeUTF()
C. readUTF()
D. readData()

Answer: B

What happens if you try to deserialize an object that has been changed since it was serialized?

A ClassNotFoundException will be thrown.
B. A InvalidClassException will be thrown.
C. The object will be deserialized with default values.
D. The program will ignore the changes.

Answer: B

What is the purpose of the FileReader class in Java?

To write bytes to a file.
B. To read characters from a file.
C. To read binary data from a file.
D. To write characters to a file.

Answer: B

How does the PrintWriter class differ from BufferedWriter?

PrintWriter can print formatted representations of objects.
B. BufferedWriter can write characters to a file, while PrintWriter can write only primitive data types.
C. PrintWriter does not support writing to files.
D. There is no difference between the two classes.

Answer: A

Which of the following classes is used for reading from a file using a buffered approach?

BufferedReader
B. FileReader
C. FileInputStream
D. ObjectInputStream

Answer: A

What is the role of Serializable interface in Java?

It allows an object to be converted to a stream of bytes for storage or transmission.
B. It ensures that an object can be read by the system.
C. It marks a class as immutable.
D. It automatically synchronizes data across threads.

Answer: A

 

Which of the following interfaces is part of the java.util.function package in Java?

Function
B. Consumer
C. Supplier
D. All of the above

Answer: D

Which of the following methods is used to execute a functional interface in Java?

run()
B. apply()
C. execute()
D. accept()

Answer: B

In Java, what does the Predicate interface represent?

A function that takes no arguments and returns no result.
B. A function that accepts one argument and produces a result.
C. A function that returns a boolean value based on input.
D. A function that returns a result of any type.

Answer: C

Which method is used to combine two Predicate instances in Java?

and()
B. or()
C. not()
D. All of the above

Answer: D

What is the primary purpose of the Function interface in Java functional programming?

To accept a single argument and return a result.
B. To provide a boolean value based on a condition.
C. To process and consume values without returning any result.
D. To generate a value based on input.

Answer: A

How do you use the Consumer interface in Java?

It processes input data and returns a result.
B. It consumes a value and performs an action on it.
C. It supplies values to a consumer function.
D. It produces a boolean value.

Answer: B

What is the purpose of the Supplier interface in Java functional programming?

It consumes data and performs an action.
B. It produces results without accepting any input.
C. It processes and filters data.
D. It generates a boolean value.

Answer: B

Which of the following is true about the default keyword in Java?

It is used to define default values for variables.
B. It is used to define methods in interfaces that have an implementation.
C. It marks methods as final.
D. It defines abstract methods in interfaces.

Answer: B

What does the Optional class in Java represent?

It is used to create objects that are always non-null.
B. It is used to represent values that may or may not be present.
C. It is used to replace null values with a default value.
D. It is used to represent boolean values.

Answer: B

Which of the following operations can be performed using the Stream interface in Java?

Filtering elements
B. Mapping elements
C. Reducing elements
D. All of the above

Answer: D

How do you create an immutable collection in Java?

By using ArrayList.
B. By using List.of() or Collections.unmodifiableList().
C. By using TreeMap.
D. By using HashSet.

Answer: B

Which of the following methods in the Stream interface returns a stream consisting of the elements of the original stream that match a given predicate?

map()
B. filter()
C. reduce()
D. forEach()

Answer: B

Which of the following is an example of a higher-order function in Java functional programming?

map()
B. filter()
C. reduce()
D. All of the above

Answer: D

Which of the following stream operations is considered a “terminal” operation in Java?

map()
B. filter()
C. collect()
D. flatMap()

Answer: C

Which method can you use to combine multiple Function instances into one function?

compose()
B. andThen()
C. apply()
D. combine()

Answer: B

What is the result of calling Stream.of(1, 2, 3).reduce(0, Integer::sum) in Java?

0
B. 3
C. 6
D. 1

Answer: C

What is a lambda expression in Java?

A way to define anonymous functions using the lambda keyword.
B. A way to write classes in a more concise manner.
C. A shorthand for defining methods in a class.
D. A feature used to declare constructors in interfaces.

Answer: A

Which of the following statements about lambda expressions is true?

Lambda expressions can have multiple statements.
B. Lambda expressions cannot be used to implement functional interfaces.
C. Lambda expressions can return multiple values.
D. Lambda expressions must have a name.

Answer: A

What is the difference between map() and flatMap() in Java streams?

map() returns a single value, while flatMap() returns a stream of values.
B. map() is a terminal operation, while flatMap() is an intermediate operation.
C. map() is used for flat transformations, while flatMap() is used for deep transformations.
D. Both perform the same function.

Answer: A

Which method in the Stream interface is used to transform each element of a stream into a new form?

collect()
B. map()
C. flatMap()
D. forEach()

Answer: B

What does the forEach() method in the Stream interface do?

It performs a reduction on the elements of the stream.
B. It iterates over the elements of the stream and performs an action on each.
C. It filters the elements of the stream.
D. It creates a new stream based on the existing one.

Answer: B

Which of the following is an example of a functional interface in Java?

Runnable
B. Comparator
C. Function
D. All of the above

Answer: D

What does the reduce() method in Java streams do?

It returns the sum of all elements in the stream.
B. It transforms the elements of the stream into a new form.
C. It combines the elements of the stream into a single result.
D. It removes duplicate elements from the stream.

Answer: C

How do you create a Stream from a list of items in Java?

By using Stream.of().
B. By using Arrays.stream().
C. By using list.stream().
D. All of the above

Answer: D

Which of the following is an example of using the Optional class in Java?

Optional.ofNullable(value)
B. Optional.of(value)
C. Optional.empty()
D. All of the above

Answer: D

What does the empty() method of the Optional class do?

It creates an Optional that contains no value.
B. It checks if the Optional has a value.
C. It returns the default value from the Optional.
D. It makes the Optional non-null.

Answer: A

What type of function is represented by the UnaryOperator interface in Java?

A function that accepts two arguments and returns a result.
B. A function that accepts one argument and returns a result of the same type.
C. A function that returns a boolean value.
D. A function that accepts a boolean and returns an integer.

Answer: B

What is the purpose of the DoubleStream class in Java?

To represent a stream of primitive double values.
B. To convert Double objects into Stream objects.
C. To represent a stream of all objects of type Double.
D. To represent streams that can be used for mathematical operations.

Answer: A

Which of the following is NOT a method in the Stream interface?

peek()
B. allMatch()
C. stream()
D. collect()

Answer: C

How does Java’s functional programming model help in parallel processing?

It encourages the use of immutable data structures.
B. It supports efficient parallel processing with parallelStream().
C. It avoids the use of lambda expressions.
D. It forces sequential processing.

Answer: B