Practice interview questions and answers. Filter by level and topic.
What is Quarkus? (Kubernetes-native Java framework, fast startup, low memory)
Kubernetes
Quarkus on Kubernetes
Video reference : https://www.youtube.com/watch?v=prdZmxGi0hQ&list=PLzdlNxYnNoaf5bb-Pwb7MbWHGlRf28pVO
String numString = "1000";
int id=Integer.valueOf(numString).intValue();
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
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:
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.
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:
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.
When our Java project wants to perform the following operations, it’s better to use Java 8 Stream API to get lot of benefits:
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:
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.
| Methods | Description |
|---|---|
boolean allMatch(Predicate
31. Sorting using comparable interface?
JDK features
Level 1
https://www.geeksforgeeks.org/collections-sort-java-examples/
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.
@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?
@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
Spring Boot Framework has the following components:
With Spring Boot CLI:
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
Microservices Disadvantages
What is Spring Cloud?
Spring Cloud annotations and configuration?
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?
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.
|