Java Interview question-5
Java || SpringBoot ||AWS
Question 41: How is rest API secured?
There are several ways to secure a REST API:
Use HTTPS: This ensures that all data transferred between the client and the server is encrypted.
Use OAuth: OAuth is an authorization framework that allows a user to grant a third-party application access to their resources without sharing their passwords.
Use JSON Web Tokens (JWT): A JWT is a JSON object that is used to securely transmit information between parties. The information can be verified and trusted, because it is digitally signed.
Use API keys: An API key is a unique string that is used to authenticate API requests. The key is usually passed in the HTTP header of an API request.
Use basic authentication: In this method, the client sends an HTTP request with a username and password for authentication.
Use multi-factor authentication: This method combines two or more authentication methods for added security.
It is important to choose an appropriate security measure based on the sensitivity of the data being transferred and the level of trust between the client and the server.
Question 42: What are Composition and Aggregation with examples?
A composition is a strong form of association that represents a “has-a” relationship between two objects. It is used to represent a part-whole or whole-part relationship, where the whole object contains the part object and has sole responsibility for its lifetime.
For example, a Car class might be composed of a Wheel class, where a car "has-a" set of wheels. If the car is destroyed, the wheels are also destroyed, because they cannot exist independently of the car.
class Wheel {
// ...
}
class Car {
private final List<Wheel> wheels = new ArrayList<>();
// ...
}
Aggregation is a weaker form of association that represents a “has-a” relationship between two objects. It is used to represent a loose coupling between two objects, where the lifetime of the contained object is not directly tied to the lifecycle of the containing object. For example, a Department class might be aggregated by a Employee class, where an employee "has-a" a department. If the employee leaves the company, the department still exists and can have other employees.
class Department {
// ...
}
class Employee {
private Department department;
// ...
}
Question 43: What is a Concurrent Modification exception, and how to prevent that?
A ConcurrentModificationException is a runtime exception that occurs when an application concurrently modifies an object in a way that violates the object’s concurrent modification rules.
This exception can occur when multiple threads are attempting to modify an object concurrently, and the object is not designed to be modified concurrently. It can also occur when a single thread is iterating over a collection and modifies the collection in some way, such as by adding or removing an element, while the iteration is in progress.
Here is an example of how a ConcurrentModificationException will be thrown:
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.equals("a")) {
list.remove(s); // This will throw a ConcurrentModificationException
}
}
To avoid ConcurrentModificationExceptions, you can:
Use thread-safe collections such as
VectororCopyOnWriteArrayListinstead of non-thread-safe collections likeArrayList.Use synchronization to ensure that only one thread can modify the collection at a time.
Use an iterator that supports the
remove()(iterator.remove()) method and call that method instead of modifying the collection directly.
Question 44: Cohesion vs Coupling, Explain that?
Cohesion and coupling are two measures of the design quality of a software system.
Cohesion refers to the degree to which the elements within a single module or component work together to achieve a single, well-defined purpose. A highly cohesive system is one in which all the elements within a module are strongly related and work together towards a common goal. High cohesion is generally seen as a desirable characteristic of a software system, as it makes the system easier to understand and maintain.
Coupling, on the other hand, refers to the degree to which one module or component depends
Question 45: Do you know Distributed tracing? what is the use of it?
Distributed tracing is a technique used to track the progress of a request as it travels through a distributed system. It allows you to see how different components of the system interact with each other and can help you identify bottlenecks and other issues that may be affecting the performance of your application.
In Spring Boot, you can use the Spring Cloud Sleuth library to add distributed tracing to your application. Sleuth integrates with popular tracing systems such as Zipkin, Jaeger, and Elastic APM to collect and display trace data.
To use Sleuth in your Spring Boot application, you will need to:
Add the Spring Cloud Sleuth starter dependency to your project.
Configure your tracing system of choice (e.g. Zipkin, Jaeger, etc.).
Annotate your service beans with the
@Traceannotation to enable tracing for individual methods.
Sleuth will automatically add trace information to your application logs, which can then be collected and displayed by your tracing system. You can also use the Sleuth API to manually add trace information to your application code.
Question 46: Do you follow any standards to build a rest service?
There are several standards that you should follow when building a RESTful service:
- Use HTTP methods (e.g. GET, POST, PUT, DELETE) appropriately:
GET should be used to retrieve data.
POST should be used to create new data.
PUT should be used to update existing data.
DELETE should be used to delete data.
Use HTTP status codes correctly:
2xx status codes (e.g. 200, 201) should be used to indicate success.
4xx status codes (e.g. 400, 401) should be used to indicate an error that occurred due to the client.
5xx status codes (e.g. 500, 501) should be used to indicate an error that occurred on the server.
2. Use a consistent and logical URL structure.
Use appropriate HTTP headers (e.g. Content-Type, Authorization).
Allow for flexible content negotiation (e.g. support different formats such as JSON and XML).
Follow the principles of REST (e.g. use hypermedia, cache resources, and design for visibility and reliability).
It’s also a good idea to design your RESTful service in a way that is easy for developers to use and understand and follows common conventions for building APIs.
Question 47: Do you know the 12-factor methodology to build a microservice?
The 12-factor methodology is a set of best practices for building software-as-a-service (SaaS) applications that are:
Build for scale from the start
Use the declarative format for setup and deploy
Strictly separate build and run stages
Export services via port binding
Use a dependency injection
Store config in the environment
Treat logs as event streams
Run as a single process
Disposability
Maximize robustness with fast startup and graceful shutdown
Keep development, staging, and production as similar as possible
Treat backing services as attached resources
The goal of the 12-factor methodology is to provide a set of guidelines for building software that is easy to scale, maintain, and deploy. It is particularly well-suited for building microservices, which are modular, independently deployable units of software that work together to form a larger application.
Question 48: What is a pod in Kubernetes?
In Kubernetes, a pod is the basic unit of deployment. It is the smallest deployable unit in the Kubernetes object model.
A pod consists of one or more containers, such as Docker containers, and is used to host the containers that make up an application. The containers in a pod share the same network namespace and can communicate with each other using localhost. Pods are also co-located and co-scheduled, which means that they are scheduled to run on the same node and they share the same resources (e.g. CPU, memory).
Pods are intended to be ephemeral, meaning that they are expected to be terminated and replaced over time. This allows for easy scaling and rolling updates of applications.
Pods are created and managed by the Kubernetes control plane, which is responsible for ensuring that the desired number of replicas of a pod are running at any given time.
Question 49: Write a Program to print only numbers from alphanumeric char array using stream API in java-8.
package learning;
import java.util.Arrays;
public class OnlyNumberFromAlphanumeric {
public static void main(String[] args) {
Character[] alphanumericArray = {'a', '1', 'b', '2', 'c'};
printOnlyNumberFromAlphanumeric(alphanumericArray);
}
private static void
printOnlyNumberFromAlphanumeric(Character[] charArray) {
Arrays.stream(charArray)
.filter(Character::isDigit)
.forEach(System.out::println);
}
}
/**
* Output:
* 1
* 2
*/
Question 50: Write a program to convert string to integer in java without any API?
package learning;
public class ConvertStringToInteger {
public static void main(String[] args) {
System.out.println(convertStringToInteger("12345"));
}
private static Integer convertStringToInteger(String str) {
int result = 0;
for (int i = 0; i < str.length(); i++) {
result = result * 10 + str.charAt(i) - '0';
}
return result;
}
}
/**
* Output: 12345
*/
The algorithm works by iterating through each character in the string, starting from the leftmost character. For each character, it multiplies the current result by 10 and adds the numeric value of the character. The numeric value of a character is obtained by subtracting the ASCII value of the character ‘0’ from the ASCII value of the character. This is equivalent to calling the Character.getNumericValue() method, which returns the integer value of a digit character.
For example, if the string is “12345”, the first iteration will calculate result = 0 * 10 + 1, the second iteration will calculate result = 1 * 10 + 2, and so on. After all iterations are complete, the final value of result will be 12345
