Java Interview Q&A

Practice interview questions and answers. Filter by level and topic.

Java Interview Q&A (39)
1. Quarkus notes
AJAX Level 1

What is Quarkus? (Kubernetes-native Java framework, fast startup, low memory)

  • Core Features ? CDI, Hibernate ORM, RESTEasy, Panache
  • Developed by redhat
  • Dev Experience ? Live coding, hot reload, fast build
  • Native Mode ? GraalVM compilation, reduced footprint
  • Deployment ? Optimized for containers, works with Kubernetes/OpenShift
  • Configuration ? MicroProfile Config, YAML/Properties support
  • Reactive Programming ? Mutiny, non-blocking I/O
  • Testing ? JUnit, RESTAssured integration
  • Security ? OIDC, JWT, role-based access
  • Comparison ? Quarkus vs Spring Boot (faster startup, lower memory)


Kubernetes

  • Open-source container orchestration platform
  • Automates deployment, scaling, and management of apps
  • Uses Pods, Services, Deployments, and ConfigMaps
  • Provides self-healing, load balancing, and rolling updates
  • Works seamlessly with cloud providers (AWS, GCP, Azure)

Quarkus on Kubernetes

  • Quarkus apps fit well into containerized microservices
  • Small memory + fast boot ? better pod density
  • Easy integration with Kubernetes Config, Secrets, and Operators
  • Enables cloud-native workflows like CI/CD, auto-scaling, monitoring


Video reference : https://www.youtube.com/watch?v=prdZmxGi0hQ&list=PLzdlNxYnNoaf5bb-Pwb7MbWHGlRf28pVO


2. What if

1. Main method is declared as private?

2. Static modifier is removed from the signature of the main method?

3. I do not provide the String array as the argument to the method?
Basics Basic

  1. The program compiles properly but at runtime it will give "Main method not public" error message.

  2. Program compiles.But at runtime throws an error "NoSuchMethodError"

  3. The program works fine.

3. What is the difference between a while statement and a do statement?
Basics Level 1
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur.
A do while statement (post test) checks at the end of a loop.
The do statement will always execute the loop body at least once.
4. What is the difference between declaring a variable and defining a variable?
Basics Level 1
In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization.

E.g. String s; is just a declaration while String s = new String ("bob"); is a definition.
5. Expain the reason for each keyword of public static void main(String args[])?
Basics Level 1

  • public main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

  • static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

  • void: main does not return anything so the return type must be void

  • String args[] The argument String indicates the argument type which is given at the command line and args is an array for string given during command line.

6. What do you understand by casting in java language? What are the types of casting?
Basics Level 1
The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.
7. Can an application have multiple classes having main method?
Basics Level 1
Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
8. What is a native method?
Basics Level 1
A native method is a method that is implemented in a language other than Java.
9. How to convert String to Number in java program?
Basics Level 1
The valueOf() function of Integer class is is used to convert string to Number. Here is the code Eg:

String numString = "1000";
int id=Integer.valueOf(numString).intValue();
10. What if I write static public void instead of public static void?
Basics Level 1
Program compiles and runs properly.
11. Explain working of Java Virtual Machine (JVM)?
Basics Level 1
Java compiler first converts .java file into .class byte code file.Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc.
The JVM is called "virtual" because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture. This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs
12. What is the first argument of the String array in main method? How can one prove that the array is not null but empty?
Basics Level 1
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.
Print array.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print array.length.
13. Which class is the superclass of every class?
Basics Level 1
Object.
14. Is sizeof a keyword in java?
Basics Level 1
The sizeof method is not a keyword.
15. What do you understand by a variable?
Basics Level 1
Variable is a named memory location that can be easily referred in the program. A variable is just a container for holding data and is accesible through a reference.
16. In S.o.p(), what is System, out and println?
Basics Level 1
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.
17. Describe the principles of OOPS.
Basics Level 1
There are three main principles:

  • Polymorphism

  • Inheritance

  • Encapsulation


