Java, Microservices, Spring Boot and Cloud Interview questions for MNCs

Java, Microservices, Spring Boot and Cloud Interview questions for MNCs

Table of Contents

1. Tell some HTTP response codes.

HTTP status codes has five classes defined by the IANA standard:

  1. 1xx- Informational
  2. 2xx- Success
  3. 3xx- Redirection
  4. 4xx- Client error
  5. 5xx- Server error

List of status code with their meaning are:

  • 100 Continue
  • 101 Switching Protocols
  • 200 OK
  • 201 Created
  • 202 Accepted
  • 203 Non-authoritative Information
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content
  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found
  • 303 See Other
  • 304 Not Modified
  • 305 Use Proxy
  • 306 Unused
  • 307 Temporary Redirect
  • 400 Bad Request
  • 401 Unauthorized
  • 402 Payment Required
  • 403 Forbidden
  • 404 Not Found
  • 405 Method Not Allowed
  • 406 Not Acceptable
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Request Entity Too Large
  • 414 Request-url Too Long
  • 415 Unsupported Media Type
  • 417 Expectation Failed
  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported

2. What are circuit breakers?

A circuit breaker is very important in microservice architecture to handle failure in microservices. Now it is widely implemented both as a library and as a pattern embedded in the service and client modules.

3. What is Feign Client?

The Feign is a declarative web service (HTTP client) developed by Netflix as an abstraction over REST-based calls. With the help of feign client, microservices can communicate with each other, but developers don’t have to bother about REST internal details.

To use Feign client we have to create an interface and annotate it with @FeignClient annotation. It provides pluggable annotation support, including Feign annotations and JAX-RS annotations.

4. What is scalability?

Scalability or Cloud scalability in the cloud represents the ability to increase or decrease IT resources as per need to meet changing demand.

Basically, the Idea behind scalability is every application or piece of infrastructure can be expanded to handle the increased load. Suppose you have launched your web application. Now your web application gets featured on big and famous websites. As you have featured your website so there is high chance of increasing the number of visitors.

Now Suddenly visitors started coming on your website. can your current infrastructure handle the traffic? Having a scalable web application ensures that if the traffic and visitors increased on website, we will scale up to handle the load and not crash. Crashing (or even just slow) pages leave your users unhappy and your app with a bad reputation.

Scalability can apply on these 4 components:

  1. Disk I/O
  2. Memory
  3. Network I/O
  4. CPU

There are two types of scaling

  1. Horizontal Scaling
  2. Vertical Scaling

5. How would you design a microservice that uses restapis and db?

6. How do you provide authentication /authorization?

With the help of Spring Security we can provide authentication /authorization. Spring Security is really just a bunch of servlet filters that help you add authentication and authorization to your web application.

Authentication basically includes username and password check.

Authorization checks the permissions of an authenticated user. It confirms whether you have the capability to access a particular area of application or not.

7. Differences between a microservice and a monolithic architecture.

  • Monolithic architecture is one large system or we can say that one code base whereas microservice architecture is an independent module based on business functionality.
  • Monolithic architecture is very complex to scale whereas microservice architecture is very easy to scale.
  • In Monolithic architecture, we have one database shared with the whole application. But in a microservice architecture, each service or module has its own database.
  • In Monolithic architecture, as the codebase is large it makes IDE slow and build time gets increases. Whereas in Microservice architecture each project is independent and its size are also small. As Its size are small it takes less build and development time.

8. Is Try catch within try block possible?

Yes, we can declare a try-catch block within another try-catch block, this is called a nested try-catch block.

Syntax :

try {
   statement 1;
   statement 2;
   try {
      statement 3;
      statement 4;
   }
   catch(Exception e) {
      // catch the corresponding exception  
   }  
}
catch(Exception e) {
   // catch the corresponding exception
}

Example Program of nested try catch

import java.io.*;
public class Main {
   public static void main (String args[]) throws IOException {
    int n = 10, result = 0;
      try { 
         FileInputStream fis = null;
         fis = new FileInputStream (new File (args[0]));
         try { 
            result = n/0;
            System.out.println("The result is"+result);
         } 
         catch(ArithmeticException e) { 
            System.out.println("Division by Zero");
         }
      }
      catch (FileNotFoundException e) {
         System.out.println("File was not found");
      }
      catch(ArrayIndexOutOfBoundsException e) { 
         System.out.println("Array Index Out Of Bounds Exception occured ");
      }
      catch(Exception e) { // outer catch block
         System.out.println("Exception occured"+e);
      }
   }
}

