0% found this document useful (0 votes)
22 views88 pages

Interview Notes Java Springboot HCL

The document outlines three distinct problems involving Spring Boot applications: a financial system with Account and Transaction services, a student management system with validation and exception handling, and a To-do application. Each problem includes a problem statement, technical specifications, tasks to complete, and example code for various components such as controllers, services, and models. The document emphasizes the use of RESTful APIs for communication and data management in each application.

Uploaded by

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

Interview Notes Java Springboot HCL

The document outlines three distinct problems involving Spring Boot applications: a financial system with Account and Transaction services, a student management system with validation and exception handling, and a To-do application. Each problem includes a problem statement, technical specifications, tasks to complete, and example code for various components such as controllers, services, and models. The document emphasizes the use of RESTful APIs for communication and data management in each application.

Uploaded by

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

Full Stack Questions:

[Link] name

[Spring Boot Microservices] Account-Transaction Services

Problem statement

Microservices architecture promotes modularity, scalability, and maintainability. Your task is to build
a financial system consisting of two services: Account Service and Transaction Service. These services
will communicate with each other to manage account information and financial transactions. You will
implement and complete the code for the following services to handle deposits, withdrawals,
account management, and fund transfers.
Technical specifications

 Tech Stack

o Backend: Spring Boot

o Database: SQLite

 Database model parameters

o Account: [ Long: id, String: accountHolder, Double: balance, AccountStatus: status ]

o Transaction: [ Long: id, Long: accountId, Double: amount, TransactionType: type (DEPOSIT or
WITHDRAWAL) ]

 Port

o Account-service: 8001

o Transaction-service: 8002

Tasks

Complete the code in [Link] and [Link] to handle various operations


related to orders and inventory. These services communicate using the Rest Template.

1. Account Service

o POST /api/account/open

 Create a new account with the given account holder name and initial balance.

o GET /api/account/{id}

 Fetch the details of a single account by ID.

o GET /api/account/balance/{id}

 Retrieve the current balance of an account.

o PUT /api/account/update-balance/{id}/{amount}

 Update the balance of the specified account by adding or subtracting the given amount. If
the new balance is negative, throw an exception.

o POST /api/account/transfer
 Transfer funds between two accounts using the fromId, toId, and amount. Throw an
exception if there is insufficient balance in the source account.

o GET /api/account/interest/{id}

 Calculate interest on the account's balance based on the provided rate.

2. Transacion Service

o POST /api/transaction/deposit/{id}/{amount}

 Perform a deposit by adding the specified amount to the account balance and recording the
transaction.

o POST /api/transaction/withdraw/{id}/{amount}

 Perform a withdrawal by deducting the specified amount from the account balance. Ensure
the account has sufficient funds before proceeding.

Testing instructions

1. To run any additional commands, navigate to the respective directories in the Terminal. Refer
to the given examples:

o '/account-service' and use the command: mvn compile.

o '/transaction-service' and use the command: mvn compile.

2. Use the Thunder Client extension in the IDE's left sidebar to test API requests.

3. After clicking the Run code or Submit code, you can access the Build log or Execution log to
review comprehensive details about the test outcomes.

Answer Ref:

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@Entity