18. How are this() and super() used with constructors?
Classes and objects Level 1
this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
19. What is the difference between an Interface and an Abstract class?
Classes and objects Level 1
1. An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.


2. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
20. What is the List,Vector,Iterator,Map,Set interface?
Collections Level 1

  • List interface provides support for ordered collections of objects.

  • Vector class provides capability to implement a growable array of objects.

  • Iterator interface is used to step through elements of a Collection .

  • Map interface replaces JDK 1.1 Dictionary class and is used associate keys with values.

  • Set interface provides methods for accessing elements of a finite mathematical set. Sets do not allow duplicate elements

21. Can a vector or ArrayList contain heterogenous objects?
Collections Level 1
Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
22. Java SE 8 Why do we need change to Java 8 again?
Java 8 Level 1
  • To Utilize Current Multi-Core CPUs Efficiently
  • To Utilize Functional Programming Features
23. Java SE 8 New Features?
Java 8 Level 1

Lambda Expressions

     An anonymous function which accepts a set of input parameters and returns results. Lambda Expression is a block of code without any name, with or without parameters and with or without results. This block of code is executed on demand.


Functional Interfaces

     Java Stream doesn’t store data, it operates on the source data structure (collection and array) and produce pipelined data that we can use and perform specific operations. Such as we can create a stream from the list and filter it based on a condition. Java Stream operations use functional interfaces, that makes it a very good fit for functional programming using lambda expression


Stream API (link 2 journal dev)

     New package java.util.stream. This package consists of classes, interfaces and enum to allows functional-style operations on the elements. Stream does not store elements. It simply conveys elements from a source such as a data structure, an array, or an I/O channel, through a pipeline of computational operations.


Interface Default Methods and Static Methods

Methods which are defined inside the interface and tagged with default are known as default methods. These methods are non-abstract methods.


Spliterator :

For supporting parallel execution in Java 8 Stream API, Spliterator interface is used. Spliterator trySplit method returns a new Spliterator that manages a subset of the elements of the original Spliterator.


Method and Constructor References

 Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. 


Optional

used to deal with NullPointerException in Java application


Parallel Array and Parallel Collection Operations

Type Annotations and Repeatable Annotations

Date and Time API - LocalDate

Collections API Enhancements

Concurrency Utils Enhancements

Fork/Join Framework Enhancements

Internal Iteration


Method Parameter Reflection

Base64 Encoding and Decoding

IO and NIO2 Enhancements

Nashorn JavaScript Engine

javac Enhancements

JVM Changes

Java 8 Compact Profiles: compact1,compact2,compact3

JDBC 4.2

JAXP 1.6

Java DB 10.10

Networking

Security Changes


24. What is Lambda Expression? What are its three parts?
Java 8 Level 1

Lambda Expression is an anonymous function which accepts a set of input parameters and returns results.Lambda Expression is a block of code without any name, with or without parameters and with or without results. This block of code is executed on demand.


A Lambda Expression contains 3 parts:

  • Parameter List A Lambda Expression can contain zero or one or more parameters. It is optional.
  • Lambda Arrow Operator “->” is known as Lambda Arrow operator. It separates parameters list and body.
  • Lambda Expression Body


The type of “Journal Dev” is java.lang.String. The type of “true” is Boolean. In the same way, what is the type of a Lambda Expression?

The Type of a Lambda Expression is a Functional Interface.

Example:- What is the type of the following Lambda Expression?

   () -> System.out.println("Hello World");

This Lambda Expression does not have parameters and does return any results. So it’s type is “java.lang.Runnable” Functional Interface.


25. What is Functional interface in Java 8
Java 8 Level 1

What is a Functional Interface? What is SAM Interface?

A Functional Interface is an interface, which contains one and only one abstract method. Functional Interface is also know as SAM Interface because it contains only one abstract method.SAM Interface stands for Single Abstract Method Interface. Java SE 8 API has defined many Functional Interfaces.


Is is possible to define our own Functional Interface? What is @FunctionalInterface? What are the rules to define a Functional Interface?

