Looking forward to appear in Java Interview, here are the key Java Interview Questions with Answers only for you.
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
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.
Yes, I have developed all CRUD services in Spring boot and inSpring MVC as well.
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. |
Wish you all the luck.