Looking forward to appear in Java Interview, here are the key 100+ Java Interview Questions with Answers only for you including some of the tricky questions with answers.
Java 8 provides following features for Java Programming:
- Lambda expressions - Adds functional processing capability to Java.
- Method references - Referencing functions by their names instead of invoking them directly. Using functions as parameters.
- Functional interfaces,
- Stream API - New stream API to facilitate pipeline processing.
- Default methods,
- Base64 Encode Decode,
- Static methods in interface,
- Optional class,
- Collectors class,
- ForEach() method,
- +36
- Parallel array sorting,
- Nashorn JavaScript Engine - A Java-based engine to execute JavaScript code.
- Parallel Array Sorting,
- Type and Repeating Annotations,
- IO Enhancements,
- Concurrency Enhancements,
- JDBC Enhancements etc.
GET | POST |
---|---|
Limited amount of data can be sent because data is sent in the header. | Large amount of data can be sent because data is sent in the body. |
Not Secured because data is exposed in the URL bar. | Secured because data is not exposed in the URL bar. |
Can be bookmarked | Cannot be bookmarked |
Idempotent | Non-Idempotent |
It is more efficient and use than Post | It is less efficient and used |
forward() method | sendRedirect() method |
---|---|
forward() sends the same request to another resource. | sendRedirect() method sends new request always because it uses the URL bar of the browser. |
forward() method works at server side. | sendRedirect() method works at client side. |
forward() method works within the server only. | sendRedirect() method works within and outside the server. |
HashMap | HashTable |
---|---|
Methods are not synchronized | Key methods are synchronized |
Not thread safe | Thread safe |
Iterator is used to iterate the values | Enumerator is used to iterate the values |
Allows one null key and multiple null values | Doesn’t allow anything that is null |
Performance is high than HashTable | Performance is slow |
HashSet | TreeSet |
---|---|
Inserted elements are in random order | Maintains the elements in the sorted order |
Can store null objects | Couldn’t store null objects |
Performance is fast | Performance is slow |
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on data such as searching, sorting, insertion, manipulation, and deletion.Java Collection means a single unit of objects. The Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Collections are used to perform the following operations:
- Searching
- Sorting
- Manipulation
- Insertion
- Deletion
Ordered:
It means the values that are stored in a collection is based on the values that are added to the collection. So we can iterate the values from the collection in a specific order.
Sorted:
Sorting mechanism can be applied internally or externally so that the group of objects sorted in a particular collection is based on properties of the objects.
Set
Set cares about uniqueness. It doesn’t allow duplicates. Here the “equals ( )” method is used to determine whether two objects are identical or not.
Hash Set:
- Unordered and unsorted.
- Uses the hash code of the object to insert the values.
- Use this when the requirement is “no duplicates and don’t care about the order”.
Example:
public class Fruit {
public static void main (String[] args){
HashSet<String> names = new HashSet <=String>();
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println(names);
}
}
Output:
[banana, cherry, kiwi, apple]
Doesn’t follow any insertion order. Duplicates are not allowed.
Linked Hash set:
- An ordered version of the hash set is known as Linked Hash Set.
- Maintains a doubly-Linked list of all the elements.
- Use this when the iteration order is required.
Example:
public class Fruit {
public static void main (String[] args){
LinkedHashSet<String> names = new LinkedHashSet <String>();
names.add(“banana”);
names.add(“cherry”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“banana”);
System.out.println(names);
}
}
Output:
[banana, cherry, apple, kiwi]
Maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.
Tree Set:
- It is one of the two sorted collections.
- Uses “Read-Black” tree structure and guarantees that the elements will be in an ascending order.
- We can construct a tree set with the constructor by using comparable (or) comparator.
Example:
public class Fruits{
public static void main (String[] args) {
Treeset<String> names= new TreeSet<String>();
names.add(“cherry”);
names.add(“banana”);
names.add(“apple”);
names.add(“kiwi”);
names.add(“cherry”);
System.out.println(names);
}
}
Output:
[apple, banana, cherry, kiwi]
TreeSet sorts the elements in an ascending order. And duplicates are not allowed.
Final variable:
Once a variable is declared as final, then the value of the variable could not be changed. It is like a constant.
Example:
final int = 12;
Final method:
A final keyword in a method that couldn’t be overridden. If a method is marked as a final, then it can’t be overridden by the subclass.
Final class:
If a class is declared as final, then the class couldn’t be subclassed. No class can extend/inherit the final class.
In Java, the flow of an execution is called Thread. Every java program has at least one thread called main thread, the Main thread is created by JVM. The user can define their own threads by extending Thread class (or) by implementing Runnable interface. Threads are executed concurrently.
Example:
public static void main(String[] args){//main thread starts here
}
Thread has the following states:
- New
- Runnable
- Running
- Non-runnable (Blocked)
- Terminated
- New: In New state, Thread instance has been created but start () method is not yet invoked. Now the thread is not considered alive.
- Runnable: The Thread is in runnable state after invocation of the start () method, but before the run () method is invoked. But a thread can also return to the runnable state from waiting/sleeping. In this state the thread is considered alive.
- Running: The thread is in running state after it calls the run () method. Now the thread begins the execution.
- Non-Runnable(Blocked): The thread is alive but it is not eligible to run. It is not in a runnable state but also, it will return to runnable state after some time. For Example: wait, sleep, block.
- Terminated: Once the run method is completed then it is terminated. Now the thread is not alive.
ObjectOutputStream and ObjectInputStream classes are higher level java.io. package. We will use them with lower level classes FileOutputStream and FileInputStream.
ObjectOutputStream.writeObject —->Serialize the object and write the serialized object to a file.
ObjectInputStream.readObject —> Reads the file and deserializes the object.
To be serialized, an object must implement the serializable interface. If a superclass implements Serializable, then the subclass will automatically be serializable.
Serialization | Deserialization |
---|---|
Serialization is the process which is used to convert the objects into byte stream | Deserialization is the opposite process of serialization where we can get the objects back from the byte stream. |
An object is serialized by writing it an ObjectOutputStream. | An object is deserialized by reading it from an ObjectInputStream. |
If we need our class to extend some other classes other than the thread then we can go with the runnable interface because in java we can extend only one class. If we are not going to extend any class then we can extend the thread class.
There are 5 stages in the lifecycle of a servlet:
- Servlet is loaded
- Servlet is instantiated
- Servlet is initialized
- Service the request
- Servlet is destroyed
ServletConfig | ServletContext |
---|---|
Servlet config object represent single servlet | It represent whole web application running on particular JVM and common for all the servlet |
Its like local parameter associated with particular servlet | Its like global parameter associated with whole application |
It’s a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope | ServletContext has application wide scope so define outside of servlet tag in web.xml file. |
getServletConfig() method is used to get the config object | getServletContext() method is used to get the context object. |
for example shopping cart of a user is a specific to particular user so here we can use servlet config | To get the MIME type of a file or application session related information is stored using servlet context object. |
Spring Framework:
- Spring is one of the most widely used Java EE Frameworks for building applications.
- For the Java platform, the Spring framework provides an elaborate programming and configuration model.
- It aims to simplify the Java EE development and helps developers be more productive at work.
- It can be used at any kind of deployment platform.
- One of the major features of the Spring framework is the dependency injection.
- It helps make things simpler by allowing us to develop loosely coupled applications.
Spring Boot:
- While the Spring framework focuses on providing flexibility to you, Spring Boot aims to shorten the code length and provide you with the easiest way to develop a web application.
- With annotation configuration and default codes, Spring Boot shortens the time involved in developing an application.
- It helps create a stand-alone application with less or almost zero-configuration.
- Autoconfiguration is a special feature in Spring Boot.
- It automatically configures a class based on that requirement.
Spring | Spring Boot |
---|---|
Spring Framework is a widely used Java EE framework for building applications. | Spring Boot Framework is widely used to develop REST APIs. |
It aims to simplify Java EE development that makes developers more productive. | It aims to shorten the code length and provide the easiest way to develop Web Applications. |
The primary feature of the Spring Framework is dependency injection. | The primary feature of Spring Boot is Autoconfiguration. It automatically configures the classes based on the requirement. |
It helps to make things simpler by allowing us to develop loosely coupled applications. | It helps to create a stand-alone application with less configuration. |
The developer writes a lot of code (boilerplate code) to do the minimal task. | It reduces boilerplate code. |
To test the Spring project, we need to set up the sever explicitly. | To test the Spring project, we need to set up the sever explicitly. |
It does not provide support for an in-memory database. | It offers several plugins for working with an embedded and in-memory database such as H2. |
Developers manually define dependencies for the Spring project in pom.xml. | Spring Boot comes with the concept of starter in pom.xml file that internally takes care of downloading the dependencies JARs based on Spring Boot Requirement. |
Spring is an open-source lightweight framework widely used to develop enterprise applications. | Spring Boot is built on top of the conven |
tional spring framework, widely used to develop REST APIs. |
**REST API :- **
- REST stands for representational state transfer.
- A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services.
- An API is a set of definitions and protocols for building and integrating application software.
- It’s sometimes referred to as a contract between an information provider and an information user—establishing the content required from the consumer (the call) and the content required by the producer (the response).
- When a client request is made via a RESTful API, it transfers a representation of the state of the resource to the requester or endpoint.
- This information, or representation, is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XLT, Python, PHP, or plain text.
**Benefits of using JSON over XML :- **
- Less Verbose: JSON has a more compact style than XML, and it is often more readable. The lightweight approach of JSON can make significant improvements in RESTful APIs working with complex systems.
- Faster: The XML software parsing process can take a long time. One reason for this problem is the DOM manipulation libraries that require more memory to handle large XML files. JSON uses less data overall, so you reduce the cost and increase the parsing speed.
- Readable: The JSON structure is straightforward and readable. You have an easier time mapping to domain objects, no matter what programming language you're working with.
- Structure Matches the Data: JSON uses a map data structure rather than XML's tree. In some situations, key/value pairs can limit what you can do, but you get a predictable and easy-to-understand data model.
- Objects Align in Code: JSON objects and code objects match, which is beneficial when quickly creating domain objects in dynamic languages.
- JSON Limitations: The limitations in JSON actually end up being one of its biggest benefits. A common line of thought among developers is that XML comes out on top because it supports modeling more objects. However, JSON's limitations simplify the code, add predictability and increase readability.
In comparison to an XML model, a JSON data structure is intuitive, making it easy to read and map directly to domain objects in whatever programming language is being used.
Session is a conversational state between client and server and it can consist of multiple requests and responses between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.
Some of the common ways of session management in servlets are:
- User Authentication
- HTML Hidden Field
- Cookies
- URL Rewriting
- Session Management API
19. Let's talk about SOLID design principles. Could you quickly explain what are the main design principles in the current project?
SOLID principles came from an essay written in 2000 by Robert Martin, known as Uncle Bob, where he discussed that a successful application will change and, without good design, can become rigid, fragile, immobile and viscous.
Rigid — Things are very fixed. You can’t move or change things without affecting other things, but it’s clear what will break if you make a change.
Fragile — Easy to move and change things but not obvious what else might break as a result.
Immobile — Code works fine but you can’t re-use code without duplicating or replicating it.
Viscous — Everything falls apart when you make a change, you quickly push it back together and get your change working. The same thing happens when somebody else comes along to make a change.
The SOLID Principles -
S — Single Responsibility:
- A class should have a single responsibility.
- ‘There should never be more than one reason for a class to change’.
O — Open-Closed
- Classes should be open for extension, but closed for modification.
- ‘A module should be open for extension but closed for modification’.
L — Liskov Substitution
- If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.
- ‘Subclasses should be substitutable for their base classes’.
I — Interface Segregation
- Clients should not be forced to depend on methods that they do not use.
- ‘Many client specific interfaces are better than one general purpose interface’.
D — Dependency Inversion
- High-level modules should not depend on low-level modules. Both should depend on the abstraction.
- Abstractions should not depend on details. Details should depend on abstractions.
- ‘Depend upon abstractions. Do not depend upon concretions.’
wait() | notify() |
---|---|
When wait() is called on a thread holding the monitor lock, it surrenders the monitor lock and enters the waiting state. | When the notify() is called on a thread holding the monitor lock, it symbolizes that the thread is soon going to surrender the lock. Syntax: public final void notify() |
There can be multiple threads in the waiting state at a time. | One of the waiting threads is randomly selected and notified about the same. The notified thread then exits the waiting state and enters the blocked state where it waits till the previous thread has given up the lock and this thread has acquired it. Once it acquires the lock, it enters the runnable state where it waits for CPU time and then it starts running. |
Object.wait() to suspend a thread | Object.notify() to wake a thread up |
Causes the current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. | Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. |
Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors.
The four access levels are - ● Visible to the package, the default. No modifiers are needed. ● Visible to the class only (private). ● Visible to the world (public). ● Visible to the package and all subclasses (protected). ● Class(static), instance and method(local) variables
Buffered Reader, Scanner, Files, FileReader
With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating the same shared variable.
An Iterator is an object that can be used to loop through collections, like ArrayList and HashSet.
private, static and final
If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.
There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use.
You don't need instance of class to call that method or field,the static modifier means something is directly related to a class
// -- single line, /* */ -- multiline
In the Java programming language, strings are treated as objects. The Java platform provides the String class to create and manipulate strings. Whereas, StringBuffer class is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
J2EE is a platform-independent, Java-centric environment from Sun for developing, building and deploying Web-based enterprise applications online. The J2EE platform consists of a set of services, APIs, and protocols that provide the functionality for developing multitiered, Web-based applications.
A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. This type of bean normally acts as a JMS message listener, which is similar to an event listener but receives JMS messages instead of events.
Entity bean represents the persistent data stored in the database. It is a server-side component.
Callback is a mechanism by which the life cycle of an enterprise bean can be intercepted. EJB 3.0 specification has specified callbacks for which callback handler methods are created. EJB Container calls these callbacks. We can define callback methods in the EJB class itself or in a separate class. EJB 3.0 has provided many annotations for callbacks.
Application client module: Contains an application client deployment descriptor, which is an Extensible Markup Language (XML) file with an .xml extension, in addition to class files, which are packed as Java Archive (JAR) files with .jar extensions.
Enterprise JavaBeans (EJB) module: Contains an EJB deployment descriptor and class files.Web module: Contains a Web application deployment descriptor, servlet class files and Java Server Pages (JSP) files.Resource adapter module: Contains Java interfaces, classes, libraries, documentation and a resource adapter deployment descriptor.
The deployment descriptor is the file used by the servlet container to define which servlets match up with which URLs. It also defines which servlet or resource provides the landing page for the root of the service.
This property means that each transaction is executed in isolation from others, and that concurrent transactions do not affect the transaction. This property level is variable, and as this article will discuss, SQL Server has five levels of transaction isolation depending on the requirements of the database.
JDBC provides support 5 transaction isolation levels through Connection interface.
TRANSACTION_NONE: It is represented by integer value 0 does not support transactions.
TRANSACTION_READ_COMMITTED: It is represented by integer value 2 supports transactions allowing Non-Repeatable Reads and, Phantom Reads.
TRANSACTION_READ_UNCOMMITTED: It is represented by integer value 1 supports transactions allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads.
TRANSACTION_REPEATABLE_READ: It is represented by integer value 4 supports transactions allowing only Phantom Reads.
TRANSACTION_SERIALIZABLE: It is represented by integer value 8 supports transactions with out allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads.
38. What are Microservices and what are the services that make a microservices and what makes it a good one?
Microservice is a service-based application development methodology. In this methodology, big applications will be divided into smallest independent service units.
Microservice is the process of implementing Service-oriented Architecture (SOA) by dividing the entire application as a collection of interconnected services, where each service will serve only one business need. Some of the features which makes this architecture more useful:
- Small in size
- Focused
- Autonomous
- Technology heterogeneity
- Resilience
- Ease of deployment
Microservice is a service-based application development methodology. In this methodology, big applications will be divided into smallest independent service units. Microservice is the process of implementing Service-oriented Architecture (SOA) by dividing the entire application as a collection of interconnected services, where each service will serve only one business need.
Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive types or objects. The volatile keyword does not cache the value of the variable and always reads the variable from the main memory. The volatile keyword cannot be used with classes or methods. However, it is used with variables. It also guarantees visibility and ordering. It prevents the compiler from the reordering of code.
The contents of the particular device register could change at any time, so you need the volatile keyword to ensure that such accesses are not optimized away by the compiler.
Yes, First we will create a controller and in that controller we will be calling service layer and service will be calling the DAO layer which will be interacting with db. We use @RestController to declare any class as Rest Controller. In this class we will be writing our business logic and with that we will be implementing GET/POST/PUT/DELETE requests.
Benefits of DynamoDB for Operations:
- Performance and scalability
- Access to control rules
- Persistence of event stream data
- Time To Live
- Storage of inconsistent schema items
- Automatic data management
Even though Kotlin is a full-fledged functional programming language, it preserves most of the object-oriented nature of Java as an alternative programming style, which is very handy when converting existing Java code. Kotlin has classes with constructors, along with nested, inner, and anonymous inner classes, and it has interfaces like Java 8. Kotlin does not have a new keyword. To create a class instance, call the constructor just like a regular function.
Although Kotlin can be used anywhere Java is used (and soon in more places), it is currently predominantly used for Android app development, spurred on by Google’s official support. Companies using Kotlin to stay competitive include Google, Trello/Atlassian, Pinterest, Kickstarter and Uber to name just a few.
The Benefit of Kotlin -
- Kotlin allows writing less code
- It solves developer challenges
- Adopting Kotlin is easy
- Kotlin is fully compatible with Java
- It imposes no runtime overhead
- Kotlin has a strong community
- Kotlin suits for the multi-platform development
- Kotlin development offers more safety
AWS Lambda is a serverless, event-driven compute service that lets you run code for virtually any type of application or backend service without provisioning or managing servers. You can trigger Lambda from over 200 AWS services and software as a service (SaaS) applications, and only pay for what you use
Writing testable code means that the smallest components are independently verifiable. In order to do this, each component must have its dependencies injected into it. This means that code can't reference global variables or use read/write singletons or service locators, etc. This may be a slightly different way of thinking about building a program than you're used to, but it can be a highly efficient and effective way of building software and it can be programmatically verified.
A URL shortening service is a simple service that takes a long URL and converts it to a short link. Once that link is visited, the user is redirected to the original URL.
A URL shortener is a service that is used to create short links from very long URLs.
Usually, short links have the size of one third or even one-fourth of the original URL, which makes them easier to type, present, or tweet. Clicking on a short link user will be automatically redirected to the original URL.
There are many URL shortening services available online, like tiny.cc, bitly.com, cutt.ly, etc.
- Every time the URL Shortener receives a link to shorten, it saves that link into a Dictionary and returns a short URL to the individual requesting the URL.
- When a shortened URL is given to the URL Shortener, the URL Shortener looks into the Dictionary and retrieves the original link.
Caching is a technique wherein objects in your application are stored in a temporary storage area known as a cache. A caching strategy is to determine the relationship between the data source and your caching system, and how your data can be accessed. There are various strategies to implement cache but each will have different impacts on your system design and the resulting performance. Before designing your architecture, it is useful to go through how your data needs to be accessed so that you can determine which strategy suits best. Below we will analyse some of the most adopted ones.
- Cache Aside
- Read Through
- Write Through
- Write Back/Behind
- Write Around
SDN helps you transform your network, breaking away from its restrictive hardware constraints and getting improved agility, security, scalability and programmability. IBM offers a consulting-led approach that helps you create the cloud-enabled, dynamic, and resilient network that your enterprise needs. Benefits:
- Security
- Holistic enterprise management
- Centralized network provisioning
Java is a multi-threaded programming language which means we can develop multi-threaded programs using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.
By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.
ReadWriteLock is a high-level thread lock tool. It allows various threads to read a specific resource but allows only one to write it, at a time. The approach is that multiple threads can read from a shared resource without causing concurrency errors.
A java.util.concurrent.locks.ReadWriteLock is an advanced thread lock mechanism. It allows multiple threads to read a certain resource, but only one to write it, at a time.
The rules by which a thread is allowed to lock the ReadWriteLock either for reading or writing the guarded resource, are as follows:
Read Lock | Write Lock |
---|---|
If no threads have locked the ReadWriteLock for writing, | |
and no thread has requested a write lock (but not yet obtained it). Thus, multiple threads can lock the lock for reading. | If no threads are reading or writing. Thus, only one thread at a time can lock the lock for writing. |
A data structure is a particular way of organizing data in a computer so that it can be used effectively. When we think of data structures, there are generally four forms:
- Linear: arrays, lists.
- Tree: binary, heaps, space partitioning etc.
- Hash: distributed hash table, hash tree etc.
- Graphs: decision, directed, acyclic etc.
Data Structures are a specialized means of organizing and storing data in computers in such a way that we can perform operations on the stored data more efficiently. I have used array, hashtable, linked list and stacks.
HashMap is a part of the Java collection framework. It uses a technique called Hashing. It implements the map interface. It stores the data in the pair of Key and Value. HashMap contains an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data structure internally for storing Key and Value. There are four fields in HashMap.
It allows concurrent access to the map. Part of the map called Segment (internal data structure) is only getting locked while adding or updating the map. So ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance.
Docker is container based technology and containers are just user space of the operating system. It is built for running applications. In Docker, the containers running share the host OS kernel.
A Virtual Machine, on the other hand, is not based on container technology. They are made up of user space plus kernel space of an operating system. Under VMs, server hardware is virtualized. Each VM has Operating system (OS) & apps. It shares hardware resource from the host.
56. When you do the microservices we have multiple microservices and there are Difference pros and cons?
Microservice architecture is a software development style that breaks the system down into smaller independent components. It is a collection of autonomous services designed around a single business domain.These individual units are capable of handling one part of the functionality of the software. Below are the pros and cons of the microservices architecture:
Pros:
- Easier scaling up
- Improved tolerance level
- Ease of understanding codebase
- Independent deployment
- Scope of experiment
Cons:
- Increased complexed communication
- Complex deployment
- Need more resources
- Global testing is difficult
- Not recommended for smaller application
Closed state: This state implies that the service is up and running(properly). Then if the number of error responses from the needed service passes a threshold limit, the circuit breaker will be tripped (ie: goes to the open stage).
Open state: In this state the circuit breaker will not make the remote calls. Since the requests failed more than the threshold, we will know that the service is not working properly. Actually, the result need not be a 500 error message to the client. With the circuit breakers, we implement a fallback method which will handle the case if the needed service is down. So in the open state, the circuit breaker will trigger the fallback method. After a considerable time, the circuit breaker will go to half-open state.
When the circuit is open what can be done?
- You can show error message
- You can return cached data
Half Open State: This is a stage that the circuit breaker takes after spending some time in the closed stage. During this stage, the circuit breaker makes a remote call to the service. If the request fails, the circuit breaker will go to the open stage. If the service gives the proper response, the circuit breaker will go to the closed stage. So with a specified time period, the circuit breaker will check the service and decides which state to go.
Hystrix is a latency and fault tolerance java library designed to isolate points of access to remote systems, services, and 3rd-party libraries in a distributed environment. It helps to stop cascading failure and enable resilience in complex distributed systems where failure is inevitable.
Partition Key − This simple primary key consists of a single attribute referred to as the “partition key.” Internally, DynamoDB uses the key value as input for a hash function to determine storage.
Partition Key and Sort Key − This key, known as the “Composite Primary Key”, consists of two attributes.
I. The partition key II. The sort key.
DynamoDB applies the first attribute to a hash function, and stores items with the same partition key together; with their order determined by the sort key. Items can share partition keys, but not sort keys.
The Primary Key attributes only allow scalar (single) values; and string, number, or binary data types. The non-key attributes do not have these constraints.
ArrayList is an ordered Collection of objects, the objects will be in the same order that you use to add them to the ArrayList.
HashTable is a Collection of Key Value Pair. Each object in the HashTable is defined by a Key and Value.
Generally the ArrayList is quicker than the HashTable to insert elements in some cases. But when you have to lookup for an element the HashTable (using the key to search) is faster than the ArrayList.
Will create a hashtable in which I will insert an integer id as key and Map as value.
A piece of logic marked with synchronized becomes a synchronized block, allowing only one thread to execute at any given time.
63. What is a synchronized block? What is the difference between synchronized block and synchronized method?
A piece of logic marked with synchronized becomes a synchronized block, allowing only one thread to execute at any given time.
Synchronized method provides a lock corresponding to class level or object level, whereas Synchronized block provides a lock on any object depending on the parameter.
Concurrent accumulator classes that enable you to very efficiently increase / decrease the value of a counter in a thread safe manner. This is really a case where it’s not a question of taste, or preference – using these new classes in your code is really a no-brainer.
Concurrent accumulator classes that enable you to very efficiently increase / decrease the value of a counter in a thread safe manner. This is really a case where it’s not a question of taste, or preference – using these new classes in your code is really a no-brainer
Hot storage: represents frequently used and critical files stored at the edge for fast local access.
Warm storage: is often illustrated as files stored on a cloud storage gateway or file server/NAS for fast retrieval, most often at a corporate headquarters or remote office/branch office (ROBO).
Cold storage: doesn’t require fast access. It mostly represents archived materials and infrequently accessed projects and documents. These are increasingly stored in low-cost object and cloud storage tiers
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body). Abstraction is a process of hiding the implementation details and showing only functionality to the user.
An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method bodies. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also represents the IS-A relationship.
The equals() method compares two strings, and returns true if the strings are equal, and false if not.
Amazon Elastic Kubernetes Service (Amazon EKS) is a managed service that you can use to run Kubernetes on AWS without needing to install, operate, and maintain your own Kubernetes control plane or nodes.
Amazon Elastic Container Service for Kubernetes (EKS) is a cloud-based container management service that natively integrates with Kubernetes to deploy applications.
The EKS service automatically manages and scales clusters of infrastructure resources on AWS with Kubernetes, an open source tool for container orchestration that can be difficult for an enterprise to administer on its own. With Amazon EKS, an enterprise can use Kubernetes without having to install, operate or manage the container orchestration software.
Amazon Elastic Kubernetes Service (Amazon EKS) makes it easy to deploy, manage, and scale containerized applications using Kubernetes on Amazon Web Services.
Amazon EKS runs the Kubernetes management infrastructure for you across multiple Amazon Web Services availability zones to eliminate a single point of failure. Amazon EKS is certified Kubernetes conformant so you can use existing tooling and plugins from partners and the Kubernetes community. Applications running on any standard Kubernetes environment are fully compatible and can be easily migrated to Amazon EKS.
Amazon EKS is generally available for all Amazon Web Services customers.
https://docs.aws.amazon.com/cli/latest/reference/eks/index.html
Versioning is a means of keeping the multiple forms of an object in the same S3 bucket. Versioning can be used to retrieve, preserve and restore every version of an object in S3 bucket.
Versioning-enabled buckets allow you to recover the objects from the deletion or overwrite. It serves two purposes:
- If you delete an object, instead of deleting the object permanently, it creates a delete marker which becomes a current version of an object.
- If you overwrite an object, it creates a new version of the object and also restores the previous version of the object.
A thread can be in one of the five states. According to Sun, there is only 4 states in thread life cycle in Java: new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
- New
- Runnable
- Running
- Non-Runnable (Blocked)
- Terminated
Versioning is the creation and management of multiple releases of a product, all of which have the same general function but are improved, upgraded or customized. The term applies especially to operating systems (OSs), software and Web services.
You can use versioning to retain multiple versions of an object, which protects against accidental deletion of objects, and enables you to retrieve and restore earlier versions of an object.
SOAP | REST |
---|---|
SOAP is a protocol. | REST is an architectural style. |
SOAP stands for Simple Object Access Protocol. | REST stands for REpresentational State Transfer. |
SOAP can't use REST because its a protocol. | REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP. |
SOAP uses Services Interfaces to expose the business logic. | REST uses URI to expose business logic. |
JAX-WS is the Java API for SOAP web services. | JAX-RS is the Java API for RESTful web services. |
SOAP defines standards to be strictly followed. | Rest does not defines too much standards like SOAP. |
SOAP is more secure than REST as it uses WS-Security for transmission along with Secure Socket Layer. | REST is less secure than SOAP. |
Kubernetes is a production-grade open-source container orchestration service for automating deployment, scaling, and managing containerized workloads and services.
Google App Engine is a managed service by Google Cloud Platform for building and running applications in the form of containers.
Sr. No. | Key | @bean | @component |
---|---|---|---|
1 | Auto detection | It is used to explicitly declare a single bean, rather than letting Spring do it automatically. | If any class is annotated with @Component it will be automatically detect by using classpath scan. |
2 | Spring Container | Bean can be created even class is outside the spring container | We can’t create bean if class is outside spring container |
3 | Class/Method Level Annotation | It is a method level annotation | It is a class level annotation |
4 | @Configuration | It works only when class is also annotated with @Configuration | It works without @Configuration annotation |
5 | Use Case | We should use @bean, if you want specific implementation based on dynamic condition. | We can’t write specific implementation based on dynamic condition |
Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called a functional interface. An example is a java.lang.Runnable). Lambda expressions implement the only abstract function and therefore implement functional interfaces.
Lambda expressions are added in Java 8 and provide the below functionalities :
- Enable to treat functionality as a method argument, or code as data.
- A function that can be created without belonging to any class.
- A lambda expression can be passed around as if it was an object and executed on demand.
Predicates in Java are implemented with interfaces. Predicate is a generic functional interface representing a single argument function that returns a boolean value. It is located in the java.util.function package. It contains a test(T t) method that evaluates the predicate on the given argument.
A Functional Interface is an interface that allows only one Abstract method within the Interface scope. There are some predefined functional interfaces in Java-like Predicate, consumer, supplier, etc. The return type of a Lambda function (introduced in JDK 1.8) is also a functional interface.
The Functional Interface PREDICATE is defined in the java.util.Function package. It improves the manageability of code, helps in unit-testing them separately, and contains some methods
Singleton Pattern says that just “define a class that has only one instance and provides a global point of access to it".
There are two forms of singleton design pattern -
- Early Instantiation: the creation of instances at load time.
- Lazy Instantiation: the creation of instances when required.
An interface that does not contain methods, fields, and constants is known as marker interface. In other words, an empty interface is known as marker interface or tag interface. It delivers the run-time type information about an object. It is the reason that the JVM and compiler have additional information about an object. In short, it indicates a signal or command to the JVM.
java.lang.Cloneable and java.io.Serializable are examples of marker interfaces.
The declaration of marker interface is the same as interface in Java but the interface must be empty. For example:
public interface Serializable
{
}
Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB, and JMS technologies.
The reverse operation of serialization is called deserialization where a byte-stream is converted into an object. The serialization and deserialization process is platform-independent, which means you can serialize an object in a platform and deserialize it in a different platform.
For serializing the object, we call the writeObject() method ObjectOutputStream, and for deserialization we call the readObject() method of the ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
It is mainly used to travel an object's state on the network (which is known as marshaling).
Materialized views are the views that are similar to the normal views except for one property that they are refreshed faster. These views are updated automatically when any update happens in the master table.
- It is a logical and virtual copy of data.
- It is the result of a ‘select query’, given that the query is stored in the table or disk.
- The query expression and the resultant tuple are stored on the disk.
- The query expression isn’t executed every time the user tries to fetch data.
- This means, the user doesn’t get the most recently updated values of a table in the database.
- It has a storage and update cost associated with it.
- They are designed with a generic architecture, hence there is no SQL standard to define it.
- Its functionality is provided by certain databases as an extension.
- It is used when data has to be accessed frequently but the data in the table isn’t updated frequently.
Nonfunctional Requirements (NFRs) define system attributes such as security, reliability, performance, maintainability, scalability, and usability. They serve as constraints or restrictions on the design of the system across the different backlogs
An application's resiliency is its ability to recover from failures. Microservices-based applications often have several dependencies -- including databases, back-end components, and APIs -- that can potentially cause service call failures, categorized as;
- Transient faults
- Permanent faults
There are three proven microservices resilience patterns that boost fault tolerance and enable applications to handle failures gracefully.
Retry:
Microservices often have many dependencies, including databases, components, back-end services and APIs. Any of these dependencies can intermittently fail, and consequently create numerous service call failures. The retry pattern provides a solution to these transient errors.
Circuit Breaker:
While the retry pattern works for transient failures, teams still need a reliable microservices resiliency pattern that handles larger, long-term, permanent faults. If a retry mechanism accidentally invokes a severely damaged service several times until it gets the desired result, it could result in cascading service failures that become increasingly difficult to identify and fix.
Correlation ID:
In a typical microservices-based application, several services span different systems, possibly separated by large geographical distances. This means each service must log useful and meaningful data that specifies what it has been doing and details any failures. This requires a third microservices resiliency pattern geared towards service tracking.
The basic idea behind the circuit breaker is very simple. You wrap a protected function call in a circuit breaker object, which monitors it for failures. When we apply this pattern, we prevent possible application problems. This pattern follows the same concept as the safety electrical component named circuit breaker.
Once the failures reach a certain threshold, the circuit breaker trips, and all further calls to the circuit breaker return with an error or with some alternative service or default message, without the protected call being made at all. This will assure that the system is responsive and threads are not waiting for an unresponsive call, protecting the system to avoid catastrophic failures.
- In case service B goes down, service A should still try to recover from this and try to do one of the followings actions:
- Custom fallback: Try to get the same data from some other source. If not possible, use its own cache value or your custom client error response.
- Fail fast: If service A knows that service B is down, there is no point waiting for the timeout and consuming its own resources.
- Heal automatic: Periodically check if service B is working again.
- Other APIs should work: All other APIs should continue to work.
Closed: When everything is normal, the Circuit Breaker remains CLOSED and all calls to service B occur normally. If the number of failures exceeds a predetermined limit, the status changes to OPEN.
Open: In this state, the Circuit Breaker will not execute the service B call and return a treated error.
Half-Open: After a timeout period, the circuit switches to a half-open state to test if the underlying problem still exists. If a single call fails in this HALF-OPEN state, the breaker is once again tripped. If it succeeds, it resets back to the normal, CLOSED state.
Design Patterns in Java -* A design pattern is a well-proven solution for solving a specific problem/task.
Advantages of design pattern:
- They are reusable in multiple projects.
- They provide the solutions that help to define the system architecture.
- They capture the software engineering experiences.
- They provide transparency to the design of an application.
- They are well-proved and testified solutions since they have been built upon the knowledge and experience of expert software developers.
- Design patterns don’t guarantee an absolute solution to a problem. They provide clarity to the system architecture and the possibility of building a better system.
Categorization of design patterns: Basically, design patterns are categorized into two parts:
- Core Java (or JSE) Design Patterns.
- JEE Design Patterns.
Core Java Design Patterns In core java, there are mainly three types of design patterns, which are further divided into their sub-parts:
1.Creational Design Pattern
- Factory Pattern
- Abstract Factory Pattern
- Singleton Pattern
- Prototype Pattern
- Builder Pattern.
2. Structural Design Pattern
- Adapter Pattern
- Bridge Pattern
- Composite Pattern
- Decorator Pattern
- Facade Pattern
- Flyweight Pattern
- Proxy Pattern
3. Behavioral Design Pattern
- Chain Of Responsibility Pattern
- Command Pattern
- Interpreter Pattern
- Iterator Pattern
- Mediator Pattern
- Memento Pattern
- Observer Pattern
- State Pattern
- Strategy Pattern
- Template Pattern
- Visitor Pattern
There are two ways to create a thread:
- By extending the Thread class
- By implementing a Runnable interface.
Thread class: Thread class provides constructors and methods to create and perform operations on a thread. Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
- Thread()
- Thread(String name)
- Thread(Runnable r)
- Thread(Runnable r, String name)
Starting a thread: start() method of Thread class is used to start a newly created thread. It performs the following tasks:
- A new thread starts (with a new call stack)
- The thread moves from the New state to the Runnable state.
- When the thread gets a chance to execute, its target run() method will run.
Spring Boot Annotations are a form of metadata that provides data about a program. In other words, annotations are used to provide supplemental information about a program. It is not a part of the application that we develop. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program.
We can leverage the capabilities of the Spring DI engine using the annotations in the org.springframework.beans.factory.annotation and org.springframework.context.annotation packages.
DI-Related Annotations -
@Autowired: We can use the @Autowired to mark a dependency which Spring is going to resolve and inject. We can use this annotation with a constructor, setter, or field injection. @Autowired has a boolean argument called required with a default value of true. It tunes Spring's behavior when it doesn't find a suitable bean to wire. When true, an exception is thrown, otherwise, nothing is wired.
@Bean: @Bean marks a factory method which instantiates a Spring bean.
@Qualifier: We use @Qualifier along with @Autowired to provide the bean id or bean name we want to use in ambiguous situations.
@Required: @Required on setter methods to mark dependencies that we want to populate through XML.
@Value: We can use @Value for injecting property values into beans. It's compatible with constructor, setter, and field injection.
@DependsOn: We can use this annotation to make Spring initialize other beans before the annotated one. Usually, this behavior is automatic, based on the explicit dependencies between beans.
@Lazy: We use @Lazy when we want to initialize our bean lazily. By default, Spring creates all singleton beans eagerly at the startup/bootstrapping of the application context.
@Lookup: A method annotated with @Lookup tells Spring to return an instance of the method’s return type when we invoke it.
@Primary: Sometimes we need to define multiple beans of the same type. In these cases, the injection will be unsuccessful because Spring has no clue which bean we need.
@Scope: We use @Scope to define the scope of a @Component class or a @Bean definition. It can be either singleton, prototype, request, session, globalSession or some custom scope.
Context Configuration Annotations -
@Profile: If we want Spring to use a @Component class or a @Bean method only when a specific profile is active, we can mark it with @Profile.
@Import: We can use specific @Configuration classes without component scanning with this annotation.
@ImportResource: We can import XML configurations with this annotation. We can specify the XML file locations with the locations argument, or with its alias, the value argument.
@PropertySource: With this annotation, we can define property files for application settings.
@PropertySources: We can use this annotation to specify multiple @PropertySource configurations.
Splunk is an advanced, scalable, and effective technology that indexes and searches log files stored in a system. It analyzes the machine-generated data to provide operational intelligence. The main advantage of using Splunk is that it does not need any database to store its data, as it extensively makes use of its indexes to store the data.
Splunk is a software that processes and brings out insight from machine data and other forms of big data. This machine data is generated by a CPU running a webserver, IoT devices, logs from mobile apps, etc. It is not necessary to provide this data to the end-users and does not have any business meaning. However, they are extremely important to understand, monitor, and optimize the performance of the machines.
Data Ingestion Splunk can ingest a variety of data formats like JSON, XML, and unstructured machine data like web and application logs. The unstructured data can be modeled into a data structure as needed by the user.
Data Indexing The ingested data is indexed by Splunk for faster searching and querying on different conditions.
Data Searching Searching in Splunk involves using the indexed data for the purpose of creating metrics, predicting future trends, and identifying patterns in the data.
Using Alerts Splunk alerts can be used to trigger emails or RSS feeds when some specific criteria are found in the data being analyzed.
Dashboards Splunk Dashboards can show the search results in the form of charts, reports, pivots, etc.
Data Model The indexed data can be modeled into one or more data sets that are based on specialized domain knowledge.
Resilient Microservice Design – Bulkhead Pattern: The ability of the system to recover from the failure and remain functional makes the system more resilient. It also avoids any cascading failures.
Need For Resiliency: MicroServices are distributed in nature. It has more components and moving parts. In a distributed architecture, dealing with any unexpected failure is one of the biggest challenges to solve. It could be a hardware failure, network failure, etc. The ability of the system to recover from the failure and remain functional makes the system more resilient. It also avoids any cascading failures.
When one service synchronously invokes another there is always the possibility that the other service is unavailable or is exhibiting such high latency it is essentially unusable. Precious resources such as threads might be consumed by the caller while waiting for the other service to respond.
Problem How to prevent a network or service failure from cascading to other services?
Solution A service client should invoke a remote service via a proxy that functions in a similar fashion to an electrical circuit breaker. When the number of consecutive failures crosses a threshold, the circuit breaker trips, and for the duration of a timeout period, all attempts to invoke the remote service will fail immediately. After the timeout expires the circuit breaker allows a limited number of test requests to pass through. If those requests succeed the circuit breaker resumes normal operation. Otherwise, if there is a failure the timeout period begins again.
The circuit breaker has three distinct stages:
- Closed
- Open
- Half-Open
Closed – When everything is normal, the circuit breaker remains in the closed state and all calls pass through to the services. When the number of failures exceeds a predetermined threshold the breaker trips, and it goes into the Open state.
Open – The circuit breaker returns an error for calls without executing the function.
Half-Open – After a timeout period, the circuit switches to a half-open state to test if the underlying problem still exists. If a single call fails in this half-open state, the breaker is once again tripped. If it succeeds, the circuit breaker resets back to the normal, closed state.
Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.
The Hibernate Session interface provides createCriteria() method, which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query.
Restrictions with Criteria You can use the add() method available for the Criteria object to add restrictions for a criteria query.
Pagination Using Criteria There are two methods of the Criteria interface for pagination.
1. public Criteria setFirstResult(int firstResult) This method takes an integer that represents the first row in your result set, starting with row 0.
2. public Criteria setMaxResults(int maxResults) This method tells Hibernate to retrieve a fixed number maxResults of objects.
When a client needs to replace an existing Resource entirely, they can use PUT. When they're doing a partial update, they can use HTTP PATCH.
For instance, when updating a single field of the Resource, sending the complete Resource representation might be cumbersome and utilizes a lot of unnecessary bandwidth. In such cases, the semantics of PATCH makes a lot more sense.
Another important aspect to consider here is idempotence; PUT is idempotent; PATCH can be, but isn't required to. And, so – depending on the semantics of the operation we're implementing, we can also choose one or the other based on this characteristic.
Java provides a new additional package in Java 8 called java.util.stream. This package consists of classes, interfaces and enum to allow functional-style operations on the elements. You can use stream by importing the java.util.stream package.
Using stream, you can process data in a declarative way similar to SQL statements. You can use streams to filter, collect, print, and convert from one data structure to another etc.
Generating Streams With Java 8, the Collection interface has two methods to generate a Stream.
- stream() − Returns a sequential stream considering collection as its source.
- parallelStream() − Returns a parallel Stream considering collection as its source.
Stream provides the following features:
- 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.
- Streams are functional in nature. Operations performed on a stream do not modify its source. For example, filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather than removing elements from the source collection.
- Stream is lazy and evaluates code only when required.
- The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source.
static: We don’t create instance of Interface, so for accessing this variables we have only interface name, for that purpose: variables in java are static.
final: To make them constants. If 2 classes implement the same interface and you give both of them the right to change the value, conflict will occur in the current value of the var, which is why only one time initialization is permitted.
Variables in java are by default public static final, so if any class implementing this variables we can use this variables by using interface name only. Variables overridng is not in java.
99. What will happen if you put return statement or System.exit () on try or catch block? Will finally block execute?
Many programmers think that no matter what, but the finally block will always execute. This question challenge that concept by putting a return statement in the try or catch block or calling System.exit() from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put a return statement in the try block or catch block but finally block won't run if you call System.exit() from try or catch block.
You can not override a private or static method in Java , if you create a similar method with same return type and same method arguments in child class then it will hide the superclass method, this is known as method hiding.
Similarly, you cannot override a private method in sub class because it's not accessible there, what you do is create another private method with the same name in the child class.
public class Test {
public static void main ( String [] args) {
System. out . println( Math. min( Double. MIN_VALUE , 0.0d ));
}
}
This question is tricky because unlike the Integer , where MIN_VALUE is negative, both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers. The Double.MIN_VALUE is 2^(-1074) , a double constant whose magnitude is the least among all double values. So unlike the obvious answer, this program will print 0.0 because Double.MIN_VALUE is greater than 0. I have asked this question to Java developer having experience up to 3 to 5 years and surprisingly almost 70% candidate got it wrong.
Wish you all the luck.
- International Trainer and Author
- 12 Awards till date
- 14+ years of experience
- Trained more than 500000 candidates globally
- Blog : http://aatul.me
- LinkedIn : https://in.linkedin.com/in/atulpalandurkar
- Facebook : https://facebook.com/aatulpalandurkar
- Instagram : https://instagram.com/aatulpalandurkar
- YouTube : https://www.youtube.com/user/AtulPalandurkar?sub_confirmation=1
- Write to me : atul.palandurkar@gmail.com