Yes, it is possible to define our own Functional Interfaces. We use Java SE 8’s @FunctionalInterface annotation to mark an interface as Functional Interface.We need to follow these rules to define a Functional Interface:

  • Define an interface with one and only one abstract method.
  • We cannot define more than one abstract method.
  • Use @FunctionalInterface annotation in interface definition.
  • We can define any number of other methods like Default methods, Static methods.
  • If we override java.lang.Object class’s method as an abstract method, which does not count as an abstract method.

Is @FunctionalInterface annotation mandatory to define a Functional Interface? What is the use of @FunctionalInterface annotation? Why do we need Functional Interfaces in Java?

It is not mandatory to define a Functional Interface with @FunctionalInterface annotation. If we don’t want, We can omit this annotation. However, if we use it in Functional Interface definition, Java Compiler forces to use one and only one abstract method inside that interface.Why do we need Functional Interfaces? The type of a Java SE 8’s Lambda Expression is a Functional Interface. Whereever we use Lambda Expressions that means we are using Functional Interfaces.


26. When do we go for Java 8 Stream API? Why do we need to use Java 8 Stream API in our projects?
Java 8 Level 1

When our Java project wants to perform the following operations, it’s better to use Java 8 Stream API to get lot of benefits:

  • When we want perform Database like Operations. For instance, we want perform groupby operation, orderby operation etc.
  • When want to Perform operations Lazily.
  • When we want to write Functional Style programming.
  • When we want to perform Parallel Operations.
  • When want to use Internal Iteration
  • When we want to perform Pipelining operations.
  • When we want to achieve better performance.


S.No.Collection APIStream API
1.It’s available since Java 1.2It is introduced in Java SE8
2.It is used to store Data(A set of Objects).It is used to compute data(Computation on a set of Objects).
3.We can use both Spliterator and Iterator to iterate elements. We can use forEach to performs an action for each element of this stream.We can’t use Spliterator or Iterator to iterate elements.
4.It is used to store limited number of Elements.It is used to store either Limited or Infinite Number of Elements.
5.Typically, it uses Internal Iteration concept to iterate Elements.It uses External Iteration to iterate Elements.
6.Collection Object is constructed Eagerly.Stream Object is constructed Lazily.
7.We add elements to Collection object only after it is computed completely.We can add elements to Stream Object without any prior computation. That means Stream objects are computed on-demand.
8.We can iterate and consume elements from a Collection Object at any number of times.We can iterate and consume elements from a Stream Object only once.
27. What is Spliterator in Java SE 8?Differences between Iterator and Spliterator in Java SE 8?
Java 8 Level 1
Spliterator stands for Splitable Iterator. It is newly introduced by Oracle Corporation as part Java SE 8. Like Iterator and ListIterator, It is also one of the Iterator interface.
S.No.SpliteratorIterator
1.It is introduced in Java SE 8.It is available since Java 1.2.
2.Splitable IteratorNon-Splitable Iterator
3.It is used in Stream API.It is used for Collection API.
4.It uses Internal Iteration concept to iterate Streams.It uses External Iteration concept to iterate Collections.
5.We can use Spliterator to iterate Streams in Parallel and Sequential order.We can use Iterator to iterate Collections only in Sequential order.
6.We can get Spliterator by calling spliterator() method on Stream Object.We can get Iterator by calling iterator() method on Collection Object.
7.Important Method: tryAdvance()Important Methods: next(), hasNext()
28. What is Optional in Java 8? What is the use of Optional?Advantages of Java 8 Optional?
Java 8 Level 1

Optional:

Optional is a final Class introduced as part of Java SE 8. It is defined in java.util package.

It is used to represent optional values that is either exist or not exist. It can contain either one value or zero value. If it contains a value, we can get it. Otherwise, we get nothing.

It is a bounded collection that is it contains at most one element only. It is an alternative to “null” value.

Main Advantage of Optional is:

  • It is used to avoid null checks.
  • It is used to avoid “NullPointerException”.



29. What is Type Inference? Is Type Inference available in older versions like Java 7 and Before 7 or it is available only in Java SE 8?
Java 8 Level 1

