0% found this document useful (0 votes)
32 views6 pages

Java OOP, REST API, and Microservices Guide

Uploaded by

Malay Kumar Dey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views6 pages

Java OOP, REST API, and Microservices Guide

Uploaded by

Malay Kumar Dey
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Backend:

1. What are the key OOP principles in Java?

Answer:

• Encapsulation: Wrapping data and methods into a single unit (class).

• Inheritance: A child class inherits properties/methods from a parent class.

• Polymorphism: One method behaving differently based on the object (method


overloading/overriding).

• Abstraction: Hiding implementation details and showing only functionality.

2. How do you handle exceptions in Java?

Answer:

• Use try-catch blocks to handle expected exceptions.

• Use finally for cleanup code.

• Throw custom exceptions for business logic errors.

• Best Practices:

o Catch specific exceptions (IOException, SQLException, etc.)

o Don’t swallow exceptions silently.

o Always log errors with context.

3. How do you create a RESTful API in Spring Boot?

Answer:

1. Use @RestController to define the controller.

2. Use @GetMapping, @PostMapping, etc., for HTTP methods.

3. Use @RequestBody for input and @ResponseBody for output.

4. Use @PathVariable and @RequestParam to capture input from URL.

Java code:

@RestController

@RequestMapping("/api/users")