Output:

Array Index Out Of Bounds Exception occured

9. What are store procedures?

A stored procedure is a prepared SQL code that you can save and reused it later over and over again. It is the best way to utilize and reuse the SQL query that you write over and over again. Just save such query as a stored procedure, and then just call it to execute it.

You can also pass parameters to a stored procedure, so that the stored procedure can act based on the parameter value(s) that is passed.

Syntax of Stored Procedure

CREATE PROCEDURE procedure_name
AS
sql_statement
GO;

Execute a Stored Procedure

EXEC procedure_name;

Example

CREATE PROCEDURE SelectAllCustomers
AS
SELECT * FROM Customers
GO;

Execute the stored procedure above as follows

EXEC SelectAllCustomers;

10. How many types of indices are there in a database?

  1. Clustered Index
  2. Non-Clustered Index
  3. Column Store Index
  4. Filtered Index
  5. Hash Index
  6. Unique Index

11. Challenges of choosing a communication way(restful, soap, rpc)?*

12. Spring Boot –  annotations.

13. What are some Challenges in Agile.

Some Agile challenges are mentioned below

  • Selecting the right Agile methodology
  • Sometimes communication can cause bigger challenges in the execution
  • Setting the agile values and principles
  • Assessing interdependency between scrum teams
  • Prioritizing the problems and getting teams on the same page
  • Testing challenges

14. What are some Disadvantages of Agile?

Some Disadvantages of Agile Methodology are

Poor resource planning

As Agile is based on the idea that teams won’t know what their end result is little bit challenging to predict efforts like cost, time and resources required at the beginning of a project.

Limited documentation

In Agile, documentation happens throughout a project, and often “just in time” for building the output, not at the beginning. As a result, it becomes less detailed and often falls to the back burner.

Fragmented output

Incremental delivery may help bring products to market faster, but it’s also a big disadvantage of Agile methodology. That’s because when teams work on each component in different cycles, the complete output often becomes very fragmented rather than one cohesive unit.

No finite end

The fact that Agile requires minimal planning at the beginning makes it easy to get sidetracked delivering new, unexpected functionality. Additionally, it means that projects have no finite end, as there is never a clear vision of what the “final product” looks like.

Difficult measurement

Since Agile delivers in increments, tracking progress requires you to look across cycles. And the “see-as-you-go” nature means you can’t set many KPIs at the start of the project. That long game makes measuring progress difficult.                

15. Explain the Solid principles.

The SOLID Principles are five principles of Object-Oriented class design. They are a set of rules and best practices to follow while designing a class structure.

Below are the SOLID acronym :

  1. The Single Responsibility Principle
  2. The Open-Closed Principle
  3. The Liskov Substitution Principle
  4. The Interface Segregation Principle
  5. The Dependency Inversion Principle

16. Design patterns of microservices.

Below are the Microservices Design Patterns

  1. Aggregator
  2. API Gateway
  3. Chained or Chain of Responsibility
  4. Asynchronous Messaging
  5. Database or Shared Data
  6. Event Sourcing
  7. Branch
  8. Command Query Responsibility Segregator
  9. Circuit Breaker
  10. Decomposition

 17. Tell the Principles of microservice architecture

  1. Scalability
  2. Availability
  3. Resiliency
  4. Independent, autonomous
  5. Decentralized governance
  6. Failure isolation
  7. Auto-Provisioning
  8. Continuous delivery through DevOps

18. How many types of memories are there in Java?

There are 5 Types of Memories in Java

  1. Method Area
  2. Heap Memory
  3. Stack Memory
  4. PC Registers
  5. Native Area

19. Mocking without spring integration possible?

Mockito is a very popular library to support testing. It allows us to replace real objects with “mocks”, i.e. with objects that are not the real thing and whose behavior we can control within our test.

@Mock annotation is used with class name to replace real class object.

@Mock
MockClassExample mockClassExample;

20. Tell the differences between Final, finally, finalise.

final:
final is a keywords which is used with classes, methods and variables. If the class is declared as final then that class is not extended by other class. If the method is declared as final then we cannot override that method in the child class. i.e. final method is not overridden by child class. If the variable is declared as final then it behave as a constant and we cannot re-assingment for that variable.