Type Inference means determining the Type by compiler at compile-time.

It is not new feature in Java SE 8. It is available in Java 7 and before Java 7 too.

Before Java 7:-

Let us explore Java arrays. Define a String of Array with values as shown below:

String str[] = { "Java 7", "Java 8", "Java 9" };

Here we have assigned some String values at right side, but not defined it’s type. Java Compiler automatically infers it’s type and creates a String of Array.

Java 7:-

Oracle Corporation has introduced “Diamond Operator” new feature in Java SE 7 to avoid unnecessary Type definition in Generics.

Map<String,List<Customer>> customerInfoByCity = new HashMap<>();

Here we have not defined Type information at right side, simply defined Java SE 7’s Diamond Operator “”.

Java SE 8:-

Oracle Corporation has enhanced this Type Inference concept a lot in Java SE 8. We use this concept to define Lambda Expressions, Functions, Method References etc.

ToIntBiFunction<Integer,Integer> add = (a,b) -> a + b;

Here Java Compiler observes the type definition available at left-side and determines the type of Lambda Expression parameters a and b as Integers.


30. Java 8 Stream Interface Methods
Java 8 Level 1
Methods Description
boolean allMatch(Predicate
31. Sorting using comparable interface?
JDK features Level 1

https://www.geeksforgeeks.org/collections-sort-java-examples/

class Sortbyroll implements Comparator{

    // Used for sorting in ascending order of roll number

    public int compare(Student a, Student b){

        return a.rollno - b.rollno;

    }

}


ArrayList ar = new ArrayList();

ar.add(new Student(111, "bbbb", "london"));

ar.add(new Student(131, "aaaa", "nyc"));

Collections.sort(ar, new Sortbyroll());

32. What are cookies and how will you use them
Mock Java Jsp Servlets interview Basic
Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructo
33. What is Spring ?
Spring Level 1
Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development.
34. REST API in Spring
Spring Level 1

1. What does REST stand for? and what is RESTful web services?

REST stand for REpresentational State Transfer, term by Roy Fielding. REST is an architectural style that describes best practices to expose web services over HTTP with Emphasizes scalability. Web services written by apply REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol to a different clients written in different languages. In RESTful web services http methods like GET, PUT, POST and DELETE can can be used to perform CRUD operations. Read more about REST.


3. What is differences between RESTful web services and SOAP web services?

1) REST is more simple and easy to use than SOAP

2) REST uses HTTP protocol for producing or consuming web services while SOAP uses XML.

3) REST is lightweight as compared to SOAP and preferred choice in mobile devices and PDA’s.

4) REST supports different format like text, JSON and XML while SOAP only support XML.

5) REST web services call can be cached to improve performance.

4. What is a resource?

The key abstraction of information in REST is a resource. Any information that can be named can be a resource like Student, Employee etc. REST is resource based API. Expose resources through URIs like http://localhost:8080/api/employees/1111, It is based on Model nouns, not verbs. Resources support limited set of operations – GET, PUT, POST, DELETE in case of HTTP. Example: update an employee use PUT to /employees/1111 and don’t POST to /employees/edit?id=1111 and Resources can support multiple representations like HTML, XML, JSON etc. Multiple URIs may refers to same resource as like CRUD operation on employee resource using HTTP verbs. Read More>>>

5. What are safe REST operations?

Safe REST operations are HTTP methods that do not modify resources. For example, using GET or HEAD on a resource URL, should NEVER change the resource. But it is still possible, that safe operations do change things on a server or resource. For example: GET http://localhost:8080/api/employees/1111/delete HTTP/1.1 but it is incorrect, this would actually delete the employee i.e. Safe methods are methods that can be cached, prefetched without any repercussions to the resource.

6. What are idempotent operations? Why is idempotency important?

Idempotent operations are those HTTP methods that can be called repetitively many times without different outcomes. It would not matter if the method is called only once, or many times over. The result should be the same. Again, this only applies to the result, not the resource itself.

