0% found this document useful (0 votes)
0 views11 pages

Java Interview Q&A

The document covers essential concepts in Core Java, Spring Boot, SQL, and REST & Microservices, including key differences between operators, data structures, and frameworks. It explains principles like Dependency Injection, normalization, REST architecture, and microservices communication. Each section provides concise definitions and comparisons to aid understanding of these programming topics.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views11 pages

Java Interview Q&A

The document covers essential concepts in Core Java, Spring Boot, SQL, and REST & Microservices, including key differences between operators, data structures, and frameworks. It explains principles like Dependency Injection, normalization, REST architecture, and microservices communication. Each section provides concise definitions and comparisons to aid understanding of these programming topics.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

Core Java

1. What is the difference between == and .equals() in Java?


== compares object references to check if they point to the same memory location.
.equals() checks logical equality and is usually overridden in value-based classes
like String.
Use .equals() when comparing object content.

2. What is the difference between ArrayList and LinkedList?


ArrayList offers fast random access but slower insert/delete operations in the
middle due to shifting.
LinkedList provides faster insertions/deletions at both ends but slower access by
index.
Choose based on the operation frequency and use case.

3. What is the use of the final keyword?


final can be used to declare constants, prevent method overriding, and inheritance
of classes.
A final variable cannot be reassigned once set.
It's often used for safety and immutability.

4. What is a constructor and can it be inherited?


A constructor initializes objects when a class is instantiated.
Constructors are not inherited but the child class can call the parent constructor
using super().
Each class must define its own constructors as needed.

5. What is method overloading and overriding?


Overloading means having multiple methods with the same name but different
parameters.
Overriding means redefining a parent method in a subclass with the same signature.
Overloading is compile-time, overriding is runtime polymorphism.

6. What is the difference between String, StringBuilder, and StringBuffer?


String is immutable; every change creates a new object.
StringBuilder is mutable and faster, while StringBuffer is thread-safe but slower.
Use StringBuilder for most non-threaded operations.

7. Explain the concept of Garbage Collection.


Garbage Collection in Java is the process of reclaiming memory used by unreachable
objects.
It is managed by the JVM automatically using algorithms like mark-and-sweep or G1.
You can suggest GC with System.gc(), but it’s not guaranteed.

8. What are checked and unchecked exceptions?


Checked exceptions (like IOException) must be declared or handled in code.
Unchecked exceptions (like NullPointerException) are runtime errors not enforced by
the compiler.
Use checked for recoverable issues, unchecked for bugs.

9. What is a static block and when does it execute?


A static block is used to initialize static data.
It runs once when the class is first loaded into memory.
Useful for complex static initializations.

10. What is the difference between this and super?


this refers to the current class's instance, while super refers to the parent
class.
super is often used to call superclass constructors or methods.
Both help avoid ambiguity in class hierarchies.

11. What is polymorphism in Java?


Polymorphism allows objects to take many forms, mainly via method overriding and
overloading.
It supports code reuse and flexibility in object behavior.
Java supports compile-time and runtime polymorphism.

12. What is encapsulation?


Encapsulation is the concept of wrapping data and methods into a single unit
(class).
It helps in data hiding using private variables and public getters/setters.
It increases security and maintainability.

13. What is abstraction in Java?


Abstraction means hiding implementation details and exposing only essential
features.
Achieved via abstract classes or interfaces.
It helps in focusing on "what" an object does rather than "how".

14. What is inheritance in Java?


Inheritance allows a class (child) to acquire properties and behavior from another
class (parent).
It supports code reusability and method overriding.
Use extends for class inheritance and implements for interfaces.

15. What are wrapper classes?


Wrapper classes (like Integer, Double) convert primitives into objects.
Useful in collections that work with objects and for utility methods.
Java auto-boxes and unboxes between primitive and wrapper types.

16. What is the use of the transient keyword?


transient marks a variable to be skipped during serialization.
It’s often used for sensitive or non-serializable data.
Upon deserialization, the field is set to its default value.

17. What is the difference between wait(), sleep(), and join()?


sleep() pauses the current thread for a duration.
wait() causes the thread to release the lock and wait for notification.
join() makes one thread wait until another finishes execution.

18. What is the use of synchronized keyword?


synchronized ensures only one thread can access a method or block at a time.
Used for thread safety when multiple threads interact with shared data.
Avoids race conditions and data inconsistency.

19. What is a Java interface?


An interface defines a contract of methods that a class must implement.
Java 8+ allows default and static methods in interfaces.
It supports abstraction and multiple inheritance of type.

