Posted by: lrrp | May 7, 2024

Tricky Core Java Questions – 1

Explain what does this program print? Explain the code functionality.

Integer i = 260;
Integer j = 260;
if(i == j) {
System.out.println(true);
else {
System.out.println(false);
}

This program will print false. Let’s explain why:

In Java, for objects of the Integer class (and other wrapper classes like Long, Short, etc.), Java maintains a pool of objects for certain integer values within a specific range (typically between -128 and 127). This range is called the “cached” or “interned” range.

When you create an Integer object using autoboxing or by directly assigning an integer value within this range, Java will reuse an existing object from the pool if one exists. This means that if you create two Integer objects with the same value within this range, they will actually reference the same object in memory.

However, for values outside this cached range, Java will create a new Integer object for each value, even if they have the same numerical value. This means that two Integer objects with values outside the cached range will not reference the same object in memory.

In the above-mentioned code:

  • i and j are both assigned the value 260.
  • Since 260 is outside the range of -128 to 127, Java will create new Integer objects for both i and j, rather than reusing cached objects.
  • Therefore, i and j will reference different Integer objects, even though they have the same value.

As a result, when comparing i == j, the condition will be evaluated to false because i and j refer to different object instances.

So, the program will print false.

Posted by: lrrp | May 7, 2024

Spring Boot Tricky Questions -9

What are the advantages when using YAML for Spring Boot?

  • Support for maps, lists, and scalar types
  • Can include several profiles in the same file
  • More clarity and better readability
  • Perfect for hierarchical configuration data, which is also represented in a better, more readable format
  • All of above

Let’s dissect each statement to explain the advantages of using YAML for Spring Boot:

  1. Support for maps, lists, and scalar types:
    • YAML (YAML Ain’t Markup Language) is a human-readable data serialization format that supports various data structures such as maps (key-value pairs), lists (arrays), and scalar types (strings, numbers, booleans).
    • In the context of Spring Boot, YAML allows developers to represent complex configuration data in a more intuitive and concise manner compared to other formats like XML or properties files.
    • With YAML, you can easily define hierarchical configurations, organize data into structured formats, and maintain readability, making it ideal for Spring Boot application configuration.
  2. Can include several profiles in the same file:
    • This statement is TRUE. YAML supports the concept of profiles, which allows you to define configuration settings for different environments (such as development, testing, and production) within the same file.
    • By using YAML profiles, you can maintain a single configuration file for multiple environments, reducing duplication and simplifying management.
    • Profiles in YAML provide a convenient way to override or extend configuration settings based on the active profile, enhancing flexibility and maintainability.
  3. More clarity and better readability:
    • YAML is known for its readability and simplicity. Its indentation-based syntax makes it easy to read and understand, especially for developers familiar with Python or similar languages.
    • Compared to XML or properties files, YAML offers a more concise and human-friendly representation of data, reducing the cognitive load and improving maintainability.
    • With YAML, you can represent complex data structures in a natural and intuitive way, leading to clearer and more readable configuration files.
  4. Perfect for hierarchical configuration data, which is also represented in a better, more readable format:
    • YAML’s hierarchical nature and indentation-based structure make it well-suited for representing complex configuration data.
    • Hierarchical configurations, such as nested properties or multi-level settings, can be expressed elegantly in YAML, making it easy to organize and manage configuration data.
    • Additionally, YAML’s compact syntax and emphasis on readability contribute to a better understanding of the configuration, enhancing developer productivity and reducing the likelihood of errors.

In summary, the advantages of using YAML for Spring Boot configuration are:

  • Support for maps, lists, and scalar types
  • Can include several profiles in the same file
  • More clarity and better readability
  • Perfect for hierarchical configuration data, which is also represented in a better, more readable format

Hence the answer should be All of the above

Posted by: lrrp | May 7, 2024

Spring Boot Tricky Questions -8

Which of the following are TRUE about Spring Boot? (Select all that apply.)

  • Java code generation
  • Convenient dependency descriptors to load transitive dependencies
  • Auto-configuration of the Spring Framework and third libraries
  • Support both Java-based and YAML for Spring application context configuration
  • Support for Jetty and Undertow as embedded containers

Let’s break down each statement and identify whether it is TRUE about Spring Boot:

  1. Java code generation:
    • This statement is generally FALSE. Spring Boot focuses on convention over configuration and minimizing boilerplate code. While it does provide some utilities for generating projects with starter templates using Spring Initializr, it doesn’t primarily focus on code generation within the application itself.
  2. Convenient dependency descriptors to load transitive dependencies:
    • This statement is TRUE. Spring Boot simplifies dependency management by providing convenient dependency descriptors (in the form of Maven or Gradle build files) to load transitive dependencies automatically. You typically only need to declare direct dependencies, and Spring Boot takes care of resolving their transitive dependencies.
  3. Auto-configuration of the Spring Framework and third-party libraries:
    • This statement is TRUE. Spring Boot provides auto-configuration, which automatically configures the Spring Framework and third-party libraries based on the dependencies present in the classpath. It scans the classpath for certain classes, libraries, and properties and configures beans accordingly, reducing the need for explicit configuration.
  4. Support both Java-based and YAML for Spring application context configuration:
    • This statement is TRUE. Spring Boot supports both Java-based configuration (using annotations like @Configuration) and YAML configuration for defining the Spring application context. This flexibility allows developers to choose the configuration style that best suits their preferences and the requirements of their application.
  5. Support for Jetty and Undertow as embedded containers:
    • This statement is TRUE. Spring Boot provides support for multiple embedded servlet containers, including Jetty and Undertow, allowing you to run Spring Boot applications without deploying them to a standalone server. You can choose the embedded container that best fits your application’s requirements.

In summary, the TRUE statements about Spring Boot are:

  • Convenient dependency descriptors to load transitive dependencies
  • Auto-configuration of the Spring Framework and third-party libraries
  • Support both Java-based and YAML for Spring application context configuration
  • Support for Jetty and Undertow as embedded containers
Posted by: lrrp | May 7, 2024

Spring Boot Tricky Questions -7

You are a developer using Spring Boot to develop the system. You need to add an external Jar library. How can you do it?

  • Install Maven in the local repository.
  • Put that Jar file into the resources folder and use Maven to load it with systemPath.
  • Set ‘includeSystemScope’ to true.
<plugin>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
  • All of above

Let’s break down each option and evaluate its correctness in the context of adding an external JAR library to a Spring Boot project:

  1. Install Maven in the local repository:
    • This statement is incorrect. Maven itself doesn’t need to be installed in the local repository. Maven is a build automation tool and dependency management tool used in Java projects. The local repository is a directory on your machine where Maven stores project dependencies. Maven itself is installed separately on your system and doesn’t need to be installed within the local repository.
  2. Put that JAR file into the resources folder and use Maven to load it with systemPath:
    • This statement is partially correct but not the best practice.
    • While you can place the JAR file in the resources folder and use Maven to load it with the systemPath, this approach is not recommended. It bypasses Maven’s dependency management and makes it difficult to manage dependencies across different environments or share the project with other developers.
  3. Set ‘includeSystemScope’ to true:
    • This statement is incorrect. There is no configuration option named ‘includeSystemScope’ in the Spring Boot Maven plugin or in Maven itself. Therefore, this option is invalid.
  4. Use Maven plugin configuration to include the system scope:
    • This statement is incorrect. The provided XML configuration is not valid for adding an external JAR library to a Spring Boot project. Additionally, the ‘includeSystemScope’ configuration is not a valid configuration option in Maven.
  5. All of the above:
    • This option cannot be correct because several of the statements are incorrect or inappropriate for adding an external JAR library to a Spring Boot project.

Correct Approach:

The correct approach for adding an external JAR library to a Spring Boot project is to include it as a Maven dependency in the project’s pom.xml file. You can specify the dependency coordinates (groupId, artifactId, version) in the pom.xml, and Maven will automatically download and manage the JAR file for you.

Here’s an example of how to add a dependency in pom.xml:

<dependency>
    <groupId>com.example</groupId>
    <artifactId>external-library</artifactId>
    <version>1.0.0</version>
</dependency>

This approach ensures that Maven manages the dependency resolution and simplifies dependency management across different environments and for other developers working on the project.

Therefore, none of the options provided are correct. The correct approach is to declare the external JAR library as a Maven dependency in the pom.xml file.

Posted by: lrrp | May 7, 2024

Spring Boot Tricky Questions -6

You are using Spring Boot to implement APIs for an application. What is TRUE about @RestController annotation?

None of above

@RestController is treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default

@RestController annotation is itself annotated with @Controller and @ResponseBody.

@RestController is processed if an appropriate HandlerMapping – HandlerAdapter pair is configured

All of above

Let’s break down each option and identify which one is TRUE about the @RestController annotation in Spring Boot:

  1. “None of the above”:
    • This option suggests that none of the statements are correct, but we need to evaluate each statement to determine its accuracy.
  2. “@RestController is treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default”:
    • This statement is TRUE.
    • When a class is annotated with @RestController, it’s essentially a specialized version of @Controller.
    • @RestController combines the functionality of @Controller and @ResponseBody.
    • Therefore, any method inside a @RestController class is considered as if it has @ResponseBody annotation, meaning the return value of the method is automatically serialized into JSON or XML and included in the HTTP response body.
  3. “@RestController annotation is itself annotated with @Controller and @ResponseBody”:
    • This statement is TRUE.
    • Internally, the @RestController annotation is annotated with @Controller and @ResponseBody.
    • This is why it provides the behavior described in the previous option.
  4. “@RestController is processed if an appropriate HandlerMapping – HandlerAdapter pair is configured”:
    • This statement is TRUE.
    • In Spring MVC, the @RestController annotation is processed by the DispatcherServlet, which maps incoming requests to appropriate handler methods.
    • The DispatcherServlet relies on HandlerMapping to determine which controller to invoke and HandlerAdapter to execute the controller’s method.
    • Therefore, for @RestController to be processed, the appropriate HandlerMapping and HandlerAdapter must be configured in the Spring application context.

Based on the evaluation, the TRUE statement about the @RestController annotation in Spring Boot is:

  • “@RestController is treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default”
  • “@RestController annotation is itself annotated with @Controller and @ResponseBody”
  • “@RestController is processed if an appropriate HandlerMapping – HandlerAdapter pair is configured”

So, the correct option is “All of the above.”

For simple, direct communication, I would use the Rest Template, which allows services to send requests and receive responses like a two-way conversation.

For more complex interactions, especially when dealing with multiple services, I would choose Feign Client. Feign Client simplifies declaring and making web service clients, making the code cleaner and the process more efficient.

For asynchronous communication, where immediate responses aren’t necessary, I would use message brokers like RabbitMQ or Kafka. These act like community boards, where services can post messages that other services can read and act upon later. This approach ensures a robust, flexible communication.

eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

eureka.client.register-with-eureka=false

We set this to false when the service is itself a Eureka server. The default value of this property is true. When a service is not an Eureka server(normal microservice), we don’t need to set this property as it is true by default. Basically, this property is used to register a service with the Eureka server. When it is an Eureka Server we must set it to false because the Eureka server itself can’t be registered.

eureka.client.fetch-registry=false

If one microservice wants to communicate with another microservice by using Eureka then inside the microservice we should add this property (eureka.client.fetch-registry) and set it to true. It also means that the service is discoverable to other services via the Eureka server. But, inside the Eureka Server, we should include this property with the value false. Because the Eureka server will never try to fetch the registry as it is itself having a registry.

One Microservice can find and communicate with other Microservice using the Registration with Eureka only. This concept is combinedly called Service Registry and Discovery. It becomes possible with the help of ‘Registry and Discovery Server (R&D Server) i.e. Netflix Eureka.

Service Registry is the process of registering a microservice with Eureka Server. In simple words, it acts as a kind of database that stores the details of all microservices involved in the entire application. When it gets published by Eureka Server, other Microservices can discover it for further communication.

Although, Eureka Server is itself a microservice. To enable the service registry capabilities, we apply annotation @EnableEurekaServer on the top of the Application’s main class. Moreover, once we apply Spring Cloud’s annotation @EnableEurekaServer, other microservices can also register here and communicate with each other via service discovery.

Service Discovery is the process of discovering other microservices in the network to make intra-communication happen. However, a microservice first connects with Eureka to discover other microservices to communicate with each other. Using the Service Discovery concept, one microservice can discover another microservice and connect with the same via Eureka Server.

Spring Cloud: Spring Cloud is a framework designed to build microservices-based applications quickly. It can help developers with service configurations, service discovery, circuit-breaking, load-balancing, distributed tracing & logging, and monitoring, etc. Basically, Spring Cloud is the technology/framework that implements Microservices. In simple words, we can develop a Microservices-based application with the help of Spring Cloud.

Spring Boot:  Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can just run. Every Microservice internally supports all Spring boot concepts and Integrations such as MQs, Batch, Email, Camel, etc. It also supports DB operations using Spring Data JPA.

Below is the list of Spring Cloud projects that we generally use while developing a microservices-based Java Application. As the new development is always going on, therefore this list is not fixed. In the future, some projects may go out and some other new projects may come in.

  1. Spring Cloud Netflix Eureka:
    • Eureka provides service registry and discovery capabilities, allowing microservices to register themselves and discover other services in the system.
    • Microservices can dynamically locate and communicate with each other without hardcoding hostnames or port numbers.
  2. Spring Cloud OpenFeign:
    • OpenFeign is a declarative HTTP client that simplifies the process of making HTTP requests to other microservices.
    • It integrates seamlessly with service discovery mechanisms like Eureka and supports load balancing and fault tolerance.
  3. Spring Cloud Config Server:
    • Config Server provides a centralized location for storing and managing configuration properties for microservices.
    • Microservices can retrieve their configuration from the Config Server at runtime, enabling centralized configuration management.
  4. Spring Cloud Gateway:
    • Gateway is an API gateway that serves as the entry point for clients to access microservices.
    • It provides routing, filtering, and load balancing capabilities, as well as support for cross-cutting concerns like authentication and rate limiting.
  5. Spring Cloud Sleuth:
    • Sleuth provides distributed tracing capabilities for microservices, allowing developers to trace requests as they flow through the system.
    • It generates unique trace and span IDs for each request and integrates with tools like Zipkin for visualization and analysis.
  6. Spring Cloud Zipkin:
    • Zipkin is a distributed tracing system that collects and aggregates tracing data from microservices.
    • It provides visualization tools to track the flow of requests across multiple services and identify performance bottlenecks and issues.
  7. Spring Cloud Circuit Breaker:
    • Spring Cloud Circuit Breaker provides a common abstraction for implementing circuit breakers in microservices.
    • It supports various circuit breaker implementations such as Netflix Hystrix, Resilience4j, and Sentinel.
  8. Spring Cloud Stream:
    • Stream provides support for building event-driven microservices by abstracting away the complexities of messaging middleware.
    • It simplifies the development of message-driven microservices and integrates with messaging systems like Apache Kafka and RabbitMQ.
  9. Spring Cloud Security:
    • Spring Cloud Security provides authentication and authorization mechanisms for microservices.
    • It integrates with Spring Security to secure microservices endpoints and enforce access control policies.

By leveraging these Spring Cloud projects, developers can build robust, scalable, and resilient microservices architectures that are well-suited for cloud-native applications.

Older Posts »

Categories