Consider the following examples:

a = 4; (is idempotent)

a++; (is not idempotent)

Idempotency is important in building a fault-tolerant API. Suppose a client wants to update a resource through POST. Since POST is not a idempotent method, calling it multiple times can result in wrong updates. What would happen if you sent out the POST request to the server, but you get a timeout. Is the resource actually updated? Does the timeout happened during sending the request to the server, or the response to the client? Can we safely retry again, or do we need to figure out first what has happened with the resource? By using idempotent methods, we do not have to answer this question, but we can safely resend the request until we actually get a response back from the server.



HTTP Method Idempotent Safe OPTIONS yes yes GET yes yes HEAD yes yes PUT yes no POST no no DELETE yes no PATCH no no


7. Is REST scalable and/or interoperable?

Yes, REST is scalable and interoperable.

8. What is the RestTemplate and It’s advantages?

In Spring REST client, The RestTemplate is the core class for client-side access to Spring RESTful web services. It communicates HTTP server using RESTful constraints. It is very similar to other template classes in the Spring like JdbcTemplate and HibernateTemplate etc. In Spring, RestTemplate provides higher level implementation of corresponding HTTP methods such as GET, POST, PUT, DELETE, HEAD etc. It provides the methods to communicate by using these HTTP methods with URI template, URI params, request object and response type as arguments. Read More about RestTemplate.

9. Which HTTP methods does REST use?

RestTemplate provides higher level implementation of corresponding HTTP methods such as GET, POST, PUT, DELETE, HEAD etc.

10. What is an HttpMessageConverter?

HttpMessageConverter is a strategy interface that specifies a converter that can convert from and to HTTP requests and responses. Internally Spring MVC uses it to convert the Http request to an object representation and back. Message converters are used to marshall and unmarshall Java Objects to and from JSON, XML, etc – over HTTP. Read More about HttpMessageConverter in Spring.

11. Is REST normally stateless?

Yes.


11'. Sample rest controller

HttpMessageConverter is a strategy interface that specifies a converter that can convert from and to HTTP requests and responses in Spring REST Restful web services. Internally Spring MVC uses it to convert the Http request to an object representation and back. Let’s see following code for REST endpoint service.

  • MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)



@RestController
public class AccountController {
  @PostMapping("/account")
  public Account create (@RequestBody Account account){
     return accountService.create(account);
  }
}


12. What does @RequestMapping do?

@RequestMapping can be applied to the controller class as well as methods. This annotation for mapping web requests onto specific handler classes and/or handler methods. Read more about @RequestMapping annotation.

13. Is @Controller a stereotype? Is @RestController a stereotype?

Yes.

14. What is the difference between @Controller and @RestController?

The key difference between a traditional Spring MVC @Controller and the RESTful web service @RestController is the way the HTTP response body is created. While the traditional MVC controller relies on the View technology, the RESTful web service controller simply returns the object and the object data is written directly to the HTTP response as JSON/XML by registered HttpMessageConverters.

15. When do you need @ResponseBody?

When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the http response automatically. Each method in the Controller class must be annotated with @ResponseBody.

16. What does @PathVariable do?

@PathVariable is used to pass parameter along with the url, sometimes we need to pass parameters along with the url to get the data. Spring MVC provides support for customizing the URL in order to get data. To achieving this purpose @PathVariable annotation is used in Spring mvc framework. Read More about PathVariable.

17. What is the HTTP status return code for a successful DELETE statement?

Either we can return HTTP status 204 (NO CONTENT) with no response body or return HTTP status 200 (OK) along with a response body with representation of the deleted item.

18. What does CRUD mean?

In Spring REST, the primary or most-commonly-used HTTP verbs are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD) operations, respectively.

19. Is REST secure? What can you do to secure it?

REST is nothing but it architectural desgin or paradigms to design restful web service. So REST does not provide any security constraints by default but we can implement it in the RESTful web services by using security layers like transport layer security (TLS), auth token security.

20. Where do you need @EnableWebMVC?