20. What is the difference between HashMap and Hashtable?


HashMap is non-synchronized and allows one null key, while Hashtable is
synchronized and doesn’t allow null keys/values.
HashMap is faster in single-threaded contexts.
Prefer ConcurrentHashMap for thread-safe performance.
===================================================================================
==========================================
Spring Boot
--------------------
1. What is Dependency Injection (DI) in Spring?
DI allows Spring to manage and inject dependent objects into a class, instead of
instantiating them manually.
This promotes loose coupling and makes the application easier to test and maintain.
It is the core principle of Spring’s IoC (Inversion of Control) container.

2. What is the difference between @Component, @Service, @Repository, and


@Controller?
All are Spring stereotypes for component scanning and bean registration.
@Service is used for business logic, @Repository for data access (adds exception
translation), and @Controller for web layers.
They improve readability and clarify application roles.

3. What is @Autowired used for?


@Autowired tells Spring to automatically inject the required bean by type.
It can be used on constructors, setters, or fields.
If multiple beans match, use @Qualifier to resolve ambiguity.

4. How does Spring handle bean scopes?


Spring beans have scopes like singleton, prototype, request, and session.
singleton (default) means one instance per container, while prototype creates a new
instance every time.
Web scopes work with Spring MVC or WebFlux.

5. What is the difference between @ComponentScan and @Bean?


@ComponentScan automatically detects classes annotated with @Component, @Service,
etc.
@Bean manually defines beans in @Configuration classes.
Use @ComponentScan for auto-discovery and @Bean for explicit creation.

6. What is the role of @Qualifier?


@Qualifier is used when multiple beans of the same type exist, and you want to
specify which one to inject.
It resolves ambiguity by referring to the bean name.
It must be used with @Autowired or @Inject.

7. What is a Spring Boot Starter?


Starters are dependency descriptors that simplify Maven/Gradle configurations.
For example, spring-boot-starter-web includes Tomcat, Spring MVC, and Jackson.
They make project setup faster and cleaner.

8. How does Spring Boot auto-configuration work?


Auto-configuration checks the classpath and creates beans based on what's
available.
It uses @EnableAutoConfiguration and condition annotations like
@ConditionalOnClass.
You can override any auto-configured bean by declaring your own.

9. What is the purpose of @Configuration and @Bean?


@Configuration marks a class as a source of bean definitions.
Inside it, @Bean methods define and return bean instances.
It's used for manual and programmatic configuration.

10. How is @Transactional used in Spring?


@Transactional manages transactions declaratively on service methods.
It begins a transaction before the method and commits or rolls back after it ends.
Default rollback is for unchecked exceptions unless configured otherwise.
11. What is the difference between constructor and field injection?
Constructor injection is recommended as it ensures all dependencies are provided at
object creation.
Field injection is less safe and harder to test due to reflection-based assignment.
Setter injection is useful for optional dependencies.

12. What is Spring AOP?


Aspect-Oriented Programming allows modularizing cross-cutting concerns like logging
and security.
Spring AOP uses proxies to intercept method calls and apply advice.
Common advice types: @Before, @After, @Around.

13. How do you handle exceptions globally in Spring MVC?


Use @ControllerAdvice with @ExceptionHandler to handle exceptions across all
controllers.
It centralizes error handling logic and returns custom responses.
Useful for customizing HTTP error responses like 404 or 500.

14. What is the purpose of @Value?


@Value injects values from property files, system properties, or environment
variables.
It’s useful for injecting configuration values like URLs, ports, or credentials.
Syntax: @Value("${property.name}").

15. What is the role of Spring Profiles?


Profiles let you define different beans or configurations for different
environments (e.g., dev, test, prod).
Activate them via application.properties or environment variables.
Use @Profile("dev") on classes or methods.

16. What is the DispatcherServlet in Spring MVC?


DispatcherServlet is the front controller that routes HTTP requests to appropriate
controllers.
It coordinates with view resolvers, exception handlers, and model rendering.
It acts as the central engine of Spring MVC.

17. How does Spring handle form validation?


Use JSR-303/JSR-380 annotations like @NotNull, @Size with @Valid in controllers.
Spring validates request bodies or form inputs and binds results to BindingResult.
Validation messages can be customized in messages.properties.

18. What is the difference between RestController and Controller?


@Controller returns views (JSP, Thymeleaf) for UI rendering, typically in web apps.
@RestController returns JSON/XML response bodies for REST APIs.
@RestController is shorthand for @Controller + @ResponseBody.

19. What is Spring Data JPA and why use it?