finally:
finally is a block which is always associated with try-catch block. finally block is always executed whether exception is handled or not.finally block is used to execute important code such as closing connection, stream when any exception arise.

finalize();
finalize() method is used to perform cleanup operation just before destroying any object. This finalize() method is always invoked by garbage collector.

21. Tell some differences between Runnable and Callable in java.

Callable and Runnable interface are used to encapsulate tasks that will be executed by another thread.

  • The main difference between Callable and Runnable interface are Callable instances can only be executed via ExecutorServic but Runnable instances can be run by Thread class as well as ExecutorService.
  • In the runnable interface, we need to override the run() method but in the Callable interface, we have to override the call() method.
  • The runnable interface is a part of the java.lang package whereas the Callable interface is a part of the java. util.concurrent package.
  • The runnable interface cannot return the result but a Callable interface can return the result of the parallel processing of a task.

22. What is Functional programming?

Functional programming is a declarative style of programming where basic computation unit is functions. The main motive of functional programming is to make code more concise, less complex, more predictable, and easier to test which is not much possible in the legacy style of coding. 

Lambda Expression is an example of Functional programming approach that takes input parameters and returns a value. It is also called an anonymous function.

Example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>(Arrays.asList(2, 4, 6, 8 ,10));
        Integer sum = list.stream().reduce(0, Integer::sum);
        System.out.println(sum);
    }
} 

Output

30

23. What is inheritance and multiple inheritance in Java.

Inheritance is an important concept of OOP(Object-Oriented Programming) where one class inherit all the properties and behaviors of another class.

The class that inherit the properties and behaviors of another class are known as child class. And the class that is inherit by child class is know as parent class.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

24. Which class is the first one to get called in a spring boot microservice?

25. Which function is the first one to be called when an api is hit?

26. How to do a Boolean algebra evaluation in Java?

https://stackoverflow.com/questions/1736684/boolean-expression-evaluation-in-java

27. Explain the working of Concurrent Hashmap.

ConcurrentHashMap class is introduced in JDK 1.5 that implements ConcurrentMap and Serializable interface. It belongs to java.util.concurrent package. ConcurrentHashMap was introduced to improve performance becuase it allows concurrent threads to read the value without locking it.

Some terms related to concurrent hashmap are

Concurrency-Level: It Defines the number which is an estimated number of concurrently updating threads.

Load-Factor: Load factor is theresold that tells when to increase the size of map.

Initial Capacity: The implementation performs internal sizing to accommodate these many elements.

Read here in details : https://dzone.com/articles/how-concurrenthashmap-works-internally-in-java

28. Tell some Thread safe collections in Java.

Some Thread safe collections are-

1). ConcurrentHashMap

Thread safe without having to synchronize the whole map Very fast reads while write is done with a lock No locking at the object level Uses multitude of locks.

2). SynchronizedHashMap

Object level synchronization Both read and writes acquire a lock Locking the collection has a performance drawback May cause contention

3). Vector

4). HashTable

5). CopyOnWriteArrayList

6). CopyOnWriteArraySet

7). Stack

29. Explain the Maven build lifecycle.

Built-in Build Lifecycles

There are three built-in build lifecycles.

  1. default: handles project build and deployment
  2. clean: handles project cleaning
  3. site: handles the creation of project site documentation

Maven Build Phases

Maven build lifecycle goes through a set of stages, they are called build phases. For example, the default lifecycle is made up of the following phases.

  • validate
  • compile
  • test
  • package
  • verify
  • install
  • deploy

Spring boot Questions

30. What is @componentscan in Spring Boot Application?

@ComponentScan annotation enables component scanning in Spring. All the classes that are annotated with the stereotype annotations @Component, @Controller, @Service, and @Repository are autoscaned by Spring.

@ComponentScan annotation is an alternative to <context:component-scan> XML tag.

31. What is @springbootapplication?

The @SpringBootApplication annotation is a combination of the @EnableAutoConfiguration, @Configuration and the @ComponentScan annotations in a Spring Boot application.

@EnableAutoConfiguration – This annotaion enables creating beans automatically by scanning the classpath.

@ComponentScan – @ComponentScan annotation tells Spring Boot to scan the current package and its sub-packages in order to identify annotated classes and configure them as Spring beans. Annotations are like @Component, @Configuration, @Service, @Repository are specified on classes to mark them as Spring beans.