@EnableWebMvc- It used for enabling spring mvc behavior i.e. it is responsible for registering Spring MVC required Bean Post Processors in the application as like Jackson2JsonMessageConverter etc.

21. Name some common http response codes. When do you need @ResponseStatus?

  • 2xx Success
  • 200 OK
  • 201 Created
  • 204 No Content
  • 3xx Redirection
  • 304 Not Modified
  • 4xx Client Error
  • 400 Bad Request
  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 409 Conflict
  • 5xx Server Error
  • 500 Internal Server Error
  • 503 Service Unavailable

@ResponseStatus annotation available on custom exceptions and to map these exceptions to HTTP status codes.

22. Does REST work with transport layer security (TLS)?

Yes. Transport Layer Security can encrypt the communication to a RESTful Webservice and authenticate the server to a client.

23. Do you need Spring MVC in your classpath for Spring REST?

Yes, Spring REST uses the Spring MVC annotations like @RestController, @RequestBody and @ResponseBody etc.


35. Spring Boot ?
Spring Level 1

Spring Boot is a one-stop Framework to develop Spring applications very easily.

Spring Boot Framework is Auto-Dependency Resolution, Auto-Configuration, Management EndPoints, Embedded HTTP Servers(Jetty/Tomcat etc.) and Spring Boot CLI

  1. Spring Boot Framework aims to simplify Spring Development.


Spring Boot Framework has the following components:

  1. Spring Boot Starter : are just JAR Files. They are used by Spring Boot Framework to provide “Auto-Dependency Resolution”.
  2. Spring Boot AutoConfigurator : is used by Spring Boot Framework to provide “Auto-Configuration”
  3. Spring Boot Actuator : Spring Boot Actuator is used by Spring Boot Framework to provide “Management EndPoints” to see Application Internals, Metrics etc.
  4. Spring Boot CLI : In simple words, Spring Boot CLI is Auto Dependency Resolution, Auto-Configuration, Management EndPoints, Embedded HTTP Servers(Jetty,Tomcat etc.) and (Groovy,Auto-Imports)
  5. Spring Boot Initilizr : is a Spring Boot tool to bootstrap Spring Boot or Spring Applications very easily.


With Spring Boot CLI:

  • No Semicolons
  • No Public and private access modifiers
  • No Imports(Most)
  • No “return” statement
  • No setters and getters
  • No Application class with main() method(It takes care by SpringApplication class).
  • No Gradle/Maven builds.
  • No separate HTTP Servers.

Spring Boot With Maven/Gradle?

Spring Boot Framework uses one of the greatest features of Maven/Gradle build tools: â€œTransitively Dependency Resolution Management” Transitively Dependency Resolution Management” means: If we define a “A” dependency in build scripts, “A” is dependent on “B” and “B” is dependent on “C”, That means “A” is also dependent on “C”. Then Build Tools will download and add all Three Jar files “A”, “B” and “C” to our application classpath.

36. Spring micro-services?
Spring Level 1

1. What is a microservices architecture?

Microservices architecture allows to avoid monolith application for large system. It provide loose coupling between collaborating processes which running independently in different environments with tight cohesion.


2. What are the advantages and disadvantages of microservices?

Microservices Advantages

  • Smaller code base is easy to maintain.
  • Easy to scale as individual component.
  • Technology diversity i.e. we can mix libraries, databases, frameworks etc.
  • Fault isolation i.e. a process failure should not bring whole system down.
  • Better support for smaller and parallel team.
  • Independent deployment
  • Deployment time reduce

Microservices Disadvantages

  • Difficult to achieve strong consistency across services
  • ACID transactions do not span multiple processes.
  • Distributed System so hard to debug and trace the issues
  • Greater need for end to end testing
  • Required cultural changes in across teams like Dev and Ops working together even in same team.