Spring Data JPA simplifies database access by generating repository code
automatically.
You define interfaces, and Spring provides the implementation.
It supports custom queries via method names or @Query.

20. What is Spring Boot Actuator?


Actuator exposes endpoints like /health, /metrics, /info for monitoring and
managing your app.
It helps with production diagnostics and can integrate with Prometheus, Grafana,
etc.
Security and access control can be configured for endpoints.
===================================================================================
=====================================================
SQL
----------------------
1. What is normalization and why is it important?
Normalization is the process of organizing data to reduce redundancy and improve
data integrity.
It divides data into related tables using foreign keys and ensures each piece of
data is stored only once.
Common forms include 1NF, 2NF, 3NF.

2. What are primary and foreign keys?


A primary key uniquely identifies each record in a table and cannot be null.
A foreign key references the primary key of another table to establish a
relationship.
They help enforce referential integrity between tables.

3. What is the difference between INNER JOIN, LEFT JOIN, and RIGHT JOIN?
INNER JOIN returns matching rows from both tables.
LEFT JOIN returns all records from the left table and matched rows from the right.
RIGHT JOIN does the opposite—use based on what data you need to preserve.

4. How do you get the second highest salary from a table?


Use a subquery to filter salaries:

SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM
employees);
This avoids LIMIT or ROWNUM which can vary by RDBMS.

5. What is a transaction in SQL?


A transaction is a sequence of operations performed as a single unit of work.
It must follow the ACID properties—Atomicity, Consistency, Isolation, Durability.
Transactions ensure reliable and consistent data changes.

6. Explain ACID properties.


Atomicity ensures all or nothing execution of a transaction.
Consistency keeps the database in a valid state.
Isolation prevents interference between transactions; Durability ensures changes
persist.

7. What is an index?
An index improves query performance by allowing faster lookups on columns.
However, too many indexes slow down write operations.
Use indexes wisely for columns in WHERE, JOIN, or ORDER BY.

8. What is a composite key?


A composite key is a primary key made up of two or more columns.
It’s used when a single column can’t uniquely identify a row.
All parts of the composite key are required for uniqueness.

9. What is a view in SQL?


A view is a virtual table created using a SQL query.
It does not store data itself but reflects data from underlying tables.
Useful for abstraction, security, and simplifying complex joins.

10. What is the difference between DELETE, TRUNCATE, and DROP?


DELETE removes rows based on a condition and logs each row; it can be rolled back.
TRUNCATE removes all rows quickly and can't be rolled back in most databases.
DROP removes the entire table structure permanently.
11. What is a subquery?
A subquery is a query nested inside another query.
It can be used in SELECT, FROM, or WHERE clauses.
Subqueries are useful for filtering based on aggregate results.

12. What are stored procedures?


Stored procedures are precompiled SQL code saved in the database.
They accept parameters, contain logic, and return results or output variables.
They improve performance and encapsulate business rules.

13. What are triggers in SQL?


Triggers are special procedures that execute automatically in response to table
events (INSERT, UPDATE, DELETE).
They are useful for enforcing rules or logging changes.
However, overuse can affect performance and debugging.

14. Difference between clustered and non-clustered index?


A clustered index defines the actual data storage order and only one can exist per
table.
Non-clustered indexes are separate structures pointing to the data rows.
Clustered indexes speed up retrieval for range-based queries.

15. How do GROUP BY and HAVING differ?


GROUP BY aggregates rows based on column values.
HAVING filters the grouped results, while WHERE filters rows before grouping.
Used together for grouped filtering logic.

16. What is a correlated subquery?


A correlated subquery depends on the outer query for its value.
It executes once for every row in the outer query.
Useful when filtering rows based on dynamic conditions.

17. What is denormalization and when is it used?


Denormalization merges tables or repeats data to reduce complex joins.
It improves read performance at the cost of redundancy.
Used in read-heavy systems like reporting and analytics.

18. What is the purpose of foreign key constraints?


They enforce relationships between tables to ensure data integrity.
They prevent deletion or insertion of invalid foreign key values.
Crucial for maintaining consistent relational models.

19. How do you prevent SQL injection?


Use parameterized queries or prepared statements instead of string concatenation.
Avoid directly injecting user input into SQL.
ORM frameworks and validation libraries can help secure inputs.

20. What is the difference between OLTP and OLAP systems?


OLTP (Online Transaction Processing) handles real-time, frequent database
operations like inserts and updates.
OLAP (Online Analytical Processing) is for analytics and heavy reads over large
datasets.
They have different data modeling and performance needs.