public class Account {

@Id

@GeneratedValue(strategy = [Link])

private Long id;

private String accountHolder;

private Double balance;


private AccountStatus status;

// Getters and setters

[Link]

public enum AccountStatus {

ACTIVE, INACTIVE, CLOSED

[Link]

import [Link];

public interface AccountRepository extends JpaRepository<Account, Long> {

[Link]

import [Link];

import [Link];

import [Link];

@Service

public class AccountService {

@Autowired

private AccountRepository accountRepository;

public Account openAccount(Account account) {

[Link]([Link]);

return [Link](account);

public Optional<Account> getAccount(Long id) {


return [Link](id);

public Optional<Double> getBalance(Long id) {

return [Link](id).map(Account::getBalance);

public Account updateBalance(Long id, Double amount) {

Optional<Account> account = [Link](id);

if ([Link]()) {

Account acc = [Link]();

double newBalance = [Link]() + amount;

if (newBalance < 0) {

throw new IllegalArgumentException("Insufficient balance");

[Link](newBalance);

return [Link](acc);

} else {

throw new IllegalArgumentException("Account not found");

public void transfer(Long fromId, Long toId, Double amount) {

Optional<Account> fromAccount = [Link](fromId);

Optional<Account> toAccount = [Link](toId);

if ([Link]() && [Link]()) {

Account fromAcc = [Link]();

Account toAcc = [Link]();

if ([Link]() < amount) {

throw new IllegalArgumentException("Insufficient balance in source account");


}

[Link]([Link]() - amount);

[Link]([Link]() + amount);

[Link](fromAcc);

[Link](toAcc);

} else {

throw new IllegalArgumentException("Account not found");

public Optional<Double> calculateInterest(Long id, Double rate) {

return [Link](id).map(acc -> [Link]() * rate);

[Link]

import [Link];

import [Link].*;

import [Link];

import [Link];

import [Link];

@RestController

@RequestMapping("/api/account")

public class AccountController {

@Autowired

private AccountService accountService;

@PostMapping("/open")

public ResponseEntity<Account> openAccount(@RequestBody Account account) {


Account savedAccount = [Link](account);

return new ResponseEntity<>(savedAccount, [Link]);

@GetMapping("/{id}")

public ResponseEntity<Account> getAccount(@PathVariable Long id) {

Optional<Account> account = [Link](id);

return [Link](ResponseEntity::ok).orElseGet(() -> [Link]().build());

@GetMapping("/balance/{id}")

public ResponseEntity<Double> getBalance(@PathVariable Long id) {

Optional<Double> balance = [Link](id);

return [Link](ResponseEntity::ok).orElseGet(() -> [Link]().build());

@PutMapping("/update-balance/{id}/{amount}")

public ResponseEntity<Account> updateBalance(@PathVariable Long id, @PathVariable Double


amount) {

try {

Account updatedAccount = [Link](id, amount);

return [Link](updatedAccount);

} catch (IllegalArgumentException e) {

return [Link]().body(null);

@PostMapping("/transfer")

public ResponseEntity<String> transfer(@RequestParam Long fromId, @RequestParam Long toId,


@RequestParam Double amount) {

try {

[Link](fromId, toId, amount);


return [Link]("Transfer successful");

} catch (IllegalArgumentException e) {

return [Link]().body([Link]());

@GetMapping("/interest/{id}")

public ResponseEntity<Double> calculateInterest(@PathVariable Long id, @RequestParam Double


rate) {

Optional<Double> interest = [Link](id, rate);

return [Link](ResponseEntity::ok).orElseGet(() -> [Link]().build());

2 . Problem name

[Spring Boot] Validation and exceptional handling

Problem statement

You are given a student model with ID, name, age, marks, attendance, and promotion status. Your
objective is to perform validation and exception handling around student objects in given scenarios.

Technical specifications

 Tech Stack

o Backend: Spring Boot

o Database: MySQL

 Database model parameters

o Student: [id, name, age, marks, attendance, promotion_status]

 Port

o Backend: 8000

Tasks

Complete the code in [Link].

1. Save a student using POST mapping with API endpoint /students

o Throw CustomException when the value of the mark is negative or greater than 100.
o Throw CustomException when the attendance value is negative or greater than 100.

2. Fetch a single student using GET mapping with API endpoint /students/{id}

3. Fetch all students using GET mapping with API endpoint /students

4. Delete a single student using DELETE mapping with API endpoint /students/{id}

5. Update a student using PUT mapping with API endpoint /students/{id}

6. Update promotion_status for a student to true when both the marks and attendance are
greater than 85 in any other case update as false.

Testing instructions

1. To run any additional commands, use the Terminal. For example, navigate to the
'/backend' directory in the Terminal and use the command: mvn compile.

2. To test backend API endpoints, follow these steps:

o Navigate to the ‘/backend’ folder in the terminal.

o Use the CURL command to test the different endpoint requests. For example: curl -X
GET [Link] will check if your GET request for the endpoint is
working or not.

3. Upon clicking the Run code or Submit code buttons, access the Build log or Execution log to
review comprehensive details about the test outcomes.

Answer:

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@Entity

public class Student {

@Id

@GeneratedValue(strategy = [Link])

private Long id;

private String name;

private Integer age;

private Integer marks;


private Integer attendance;

private Boolean promotionStatus;

// Getters and setters

[Link]

import [Link];

public interface StudentRepository extends JpaRepository<Student, Long> {

[Link]

public class CustomException extends RuntimeException {

public CustomException(String message) {

super(message);

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@ControllerAdvice

public class GlobalExceptionHandler {

@ExceptionHandler([Link])

public ResponseEntity<String> handleCustomException(CustomException ex) {

return new ResponseEntity<>([Link](), HttpStatus.BAD_REQUEST);

[Link]
import [Link];

import [Link];

import [Link];

import [Link];

@Service

public class StudentService {

@Autowired

private StudentRepository studentRepository;

public Student saveStudent(Student student) {

if ([Link]() < 0 || [Link]() > 100) {

throw new CustomException("Marks must be between 0 and 100");

if ([Link]() < 0 || [Link]() > 100) {

throw new CustomException("Attendance must be between 0 and 100");

updatePromotionStatus(student);

return [Link](student);

public Optional<Student> getStudent(Long id) {

return [Link](id);

public List<Student> getAllStudents() {

return [Link]();

}
public void deleteStudent(Long id) {

[Link](id);

public Student updateStudent(Long id, Student studentDetails) {

Optional<Student> studentOptional = [Link](id);

if ([Link]()) {

Student student = [Link]();

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

updatePromotionStatus(student);

return [Link](student);

} else {

throw new CustomException("Student not found");

private void updatePromotionStatus(Student student) {

if ([Link]() > 85 && [Link]() > 85) {

[Link](true);

} else {

[Link](false);

[Link]

import [Link];

import [Link].*;

import [Link];
import [Link];

import [Link];

import [Link];

@RestController

@RequestMapping("/students")

public class StudentController {

@Autowired

private StudentService studentService;

@PostMapping

public ResponseEntity<Student> saveStudent(@RequestBody Student student) {

Student savedStudent = [Link](student);

return new ResponseEntity<>(savedStudent, [Link]);

@GetMapping("/{id}")

public ResponseEntity<Student> getStudent(@PathVariable Long id) {

Optional<Student> student = [Link](id);

return [Link](ResponseEntity::ok).orElseGet(() -> [Link]().build());

@GetMapping

public ResponseEntity<List<Student>> getAllStudents() {

List<Student> students = [Link]();

return [Link](students);

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {

[Link](id);

return [Link]().build();

@PutMapping("/{id}")

public ResponseEntity<Student> updateStudent(@PathVariable Long id, @RequestBody Student


studentDetails) {

try {

Student updatedStudent = [Link](id, studentDetails);

return [Link](updatedStudent);

} catch (CustomException e) {

return [Link]().body(null);

3 . Problem name

[Spring Boot] To-do Rest API

Problem statement

You are given a To-do application. The To-do model has ID, task, and status of completion. Your
objective is to complete the functions in [Link].

Technical specifications

 Tech Stack

o Backend: Spring Boot

o Database: SQLite

 Port

o Backend: 8000

Tasks

1. Fetch list of all the to-do tasks with API endpoint /api/todos

2. Fetch a single to-do task with API endpoint /api/todos/{id}


3. To save a to-do task in the database with API endpoint /api/todos

4. To delete a single to-do task from the database with API endpoint /api/todos/{id}

Testing instructions

1. To run any additional commands, use the Terminal. For example, navigate to the '/backend'
directory in the Terminal and use the command: mvn compile

2. Use the Thunder Client extension in the IDE's left sidebar to test API requests.

3. Upon clicking the Run code or Submit code buttons, access the Build log or Execution log to
review comprehensive details about the test outcomes.

Answer:

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@Entity

public class ToDo {

@Id

@GeneratedValue(strategy = [Link])

private Long id;

private String task;

private Boolean completed;

// Getters and setters

[Link]

import [Link];

public interface ToDoRepository extends JpaRepository<ToDo, Long> {

[Link]

import [Link];
import [Link];

import [Link];

import [Link];

@Service

public class ToDoService {

@Autowired

private ToDoRepository toDoRepository;

public List<ToDo> getAllToDos() {

return [Link]();

public Optional<ToDo> getToDoById(Long id) {

return [Link](id);

public ToDo saveToDo(ToDo toDo) {

return [Link](toDo);

public void deleteToDoById(Long id) {

[Link](id);

[Link]

import [Link];

import [Link].*;

import [Link];
import [Link];

import [Link];

import [Link];

@RestController

@RequestMapping("/api/todos")

public class ToDoController {

@Autowired

private ToDoService toDoService;

@GetMapping

public ResponseEntity<List<ToDo>> getAllToDos() {

List<ToDo> toDos = [Link]();

return [Link](toDos);

@GetMapping("/{id}")

public ResponseEntity<ToDo> getToDoById(@PathVariable Long id) {

Optional<ToDo> toDo = [Link](id);

return [Link](ResponseEntity::ok).orElseGet(() -> [Link]().build());

@PostMapping

public ResponseEntity<ToDo> saveToDo(@RequestBody ToDo toDo) {

ToDo savedToDo = [Link](toDo);

return new ResponseEntity<>(savedToDo, [Link]);

@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteToDoById(@PathVariable Long id) {

[Link](id);

return [Link]().build();

4 .Problem name

[Spring Boot] Employee operations

Problem statement

You are provided with an employee model comprising attributes such as ID, first name, last name,
email, department, and salary. Your task involves executing REST API operations on this model.

Technical specifications

 Tech Stack

o Backend: Spring Boot

o Database: MS SQL

 Database model parameters

o Employee: [id, firstName, lastName, email, department, salary]

 Port

o Backend: 8000

Tasks

Complete the code in [Link].

1. Save an employee using POST mapping with API endpoint /employees.

2. Fetch a single employee using GET mapping with API endpoint /employees/{id}.

3. Fetch all employees using GET mapping with API endpoint /employees.

4. Delete a single employee using DELETE mapping with API endpoint /employees/{id}.

5. Update an employee using PUT mapping with API endpoint /employees/{id}.

6. Fetch a list of employees with a given department using GET mapping API
endpoint /employees/searchDept.

o If required, write a custom query in [Link].


7. Fetch a list of employees with a salary greater than a given salary using GET mapping API
endpoint /employees/searchSalary.

o If required, write a custom query in [Link].

Note: Initially, the project may encounter build errors due to incomplete code in
the [Link] file, which you should resolve by crafting custom queries.

Testing instructions

1. To run any additional commands, use the Terminal. For example, navigate to the '/backend'
directory in the Terminal and use the command: mvn compile,

2. Use the CURL command to test the different endpoint requests. For example: curl -X
GET [Link] will check if your GET request for the endpoint is
working or not..

3. Upon clicking the Run code or Submit code buttons, access the Build log or Execution log to
review comprehensive details about the test outcomes.

Answer:

Sure, I'll provide the implementation for the [Link] along with the necessary
service, repository, and custom queries.

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@Entity

public class Employee {

@Id

@GeneratedValue(strategy = [Link])

private Long id;

private String firstName;

private String lastName;

private String email;

private String department;

private Double salary;


// Getters and setters

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

public interface EmployeeRepository extends JpaRepository<Employee, Long> {

@Query("SELECT e FROM Employee e WHERE [Link] = :department")

List<Employee> findByDepartment(@Param("department") String department);

@Query("SELECT e FROM Employee e WHERE [Link] > :salary")

List<Employee> findBySalaryGreaterThan(@Param("salary") Double salary);

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@Service

public class EmployeeService {

@Autowired

private EmployeeRepository employeeRepository;

public Employee saveEmployee(Employee employee) {


return [Link](employee);

public Optional<Employee> getEmployeeById(Long id) {

return [Link](id);

public List<Employee> getAllEmployees() {

return [Link]();

public void deleteEmployeeById(Long id) {

[Link](id);

public Employee updateEmployee(Long id, Employee employeeDetails) {

Optional<Employee> employeeOptional = [Link](id);

if ([Link]()) {

Employee employee = [Link]();

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

return [Link](employee);

} else {

throw new RuntimeException("Employee not found");

public List<Employee> getEmployeesByDepartment(String department) {


return [Link](department);

public List<Employee> getEmployeesBySalaryGreaterThan(Double salary) {

return [Link](salary);

[Link]

import [Link];

import [Link].*;

import [Link];

import [Link];

import [Link];

import [Link];

@RestController

@RequestMapping("/employees")

public class EmployeeController {

@Autowired

private EmployeeService employeeService;

@PostMapping

public ResponseEntity<Employee> saveEmployee(@RequestBody Employee employee) {

Employee savedEmployee = [Link](employee);

return new ResponseEntity<>(savedEmployee, [Link]);

@GetMapping("/{id}")

public ResponseEntity<Employee> getEmployeeById(@PathVariable Long id) {


Optional<Employee> employee = [Link](id);

return [Link](ResponseEntity::ok).orElseGet(() -> [Link]().build());

@GetMapping

public ResponseEntity<List<Employee>> getAllEmployees() {

List<Employee> employees = [Link]();

return [Link](employees);

@DeleteMapping("/{id}")

public ResponseEntity<Void> deleteEmployeeById(@PathVariable Long id) {

[Link](id);

return [Link]().build();

@PutMapping("/{id}")

public ResponseEntity<Employee> updateEmployee(@PathVariable Long id, @RequestBody


Employee employeeDetails) {

try {

Employee updatedEmployee = [Link](id, employeeDetails);

return [Link](updatedEmployee);

} catch (RuntimeException e) {

return [Link]().build();

@GetMapping("/searchDept")

public ResponseEntity<List<Employee>> getEmployeesByDepartment(@RequestParam String


department) {

List<Employee> employees = [Link](department);

return [Link](employees);
}

@GetMapping("/searchSalary")

public ResponseEntity<List<Employee>> getEmployeesBySalaryGreaterThan(@RequestParam


Double salary) {

List<Employee> employees = [Link](salary);

return [Link](employees);

5 . Problem name

[Spring Boot Microservices] Student school services

Problem statement

Microservices architecture has become a crucial approach in modern software development,


revolutionizing the way we design and construct complex systems. Your mission is to build a system
that consists of separate services, with each service responsible for managing specific functions such
as student and school. To ensure modularity and scalability, these functionalities will be separated
into individual services: Student Service, School Service, and so on.

Technical specifications

 Tech Stack

o Backend: Spring Boot

o Database: SQLite

 Database model parameters

o Student: [ Long: id, String: firstname, String: lastname, String: email, Date: dob, Long:
schoolId ]

o School: [ Long: id, String: name, String: location ]

 Port

o Student-service: 8000

o School-service: 8001

Tasks

Complete the code in [Link] and [Link].


1. Student service

1. Fetch a single student using GET mapping with API endpoint /students/{id}.

2. Fetch all students using GET mapping with API endpoint /students/.

3. Create a single student using POST mapping with API endpoint /students/.

4. Update a single student using PUT mapping with API endpoint /students/{id}.

5. Delete a single student using DELETE mapping with API endpoint /students/{id}.

6. Search for students by first name using GET mapping with API endpoint /students/search.

7. Fetch a list of students from a particular school using GET mapping with API
endpoint /students/by-school/{schoolId}.

2. School service

1. Fetch a single school using GET mapping with API endpoint /schools/{id}.

2. Fetch all schools using GET mapping with API endpoint /schools/.

3. Create a single school using POST mapping with API endpoint /schools/.

4. Update a single school using PUT mapping with API endpoint /schools/{id}.

5. Delete a single school using DELETE mapping with API endpoint /schools/{id}.

6. Search for schools by name using GET mapping with API endpoint /schools/search.

7. Fetch a list of schools by location using GET mapping with API endpoint /schools/by-
location/{location}.

Testing instructions

1. To run any additional commands, navigate to the respective directories in the Terminal. Refer
to the given examples:

o '/school-service' and use the command: mvn compile.

o '/student-service' and use the command: mvn compile.

2. Use the Thunder Client extension in the IDE's left sidebar to test API requests.

3. Upon clicking the Run code or Submit code buttons, access the Build log or Execution log to
review comprehensive details about the test outcomes.

Answer Ref:

[Link]

import [Link];

import [Link];

import [Link];
import [Link];

import [Link];

@Entity

public class Student {

@Id

@GeneratedValue(strategy = [Link])

private Long id;

private String firstname;

private String lastname;

private String email;

private Date dob;

private Long schoolId;

// Getters and setters

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@Entity

public class School {

@Id

@GeneratedValue(strategy = [Link])

private Long id;

private String name;

private String location;

// Getters and setters


}

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

public interface StudentRepository extends JpaRepository<Student, Long> {

List<Student> findByFirstname(String firstname);

@Query("SELECT s FROM Student s WHERE [Link] = :schoolId")

List<Student> findBySchoolId(@Param("schoolId") Long schoolId);

[Link]

import [Link];

public interface SchoolRepository extends JpaRepository<School, Long> {

List<School> findByName(String name);

@Query("SELECT s FROM School s WHERE [Link] = :location")

List<School> findByLocation(@Param("location") String location);

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@Service
public class StudentService {

@Autowired

private StudentRepository studentRepository;

public Optional<Student> getStudentById(Long id) {

return [Link](id);

public List<Student> getAllStudents() {

return [Link]();

public Student createStudent(Student student) {

return [Link](student);

public Student updateStudent(Long id, Student studentDetails) {

Optional<Student> studentOptional = [Link](id);

if ([Link]()) {

Student student = [Link]();

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

return [Link](student);

} else {

throw new RuntimeException("Student not found");

}
public void deleteStudent(Long id) {

[Link](id);

public List<Student> searchStudentsByFirstname(String firstname) {

return [Link](firstname);

public List<Student> getStudentsBySchoolId(Long schoolId) {

return [Link](schoolId);

[Link]

import [Link];

import [Link];

import [Link];

import [Link];

@Service

public class SchoolService {

@Autowired

private SchoolRepository schoolRepository;

public Optional<School> getSchoolById(Long id) {

return [Link](id);

public List<School> getAllSchools() {


return [Link]();

public School createSchool(School school) {

return [Link](school);

public School updateSchool(Long id, School schoolDetails) {

Optional<School> schoolOptional = [Link](id);

if ([Link]()) {

School school = [Link]();

[Link]([Link]());

[Link]([Link]());

return [Link](school);

} else {

throw new RuntimeException("School not found");

public void deleteSchool(Long id) {

[Link](id);

public List<School> searchSchoolsByName(String name) {

return [Link](name);

public List<School> getSchoolsByLocation(String location) {

return [Link](location);

}
[Link]

import [Link];

import [Link].*;

import [Link];

import [Link];

import [Link];

import [Link];

@RestController

@RequestMapping("/students")

public class StudentController {

@Autowired

private StudentService studentService;

@GetMapping("/{id}")

public ResponseEntity<Student> getStudentById(@PathVariable Long id) {

Optional<Student> student = [Link](id);

return [Link](ResponseEntity::ok).orElseGet(() -> [Link]().build());

@GetMapping

public ResponseEntity<List<Student>> getAllStudents() {

List<Student> students = [Link]();

return [Link](students);

@PostMapping

public ResponseEntity<Student> createStudent(@RequestBody Student student) {

Student savedStudent = [Link](student);


return new ResponseEntity<>(savedStudent, [Link]);

@PutMapping("/{id}")

public ResponseEntity<Student> updateStudent(@PathVariable Long id, @RequestBody Student


studentDetails) {

try {

Student updatedStudent = [Link](id, studentDetails);

return [Link](updatedStudent);

} catch (RuntimeException e) {

return [Link]().build();

@DeleteMapping("/{id}")

public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {

[Link](id);

return [Link]().build();

@GetMapping("/search")

public ResponseEntity<List<Student>> searchStudentsByFirstname(@RequestParam String


firstname) {

List<Student> students = [Link](firstname);

return [Link](students);

@GetMapping("/by-school/{schoolId}")

public ResponseEntity<List<Student>> getStudentsBySchoolId(@PathVariable Long schoolId) {

List<Student> students = [Link](schoolId);

return [Link](students);

}
}

[Link]

import [Link];

import [Link].*;

import [Link];

import [Link];

import [Link];

import [Link];

@RestController

@RequestMapping("/schools")

public class SchoolController {

@Autowired

private SchoolService schoolService;

@GetMapping("/{id}")

public ResponseEntity<School> getSchoolById(@PathVariable Long id) {

Optional<School> school = [Link](id);

return [Link](ResponseEntity::ok).orElseGet(() -> [Link]().build());

@GetMapping

public ResponseEntity<List<School>> getAllSchools() {

List<School> schools = [Link]();

return [Link](schools);

@PostMapping

public ResponseEntity<School> createSchool(@RequestBody School school) {


School savedSchool = [Link](school);

return new ResponseEntity<>(savedSchool, [Link]);

@PutMapping("/{id}")

public ResponseEntity<School> updateSchool(@PathVariable Long id, @RequestBody School


schoolDetails) {

try {

School updatedSchool = [Link](id, schoolDetails);

return [Link](updatedSchool);

} catch (RuntimeException e) {

return [Link]().build();

@DeleteMapping("/{id}")

public ResponseEntity<Void> deleteSchool(@PathVariable Long id) {

[Link](id);

return [Link]().build();

@GetMapping("/search")

public ResponseEntity<List<School>> searchSchoolsByName(@RequestParam String name) {

List<School> schools = [Link](name);

return [Link](schools);

@GetMapping("/by-location/{location}")

public ResponseEntity<List<School>> getSchoolsByLocation(@PathVariable String location) {

List<School> schools = [Link](location);

return [Link](schools);
}

Programming Question:

1 -- Ambiguity value

Problem statement

Given a 2D plane. You can move in any of the 4 directions in the first second. After the first second,
you change direction by 90 degrees every second. For example, if you just moved north or south, the
next step you take has to be either west or east and vice versa. In each second, you move 1 unit. You
are given integer N.

Calculate the ambiguity value in your position that is defined by the number of different locations
you can be after exactly N seconds.

Function description

Complete the function Ambuiguity(). This function takes the following parameter and returns the
required answer:

 N: Represents the number of seconds

Input format for custom testing

Note: Use this input format if you are testing against custom input or writing code in a language
where we don’t provide boilerplate code

 The first line contains an integer N denoting the number of seconds.

Output format

Calculate the ambiguity value in your position defined by the number of different locations you can
be after exactly N seconds.

Constraints

1<=N<=1000

Ref Answer:

Sure, here's the same program written in Java:

import [Link];

import [Link];

import [Link];
public class Ambiguity {

public static int calculateAmbiguity(int N) {

// Initialize a set to store unique positions

Set<String> positions = new HashSet<>();

// Initialize the starting position

int x = 0, y = 0;

// Initialize the direction (0: north, 1: east, 2: south, 3: west)

int direction = 0;

// Add the starting position to the set

[Link](x + "," + y);

for (int i = 1; i <= N; i++) {

if (direction == 0) {

y += 1;

} else if (direction == 1) {

x += 1;

} else if (direction == 2) {

y -= 1;

} else if (direction == 3) {

x -= 1;

// Add the new position to the set

[Link](x + "," + y);

// Change direction by 90 degrees

direction = (direction + 1) % 4;

}
// Return the number of unique positions

return [Link]();

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of seconds: ");

int N = [Link]();

[Link]("The ambiguity value after " + N + " seconds is " + calculateAmbiguity(N) +


".");

[Link]();

2.

Problem name

Valid combinations

Problem statement

Choose a stream of data of size A. You have B different types of integers from which you have to
select the stream of data. You can select an integer multiple times.

A valid combination is a stream of data in which there are exactly C integers that are different from
the previous integer in the sequence.

You are given integers A, B, and C. The first integer in the stream of data is not included among the C
integers.

Print the number of ways of selecting a valid combination modulo 998244353.


Function description

Complete the function ValidCombinations(). This function takes the following 3 parameters and
returns the required answer:

 A: Represents the number of integers in the data stream

 B: Represents the number of types of integers

 C: Represents the number of integers that should be different from the previous integer in
the sequence

Input format for custom testing

Note: Use this input format if you are testing against custom input or writing code in a language
where we don’t provide boilerplate code

 The first line contains an integer A denoting the number of integers in the data stream.

 The second line contains an integer B denoting the number of types of integers.

 The third line contains an integer C denoting the number of integers that should be different
from the previous integer in the sequence.

Output format

Print the number of ways of selecting a valid combination modulo 998244353.

Constraints

1≤A≤2000

1≤B≤2000

0≤C≤A−1

import [Link];

public class ValidCombinations {

static final int MOD = 998244353;

public static int calculateValidCombinations(int A, int B, int C) {

// Initialize a 2D dp array with dimensions (A+1) x (C+1)

int[][] dp = new int[A + 1][C + 1];

// Base case: There's one way to have a stream of length 1 with 0 changes
dp[1][0] = B;

// Fill the dp array

for (int i = 2; i <= A; i++) {

for (int j = 0; j <= C; j++) {

// If the current integer is the same as the previous one

dp[i][j] = dp[i - 1][j];

// If the current integer is different from the previous one

if (j > 0) {

dp[i][j] += dp[i - 1][j - 1] * (B - 1);

dp[i][j] %= MOD;

// Return the number of valid combinations for a stream of length A with exactly C changes

return dp[A][C];

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of integers in the data stream: ");

int A = [Link]();

[Link]("Enter the number of types of integers: ");

int B = [Link]();

[Link]("Enter the number of integers that should be different from the previous
integer in the sequence: ");

int C = [Link]();

[Link]("The number of valid combinations is " + calculateValidCombinations(A, B, C)


+ ".");

[Link]();
}

3. Problem name

Chocolate stack

Problem statement

A shop has a stack of chocolate boxes each containing a positive number of chocolates. Initially, the
stack is empty. During the next N minutes, either of these two things may happen:

 The box of chocolates on top of the stack gets sold

 You receive a box of chocolates from the warehouse and put it on top of the stack.

Determine the number of chocolates in the sold box each time he sells a box.

Notes

 If C[i] = 0, he sells a box. If C[i] > 0, he receives a box containing C[i] chocolates.

 It is confirmed that he gets a buyer only when he has a non-empty stack.

 The capacity of the stack is infinite.

Function description

Complete the solve() function provided in the editor. The function takes the following 2 parameters
and returns the solution.

 N: Represents the number of minutes

 C: Represents the description of boxes

Input format for custom testing

Note: Use this input format if you are testing against custom input or writing code in a language
where we don’t provide boilerplate code

 The first line contains N denoting the number of minutes.

 The second line contains C denoting the array consisting of the box descriptions.

Output format

Print an array, representing the number of chocolates in the sold box each time you sell a box.

Constraints

1≤N≤105

0≤C[i]≤109

Ref Answer :

import [Link];
import [Link];

public class ChocolateStack {

public static int[] solve(int N, int[] C) {

Stack<Integer> stack = new Stack<>();

int[] result = new int[N];

int resultIndex = 0;

for (int i = 0; i < N; i++) {

if (C[i] == 0) {

// Sell the box on top of the stack

result[resultIndex++] = [Link]();

} else {

// Receive a box and put it on top of the stack

[Link](C[i]);

// Trim the result array to the actual number of sold boxes

int[] trimmedResult = new int[resultIndex];

[Link](result, 0, trimmedResult, 0, resultIndex);

return trimmedResult;

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of minutes: ");

int N = [Link]();

int[] C = new int[N];

[Link]("Enter the array consisting of the box descriptions: ");

for (int i = 0; i < N; i++) {


C[i] = [Link]();

int[] result = solve(N, C);

[Link]("The number of chocolates in the sold box each time you sell a box: ");

for (int chocolates : result) {

[Link](chocolates + " ");

[Link]();

4. Problem name

Consecutive sale

Problem statement

A shop is open for N days. Each day, one of the following events may occur:

1. If shop[i] = 1, the shopkeeper returns any remaining stock from the previous batch (if there
is any) and receives a large number of items from the new batch. During this time, no
customers are served.

2. If shop[i] = 0, the shop is open for selling items to customers.

3. If shop[i] = -1, the shopkeeper returns all the items that are currently in the shop.

Find the maximum number of days the shopkeeper sells items from the same lot.

Notes

 Intiially, the shopkeeper has no stock with him.

 It is possible that a customer comes to the shop and there are no items available. In such a
case, the shopkeeper does not sell anything to that customer.

Function description

Complete the solution() function. The function takes the following 2 parameters and returns the
solution:

 N: Represents the number of days

 shop: Represents the details of each day

Input format for custom testing


Note: Use this input format if you are testing against custom input or writing code in a language
where we don’t provide boilerplate code

 The first line contains N denoting the number of days.

 The second line contains array shop of size N, denoting the details of each day.

Output format

Print a single integer representing the maximum number of days in which the shopkeeper sells
items from the same lot.

Constraints

1≤N≤105−1≤shop[i]≤1

Given

Input:

N=4

shop = [1,1,0,0]

Output: 2

Approach :

On day 1, the shopkeeper gets items from lot number say 1.

On day 2, the shopkeeper returns all items from lot number 1 and gets items from lot number 2.

For the next 2 days, the sells items from lot number 2.

Ref Answer :

import [Link];

public class ConsecutiveSale {

public static int solution(int N, int[] shop) {

int maxDays = 0;

int currentDays = 0;

boolean hasStock = false;

for (int i = 0; i < N; i++) {

if (shop[i] == 1) {

// New batch received, reset currentDays

currentDays = 0;
hasStock = true;

} else if (shop[i] == 0) {

if (hasStock) {

// Shop is open and has stock, increment currentDays

currentDays += 1;

maxDays = [Link](maxDays, currentDays);

} else if (shop[i] == -1) {

// Return all items, reset currentDays and hasStock

currentDays = 0;

hasStock = false;

return maxDays;

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of days: ");

int N = [Link]();

int[] shop = new int[N];

[Link]("Enter the array representing the details of each day: ");

for (int i = 0; i < N; i++) {

shop[i] = [Link]();

[Link]("The maximum number of days in which the shopkeeper sells items from
the same lot is " + solution(N, shop) + ".");

[Link]();

}
5 . Problem name

Minimum maximum distance

Problem statement

The Department of Parks and Recreation wants to minimize the maximum distance between any
two trees in the city by cutting exactly one tree. The trees' locations are represented by
coordinates (x, y) where x and y are the distances from the x-axis and y-axis, respectively. The
distance between two trees is defined as the Manhattan distance between them. Find the
minimum possible, maximum distance between any two trees by cutting exactly one tree.

Function description
Complete the function solve() which takes as input an integer N denoting the number of trees in
the city and a 2-D integer array trees denoting the coordinates of the trees.

Input format for custom testing

Note: Use this input format if you are testing against custom input or writing code in a language
where we don’t provide boilerplate code

 The first line contains N denoting the number of trees in the city.

 The next N lines contain 2 space-separated integers each - xi, yi.

Output format

Print a single integer representing the minimum possible, maximum distance that can be achieved
by cutting precisely one tree.

Constraints

3≤N≤1e3

1≤xi,yi≤1e9

Here coordinates of the trees are [[1,2],[2,4],[2,6],[3,9],[2,8]]

 dist(1,2)=|1-2|+|2-4|=3

 dist(1,3)=|1-2|+|2-6|=5

 dist(1,4)=|1-3|+|2-9|=9

 dist(1,5)=|1-2|+|2-8|=7

 dist(2,3)=|2-2|+|4-6|=2

 dist(2,4)=|2-3|+|4-9|=6

 dist(2,5)=|2-2|+|4-8|=4

 dist(3,4)=|2-3|+|6-9|=4

 dist(3,5)=|2-2|+|6-8|=2
 dist(4,5)=|3-2|+|9-8|=2

 Initial max
distance=max(dist(1,2),dist(1,3),dist(1,4),dist(1,5),dist(2,3),dist(2,4),dist(2,5),dist(3,4),dist(3
,5),dist(4,5)

 =max(3,5,9,7,2,6,4,4,2,2)=9

 Now we cut the tree 1.

 New max
distance=max(dist(2,3),dist(2,4),dist(2,5),dist(3,4),dist(3,5),dist(4,5))=max(2,6,4,4,2,2)=6

 It can be proved that 6 is the minimum maximum distance that can be achived.

Ref Answer :

import [Link];

public class MinimumMaximumDistance {

public static int manhattanDistance(int[] p1, int[] p2) {

return [Link](p1[0] - p2[0]) + [Link](p1[1] - p2[1]);

public static int solve(int N, int[][] trees) {

int[] maxDistances = new int[N];

for (int i = 0; i < N; i++) {

int maxDistance = 0;

for (int j = 0; j < N; j++) {

if (i != j) {

maxDistance = [Link](maxDistance, manhattanDistance(trees[i], trees[j]));

maxDistances[i] = maxDistance;

}
int minMaxDistance = Integer.MAX_VALUE;

for (int distance : maxDistances) {

minMaxDistance = [Link](minMaxDistance, distance);

return minMaxDistance;

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the number of trees: ");

int N = [Link]();

int[][] trees = new int[N][2];

[Link]("Enter the coordinates of the trees:");

for (int i = 0; i < N; i++) {

trees[i][0] = [Link]();

trees[i][1] = [Link]();

[Link]("The minimum possible, maximum distance that can be achieved by cutting


precisely one tree is " + solve(N, trees) + ".");

[Link]();

Problem statement

Which of the following command line tools is built by using the RabbitMQ HTTP API?

Choices

 Rabbitmqctl

 Rabbitmqadmin -- Correct answer

 Rabbitmq-plugins
 Rabbitmq-diagnostics

Problem statement

In the microservice architecture, which of the following modules of the Netflix Ribbon component
supports HTTP that uses the RxNetty library with the load balancing capacity?

Choices

 ribbon-eureka

 ribbon-transport Correct answer

 ribbon-loadbalancer

 ribbon-httpclient

Problem statement

While working on a large application using microservices you came across the concept of bounded
context. Which among the following options best describes the functionality of bounded context in
Microservice Architecture?

Options:

1. Cloud provider's region in which the microservice operates

2. A logic domain that is usually represented by the data consumed and emitted by a
microservice-based on its purpose, structure, and meaning

3. Common characteristics among entities belonging to one or more domains of business

Choices

 1

 2 Correct answer

 3

 None of these

In RabbitMQ, which of the following commands is used to activate the confirm mode on a channel?

Choices

 [Link] Correct answer

 [Link]

 [Link]
 [Link]

Problem statement

In the microservice architecture, which of the following statements about the Hystrix server are
correct:

Statements:

1. This is a microservice component that acts as a fault-tolerance robust system.

2. If the application is running without an issue, then the circuit remains open.

3. If the application is running without an issue, then the circuit remains closed.

4. If the application is running with an issue, then the server opens the circuit

Choices

 1, 2, and 4

 1, 3, and 4 Correct answer

 2, 3, and 4

 1, 2, and 3

Problem statement

Alice is currently using Java and wants to build a large application. For such a scenario, she wants to
make use of certain architecture. Which among the following architecture involves structuring an
application in the form of a cluster of small, autonomous services modeled around a business
domain?

Choices

 Monolithic Architecture

 SOA(Service Oriented Architecture)

 Microservice Architecture Correct answer

 Modular Architecture

Problem statement
Which of the following statements about using the microservices over the Service-Oriented
Architecture (SOA) are correct?

Statements:

1. The microservice applications are deployed to perform multiple business processes.

2. SOA is a part of microservices.

3. In microservices, the software size is bigger than conventional software.

4. In microservices, all the business units are independent of each other.

Choices

 1 and 2

 3 and 4

 2 and 3

 1 and 4 Correct answer

Which of the following components of the microservice architecture is represented as an Edge


server?

Choices

 Netflix Ribbon server

 Netflix Zuul API gateway server -- Correct answer

 Hystrix server

 Zipkin Distributed server

While working on microservices you want to test your application before deployment and wish to
make use of testing that tests the end-to-end functionality of the application. As microservices
architecture has multiple services which might need to interact with other microservices as part of a
user request, which among the following testing techniques would you choose for the above
functionality?

Choices

 End to end testing -- Correct answer

 Unit Testing

 Load Testing

 Resilience Testing
Problem statement

Mike is working on Microservice architecture. While working on an application he wants to know


about the component that contains an inbuilt load balancer which is used to load the balance of all
the incoming requests from the client. Help him to find which of the following can suit the above-
mentioned context.

Choices

 Hystrix server

 Netflix Zuul Gateway server -- Correct answer

 Zipkin Distributed server

 Spring Cloud Config server

Problem statement

In RabbitMQ, a default exchange that is referred by an empty string (" ") is a pre-declared direct
exchange that contains no name. If the default exchange is used to deliver a message to a queue,
then which of the following entities represents the name of the message?

Choices

 Queue

 Routing key -- Correct answer

 Binding

 No name is assigned to the message

You're implementing

1. Student data management.

2. Academic record tracking.


3. Student status changes.

4. Event-based notifications.

5. Data consistency checks.

6. Historical data tracking.

7. Performance monitoring.

8. Data privacy compliance.

9. Bulk data operations.

10. Integration with other services.

11. Audit logging requirements.

Which design pattern manages complex student status changes?

Choices

 Observer Pattern

 State Pattern --Correct answer

 Strategy Pattern

 Command Pattern

Problem statement

Which of the following versions of ERLANG OTP is not supported by RabbitMQ versions prior to
3.7.7?

Which of the following versions of ERLANG OTP is not supported by versions of RabbitMQ that are
older than 3.7.7?

Choices

 Erlang OTP 19 or newer

 Erlang OTP 20 or newer

 Erlang OTP 22 or newer

 Erlang OTP 21 or newer -- Correct answer


--------

John is working on a project and he is required to use MicroServices. Now he wants to know about
Microservices. help him to find which of the following statements are correct about the above-
mentioned context.

Statements:
1. While designing a microservice, the developer should be specific about the focal point of the
service.
2. Each microservice should be an autonomous business unit of the entire application.
3. It is cheaper than SOA and it is used to maintain different server spaces for different business
tasks.

Choices

 1 and 2 Correct answer

 2 and 3

 1 and 3

 All of these

Bob is working on a project using Microservices Architecture. He came across the term API gateway.
Which among the following best describes the acknowledged term?

Options

1. API Gateway is a server and is a multiple-entry point into the system.

2. API Gateway can aggregate the results from the microservices back to the client. API
Gateway can also translate between web protocols like HTTP, web socket, etc.

3. API Gateway is responsible for routing the request, composition, and translation of the
protocol.

4. API Gateway can provide only one client with a custom API.

Choices

 1 and 2

 2 and 3 Correct answer

 3 and 4

 1 and 4
Which of the following statements represent the disadvantages of using microservices:
1. A large group of developers is required to support this heterogeneous distributed software.
2. It is difficult to make a microservice application enterprise ready to compare to the conventional
software development model.
3. Microservice does not follow a high level of resilience in building methodology.

Choices

 1 and 2 Correct answer

 2 and 3

 1 and 3

 All of these

Which of the following rules should be considered while deploying a Microservice-oriented


architecture?

Choices

 Each microservice should be independently deployable.-- Correct answer

 All microservices should be strongly coupled with one another such that changes in one will
not affect the other.

 Each service unit of the entire application should be the largest and capable of delivering one
specific business goal.

 All of these

An organization is required to handle 0.96 million people every second. In order to control this heavy
traffic, the organization redirects all the traffic from one region to a specific server. If you are required
to perform the Y-axis scaling in this scenario to overcome this hindrance, then which of the following
actions is performed?

Choices

 Run the single server with the same application at a different time.

 Run the multiple servers with the same application at a different time.

 Run the single server with the same application at the same time.

 Run the multiple servers with the same application at the same time. --- correct
Bob is working on MicroServices. While working on an application he wants to know about
the benefits of using an API gateway. Help him to find which of the following statements are correct
for the above-mentioned context.

Statements:
1. It provides each kind of client with a specific API.
2. It decreases the errors at the same time.
3. It increases the number of round trips between the client and the application.
4. It simplifies the client code.

Choices

 1, 2, and 3

 2, 3, and 4

 1, 2, and 4--Correct answer

 1, 3, and 4

In the microservice architecture, which of the following represents the advantage of scaling?

Choices

 Performance

 Reuse

 Load distribution

 All of these --- Correct answer


In RabbitMQ, which of the following statements about the rabbitmqctl change_cluster_node_type
ram command is incorrect?

Choices

 The node must be stopped for this operation to succeed.

 The node must not be the only disc node in the cluster.

 This command can be used both locally and remotely.--- Correct answer

 The node must be restarted to work efficiently.

Which of the following mechanism of the Hystrix server microservice component is used to avoid the
failure of an application?

Choices

 Server resistant mechanism

 Server config mechanism

 Circuit breaker mechanism --Correct answer

 Circuit resistant mechanism

In RabbitMQ, which of the following is used to monitor and handle a server from a web browser?

Choices

 Management interface --Correct answer

 AMQP protocol

 Exchange

 Broker

In the microservice architecture, which of the following composite patterns is used to build one extra
layer by providing a dump layer?

Choices

 Aggregator pattern

 Chained pattern

 Proxy pattern -- Correct answer

 Branch microservice pattern


-----
In the microservice architecture, which of the following statements about the Branch microservice
pattern are correct:

Statement:
1. The client can directly communicate with the service.
2. One service can communicate with one service at a time.
3. The developer is allowed to configure service calls dynamically.

Choices

 1 and 2

 2 and 3

 1 and 3 --- Correct answer

 All of these

In the microservice architecture, which of the following components is used to provide the HTTP
resource-based API for the external configuration in the distributed system?

Choices

 Netflix Eureka Naming server

 Netflix Ribbon

 Spring Cloud config server --Correct answer

 Netflix Zuul API Gateway server

Which of the following statements about the microservice architecture is correct?

Statements:

1. It is an infrastructure-based architecture that can be divided into the smallest independent


service units.
2. It is a process of implementing Service-Oriented Architecture (SOA) by dividing the entire
application into a connection of interconnected services.

Choices

 1

 2 --Correct answer

 Both of these

 None of these

Which of the following tools about the monitoring microservices are correct:
1. Hystrix dashboard
2. Metasploit admin dashboard
3. Eureka admin dashboard
4. Spring boot admin dashboard

Choices

 1, 2, and 3

 2, 3, and 4

 1, 2, and 4

 1, 3, and 4Correct answer

In the microservice architecture, which of the following statements about the server-based load
balancing are correct:
1. It accepts the incoming network, application traffic, and distributes the traffic across the multiple
backend servers by using different methods.
2. The client chooses an IP from the list and forwards the request to the server.
3. The middle component is responsible for distributing the client requests to the server.

Choices

 1 and 2

 1 and 3 Correct answer

 2 and 3

 All of these

Mike is working on Microservice architecture. While working on an application he wants to know


about the method that is used to simulate the behavior of the particular elements in the various
component-based applications. Help him to find which of the following can suit the above-
mentioned context.
Choices

 Microservice virtualization --Correct answer

 System virtualization

 Application virtualization

 Cloud virtualization

You are developing a microservice. If all the business models need to be sub-divided into the smallest
business part as much as possible, then which of the following principles is represented in this
scenario?

Choices

 Observable principle

 Business Domain Centric principle

 High cohesive principle--Correct answer

 Automation principle

Which of the following is used by an application to communicate with a RabbitMQ broker?

Choices

 SSL/TLS

 Queued

 Channel--Correct answer

 Vhost

Which of the following principles about the monitoring microservices is correct?

Choices

 Alert on both the service and the client performance

 Monitor APIs --Correct answer

 Monitor the organizational security infrastructure

 All of these

In RabbitMQ, which of the following entities is used to route messages to different queues?
Choices

 Exchange

 Routing key

 Binding--Correct answer

 Topic

In the microservice architecture, if an application uses a Zipkin distributed tracing server, then
determine its port number.

Choices

 8761

 8888

 9411--Correct answer

 8765

Alice is required to prevent security problems in her organization. If she has worked closely with
different teams and fixed the issues caused during the detective control phase, then which of the
following defensive mechanisms is represented in this scenario?

Choices

 Deterrent control

 Correlative control --Correct answer

 Preventive control

 Detective control

Problem statement

Which of the following systems is used by the Service-Oriented Architecture (SOA) for
communication?

Choices

 Simple messaging system

 Enterprise Service Bus (ESB)--Correct answer

 Both of these

 None of these

John is working on MicroServices. While working on an application he is required to generate a view


by communicating with a model. Help him to find Which of the following types of scaling is used to
perform this action?
Choices

 X-axis scaling---Correct answer

 Y-axis scaling

 Z-axis scaling

 None of these

In the microservice architecture, which of the following statements about the Netflix Eureka Naming
server are correct?

Statements:

1. It provides the REST interface internally that can be used for communication.

2. Eureka client interacts with the Eureka server for service discovery.

Choices

 1

 2--Correct answer

 Both of these

 None of these

In the microservice architecture, which of the following statements about the API gateway are
correct:

Statements:

1. It is a server of multiple entry points into a system and is used to encapsulate the internal
system architecture.

2. It has responsibilities such as monitoring, caching, and load balancing.

3. It is responsible for the request routing, composition, and protocol translation.

Choices

 1 and 2

 2 and 3--Correct answer

 1 and 3

 All of these
In the microservice architecture, the security issue is associated with all kinds of services in the
market. If you are required to ensure the security protection for the service providers, then which of
the following actions must be performed?

Choices

 Background verification of the services that have direct access to the core part of the cloud.

 Background verification of the servers that have direct access to the core part of the cloud.

 Background verification of the clients that have direct access to the core part of the cloud.---
Correct answer

 Both 2 and 3

In the microservice architecture, which of the following modules of the Netflix Ribbon component
supports HTTP that uses the RxNetty library with the load balancing capacity?

Choices

 ribbon-eureka

 ribbon-transport --Correct answer

 ribbon-loadbalancer

 ribbon-httpclient

John is working on MicroService architecture. While working on an application he wants to know


about the Chained pattern. Help him to find which of the following statements are correct about the
above-mentioned.

Statements:
1. The client is allowed to communicate directly with the services.
2. The specific services are connected such that the output of one service will be the input of the
next service.
3. The client is blocked until the entire process is complete.

Choices

 1 and 2

 2 and 3

 1 and 3--Correct answer

 All of these

In RabbitMQ, which of the following actions is performed by the rabbitmqctl stop_app command?

Choices
 Stops a RabbitMQ application--Correct answer

 Stops a node on which RabbitMQ is running

 Stops the rabbitmqctl command line tool

 Stops all the RabbitMQ command line tools

MVC and AOP

Ben is working on a project in Java language. He used 'X' Framework in his project.'X' implements all
the basic features of a core spring framework like Inversion of Control, and Dependency Injection,
and provides an elegant solution to use it in the 'X' framework with the help
of [Link] among the following annotation doesn't include in it?

Choices

 @RequestParam

 @Controller

 @Component

Correct answer

 All the above

In Spring, you have developed a banking-based web application for which users need to sign-up their
information to log in to the website. Now, you are working on the Spring MVC validation to restrict
the input provided by the user. You are required to apply constraints on the object model by using
various annotations. For this, you wanted to implement the Bean validation API. Now, which of the
following statements about these annotations from this API are correct in this scenario:

Statements

1. The annotation @NotNull determines that the value can't be null.

2. The annotation @Size determines that the size must be equal to the specified value.

3. The annotation @Max determines that the number must be equal to or less than the
specified value.

4. The annotation @RegExp determines that the sequence follows the specified regular
expression.

Choices

 1, 2, and 3

Correct answer

 2, 3, and 4
 1, 3, and 4

 All of these

Bob is working on a project in Java language. He used 'X' Framework in his project.'X' implements all
the basic features of a core spring framework like Inversion of Control, and Dependency Injection and
provides an elegant solution to use it in the 'X' framework with the help of [Link]
among the following form tag does it include?

Choices

 submit

 table

 password

Correct answer

 All the above

Spring AOP –

Which of the following AOP framework objects can be used to execute aspect contracts in the Spring
framework?
1. JDK dynamic proxy
2. CGLIB proxy

Choices

 Only 1

 Only 2

 Both 1 and 2

Correct answer

 Neither 1 nor 2

You are working on developing a spring boot application. You are working with AOP which you know
is one of the key components of Spring Framework. How would you go about declaring an aspect?

Choices

 @AspectJ

 @[Link]

 @Declare

 @Aspect

Correct answer

You want to enable AspectJ support in your Spring application. Which of the following code snippets
should you use to achieve this?
Options

1.

Include <aop:aspectj-alpha-proxy> in the Spring configuration.

2.

Include <aop:aspectj-autoproxy> in the Spring configuration.

3.

Import cg-aspectjlib module while writing the program.

Choices

 1

 2--Correct answer

 3

 Both 1 and 3

What is Weaving in Spring AOP ?

Choices

 Weaving is the process of linking an aspect with other application types or objects to create
an advised object--Correct answer

 It is an expression that is matched with join points to determine whether advice needs to be
executed or not

 It is the process of creating an object after applying advice to the target object.

 None of these

Suppose Bob is working on developing a spring boot application. He is working with AOP which you
know is one of the key components of Spring Framework. He know AOP can work with 5 types of
advices, so when he see 6 types of advices, he know something is wrong. Determine the faulty type.

1. before

2. after

3. during

4. after-returning

5. after-throwing

6. around

Choices

 3----Correct answer
 4

 5

 6

 -----

What is an After Throwing Advice?

Choices

 Advice that could throw an exception

 Advice to be executed if a method exits by throwing an exception

Correct answer

 Advice that executes before a join point

 Spring does not provide this type of advice

Which of the following can be considered as a Join Point in Spring AOP ?

Choices

 A method being called

 An exception being thrown

 None of these

 Both of these

Correct answer

Alice is developing a spring boot application. She is currently working with AOP which she knows is
one of the key components of Spring Framework. She has a Pointcut signature and a Pointcut
Expression, then which of the following option is correct?

A - @Pointcut("execution(* name(..))")

B - private void anymethod() {}

Options:

1. A - Expression

2. B - Signature

3. A - Signature

4. B - Expression

Choices

 1--Correct answer
 2

 These are neither Pointers nor signatures

 There is no such thing as Pointer Expression and/or Signature

Which of the following are valid Spring's AOP configuration elements?

Options:

1. <aop:advisor>

2. <aop:around>

3. <aop:aspect>

4. <aop:after-returning>

Choices

 1, 2 and 3

 1, 2 and 4

 1, 3 and 4

 All of these--Correct answer


MCQ:

What is the output of the code :

[Link] [Link];

import [Link].*;

public class MyString {

public MyString(String val) {

[Link] = val;

private String val;

public static void main(String args[]) {

Map < String, Integer > map1 = new HashMap < String, Integer > ();

String str1 = new String("Java OOPs!");

String str2 = new String("Java OOPs");

[Link](str1, new Integer(10));

[Link](str2, new Integer(20));

Map < MyString, Integer > map2 = new HashMap < MyString, Integer > ();

MyString str3 = new MyString(str1);

MyString str4 = new MyString(str2);

[Link](str3, new Integer(10));

[Link](str4, new Integer(20));

[Link]([Link](str1));

[Link]([Link](str3));

}
}

Options:

1 – 10

20

2 – 20

10

3 –10

10 --Correct

4 –20

20

2. During the development of a web application using Spring Boot framework, Alice comes across the
following code written by his colleague. Which of the following is true about this code?

Code:

@RestController

@RequestMapping("/home")

public class InCon

@RequestMapping(value = "/fetch/{id}", method = [Link])

String getDynamicUriValue(@PathVariable String id)

[Link]("The ID is " + id);

return "The Dynamic URI parameter was fetched";

@RequestMapping(value = "/fetch/{id:[a-z]+}/{name}", method = [Link])

String getDynamicUriValueRegex(@PathVariable("name") String name)

[Link]("The Name is " + name);

return "Dynamic URI parameter fetched using regex";

}
}

1. A request to /home will be handled by the default() method as the annotation does not
specify any value.

2. A request to /home will be handled by the @RequestMapping method as the annotation


does not specify any value.

3. A request to /home will be handled by the @RequestMapping method as the annotation


does specify a specific value.

4. The method getDynamicUriValue() will execute for a request to


localhost:8080/home/fetch/10.

Choices

 1

 2

 3

 4 Correct answer

3. What is the output of the following Java code:

Code:

class HackerEarth {

int getValue() {

int returnValue = 10;

try {

String[] Languages = {

"Try block",

"Try block is running"

};

[Link](Languages[1]);

} catch (Exception e) {

[Link]("Catch Block :" + returnValue);

return returnValue;
} finally {

returnValue += 10;

[Link]("Finally Block :" + returnValue);

return returnValue;

public static void main(String args[]) {

HackerEarth

var = new HackerEarth();

[Link]("Main Block:" +

[Link]());

Options:

Option A: Try block is running

Finally Block :20

Main Block:20

Option B: Catch Block :10

Finally Block :20

Main Block:10

Option C:

Catch Block :10

Finally Block :20

Main Block:20

Option D- Compilation Error

Choices

 1Correct answer
 2

 3

 4

4.

Output of the following code

public class Main {

public static void main(String[] args) {

AbstractFactory factory = new CircleFactory();

Shape shape = [Link]();

[Link]([Link]());

AbstractFactory rectFactory = new RectangleFactory();

Shape rectShape = [Link]();

[Link]([Link]());

interface Shape {

double getArea();

class Circle implements Shape {

double radius;

Circle(double radius) {

[Link] = radius;

@Override

public double getArea() {

return [Link] * radius * radius;


}

class Rectangle implements Shape {

double width, height;

Rectangle(double width, double height) {

[Link] = width;

[Link] = height;

@Override

public double getArea() {

return width * height;

interface AbstractFactory {

Shape createShape();

class CircleFactory implements AbstractFactory {

@Override

public Shape createShape() {

return new Circle(0);

class RectangleFactory implements AbstractFactory {

@Override

public Shape createShape() {


return new Rectangle(1, 2);

Option:

A: 1.0

2.0

B: 0.0

1.0

C: 0.0

2.0

D: 0

Correct option – C

5 . Output of the following code :

public class Main {

public static void main(String[] args) {

Wheel carWheel = new Wheel();

Car car = new Car(carWheel);

[Link]();

class Wheel {

void rotate() {

[Link]("Wheel rotated");

}
class Car {

Wheel wheel;

Car(Wheel w) {

wheel = w;

void move() {

[Link]();

[Link]("Car moving");

Options:

1-- Wheel rotated

Car moving

2 -- Car moving

Wheel rotated

3 -- No Output

Correct – Option 1

6 . Alice is working on developing a spring boot application. She wants to use Spring Cloud bus as it
links nodes of a distributed system. She and her colleague know that as long as Spring Cloud Bus
AMQP and RabbitMQ are on the classpath any Spring Boot application will try to contact a RabbitMQ
server on the default value of [Link]. There is however a small hitch in
execution. Her colleague seems to have forgotten the address. What is the default value of
[Link]?

Choices

 localhost:3448

 localhost:6572

 localhost:5672 --Correct answer


 localhost:8000

7 . Output of the code:

import [Link];

import [Link];

public class Main {

public static void main(String[] args) {

Parent obj = new Child();

try {

[Link]();

} catch (IOException e) {

[Link]("IOException caught");

class Parent {

void display() throws IOException {

[Link]("Parent");

class Child extends Parent {

void display() throws FileNotFoundException {

[Link]("Child");

Options:

 Parent

 Child-------Correct answer

 IOException caught

 Compilation Error
8. A Twilio Voice application built with Java sends a request to the server using the Twilio Voice API.
Unfortunately, the server is either unreachable or encountering issues, as indicated by the response
"Bad Gateway." To address this, the Java developer handling the Twilio Voice API needs to adeptly
handle this situation and identify the appropriate exception code to effectively manage it within their
application's logic. What is the suitable exception code to address the scenario mentioned?

Choices

• EXCEPTION_BAD_GATEWAY---Correct answer

• EXCEPTION_BAD_GATEWAY_TIMEOUT

• EXCEPTION_FORBIDDEN

• EXCEPTION_FORBIDDEN_TIMEOUT

9. What is the value of the following expression?

Expression

int x = 3;

int y = 4;

double z = 2.5;

double result = x * y + z;

Options

• 19.5

• 14.5 --Correct answer

• 20

• None of the above

10 .

Ben is using the following code snippet in his application when working with List in java.
What will be the output ??

Option

1. Compilation error – correct

2. Prints “1.2.4”

3. Prints “[Link]”

4. Prints “2.4,6,8”

MCQ:

What is the output of the code :

[Link] [Link];

import [Link].*;

public class MyString {

public MyString(String val) {

[Link] = val;

private String val;

public static void main(String args[]) {

Map < String, Integer > map1 = new HashMap < String, Integer > ();

String str1 = new String("Java OOPs!");

String str2 = new String("Java OOPs");

[Link](str1, new Integer(10));

[Link](str2, new Integer(20));


Map < MyString, Integer > map2 = new HashMap < MyString, Integer > ();

MyString str3 = new MyString(str1);

MyString str4 = new MyString(str2);

[Link](str3, new Integer(10));

[Link](str4, new Integer(20));

[Link]([Link](str1));

[Link]([Link](str3));

Options:

1 – 10

20

2 – 20

10

3 –10

10 --Correct

4 –20

20

2. During the development of a web application using Spring Boot framework, Alice comes across the
following code written by his colleague. Which of the following is true about this code?

Code:

@RestController

@RequestMapping("/home")

public class InCon

@RequestMapping(value = "/fetch/{id}", method = [Link])

String getDynamicUriValue(@PathVariable String id)

[Link]("The ID is " + id);


return "The Dynamic URI parameter was fetched";

@RequestMapping(value = "/fetch/{id:[a-z]+}/{name}", method = [Link])

String getDynamicUriValueRegex(@PathVariable("name") String name)

[Link]("The Name is " + name);

return "Dynamic URI parameter fetched using regex";

1. A request to /home will be handled by the default() method as the annotation does not
specify any value.

2. A request to /home will be handled by the @RequestMapping method as the annotation


does not specify any value.

3. A request to /home will be handled by the @RequestMapping method as the annotation


does specify a specific value.

4. The method getDynamicUriValue() will execute for a request to


localhost:8080/home/fetch/10.

Choices

 1

 2

 3

 4 Correct answer

3. What is the output of the following Java code:

Code:

class HackerEarth {

int getValue() {

int returnValue = 10;

try {
String[] Languages = {

"Try block",

"Try block is running"

};

[Link](Languages[1]);

} catch (Exception e) {

[Link]("Catch Block :" + returnValue);

return returnValue;

} finally {

returnValue += 10;

[Link]("Finally Block :" + returnValue);

return returnValue;

public static void main(String args[]) {

HackerEarth

var = new HackerEarth();

[Link]("Main Block:" +

[Link]());

Options:

Option A: Try block is running

Finally Block :20

Main Block:20

Option B: Catch Block :10

Finally Block :20

Main Block:10
Option C:

Catch Block :10

Finally Block :20

Main Block:20

Option D- Compilation Error

Choices

 1Correct answer

 2

 3

 4

4.

Output of the following code

public class Main {

public static void main(String[] args) {

AbstractFactory factory = new CircleFactory();

Shape shape = [Link]();

[Link]([Link]());

AbstractFactory rectFactory = new RectangleFactory();

Shape rectShape = [Link]();

[Link]([Link]());

interface Shape {

double getArea();

class Circle implements Shape {

double radius;
Circle(double radius) {

[Link] = radius;

@Override

public double getArea() {

return [Link] * radius * radius;

class Rectangle implements Shape {

double width, height;

Rectangle(double width, double height) {

[Link] = width;

[Link] = height;

@Override

public double getArea() {

return width * height;

interface AbstractFactory {

Shape createShape();

class CircleFactory implements AbstractFactory {

@Override
public Shape createShape() {

return new Circle(0);

class RectangleFactory implements AbstractFactory {

@Override

public Shape createShape() {

return new Rectangle(1, 2);

Option:

A: 1.0

2.0

B: 0.0

1.0

C: 0.0

2.0

D: 0

Correct option – C

5 . Output of the following code :

public class Main {

public static void main(String[] args) {

Wheel carWheel = new Wheel();

Car car = new Car(carWheel);


[Link]();

class Wheel {

void rotate() {

[Link]("Wheel rotated");

class Car {

Wheel wheel;

Car(Wheel w) {

wheel = w;

void move() {

[Link]();

[Link]("Car moving");

Options:

1-- Wheel rotated

Car moving

2 -- Car moving

Wheel rotated

3 -- No Output

Correct – Option 1
6 . Alice is working on developing a spring boot application. She wants to use Spring Cloud bus as it
links nodes of a distributed system. She and her colleague know that as long as Spring Cloud Bus
AMQP and RabbitMQ are on the classpath any Spring Boot application will try to contact a RabbitMQ
server on the default value of [Link]. There is however a small hitch in
execution. Her colleague seems to have forgotten the address. What is the default value of
[Link]?

Choices

 localhost:3448

 localhost:6572

 localhost:5672 --Correct answer

 localhost:8000

7 . Output of the code:

import [Link];

import [Link];

public class Main {

public static void main(String[] args) {

Parent obj = new Child();

try {

[Link]();

} catch (IOException e) {

[Link]("IOException caught");

class Parent {

void display() throws IOException {

[Link]("Parent");

class Child extends Parent {

void display() throws FileNotFoundException {

[Link]("Child");

}
}

Options:

 Parent

 Child-------Correct answer

 IOException caught

 Compilation Error

8. A Twilio Voice application built with Java sends a request to the server using the Twilio Voice API.
Unfortunately, the server is either unreachable or encountering issues, as indicated by the response
"Bad Gateway." To address this, the Java developer handling the Twilio Voice API needs to adeptly
handle this situation and identify the appropriate exception code to effectively manage it within their
application's logic. What is the suitable exception code to address the scenario mentioned?

Choices

• EXCEPTION_BAD_GATEWAY---Correct answer

• EXCEPTION_BAD_GATEWAY_TIMEOUT

• EXCEPTION_FORBIDDEN

• EXCEPTION_FORBIDDEN_TIMEOUT

9. What is the value of the following expression?

Expression

int x = 3;

int y = 4;

double z = 2.5;

double result = x * y + z;

Options

• 19.5

• 14.5 --Correct answer

• 20
• None of the above

10 .

Ben is using the following code snippet in his application when working with List in java.

What will be the output ??

Option

1. Compilation error – correct

2. Prints “1.2.4”

3. Prints “[Link]”

4. Prints “2.4,6,8”

You might also like