@Configuration – @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.

32. Difference between @controller vs @restcontroller.

  1. @Controller annotation marks classes as Spring MVC Controller. But @restcontroller annotation marks RESTful Web services which is a combination of @Controller and @ResponseBody annotation.
  2. @Controller annotation returns a view But @restcontroller can’t return a view.
  3. @controller annotation is a specialized version of @Component annotation whereas @restcontroller is a specialized version @Controller annotation.
  4. @Controller is required to use @ResponseBody annotation on every handler method whereas @RestController annotation won’t require it.

33. Differences between @repository vs @service.

  • @Repository Annotation is used with a class that indicates the class is responsible for storage, retrieval, update, delete and search operations on objects. @Service annotation is used with classes that contain the business logic of the application.
  • @Repository annotation annotates the classes at the persistence layer whereas @Service annotation annotates classes at the service layer.

34. Explain the @getmapping and @postmapping annotations.

@GetMapping

  • @GetMapping is shortcut for @RequestMapping(method = RequestMethod.GET).
  • Methods annotated with @GetMapping  in the @Controller  classes handle the HTTP GET requests.

@postmapping

  • @postmapping is shortcut for @RequestMapping(method = RequestMethod.POST).
  • Methods annotated with @<strong>postmapping</strong> in the @Controller  classes handle the HTTP POST requests.

35. What are @ResponseStatus annotations?

In Spring MVC, we have many ways to set the status code of an HTTP response. When an endpoint returns successfully, Spring provides an HTTP 200 (OK) response.

If we want to specify the response status of a controller method, we can mark that method with @ResponseStatus.

36. What is @ConditionalOnBean ?

@ConditionalOnBean : Sometime when we are building the spring application we wanted to load bean only when defined condition meets. Only if the specified condition is satisfied then only bean will be added to the application context.

Spring has @Conditional annotations that allows us to define custom conditions.

Conditional Beans declaration

To declare a condition, we can use any of the <strong>@Conditional...</strong> annotations

Example:

@Configuration
class ConditionalBeanExample {
  @Bean
  @Conditional... 
  ConditionalBean conditionalBean(){
    return new ConditionalBean();
  };
}

@ConditionalOnBean Example:

Sometimes we want to load a bean only if a certain other bean is available in the application context:

@Configuration
@ConditionalOnBean(OtherModule.class)
class DependantBean {
  ...
}

The DependantBean will be load only if there is a bean of class OtherModule in the application context.

37. What is Spring actuators?

Spring Actuator helps us in Monitoring and Managing our application, understanding traffic etc. Spring Actuator contains various endpoints that can use HTTP and JMX endpoints to manage and monitor the Spring Boot application.

Three main features of Spring Boot Actuator are

  • Endpoints
  • Metrics
  • Audit

Dependency to enable spring boot actuator

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-actuator</artifactId>  
    <version>2.2.2.RELEASE</version>  
</dependency>  

38. What are Intermediate operations and terminal operations in Java Streams?

  • In java 8, Intermediate operations always return a stream as a result but terminal operations return primitive or object or the collection or may not return anything.
  • Intermediate operations don’t give end results They just transform one stream to another stream. Whereas terminal operations give end results.
  • Intermediate operations can be chained together to form a pipeline of operations whereas terminal operations can not be chained together.

Some intermediate operation are

map()filter()distinct()sorted()limit()skip()

Some terminal operations are

forEach()toArray()reduce()collect()min()max()count()anyMatch()allMatch()noneMatch()findFirst()findAny()

39. What is difference between findFirst and findAny in Java Stream?

  • findFirst() returns the first element from List that meeting the given criteria, while
  • findAny() function returns any element from the list that will meet the criteria. This feature is very useful when we work with a parallel stream.
import java.util.*;
public class Main {    
  public static void main(String[] args) {    
    List<String> list = Arrays.asList("A","B","C","D","E");
    Optional<String> resultFindAny = list.stream().findAny();
    Optional<String> resultFindFirst = list.stream().findFirst();
    System.out.println(resultFindAny.get());
    System.out.println(resultFindFirst.get());
  }    
}

Output

A
A

40. How will you configure https instead of http in your application from local?

https://www.freecodecamp.org/news/how-to-get-https-working-on-your-local-development-environment-in-5-minutes-7af615770eec/

https://auth0.com/blog/using-https-in-your-development-environment/