===================================================================================
========================================
Rest & Microservices
-------------------------------
1. What is REST and how does it work?
REST (Representational State Transfer) is an architectural style that uses HTTP
methods to perform CRUD operations on resources.
It treats data as resources and uses URIs to access them.
It is stateless, cacheable, and supports layered architecture.

2. What are the main HTTP methods used in REST APIs?


GET (read), POST (create), PUT (update), DELETE (remove) are the primary HTTP
verbs.
Each method performs a specific CRUD function on resources.
They align with REST principles to maintain stateless operations.

3. What is the difference between PUT and PATCH?


PUT replaces the entire resource, even if only part is updated.
PATCH modifies only the specified fields of a resource.
Use PUT for full updates, PATCH for partial ones.

4. What is idempotency in REST APIs?


An operation is idempotent if it produces the same result when called multiple
times.
GET, PUT, DELETE are idempotent; POST is not.
It ensures safe retries in distributed systems.

5. What is HATEOAS in REST?


HATEOAS (Hypermedia as the Engine of Application State) enhances REST responses
with links to related resources.
It enables discoverability and navigability within APIs.
Though ideal, it’s rarely implemented in simple APIs.

6. What status codes do REST APIs use?


Examples include: 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request), 401
(Unauthorized), 404 (Not Found), 500 (Server Error).
They help the client understand the result of the request.
Use them consistently and appropriately for clarity.

7. How do you handle versioning in REST APIs?


Common strategies: URI versioning (/v1/users), header-based (Accept:
application/vnd.api.v1+json), or query params (?version=1).
URI versioning is the most common and readable.
Helps avoid breaking changes in clients.

8. What is a Microservice Architecture?


Microservices are small, independent services that work together to form an
application.
Each service owns its data and logic and communicates over APIs.
This architecture supports scalability, flexibility, and independent deployment.

9. Difference between Monolith and Microservices?


Monoliths are single, unified applications; microservices break functionality into
independent services.
Microservices offer scalability and fault isolation but increase complexity.
Each has trade-offs based on project size and requirements.

10. How do microservices communicate?


Commonly via REST over HTTP or messaging systems like Kafka, RabbitMQ.
Synchronous communication is simple, but async is preferred for decoupling and
fault tolerance.
Use standardized contracts like OpenAPI or Avro.
11. What is an API Gateway?
It acts as the single entry point to microservices, handling routing, rate
limiting, authentication, and load balancing.
Popular gateways include Spring Cloud Gateway, Netflix Zuul, and Kong.
Helps secure and manage microservices efficiently.

12. What is service discovery?


Service discovery dynamically tracks and manages microservice instances.
Tools like Netflix Eureka or Consul allow services to register and locate each
other.
Crucial in dynamic, cloud-native environments.

13. How do you secure REST APIs?


Use authentication (e.g., JWT, OAuth2) and authorization (roles, scopes).
Use HTTPS, input validation, and rate limiting for additional security.
Spring Security integrates these easily in Java apps.

14. What is a circuit breaker pattern?


It prevents a service from repeatedly trying a failing dependency, avoiding
cascading failures.
If errors exceed a threshold, further calls are blocked temporarily.
Libraries like Resilience4j and Hystrix implement this.

15. What is API throttling or rate limiting?


Throttling limits the number of API requests per client to prevent abuse or
overload.
Helps maintain service stability and availability.
Usually configured at the API gateway or via middleware.

16. How do you implement logging in microservices?


Use structured, centralized logging with tools like ELK stack or Fluentd.
Include correlation IDs to trace requests across services.
Helps in debugging and monitoring distributed flows.

17. What is configuration management in microservices?


Centralized config (e.g., Spring Cloud Config, Consul) allows services to fetch
settings dynamically.
Enables environment-specific configuration without rebuilding services.
Supports real-time updates with minimal downtime.

18. What are common challenges in microservices?


Challenges include data consistency, distributed logging, service orchestration,
and network latency.
Requires DevOps maturity and good observability practices.
Resilience, monitoring, and testing strategies must evolve.

19. How do you test microservices?


Use unit tests for logic, integration tests for APIs, and contract tests for
service interactions.
Tools like Postman, REST Assured, and WireMock help validate APIs.
Service virtualization is useful when dependencies are unavailable.

20. How do you handle distributed transactions?


Use patterns like Saga for eventual consistency or orchestration/choreography
models.
Avoid global ACID transactions; they don’t scale well.
Each microservice should manage its own data independently.
===================================================================================
=====================================
1. What is Docker and why is it used?
Docker is a containerization platform that packages applications and their
dependencies into containers.
It ensures consistent environments across development, testing, and production.
Helps reduce deployment issues and simplifies scalability.