What is Spring Cloud?

  • It is building blocks for Cloud and Microservices
  • It provides microservices infrastructure like provide use services such as Service Discovery, Configuration server and Monitoring.
  • It provides several other open source projects like Netflix OSS.
  • It provides PaaS like Cloud Foundry, AWS and Heroku.
  • It uses Spring Boot style starters
  • There are many use-cases supported by Spring Cloud like Cloud Integration, Dynamic Reconfiguration, Service Discovery, Security,Client side Load Balancing etc. But in this post we concentrate on following microservices support
  • Service Discovery (How do services find each other?)
  • Client-side Load Balancing (How do we decide which service instance to use?)


Spring Cloud annotations and configuration?

  • @EnableEurekaServer annotation allows us to register microservices to the spring cloud.
  • @EnableDiscoveryClient annotation also allows us to query Discovery server to find miroservices.
  • Spring provide smart RestTemplate for service discovery and load balancing by using @LoadBalancedannotation with RestTemplate instance.


What Netflix projects did we use?

Eureka created by Netflix, it is the Netflix Service Discovery Server and Client. Netflix Ribbon, it provide several algorithm for Client-Side Load Balancing. Spring provide smart RestTemplate for service discovery and load balancing by using @LoadBalanced annotation with RestTemplate instance.


How do you setup Service Discovery?

Spring Cloud support several ways to implement service discovery but for this I am going to use Eureka created by Netflix. Spring Cloud provide several annotation to make it use easy and hiding lots of complexity


How do you access a RESTful microservice?

  • Load Balanced RestTemplate
  • If there are multiple RestTemplate you get the right one.
  • It can used to access multiple microservices

 What is Eureka?

Eureka is the Netflix Service Discovery Server and Client. Eureka Server is using Spring Cloud.

Registering with Eureka

When a client registers with Eureka, it provides meta-data about itself such as host and port, health indicator URL, home page etc. Eureka receives heartbeat messages from each instance belonging to a service. If the heartbeat fails over a configurable timetable, the instance is normally removed from the registry.

Example eureka client:

@Configuration
@ComponentScan
@EnableAutoConfiguration
@EnableEurekaClient
@RestController
public class Application {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}


37. Kafka spring boot inteview questions
Spring Level 1

1) What's an easy way to create a new topic with Spring Boot?

You can create a new topic via Spring Boot configuration by defining a NewTopic @Bean in the application context:


@Bean
public NewTopic topic1(){
    return TopicBuilder.name("myTopic")
        .partitions(10)
        .replicas(3)
        .build();
}

2) Is a KafkaAdmin bean automatically registered for you when using Spring Boot?

Yes.



3) What happens when a broker is not available when starting the Spring Boot app?

The default behavior is the Spring context continues to load. You can optionally consider this behavior fatal by configuring the fatalIfBrokerNotAvailable property on the admin.



4) How is the KafkaTemplate class used in Spring Boot?

The KafkaTemplate class wraps a Kafka producer and makes it easy to send data to a topic using Spring Boot...



5) What is a Message Listener?

The message listener is an interface for handling incoming messages. There are 8 supported interfaces for message listeners. The MessageListener is called for each record returned by the underlying consumer poll() method.



6) What's the difference between KafkaMessageListenerContainer and ConcurrentMessageListenerContainer?

A KafkaMessageListenerContainer receives messages for all topics and partitions on a single thread. A ConcurrentMessageListenerContainer is a collection of KafkaMessageListenerContainer instances. It distributes message consumption across multiple threads.



7) What is the @KafkaListener annotation?

The @KafkaListener annotation can be applied to Java classes, methods, and method annotations. @KafkaListener is most commonly applied to methods, registering Kafka listener containers for those methods...


@KafkaListener(topics = "test")
public void processMessage(String content){
    System.out.println("Message received: " + content);
}

In the above example, the processMessage() method is annotated with @KafkaListener. This method will be invoked when messages are read from the test topic.

38. What is the INSERT/DELETE statement?
Sql Level 1
The INSERT statement lets you insert information into a database.

Use the DELETE statement to remove records or any particular column values from a database.
39. What is SELECT statement?
Sql Level 1
The SELECT statement lets you select a set of values from a table in a database. The values selected from the database table would depend on the various conditions that are specified in the SQL query.