public class UserController {

@GetMapping("/{id}")

public ResponseEntity<User> getUser(@PathVariable Long id) {


return [Link]([Link](id));

4. What are Spring Boot Starters?

Answer:
Spring Boot starters are pre-configured dependencies for common tasks.
Example:

• spring-boot-starter-web: Includes Spring MVC, embedded Tomcat.

• spring-boot-starter-data-jpa: For JPA and Hibernate integration.

5. What is Dependency Injection (DI)?

Answer:
A design pattern where Spring injects object dependencies automatically instead of you creating
them manually using new.

• Achieved using:

o @Autowired

o Constructor Injection (recommended)

6. Difference between SQL and NoSQL databases?

Answer:

1. Data Structure

• MySQL:

• Uses a tabular structure with rows and columns.

• Requires a predefined schema, making it suitable for structured data.

• NoSQL:

• Employs various data models such as document-based, key-value, column-family, or


graph-based.

• Allows for flexible schemas, accommodating unstructured or semi-structured data.

2. Scalability

• MySQL:
• Primarily vertically scalable, meaning it requires more powerful hardware to handle
increased loads.

• Scaling can be challenging due to its rigid schema.

• NoSQL:

• Horizontally scalable, allowing data to be distributed across multiple servers.

• Better suited for handling large volumes of traffic and data.

3. Query Language

• MySQL:

• Utilizes Structured Query Language (SQL) for data manipulation and retrieval.

• Well-suited for complex queries and transactions.

• NoSQL:

• Does not have a standard query language; each NoSQL database may use its own
syntax.

• Generally optimized for fast read/write operations.

4. Data Integrity and Consistency

• MySQL:

• Follows ACID properties (Atomicity, Consistency, Isolation, Durability) to ensure


reliable transactions.

• Ideal for applications requiring strong consistency, such as banking systems.

• NoSQL:

• Often follows BASE (Basically Available, Soft state, Eventually consistent) principles,
prioritizing availability over strict consistency.

• Suitable for applications where eventual consistency is acceptable.

5. Use Cases

• MySQL:

• Best for applications with complex queries and transactional systems (e.g., ERP,
CRM).

• Commonly used in legacy systems that require a relational structure.

• NoSQL:
• Ideal for big data applications, real-time web apps, and scenarios with rapidly
changing data structures.

• Frequently used in social media, content management systems, and applications


with unstructured data.

Examples of Each Database Type

• MySQL:

• Popular implementations include MySQL, PostgreSQL, Oracle, and Microsoft SQL


Server.

• NoSQL:

• Common examples include MongoDB, Cassandra, CouchDB, and Neo4j.

7. What are key features of Microservices?

Answer:

• Independent deployable services

• Own database per service (DB per microservice)

• Communicate via REST or messaging queues (e.g., RabbitMQ)

• Use Eureka for service discovery, API Gateway for routing

• Challenges: Data consistency, latency, distributed tracing

8. How do microservices communicate?

Answer:

• Synchronous: RESTful APIs (Spring Boot controllers)

• Asynchronous: Message queues (RabbitMQ, Kafka)

• Use Feign clients or RestTemplate/WebClient for service calls

9. How do you deploy Spring Boot on AWS?

Answer:

• Package your app as a .jar using Maven.

• Deploy to:

o EC2: Launch VM, install Java, and run java -jar [Link]

o Elastic Beanstalk: Managed environment for easy deployment


o ECS/EKS: For Dockerized microservices

• Store assets in S3, use RDS for databases

• Monitor via CloudWatch, manage access with IAM

10. Given an array arr[], check if it is sorted in ascending order or not. Equal values are allowed in
an array and two consecutive equal values are considered sorted.

Examples:

Input: arr[] = [10, 20, 30, 40, 50]


Output: true
Explanation: The given array is sorted.

Input: arr[] = [90, 80, 100, 70, 40, 30]


Output: false
Explanation: The given array is not sorted.

Answer:

class GFG {

static boolean isSorted(int arr[]) {

int n = [Link];

// Iterate over the array and check if

// every element is greater than or

// equal to previous element.

for (int i = 1; i < n; i++)

if (arr[i - 1] > arr[i])

return false;

return true;

public static void main(String[] args) {

int arr[] = { 10, 20, 30, 40, 50 };

int n = [Link];
if (isSorted(arr))

[Link]("true\n");

else

[Link]("false\n");

Output:- true.

// you can add some questions more as per your project need. Also you go in depth about his
project.

// You can also conduct the interview process as per our project need.

Common questions

Powered by AI

A NoSQL database is recommended when dealing with applications that require highly flexible data models, such as those handling unstructured or semi-structured data, like content management systems or social media platforms. NoSQL databases are ideal for big data applications and real-time web applications that need to scale horizontally to accommodate large volumes of rapidly changing data. They suit scenarios where eventual consistency is acceptable over ACID transactions, offering faster read/write operations suited for applications with different query patterns and data types .

The architecture of microservices ensures independent deployability by encapsulating all functionalities within discrete services, each having its own database and business logic, allowing them to be developed, tested, and deployed independently of other services. This modular approach shortens the deployment cycle, as changes to one service don't require redeploying the entire application. It facilitates continuous delivery and integration, improving system reliability and enabling teams to scale services independently based on demand, reducing downtime and enhancing the system's overall resilience .

SQL databases like MySQL are primarily vertically scalable, requiring more powerful hardware to handle increased loads, and are best suited for applications with complex queries and transactional systems, such as ERP and CRM. They are often used in legacy systems that require a relational structure . In contrast, NoSQL databases are horizontally scalable, allowing data to be distributed across multiple servers, making them better suited for handling large volumes of traffic and data, such as big data applications, real-time web apps, social media, and content management systems .

Microservices communicate synchronously through RESTful APIs using tools like Spring Boot controllers and asynchronously via message queues like RabbitMQ and Kafka. Feign clients or RestTemplate/WebClient are used for service calls . The challenges involved include managing data consistency, handling latency issues, and implementing distributed tracing to monitor and debug service interactions .

Spring Boot starters significantly simplify application development by providing a set of pre-configured dependencies tailored for specific tasks. This abstraction layer reduces the need for manual configuration, speeds up development time, and minimizes boilerplate code. For example, the spring-boot-starter-web includes Spring MVC and embedded Tomcat, which streamlines the setup of web applications. Similarly, the spring-boot-starter-data-jpa facilitates easy integration with JPA and Hibernate for database operations .

Encapsulation enhances software security by restricting access to certain components, thus protecting them from unauthorized modifications. This is achieved by wrapping data and methods into a single unit (class) and controlling access through access modifiers. Encapsulation also improves maintenance by separating the internal implementation details from the exposed functionalities, allowing changes without affecting other parts of the application. This modularization simplifies debugging, testing, and updating components, aligning with OOP's principles for building robust software systems .

Constructor injection is preferred over field injection in Spring Boot because it facilitates immutable and easier-to-test code, ensuring that dependencies are not null by enforcing their provision at object creation. It leads to cleaner and more reliable code, as all dependencies are explicitly listed in the constructor, making classes easier to understand and reducing the risk of circular dependencies. This approach aligns with the principles of dependency injection, promoting better software design and maintainability .

Custom exceptions in Java enhance robust error handling by allowing developers to define application-specific errors, which provide more meaningful and contextual error information. This specificity aids developers in identifying the root cause of errors quickly, facilitates clear code logic, and promotes cleaner separation between technical and business concerns. By using custom exceptions, applications can enforce domain-specific rules and handle exceptional scenarios in a controlled and predictable manner .

Choosing between SQL and NoSQL databases involves trade-offs between complexity and flexibility. SQL databases like MySQL require a predefined schema and are designed for complex queries and transactional integrity, providing strong consistency and support for structured data, but are limited by vertical scalability . NoSQL databases offer flexible schemas, allowing for unstructured or semi-structured data and horizontal scalability, which can handle large volumes of data efficiently. However, NoSQL sacrifices some query complexity and consistency, operating under BASE principles, which may not suit applications needing strict transactional integrity .

Dependency Injection (DI) enhances application design by enabling loose coupling between components, making the system more modular and easier to maintain. In Spring Boot, DI allows Spring to automatically inject object dependencies, instead of manually creating them, which simplifies the testing and configuration of application components. This is typically achieved using annotations like @Autowired or through constructor injection, which is highly recommended for its testability benefits .

You might also like