2. What is the difference between a container and a virtual machine?


Containers share the host OS kernel, making them lightweight and fast.
VMs run separate OS instances, using more resources and boot time.
Containers are ideal for microservices and cloud-native apps.

3. What is a Dockerfile?
A Dockerfile is a script that contains instructions to build a Docker image.
It defines base images, copies files, installs dependencies, and sets entry points.
It enables consistent and automated image creation.

4. What is Git and why is it important?


Git is a distributed version control system used to track code changes and
collaborate on software.
It allows branching, merging, and reverting code safely.
Widely adopted in almost all modern software projects.

5. What is the difference between git pull and git fetch?


git fetch downloads changes without merging them into your branch.
git pull does both fetch and merge in a single step.
Use fetch for reviewing updates before integrating.

6. What is a CI/CD pipeline?


CI/CD automates building, testing, and deploying code changes.
CI (Continuous Integration) runs tests on every commit; CD (Continuous
Delivery/Deployment) automates releases.
It ensures fast, reliable, and repeatable deployments.

7. How do you implement CI/CD in Java projects?


Use tools like Jenkins, GitHub Actions, or GitLab CI with Maven/Gradle for builds
and tests.
Define pipelines using YAML or UI and integrate with Docker/Kubernetes for
deployments.
Add steps for unit testing, code quality, and artifact publishing.

8. What is Jenkins and how does it work?


Jenkins is an open-source CI/CD tool that runs automated tasks defined in
pipelines.
It supports plugins for integration with Git, Docker, Maven, etc.
Jenkins can be used to automate testing, builds, and deployments.

9. What is Maven and how is it different from Gradle?


Maven uses XML (pom.xml) for dependency management and project structure.
Gradle uses Groovy/Kotlin scripts and offers faster builds with incremental
compilation.
Gradle is more flexible; Maven is more widely used in legacy projects.

10. What is SonarQube and how is it useful?


SonarQube is a static code analysis tool that checks code quality, complexity,
duplication, and security.
It integrates with CI pipelines to enforce coding standards.
Helps maintain clean, maintainable codebases.

11 .What is a reverse proxy and why use it?


A reverse proxy like Nginx or HAProxy forwards client requests to backend servers.
It adds load balancing, caching, SSL termination, and security layers.
Used in front of microservices or web apps.

12 .What is the difference between blue-green and canary deployment?


Blue-green runs two environments (live and standby) and switches traffic on
release.
Canary slowly rolls out changes to a subset of users to monitor impact.
Both reduce downtime and risk during deployment.

13. What is Infrastructure as Code (IaC)?


IaC uses code (e.g., Terraform, Ansible) to provision infrastructure instead of
manual steps.
It enables reproducibility, versioning, and automated environments.
Essential for managing cloud infrastructure at scale.

14. What is log aggregation and why is it important?


Log aggregation collects logs from multiple services into one searchable platform.
Tools like ELK (Elasticsearch, Logstash, Kibana) help monitor and troubleshoot
distributed systems.
Critical for debugging and performance monitoring in microservices.

15. What is container orchestration?


It manages containerized applications’ lifecycle: deployment, scaling, networking,
and healing.
Kubernetes is the most popular orchestration tool.
Essential for running microservices in production at scale.

16. What is Kubernetes and why is it used?


Kubernetes is a container orchestration platform that automates deploying and
managing containers.
It supports scaling, self-healing, service discovery, and rolling updates.
Used to run cloud-native applications reliably.

17. What is a YAML file used for in DevOps?


YAML files define configurations for CI/CD pipelines, Kubernetes manifests, and
application settings.
They are readable, hierarchical, and widely adopted in automation tools.
Common in GitHub Actions, Jenkins, and Docker Compose.

18. What is a service mesh and when would you use it?
A service mesh like Istio or Linkerd manages microservice-to-microservice
communication.
It adds observability, traffic control, and security without changing application
code.
Used in complex microservices environments.

19. What is OAuth2 and how is it used in APIs?


OAuth2 is a secure authorization framework that allows apps to access user
resources via access tokens.
It separates authentication (login) from authorization (access control).
Common in securing REST APIs and integrating with identity providers.

20. How do you ensure high availability in distributed systems?


Use load balancers, redundant services, failover strategies, and stateless designs.
Monitor health and auto-restart failed components.
Cloud platforms and Kubernetes help achieve this at scale.

You might also like