Interview Questions
Interview Questions
26 October 2021
12:58
What is Annotations?
Spring :
Dependency injection : which is better either setter or
constructor
Bean Life Cycle
1. oops concept
2. what is abstraction how we achieve it?
3. Can we pass by reference. dfeault type of passing parameter :
There is only call by value in java, not call by reference.
4. What happen if we override static method
// As per overriding rules this should call to class Child static overridden method.
Since static method cannot be overridden, it calls Parent static method . Method
Hiding in child class
Parent p = new Child();
p.staticMethod();
collection:
------------------------------
1. which data type is ideal for map key.
2. what needs to be done if we want to use custom object as key
3. what is hash collision
4. how java 8 improved performance in case of more hash collision:
multi-thread:
---------------------------
1. can we call run/call method ouside thread and how it will behave
2. why wait/notify/notifyall method associated with object class
3. can we call wait/notify/notifyall methods outside synchronization
https://www.zdnet.com/article/calling-wait-notify-and-notifyall-within-a-non-
synchronized-method/
4. what is class level locking and bucket level locking
5. what is countdown latch
design pattern:
-------------------------
1. singleton implementation
2. how to break singleton pattern
3. how to prevent it
4. Factory and AbstractFactory pattern in details
5. Builder pattern
Spring/Spring boot:
--------------------------
1. What are the benefits/disadvantages of using spring framework and springboot
2. What are the events generated when running springboot application
3. what are springboot annotation
4. benefits/features of using @service/@repository/@controller/@restcontroller
5. diff between @primary and @qualifier
6. centralize exception handling (@controlleradvice)
7. session scopes in spring
8. @transaction and its attributes
9. repository interfaces/classes(repository/curdrepository/pagingandsortingrepository/
jparepository/simplejparepository)
10. how to configure multiple database/datasource in springboot application
11. sessions in jpa/hibernate
12. entity object represents whole table data or single row
13. bean initialization @lazy and eager initialization
14. how to register external bean in spring context
15. how to use propertise in class
16. how to configure external server in springboot
stream api:
--------------------------------
1. advantage of stream api over collection
2. what is intermediate and terminal operations
3. how streams internally works
4. calculate min/min/sum/count distinct/grouping by/
Reduce
Diamond Problem
1, Dilip ,90000
1, Dilip ,100000
Interview Programs
11 October 2022
20:17
Checking for prime number. Program to verify whether a given number is a prime or composite.
https://javaconceptoftheday.com/solving-real-time-queries-using-java-8-features-employee-
management-system/
Access Specifiers
17 March 2022
07:15
In Java, methods and data members can be encapsulated by the following four access specifiers. The
access specifiers are listed according to their restrictiveness order.
But, the classes and interfaces themselves can have only two access specifiers when declared
outside any other class.
1) public
2) default (when no access specifier is specified)
Note: Nested interfaces and classes can have all access specifiers.
Note: We cannot declare class/interface with private or protected access specifiers.
interface Test {
int x = 10; // x is public static final and must be
initialized here
void foo(); // foo() is public
}
Strings
18 November 2021
19:55
1. Find every character count from String
2. print the reverse of the string
Threads
22 December 2021
13:49
Example
Suppose, there are two threads A and B. The thread A and B acquired the
lock of Object-A and Object-B, respectively. Assume that thread A
executing method A and wants to acquire the lock on Object-B, while
thread B is already acquired a lock on Object-B.
On the other hand, thread B also tries to acquire a lock on Object-A, while
thread A is acquired a lock on Object-A. In such a situation both threads
will not complete their execution and wait for releasing the lock. The
situation is known as, deadlock.
A race condition occurs when two or more threads can access shared
data and they try to change it at the same time. Because the thread
scheduling algorithm can swap between threads at any time, you don't
know the order in which the threads will attempt to access the shared
data. Therefore, the result of the change in data is dependent on the
thread scheduling algorithm, i.e. both threads are "racing" to
access/change the data.
if (x == 5) // The "Check"
{
y = x * 2; // The "Act"
// If another thread changed x in between "if (x == 5)" and "y = x * 2"
above,
// y will not be equal to 10.
}
The point being, y could be 10, or it could be anything, depending on
whether another thread changed x in between the check and act. You
have no real way of knowing.
In order to prevent race conditions from occurring, you would typically
put a lock around the shared data to ensure only one thread can access
the data at a time. This would mean something like this:
// Obtain lock for x
if (x == 5)
{
y = x * 2; // Now, nothing can change x until the lock is released.
// Therefore y = 10
}
// release lock for x
https://stackoverflow.com/questions/34510/what-is-a-race-condition
Wait(), notify(), notifyAll() why these are part of Object but not Thread.
If wait() and notify() were on the Thread instead then each thread would
have to know the status of every other thread. How would thread1 know
that thread2 was waiting for access to a particular resource? If thread1
needed to call thread2.notify() it would have to somehow find out that
thread2 was waiting. There would need to be some mechanism for
threads to register the resources or actions that they need so others
could signal them when stuff was ready or available.
In Java, the object itself is the entity that is shared between threads
which allows them to communicate with each other. The threads have no
specific knowledge of each other and they can run asynchronously. They
run and they lock, wait, and notify on the object that they want to get
access to. They have no knowledge of other threads and don't need to
know their status. They don't need to know that it is thread2 which is
waiting for the resource -- they just notify on the resource and
whomever it is that is waiting (if anyone) will be notified.
The threads can communicate with each other through wait(), notify()
and notifyAll() methods in Java. These are final methods defined in the
Object class and can be called only from within a synchronized context.
The wait() method causes the current thread to wait until another thread
invokes the notify() or notifyAll() methods for that object. The notify()
method wakes up a single thread that is waiting on that object’s monitor.
The notifyAll() method wakes up all threads that are waiting on that
object’s monitor. A thread waits on an object’s monitor by calling one of
the wait() method. These methods can throw
IllegalMonitorStateException if the current thread is not the owner of the
object’s monitor.
https://www.tutorialspoint.com/importance-of-wait-notify-and-notifyall-methods-in-java
Sleep(): This Method is used to pause the execution of current thread for a specified
time in Milliseconds. Here, Thread does not lose its ownership of the monitor and
resume’s it’s execution
Wait(): This method is defined in object class. It tells the calling thread (a.k.a Current
Thread) to wait until another thread invoke’s the notify() or notifyAll() method for this
object, The thread waits until it reobtains the ownership of the monitor and Resume’s
Execution.
What is Callable Interface?
Data Structures
16 December 2021
09:13
Time Complexity
Space Complexity
Time Complexity: It is defined as the number of times a particular instruction set is executed rather
than the total time is taken. It is because the total time took also depends on some external factors
like the compiler used, processor’s speed, etc.
Space Complexity: It is the total memory space required by the program for its execution.
Average time complexity of different data structures for different operations
Exception Handling
11 December 2021
15:33
Types of problems:
There are two types of problems associated with it which are as follows:
Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception
Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked exception
Case 1: If SuperClass doesn’t declare any exception and subclass declare checked exception.
package com.practice.exception.handling;
import java.io.IOException;
class SuperClass{
Result :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Exception IOException is not compatible with throws clause in
SuperClass.methodOne()
Case 2: If SuperClass doesn’t declare any exception and SubClass declare Unchecked
exception
package com.practice.exception.handling;
class ParentClass {
The SuperClass declares an exception. In this problem 3 cases will arise as follows:
Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child
exception of the SuperClass declared Exception.
Case 2: If SuperClass declares an exception and SubClass declares a child exception of the SuperClass
declared Exception.
Case 3: If SuperClass declares an exception and SubClass declares without exception.
Case 1: If SuperClass declares an exception and SubClass declares exceptions other than the child
exception of the SuperClass declared Exception.
package com.practice.exception.handling;
class Parent {
// SuperClass declare an exception
public void methodOne() throws RuntimeException{
System.out.println("Parent : methodOne");
}
}
Case 2: If SuperClass declares an exception and SubClass declares a child exception of the
SuperClass declared Exception.
package com.practice.exception.handling;
//If SuperClass declares an exception and SubClass declares exceptions child exception of the
SuperClass declared Exception.
class Parent {
// SuperClass declare an exception
public void methodOne() throws RuntimeException{
System.out.println("Parent : methodOne");
}
package com.practice.exception.handling;
class ParentTwo{
// SuperClass declare an exception
public void methodOne() throws RuntimeException {
System.out.println("ParentTwo : methodOne");
}
Rule 1: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.
Rule 2: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.
Rule 3: If the superclass method declares an exception, subclass overridden method can declare
the same subclass exception or no exception but cannot declare parent exception.
Question 1 : Parent class method contains unchecked exception, child class method contains
checked exception , is this works?
As per Rule 3 , Compilation issue.
Inheritance
07 December 2021
12:49
Association in Java
Association in Java defines the connection between two classes that are
set up through their objects. Association manages one-to-one, one-to-
many, and many-to-many relationships.
Types of Association
In Java, two types of Association are possible:
1. IS-A Association
2. HAS-A Association
1. Aggregation
2. Composition
1) IS-A Association
The IS-A Association is also referred to as Inheritance
2) HAS-A Association
The HAS-A Association is further classified into two parts, i.e.,
Aggregation and Composition. Let's understand the difference between
both of them one by one.
1) Aggregation
In Java, the Aggregation association defines the HAS-A relationship. Aggregation
follows the one-to-one or one-way relationship. If two entities are in the aggregation composition,
and one entity fails due to some error, it will not affect the other entity.
Let's take the example of a toy and its battery. The battery belongs to a
toy, and if the toy breaks and deletes from our database, the battery will
still remaining in our database, and it may still be working. So in
Aggregation, objects always have their own lifecycles when the ownership
exists there.
2) Composition
A restricted form of the Aggregation where the entities are strongly
dependent on each other. Unlike Aggregation, Composition
represents the part-of relationship. When there is an aggregation between two entities, the
aggregate object can exist without the other entity, but in the case of Composition, the composed
object can't exist. To learn more about Composition, click here
.
Let's take an example to understand the concept of Composition.
We create a class Mobile that contains variables, i.e., name,
ram and rom. We also create a class MobileStore that has a reference
to refer to the list of mobiles. A mobile store can have more than one
mobile. So, if a mobile store is destroyed, then all mobiles within that
particular mobile store will also be destroyed because mobiles cannot
exist without a mobile store. The relationship between the mobile store
and mobiles is Composition.
Shallow Copy
The default implementation of the clone method creates a
shallow copy of the source object, it means a new instance of
type Object is created, it copies all the fields to a new instance
and returns a new object of type ‘Object’. This Object explicitly
needs to be typecast in object type of source object.
This object will have an exact copy of all the fields of source
object including the primitive type and object references. If the
source object contains any references to other objects in field
then in the new instance will have only references to those
objects, a copy of those objects is not created. This means if we
make changes in shallow copy then changes will get reflected
in the source object. Both instances are not independent.
The clone method in Object class is protected in nature, so not
all classes can use the clone() method. You need to implement
Cloneable interface and override the clone method. If the
Cloneable interface is not implemented then you will get
CloneNotSupportedException.super.clone () will return shallow
copy as per implementation in Object class.
System.out.println(emp1.dept.designation); // Output :
Director
}
}
Output:
Deep Copy
emp2.dept.designation = "Director";
System.out.println(emp1.dept.designation); //
Output : AVP
}
}
Output:
2. Composition Vs Aggregation
Java
Composition
Composition is a “belongs-to” type of relationship. It
means that one of the objects is a logically larger
structure, which contains the other object. In other
words, it's part or member of the other object.
Alternatively, we often call it a “has-a”
relationship (as opposed to an “is-a” relationship,
which is inheritance).
For example, a room belongs to a building, or in
other words a building has a room. So basically,
whether we call it “belongs-to” or “has-a” is only a
matter of point of view.
Aggregation
Aggregation is also a “has-a” relationship. What
distinguishes it from composition, that it doesn't
involve owning. As a result, the lifecycles of the
objects aren't tied: every one of them can exist
independently of each other.
For example, a car and its wheels. We can take off
the wheels, and they'll still exist. We can mount
other (preexisting) wheels, or install these to
another car and everything will work just fine.
Of course, a car without wheels or a detached wheel
won't be as useful as a car with its wheels on. But
that's why this relationship existed in the first place:
to assemble the parts to a bigger construct,
which is capable of more things than its parts.
Since aggregation doesn't involve owning, a
member doesn't need to be tied to only one
container. For example, a triangle is made of
segments. But triangles can share segments as their
sides.
3. Type Casting (Widening and
Narrowing ) in Java
Type casting is a method or process that converts a data
type into another data type in both ways manually and
automatically. The automatic conversion is done by the
compiler and manual conversion performed by the
programmer. In this section, we will discuss type
casting and its types with proper examples.
Example :
1. int x = 7;
2. //automatically converts the integer type into long type
3. long y = x;
4. //automatically converts the long type into float type
5. float z = y;
double -> float -> long -> int -> char -> short -> b
yte
Example:
1. double d = 166.66;
2. //converting double data type into long data type
3. long l = (long)d;
4. //converting long data type into int data type
5. int i = (int)l;
The System class is a final class and do not provide any public
constructors. Because of this all of the members are methods
contained in this class are static in nature.
The System class also provides facilities like standard input,
standard output, and error output Streams. it can't be
instantiated.
Program - 2
class datas
{
public static final int data =100;
}
public class program1
{
public static void main(String args[])
{
System.out.printf("The value of data is : "+datas.data);
}
}
File Operations
27 November 2021
14:28
JAVA8
22 November 2021
16:29
A container object which may or may not contain a non-null value. If a value is
present, isPresent() will return true and get() will return the value.
empty()
Returns an empty Optional instance.
filter(Predicate<? super T> predicate)
If a value is present, and the value matches the given predicate, return
an Optional describing the value, otherwise return an empty Optional.
get()
If a value is present in this Optional, returns the value, otherwise
throws NoSuchElementException.
ifPresent(Consumer<? super T> consumer)
If a value is present, invoke the specified consumer with the value,
otherwise do nothing.
isPresent()
Return true if there is a value present, otherwise false.
ofNullable(T value)
Returns an Optional describing the specified value, if non-null, otherwise
returns an empty Optional.
orElse(T other)
Return the value if present, otherwise return other.
orElseThrow(Supplier<? extends X> exceptionSupplier)
Return the contained value, if present, otherwise throw an exception to
be created by the provided supplier.
the Stream interface has a map() and flatmap() methods and both have intermediate stream
operation and return another stream as method output. Both of the functions map() and
flatMap are used for transformation and mapping operations. map() function produces one
output for one input value, whereas flatMap() function produces an arbitrary no of values as
output (ie zero or more than zero) for each input value.
map() can be used where we have to map the elements of a particular collection to a certain
function, and then we need to return the stream which contains the updated results.
Example: Multiplying All the elements of the list by 3 and returning the updated list.
flatMap() can be used where we have to flatten or transform out the string, as we cannot
flatten our string using map().
Example: Getting the 1st Character of all the String present in a List of Strings and returning
the result in form of a stream.
Difference Between map() and flatmap()
map() flatMap()
One-to-one mapping occurs in map(). One too many mapping occurs in flatMap().
The function passed to map() The function you pass to flatmap() operation
operation returns a single value for a returns an arbitrary number of values as the
single input. output.
Only perform the mapping. Perform mapping as well as flattening.
Produce a stream of value. Produce a stream of stream value.
map() is used only for flatMap() is used both for transformation
transformation. and mapping.
https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html
// Assignment context
Predicate<String> p = String::isEmpty;
// Method invocation context
stream.filter(e -> e.getSize() > 10)...
// Cast context
stream.map((ToIntFunction) e -> e.getSize())...
The interfaces in this package are general purpose functional interfaces used
by the JDK, and are available to be used by user code as well. While they do
not identify a complete set of function shapes to which lambda expressions
might be adapted, they provide enough to cover common requirements. Other
functional interfaces provided for specific purposes, such as FileFilter, are
defined in the packages where they are used.
The interfaces in this package are annotated with FunctionalInterface. This
annotation is not a requirement for the compiler to recognize an interface as a
functional interface, but merely an aid to capture design intent and enlist the
help of the compiler in identifying accidental violations of design intent.
Functional interfaces often represent abstract concepts like functions, actions,
or predicates. In documenting functional interfaces, or referring to variables
typed as functional interfaces, it is common to refer directly to those abstract
concepts, for example using "this function" instead of "the function
represented by this object". When an API method is said to accept or return a
functional interface in this manner, such as "applies the provided function
to...", this is understood to mean a non-null reference to an object
implementing the appropriate functional interface, unless potential nullity is
explicitly specified.
The functional interfaces in this package follow an extensible naming
convention, as follows:
There are several basic function shapes, including Function (unary function
from T to R), Consumer (unary function from T to void), Predicate (unary
function from T to boolean), and Supplier (nilary function to R).
Function shapes have a natural arity based on how they are most commonly
used. The basic shapes can be modified by an arity prefix to indicate a
different arity, such as BiFunction (binary function from T and U to R).
There are additional derived function shapes which extend the basic function
shapes, including UnaryOperator (extends Function)
and BinaryOperator (extends BiFunction).
Type parameters of functional interfaces can be specialized to primitives
with additional type prefixes. To specialize the return type for a type that has
both generic return type and generic arguments, we prefix ToXxx, as
in ToIntFunction. Otherwise, type arguments are specialized left-to-right, as
in DoubleConsumer or ObjIntConsumer. (The type prefix Obj is used to
indicate that we don't want to specialize this parameter, but want to move on
to the next parameter, as in ObjIntConsumer.) These schemes can be
combined, as in IntToDoubleFunction.
If there are specialization prefixes for all arguments, the arity prefix may be
left out (as in ObjIntConsumer).
System.out::println
where “::” is an operator that distinguishes class name from the method
name.
Optional Class
21 September 2022
19:20
Every Java Programmer is familiar with NullPointerException. It can crash your code. And it is very
hard to avoid it without using too many null checks. So, to overcome this, Java 8 has introduced a
new class Optional in java.util package. It can help in writing a neat code without using too many null
checks. By using Optional, we can specify alternate values to return or alternate code to run. This
makes the code more readable because the facts which were hidden are now visible to the
developer.
Method References
17 March 2022
07:54
Java provides a new feature called method reference in Java 8. Method reference is used to refer
method of functional interface. It is compact and easy form of lambda expression. Each time when
you are using lambda expression to just referring a method, you can replace your lambda expression
with method reference.
Lambda Expressions
17 March 2022
07:54
It provides a clear and concise way to represent one method interface using an
expression.
Lambda expressions basically express instances of functional interfaces
Enable to treat functionality as a method argument, or
code as data.
interface Addable{
int add(int a,int b);
}
public class LambdaExpressionExample6 {
public static void main(String[] args) {
// Lambda expression without return keyword.
Addable ad1=(a,b)->(a+b);
System.out.println(ad1.add(10,20));
// Lambda expression with return keyword.
Addable ad2=(int a,int b)->{
return (a+b);
};
System.out.println(ad2.add(100,200));
}
}
How will you get the current date and time using Java 8 Date and
Time API?
Answer: The below program is written with the help of the new API
introduced in Java 8. We have made use of LocalDate, LocalTime, and
LocalDateTime API to get the current date and time.
In the first and second print statement, we have retrieved the current date
and time from the system clock with the time-zone set as default. In the third
print statement, we have used LocalDateTime API which will print both date
and time.
class Java8 {
public static void main(String[] args) {
System.out.println("Current Local Date: " + java.time.LocalDate.now());
//Used LocalDate API to get the date
System.out.println("Current Local Time: " + java.time.LocalTime.now());
//Used LocalTime API to get the time
System.out.println("Current Local Date and Time: " +
java.time.LocalDateTime.now());
//Used LocalDateTime API to get both date and time
}
}
Output:
Streams
25 November 2021
08:11
https://javaconceptoftheday.com/solving-real-time-queries-using-java-8-features-employee-
management-system/
For example after calling map() or flatMap() you can still call filter() method on Stream.
On the other hand, the terminal operation produces a result other than Streams like a value or
a Collection.
Once a terminal method like forEach() or collect() is called, you cannot call any other
method of Stream or reuse the Stream.
What does the peek() method do? When should you use it?
The peek() method of Stream class allows you to see through a Stream pipeline. You can peek
through each step and print meaningful messages on the console. It's generally used for debugging
issues related to lambda expression and Stream processing.
Example :
Output :
They only work when you call a terminal method on the Stream and finish as soon as they find the
data they are looking for rather than scanning through the whole set of data.
You can see it just has one test() method which takes an object and returns a boolean. The
method is used to test a condition if it passes; it returns true otherwise false.
Since it is a functional interface, you can also use it as the assignment target for a lambda
expression or method reference.
A Consumer is also a functional interface in JDK 8, which represents an operation that accepts a
single input argument and returns no result.
Unlike other functional interfaces, Consumer is expected to operate via side-effects. The
functional method of Consumer is accept(T t), and because it's a functional interface, you
can use it as the assignment target for a lambda expression or method interface in Java 8.
Unlike sequential Stream, the parallel Stream can launch multiple threads to search for those
orders on the different parts of the Stream and then combine the result.
Streams Notes
04 September 2022
11:54
Intermediate operations return a new stream. They are always lazy; executing an intermediate
operation such as filter() does not actually perform any filtering, but instead creates a new
stream that, when traversed, contains the elements of the initial stream that match the given
predicate. Traversal of the pipeline source does not begin until the terminal operation of the
pipeline is executed.
Processing streams lazily allows for significant efficiencies; in a pipeline such as the filter-map-sum
example above, filtering, mapping, and summing can be fused into a single pass on the data, with
minimal intermediate state. Laziness also allows avoiding examining all the data when it is not
necessary; for operations such as "find the first string longer than 1000 characters", it is only
necessary to examine just enough strings to find one that has the desired characteristics without
examining all of the strings available from the source. (This behavior becomes even more important
when the input stream is infinite and not merely large.)
Intermediate operations are further divided into stateless and stateful operations. Stateless
operations, such as filter and map, retain no state from previously seen element when processing a
new element -- each element can be processed independently of operations on other elements.
Stateful operations, such as distinct and sorted, may incorporate state from previously seen
elements when processing new elements.
Stateful operations may need to process the entire input before producing a result. For example,
one cannot produce any results from sorting a stream until one has seen all elements of the stream.
As a result, under parallel computation, some pipelines containing stateful intermediate operations
may require multiple passes on the data or may need to buffer significant data. Pipelines containing
exclusively stateless intermediate operations can be processed in a single pass, whether sequential
or parallel, with minimal data buffering.
Parallelism
Processing elements with an explicit for-loop is inherently serial. Streams facilitate parallel execution
by reframing the computation as a pipeline of aggregate operations, rather than as imperative
operations on each individual element. All streams operations can execute either in serial or in
parallel. The stream implementations in the JDK create serial streams unless parallelism is explicitly
requested. For example, Collection has methods Collection.stream() and Collection.parallelStream(),
which produce sequential and parallel streams respectively; other stream-bearing methods such
as IntStream.range(int, int) produce sequential streams but these streams can be efficiently
parallelized by invoking their BaseStream.parallel() method. To execute the prior "sum of weights of
widgets" query in parallel, we would do:
The only difference between the serial and parallel versions of this example is the creation of the
initial stream, using "parallelStream()" instead of "stream()". When the terminal operation
is initiated, the stream pipeline is executed sequentially or in parallel depending on the orientation
of the stream on which it is invoked. Whether a stream will execute in serial or parallel can be
determined with the isParallel() method, and the orientation of a stream can be modified with
the BaseStream.sequential() and BaseStream.parallel() operations. When the
terminal operation is initiated, the stream pipeline is executed sequentially or in parallel depending
on the mode of the stream on which it is invoked.
Except for operations identified as explicitly nondeterministic, such as findAny(), whether a stream
executes sequentially or in parallel should not change the result of the computation.
Most stream operations accept parameters that describe user-specified behavior, which are often
lambda expressions. To preserve correct behavior, these behavioral parameters must be non-
interfering, and in most cases must be stateless. Such parameters are always instances of
a functional interface such as Function, and are often lambda expressions or method references.
Non-interference
Streams enable you to execute possibly-parallel aggregate operations over a variety of data sources,
including even non-thread-safe collections such as ArrayList. This is possible only if we can
prevent interference with the data source during the execution of a stream pipeline. Except for
the escape-hatch operations iterator() and spliterator(), execution begins when the
terminal operation is invoked, and ends when the terminal operation completes. For most data
sources, preventing interference means ensuring that the data source is not modified at
all during the execution of the stream pipeline. The notable exception to this are streams whose
sources are concurrent collections, which are specifically designed to handle concurrent
modification. Concurrent stream sources are those whose Spliterator reports
the CONCURRENT characteristic.
Accordingly, behavioral parameters in stream pipelines whose source might not be concurrent
should never modify the stream's data source. A behavioral parameter is said to interfere with a
non-concurrent data source if it modifies, or causes to be modified, the stream's data source. The
need for non-interference applies to all pipelines, not just parallel ones. Unless the stream source is
concurrent, modifying a stream's data source during execution of a stream pipeline can cause
exceptions, incorrect answers, or nonconformant behavior. For well-behaved stream sources, the
source can be modified before the terminal operation commences and those modifications will be
reflected in the covered elements. For example, consider the following code:
As the name suggests, a functional interface is an interface that represents a function. Technically,
an interface with just one abstract method is called a functional interface.
You can also use @FunctionalInterface to annotated a functional interface. In that case, the
compiler will verify if the interface actually contains just one abstract method or not. It's like
the @Override annotation, which prevents you from accidental errors.
Another useful thing to know is that If a method accepts a functional interface, then you can pass a
lambda expression to it.
Arrays
18 November 2021
19:56
int temp;
int maxValue = 0 ;
for(int i=0;i++;i<numbers.length()){
temp = numbers[i];
if(temp > maxVlue){
maxValue = temp;
}
}
Collections
26 October 2021
12:59
Concurrent Modification Exception
Comparable and Comparator both are interfaces and can be used to sort
collection elements.
However, there are many differences between Comparable and
Comparator interfaces that are given below.
Comparable Comparator
1) Comparable provides a single The Comparator
sorting sequence. In other words, we provides multiple sorting
can sort the collection on the basis of a sequences. In other words, we
single element such as id, name, and can sort the collection on the
price. basis of multiple elements such
as id, name, and price etc.
2) Comparable affects the original Comparator doesn't affect the
class, i.e., the actual class is modified. original class, i.e., the actual
class is not modified.
3) Comparable provides compareTo() Comparator provides compare()
method to sort elements. method to sort elements.
4) Comparable is present A Comparator is present in
in java.lang package. the java.util package.
5) We can sort the list elements of We can sort the list elements of
Comparable type Comparator type
by Collections.sort(List) method. by Collections.sort(List,
Comparator) method.
@Override
public int compare(Employee emp1, Employee emp2) {
/*
* if (emp1.getEmp_id() == emp2.getEmp_id()) { return 0; } else if
* (emp1.getEmp_id() > emp2.getEmp_id()) { return 1; } return -1;
*/
}
What is Generics?
Time Complexity of Array list Operations, Linked List Operations , Hashmap Operations
Iterators
27 November 2021
07:34
The Java Collection supports two types of iterators; Fail Fast and Fail Safe. These iterators
are very useful in exception handling.
The Fail fast iterator aborts the operation as soon it exposes failures and stops the entire
operation. Comparatively, Fail Safe iterator doesn't abort the operation in case of a failure.
Instead, it tries to avoid failures as much as possible.
Concurrent Modification
The Concurrent modification in Java is to modify an object
concurrently while another task is running over it. In simple terms,
concurrent modification is the process of modifying objects while
another thread is running over them. It will change the structure of
the data collection, either by removing, adding, or updating the
value of the elements in the collection.
Not all iterators support this behavior; implementation of some
iterator may throw ConcurrentModificationException.
Fail Fast:
The Fail Fast iterators immediately throw ConcurrentModificationException in case of
structural modification of the collection. Structural modification means adding, removing,
updating the value of an element in a data collection while another thread is iterating over
that collection. Some examples of Fail Fast iterator are iterator on ArrayList, HashMap
collection classes.
How it Works
The Fail Fast iterator uses an internal flag called modCount to know
the status of the collection, whether the collection is structurally
modified or not. The modCount flag is updated each time a
collection is modified; it checks the next value; if it finds, then the
modCount will be modified after this iterator has been created. It
will throw ConcurrentModificationException.
Consider the below example to understand the behaviour of the Fail
Fast iterator:
1. import java.util.HashMap;
2. import java.util.Iterator;
3. import java.util.Map;
4. public class FailFastDemo {
5. public static void main(String[] args)
6. {
7. Map<String, String> empName = new HashMap<Strin
g, String>();
8. empName.put("Sam Hanks", "New york");
9. empName.put("Will Smith", "LA");
10. empName.put("Scarlett", "Chicago");
11. Iterator iterator = empName.keySet().iterator();
12. while (iterator.hasNext()) {
13. System.out.println(empName.get(iterator.next()));
14. // adding an element to Map
15. // exception will be thrown on next call
16. // of next() method.
17. empName.put("Istanbul", "Turkey");
18. }
19. }
20. }
Output:
LA
Exception in thread "main"
java.util.ConcurrentModificationException
at
java.util.HashMap$HashIterator.nextNode(HashMap.java:1445)
at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
at FailFastDemo.main(FailFastDemo.java:14)
From the above output, we can notice the following points:
The Fail Fast iterator throws a
ConcurrentModificationException if a collection is modified
while iterating over it.
The Fail Fast iterator uses an original collection to traverse
over the collection's elements.
They are memory savers, don't require extra memory.
The Fail Fast iterators returned by ArrayList, HashMap, Vector
classes.
Output:
EIGHT : 8
FIVE : 5
NINE : 9
ONE : 1
SEVEN : 7
From the above example, we can see we are iterating the collection
while the other thread is performing. The iteration result is placed in
the same collection, which means it is not creating any separate
copy of the object and also does not throwing any
ConcurrentModificationException.
From the above examples, we can notice the following points about
the Fail Safe iterators:
We can perform the modification operations on a collection
while iterating over it.
They will not throw ConcurrentModificationException during
the iteration.
The Fail Safe iterators use a copy of the collection to traverse
over the elements.
Unlike the Fail Fast, they require more memory as they cloned
the collection.
The examples of Fail Safe iterators are ConcurrentHashMap,
CopyOnWriteArrayList, etc.
ArrayList
The ArrayList class implements the List interface.
It uses a dynamic array to store the duplicate element of different
data types.
The ArrayList class maintains the insertion order and is non-
synchronized.
The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
LinkedList
LinkedList implements the Collection interface.
It uses a doubly linked list internally to store the elements.
It can store the duplicate elements.
It maintains the insertion order and is not synchronized.
In LinkedList, the manipulation is fast because no shifting is
required.
Set Interface
Set Interface in Java is present in java.util package. It extends the
Collection interface. It represents the unordered set of elements
which doesn't allow us to store the duplicate items. We can store at
most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.
Set can be instantiated as:
1. Set<data-type> s1 = new HashSet<data-type>();
2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();
Map
18 November 2021
19:59
Advantages of ConcurrentHashMap?
Spring Boot
16 November 2021
13:33
Why we are using @SpringBootApplication
What is @EnableAutoConfiguration
@Bean and @Component. What is the different? Which one should use be
used?
The most benefit of using a framework like Spring is auto-configuration. By only introducing the
library or the module to the classpath, Spring could automatically scan it and create the necessary
object and @Autowrired it.
@Component is an annotation that annotates a class. It tells Spring to use this class to create a bean
if there is somewhere else depend on this class. The creation of the class is totally controlled by
Spring. And only one bean created per class.
@Component
class UserService {
public void updateUser(User user) {
…
}
}
@Controller
class UserController {
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
}
In this example, Spring will recognize the appearance of the UserSerivce class because it was marked
with @Component annotation. So when it tries to initiate the UserController object, it knows that it
needs a UserService to put to UserController constructor. And the creation of the UserService will be
controlled totally by Spring. It is a pretty declarative way to define dependency.
With @Component our life is so good. So why do we even need something like @Bean annotation?
When should we use it? First, @Bean is an annotation that used for annotating the function (not a
class) that will return an object of a class that will be registered as a bean object by Spring.
You could use it in case you are using a third-party library when you don’t have access to the source
code of the library. So you can’t just put @Component annotation of the class that you to create a
bean.
You can combine with the @Configuration annotated the class that contains the method return the
beans or otherwise Spring won’t catch and register it as a bean for your dependency resolution.
Let’s consider this example.
class UserService {
private final PasswordEncoder encoder;
@Autowired
public UserService(PasswordEncoder encoder) {
this.encoder = encoder;
}
@Configuration
class PasswordEncoderConfiguration {
@Bean
public PasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
In this example, I couldn’t change the code base of the bcrypt library so to create the encoder
object. I have to use a @Configuration class to create the bean that I need in a method inside that
@Configuration class. In this way, we could create as many as you want bean objects. And you have
to explicitly configure those bean by yourself when the conflict happens. One way to resolve that
conflict is by using the @Qualifier annotation in the constructor of the dependent class.
When for 2 different methods making as sēāāēḥūr̥r̥ṁame endpoint.
@GetMapping(path = "/{id}")
public UserDetails getUserDetails() {}
@GetMapping(path = "/{userId}")
public String getUser(@PathVariable String userId) {}
ERROR:
java.lang.IllegalStateException: Ambiguous handler methods mapped for '/users/1': {public
java.lang.String com.kidskart.app.controller.UsersController.getUser(java.lang.String), public
com.kidskart.app.pojo.UserDetails com.kidskart.app.controller.UsersController.getUserDetails()}
Core Module
14 July 2022
15:23
Types of autowiring ?
Bean scopes:
https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html
When you create a bean definition what you are actually creating is a recipe for creating
actual instances of the class defined by that bean definition. The idea that a bean definition
is a recipe is important, because it means that, just like a class, you can potentially have
many object instances created from a single recipe.
You can control not only the various dependencies and configuration values that are to be
plugged into an object that is created from a particular bean definition, but also the scope of
the objects created from a particular bean definition. This approach is very powerful and
gives you the flexibility to choose the scope of the objects you create through configuration
instead of having to 'bake in' the scope of an object at the Java class level. Beans can be
defined to be deployed in one of a number of scopes: out of the box, the Spring Framework
supports exactly five scopes (of which three are available only if you are using a web-
aware ApplicationContext).
Scope Description
singleton Scopes a single bean definition to a single object instance per Spring IoC container.
request Scopes a single bean definition to the lifecycle of a single HTTP request; that is
each and every HTTP request will have its own instance of a bean created off the
back of a single bean definition. Only valid in the context of a web-aware
Spring ApplicationContext.
session Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the
context of a web-aware Spring ApplicationContext.
global session Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically
only valid when used in a portlet context. Only valid in the context of a web-aware
Spring ApplicationContext.
Question:
Circular Dependencies
Simply put, circular dependencies occur when two or more
classes depend on each other. Because of these dependencies,
it’s impossible to construct objects, and the execution can end up
with runtime errors or infinite loops.
Properties
26 March 2022
06:38
Placeholders in Properties
The values in application.properties are filtered through the
existing Environment when they are used, so you can refer back to previously defined
values (for example, from System properties).
app.name=MyApp
app.description=${app.name} is a Spring Boot application
Using YAML Instead of Properties
YAML is a superset of JSON and, as such, is a convenient format for specifying hierarchical
configuration data. The SpringApplication class automatically supports YAML as an alternative to
properties whenever you have the SnakeYAML library on your classpath.
Stateless Vs Stateful
17 March 2022
07:57
Stateless Protocol:
Stateless Protocols are the type of network protocols in which Client send request to the server and
server response back according to current state. It does not require the server to retain session
information or a status about each communicating partner for multiple request.
2. Stateful Protocol:
In Stateful Protocol If client send a request to the server then it expects some kind of response, if it
does not get any response then it resend the request. FTP (File Transfer
Protocol), Telnet are the example of Stateful Protocol.
Silent features of Stateful Protocol:
There are a few steps that we must do for deploying and running the Spring Boot
Application WAR with external Tomcat.
The very first step that we have to do is setting up the packaging of the artifact to
WAR so that it creates a WAR file for us instead of the jar.
<packaging>war</packaging>
The second important step that is needed is that we have to add Tomcat server
dependency and set its scope to provided.
Below is the way that you have to use it for extending your Spring Boot Application.
Basically, you need to extend your Application with SpringBootServletInitializer like
below mention code snippet.
@SpringBootApplicationpublicclassYourSpringBootApplicationextendsSpringBootServletI
nitializer{/**
* The entry point of application.
*
* @param args the input arguments
*/publicstaticvoidmain(String[]args)
{SpringApplication.run(YourSpringBootApplication.class,args);}@OverrideprotectedSpr
ingApplicationBuilderconfigure(SpringApplicationBuilderbuilder)
{returnbuilder.sources(YourSpringBootApplication.class);}}
After doing all these steps you will be able to run your Spring Boot Application WAR
on an external tomcat.
Basic information about this is that if you want to deploy a Servlet-based web
application like Spring then actually you need to provide the traditional XML file that
is web.xml file.
And if you go through the official docs of Spring then we can do the same things with
the WebApplicationInitializer interface.
Spring Boot simply suggests using Java Configuration over XML configuration. In very
simple terms we can say that it uses Java Configuration instead of XML. It
has SpringBootServletInitializer class which eventually implements
the WebApplicationInitializer interface and overrides its onStartup and configure
things for us.
Security
04 January 2022
08:13
http.authorizeRequests()
.antMatchers("/students/{id}").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
Similarly, we may want only a specific HTTP methods on specific endpoints to be authenticated. Like,
we may want to allow free access to read only endpoints like GET students, but mandate
authentication for any PUT or POST.
Autowiring
16 December 2021
10:43
https://stackoverflow.com/questions/56642356/when-to-use-qualifier-and-primary-in-spring
Autowiring in Spring
Autowiring feature of spring framework enables you to inject the object
dependency implicitly. It internally uses setter or constructor injection.
Autowiring can't be used to inject primitive and string values. It works with
reference only.
Profiles
13 December 2021
18:28
Spring Profiles provide a way to segregate parts of your application configuration and make
it only available in certain environments. Any @Component or @Configuration can be
marked with @Profile to limit when it is loaded:
@Configuration@Profile("production")publicclassProductionConfigur
ation {
// ...}
spring.profiles.active=dev,hsqldb
The concept of transactions can be described with the following four key properties
described as
ACID:
https://docs.spring.io/spring-framework/docs/4.2.x/spring-framework-reference/html/
transaction.html
https://www.marcobehler.com/guides/spring-transaction-management-transactional-in-
depth
Isolation:
The degree to which this transaction is isolated from the work of other
transactions. For example, can this transaction see uncommitted writes
from other transactions?
Propagation:
Typically, all code executed within a transaction scope will run in that
transaction. However, you have the option of specifying the behavior in the
event that a transactional method is executed when a transaction context
already exists. For example, code can continue running in the existing
transaction (the common case); or the existing transaction can be
suspended and a new transaction created. Spring offers all of the
transaction propagation options familiar from EJB CMT. To read about the
semantics of transaction propagation in Spring, see Section 16.5.7,
“Transaction propagation”.
Timeout:
How long this transaction runs before timing out and being rolled back
automatically by the underlying transaction infrastructure.
Read-only status:
A read-only transaction can be used when your code reads but does not
modify data. Read-only transactions can be a useful optimization in some
cases, such as when you are using Hibernate.
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
void flush();
boolean isCompleted();
@Transactional
public Long registerUser(User user) {
// execute some SQL that e.g.
// inserts the user into the db and retrieves the autogenerated id
// userDao.save(user);
return id;
}
}
How is this possible? There is no more XML configuration and there’s also no
other code needed. Instead, you now need to do two things:
Make sure you specify a transaction manager in your Spring Configuration (this
you need to do anyway).
And then Spring is smart enough to transparently handle transactions for you:
Any bean’s public method you annotate with the @Transactional annotation,
will execute inside a database transaction (note: there are some pitfalls).
So, to get the @Transactional annotation working, all you need to do is this:
@Configuration
@EnableTransactionManagement
public class MySpringConfig {
@Bean
public PlatformTransactionManager txManager() {
return yourTxManager; // more on that later
}
Now, when I say Spring transparently handles transactions for you. What does
that really mean?
Armed with the knowledge from the JDBC transaction example, the
@Transactional UserService code above translates (simplified) directly to this:
connection.commit(); // (1)
} catch (SQLException e) {
connection.rollback(); // (1)
}
}
}
As you can see from that diagram, the proxy has one job.
Opening and closing database connections/transactions.
And then delegating to the real UserService, the one you
wrote.
And other beans, like your UserRestController will never
know that they are talking to a proxy, and not
the real thing.
Quick Exam
Have a look at the following source code and tell me what type of
UserService Spring automatically constructs, assuming it is marked with
@Transactional or has a @Transactional method.
@Configuration
@EnableTransactionManagement
public static class MyAppConfig {
@Bean
public UserService userService() { // (1)
return new UserService();
}
}
Correct. Spring constructs a dynamic CGLib proxy of your UserService
class here that can open and close database transactions for you. You
or any other beans won’t even notice that it is not your UserService,
but a proxy wrapping your UserService.
Now there’s only one crucial piece of information missing, even though
we have mentioned it a couple of times already.
Your UserService gets proxied on the fly, and the proxy manages
transactions for you. But it is not the proxy itself handling all this
transactional state (open, commit, close), the proxy delegates that
work to a transaction manager.
It does exactly what you did so far to manage transactions, but first,
let’s look at the needed Spring configuration:
@Bean
public DataSource dataSource() {
return new MysqlDataSource(); // (1)
}
@Bean
public PlatformTransactionManager txManager() {
return new
DataSourceTransactionManager(dataSource()); // (2)
}
Here, you create your transaction manager, which needs a data source
to be able to manage transactions.
Simple as. All transaction managers then have methods like "doBegin"
(for starting a transaction) or "doCommit", which look like this - taken
straight from Spring’s source code and simplified a bit:
@Override
protected void doBegin(Object transaction,
TransactionDefinition definition) {
Connection newCon =
obtainDataSource().getConnection();
// ...
con.setAutoCommit(false);
// yes, that's it!
}
@Override
protected void doCommit(DefaultTransactionStatus status) {
// ...
Connection connection =
status.getTransaction().getConnectionHolder().getConnection(
);
try {
con.commit();
} catch (SQLException ex) {
throw new TransactionSystemException("Could not
commit JDBC transaction", ex);
}
}
}
So, the datasource transaction manager uses exactly the same code
that you saw in the JDBC section, when managing transactions.
2. The proxy has access to a transaction manager and will ask it to open
and close transactions / connections.
3. The transaction manager itself will simply do what you did in the plain
Java section: Manage a good, old JDBC connection.
@Service
public class UserService {
@Autowired
private InvoiceService invoiceService;
@Transactional
public void invoice() {
invoiceService.createPdf();
// send invoice as email, etc.
}
}
@Service
public class InvoiceService {
@Transactional
public void createPdf() {
// ...
}
}
@Service
public class InvoiceService {
@Transactional(propagation =
Propagation.REQUIRES_NEW)
public void createPdf() {
// ...
}
}
Changing the propagation mode to requires_new is telling Spring that
createPDF() needs to execute in its own transaction, independent of
any other, already existing transaction. Thinking back to the plain Java
section of this guide, did you see a way to "split" a transaction in half?
Neither did I.
@Transactional(propagation = Propagation.REQUIRED)
// or
@Transactional(propagation =
Propagation.REQUIRES_NEW)
// etc
The full list:
1. REQUIRED
2. SUPPORTS
3. MANDATORY
4. REQUIRES_NEW
5. NOT_SUPPORTED
6. NEVER
7. NESTED
Exercise:
In the plain Java section, I showed you everything that
JDBC can do when it comes to transactions. Take a
minute to think about what every single Spring
propagation mode at the end REALLY does to your
datasource or rather, your JDBC connection.
Then have a look at the following answers.
Answers:
Required (default): My method needs a transaction,
either open one for me or use an existing one
→ getConnection(). setAutocommit(false). commit().
Supports: I don’t really care if a transaction is open or
not, i can work either way → nothing to do with JDBC
Mandatory: I’m not going to open up a transaction
myself, but I’m going to cry if no one else opened one
up → nothing to do with JDBC
Require_new: I want my completely own transaction
→ getConnection(). setAutocommit(false). commit().
Not_Supported: I really don’t like transactions, I will
even try and suspend a current, running transaction →
nothing to do with JDBC
Never: I’m going to cry if someone else started up a
transaction → nothing to do with JDBC
Nested: It sounds so complicated, but we are just
talking savepoints! → connection.setSavepoint()
As you can see, most propagation modes really have nothing to do with
the database or JDBC, but more with how you structure your program
with Spring and how/when/where Spring expects transactions to be
there.
@Transactional(propagation =
Propagation.MANDATORY)
public void myMethod() {
// execute some sql
}
}
In this case, Spring will expect a transaction to be open, whenever you
call myMethod() of the UserService class. It does not open one itself,
instead, if you call that method without a pre-existing transaction,
Spring will throw an exception. Keep this in mind as additional points
for "logical transaction handling".
This is almost a trick question at this point, but what happens when you
configure the @Transactional annotation like so?
@Transactional(isolation = Isolation.REPEATABLE_READ)
Yes, it does simply lead to this:
connection.setTransactionIsolation(Connection.TRANSACTION
_REPEATABLE_READ);
Database isolation levels are, however, a complex topic, and you should
take some time to fully grasp them. A good start is the official Postgres
Documentation and their section on isolation levels.
@Service
public class UserService {
@Transactional
public void invoice() {
createPdf();
// send invoice as email, etc.
}
@Transactional(propagation =
Propagation.REQUIRES_NEW)
public void createPdf() {
// ...
}
}
Let’s go back to the proxies' section of this guide. Spring creates that
transactional UserService proxy for you, but once you are inside the
UserService class and call other inner methods, there is no more proxy
involved. This means, no new transaction for you.
There’s some tricks (like self-injection), which you can use to get
around this limitation. But the main takeaway is: always keep the proxy
transaction boundaries in mind.
@Autowired
private SessionFactory sessionFactory; // (1)
public void registerUser(User user) {
// and commit it
session.getTransaction().commit();
In plain code:
@Service
public class UserService {
@Autowired
private SessionFactory sessionFactory; // (1)
@Transactional
public void registerUser(User user) {
sessionFactory.getCurrentSession().save(user); //
(2)
}
Instead of using a
DataSourcePlatformTransactionManager in your Spring
configuration, you will be using a
HibernateTransactionManager (if using plain Hibernate)
or JpaTransactionManager (if using Hibernate through
JPA).
Annotations
06 December 2021
10:41
https://javatechonline.com/spring-boot-annotations-with-examples/
This code uses Spring @RestController annotation, which marks the class as a controller where
every method returns a domain object instead of a view.
It is shorthand for including both @Controller and @ResponseBody.
The main() method uses Spring Boot’s SpringApplication.run() method to launch an application. Did
you notice that there was not a single line of XML? There is no web.xml file, either. This web
application is 100% pure Java and you did not have to deal with configuring any plumbing or
infrastructure.
Hibernate
Hibernate mappings.
but then jackson will not serialize the field when converting to JSON.
If you need mix JPA with JSON(omit by JPA but still include in Jackson) use @JsonInclude :
@JsonInclude()
@Transient
private String token;
Inheritance Mapping
We can map the inheritance hierarchy classes with the table of the
database. There are three inheritance mapping strategies defined in the
hibernate:
1. Table Per Hierarchy :
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
2. Table Per Concrete class : @Inheritance(strategy =
InheritanceType.TABLE_PER_CLASS)
3. Table Per Subclass :
@Inheritance(strategy=InheritanceType.JOINED)
@Entity
@Table(name = "employee101")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="employee")
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Entity
@DiscriminatorValue("regularemployee")
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Output:
In case of Table Per Concrete class, tables are created per class. So there are no nullable values in
the table. Disadvantage of this approach is that duplicate columns are created in the subclass tables.
@AttributeOverrides defines that parent class attributes will be overriden in this class. In table
structure, parent class table columns will be added in the subclass table.
@Entity
@Table(name = "employee102")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Entity
@Table(name="regularemployee102")
@AttributeOverrides({
@AttributeOverride(name="id", column=@Column(name="id")),
@AttributeOverride(name="name", column=@Column(name="name"))
})
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
@Entity
@Table(name="contractemployee102")
@AttributeOverrides({
@AttributeOverride(name="id", column=@Column(name="id")),
@AttributeOverride(name="name", column=@Column(name="name"))
})
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
StandardServiceRegistry ssr=new
StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
t.commit();
session.close();
System.out.println("success");
}
}
As we have specified earlier, in case of table per subclass strategy, tables are created as per
persistent classes but they are treated using primary and foreign key. So there will not be any
duplicate column in the relation.
@Entity
@Table(name = "employee103")
@Inheritance(strategy=InheritanceType.JOINED)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
@Entity
@Table(name="regularemployee103")
@PrimaryKeyJoinColumn(name="ID")
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
@Entity
@Table(name="contractemployee103")
@PrimaryKeyJoinColumn(name="ID")
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Microservices
16 November 2021
13:35
Microservices:
Microservice architectures are the ‘new normal’. Building small, self-
contained, ready to run applications can bring great flexibility and
added resilience to your code. Spring Boot’s many purpose-built
features make it easy to build and run your microservices in
production at scale. And don’t forget, no microservice architecture is
complete without Spring Cloud ‒ easing administration and boosting
your fault-tolerance.
Each microservice has its own data model and manages its own
data.
Data moves between microservices using “dumb pipes” such as an
event broker and/or a lightweight protocol like REST.
Small scope that encompasses a single piece of business
functionality
Internal operations are a “black box”, accessible to external
programs only via API
https://www.edureka.co/blog/interview-questions/microservices-interview-questions/
Fault Tolerance
Consider a scenario in which six microservices are communicating
with each other. The microservice-5 becomes down at some point,
and all the other microservices are directly or indirectly depend on
it, so all other services also go down.
The solution to this problem is to use a fallback in case of failure of
a microservice. This aspect of a microservice is called fault
tolerance.
@HystrixCommand(fallbackMethod =
"callStudentServiceAndGetData_Fallback")
public String callStudentServiceAndGetData(String schoolname) {
}
This time it will return the fall back method response. Here Hystrix comes into picture, it
monitors Student service in frequent interval and as it is down, Hystrix component has
opened the Circuit and fallback path enabled.
How do we implement asynchronous and synchronous communication
between Micro services.
Communication types
Client and services can communicate through many different types of communication, each
one targeting a different scenario and goals. Initially, those types of communications can be
classified in two axes.
Synchronous protocol. HTTP is a synchronous protocol. The client sends a request and waits
for a response from the service. That's independent of the client code execution that could
be synchronous (thread is blocked) or asynchronous (thread isn't blocked, and the response
will reach a callback eventually). The important point here is that the protocol (HTTP/HTTPS)
is synchronous and the client code can only continue its task when it receives the HTTP
server response.
Asynchronous protocol. Other protocols like AMQP (a protocol supported by many operating
systems and cloud environments) use asynchronous messages. The client code or message
sender usually doesn't wait for a response. It just sends the message as when sending a
message to a RabbitMQ queue or any other message broker.
https://docs.microsoft.com/en-us/dotnet/architecture/microservices/architect-
microservice-container-applications/communication-in-microservice-architecture
Feign Client
03 December 2021
09:06
Feign is a declarative web service client. It makes writing web service clients easier.
To use Feign create an interface and annotate it. It has pluggable annotation support
including Feign annotations and JAX-RS annotations.
@SpringBootApplication@EnableFeignClientspublicclassApplication {
publicstaticvoidmain(String[] args) {
SpringApplication.run(Application.class, args);
}
}
StoreClient.java.
@FeignClient("stores")publicinterfaceStoreClient {
@RequestMapping(method = RequestMethod.GET, value =
"/stores")List<Store> getStores();
@RequestMapping(method = RequestMethod.POST, value =
"/stores/{storeId}", consumes = "application/json")Store
update(@PathVariable("storeId")Long storeId, Store store);
}
API Gateway
17 March 2022
07:59
Design Patterns
16 November 2021
13:38
Design pattern is a general, reusable solution to a commonly occurring problem within a given
context in software design. It is not a finished design that can be transformed directly into
source or machine code. Rather, it is a description or template for how to solve a problem that
can be used in many different situations. Design patterns are formalized best practices that the
programmer can use to solve common problems when designing an application or system.
Design patterns had originally been categorized into 3 sub-classifications based on what kind
of problem they solve.
Creational patterns
Name Description
Abstract factory Provide an interface for creating families of related or dependent objects
without specifying their concrete classes.
Dependency Injection A class accepts the objects it requires from an injector instead of creating
the objects directly.
Factory method Define an interface for creating a single object, but let subclasses decide
which class to instantiate. Factory Method lets a class defer instantiation to
subclasses.
Singleton Ensure a class has only one instance, and provide a global point of access to
it.
Structural patterns
Name Description
Adapter, Wrapper, Convert the interface of a class into another interface clients expect. An
or Translator adapter lets classes work together that could not otherwise because of
incompatible interfaces. The enterprise integration pattern equivalent is the
translator.
Bridge Decouple an abstraction from its implementation allowing the two to vary
independently.
Front controller The pattern relates to the design of Web applications. It provides a
centralized entry point for handling requests.
Proxy Provide a surrogate or placeholder for another object to control access to it.
Behavioural patterns
Name Description
State Allow an object to alter its behavior when its internal state
changes. The object will appear to change its class.
Singleton pattern is a software design pattern that restricts the instantiation of a class to one
"single" instance. This is useful when exactly one object is needed to coordinate actions across
the system.
Ensure that only one instance of the singleton class ever exists and Provide global access to that
instance.
Typically, this is done by:
private Singleton() {}
we will see that what are various concepts which can break singleton property of a class and
how to avoid them. There are mainly 3 concepts which can break singleton property of a class.
Let’s discuss them one by one.
1. Reflection
Overcome reflection issue: To overcome issue raised by
reflection, enums are used because java ensures internally that
enum value is instantiated only once. Since java Enums are
globally accessible, they can be used for singletons. Its only
drawback is that it is not flexible i.e it does not allow lazy
initialization.
2. Serialization
Overcome serialization issue:- To overcome this issue, we
have to implement method readResolve() method.
3. Cloning
Overcome Cloning issue:- To overcome this issue, override
clone() method and throw an exception from clone method that
is CloneNotSupportedException. Now whenever user will try to
create clone of singleton object, it will throw exception and
hence our class remains singleton. If you don't want to throw
exception you can also return the same instance from clone
method.
import java.lang.reflect.Constructor;
// Singleton class
class Singleton
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("instance1.hashCode():- " +
instance1.hashCode());
System.out.println("instance2.hashCode():- " +
instance2.hashCode());
}
}
Output:-
instance1.hashCode():- 366712642
instance2.hashCode():- 1829164700
After running this class, you will see that hashCodes are
different that means, 2 objects of same class are created and
singleton pattern has been destroyed.
Overcome reflection issue: To overcome issue raised by
reflection, enums are used because java ensures internally that
enum value is instantiated only once. Since java Enums are
globally accessible, they can be used for singletons. Its only
drawback is that it is not flexible i.e it does not allow lazy
initialization.
private Singleton()
{
// private constructor
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:-
instance1 hashCode:- 1550089733
instance2 hashCode:- 865113938
As you can see, hashCode of both instances is different, hence
there are 2 objects of a singleton class. Thus, the class is no
more singleton.
Overcome serialization issue:- To overcome this issue, we
have to implement method readResolve() method.
private Singleton()
{
// private constructor
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Output:-
instance1 hashCode:- 1550089733
instance2 hashCode:- 1550089733
Above both hashcodes are same hence no other instance is
created.
// Singleton class
class Singleton extends SuperClass
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
}
@Override
protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
// Singleton class
class Singleton extends SuperClass
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
@Override
protected Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}
}
@Override
protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
}
// Singleton class
class Singleton extends SuperClass
{
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
@Override
protected Object clone() throws CloneNotSupportedException
{
return instance;
}
}
import java.io.*;
abstract class Plan{
protected double rate;
abstract void getRate();
Step 2: Create the concrete classes that extends Plan abstract class.
class GetPlanFactory{
import java.io.*;
class GenerateBill{
Plan p = planFactory.getPlan("INSTITUTIONALPLAN");
//call getRate() method and calculateBill()method of DomesticPaln.
import java.io.*;
interface Bank{
String getBankName();
}
n=years*12;
rate=rate/1200;
EMI=((rate*Math.pow((1+rate),n))/((Math.pow((1+rate),n))-
1))*loanamount;
class FactoryCreator {
if(choice.equalsIgnoreCase("Bank")){
return new BankFactory();
} else if(choice.equalsIgnoreCase("Loan")){
return new LoanFactory();
}
return null;
}
}
import java.io.*;
class AbstractFactoryPatternExample {
System.out.print("\n");
System.out.print("Enter the interest rate for "+b.getBankName()+ ":
");
double rate=Double.parseDouble(br.readLine());
System.out.print("\n");
System.out.print("Enter the loan amount you want to take: ");
double loanAmount=Double.parseDouble(br.readLine());
System.out.print("\n");
System.out.print("Enter the number of years to pay your entire loan a
mount: ");
int years=Integer.parseInt(br.readLine());
System.out.print("\n");
System.out.println("you are taking the loan from "+ b.getBankName()
);
Loan l= loanFactory.getLoan(loanName);
l.getInterestRate(rate);
l.calculateLoanPayment(loanAmount,years);
}
}
Proxy means ‘in place of’, representing’ or ‘in place of’ or ‘on behalf of’ are literal meanings
of proxy and that directly explains Proxy Design Pattern.
Proxies are also called surrogates, handles, and wrappers. They are closely related in
structure, but not purpose, to Adapters and Decorators.
A real world example can be a cheque or credit card is a proxy for what is in our bank
account.
It can be used in place of cash, and provides a means of accessing that cash when required.
And that’s exactly what the Proxy pattern does – “Controls and manage access to the object
they are protecting“.
//Proxy pattern is used when we need to create a wrapper to cover the main object’s
complexity from the client.
interface Internet {
public void connectTo(String serverhost) throws Exception;
}
static {
bannedSites = new ArrayList<String>();
bannedSites.add("abc.com");
bannedSites.add("def.com");
bannedSites.add("ijk.com");
bannedSites.add("lnm.com");
}
@Override
public void connectTo(String serverhost) throws Exception {
if (bannedSites.contains(serverhost.toLowerCase())) {
throw new Exception("Access Denied");
}
internet.connectTo(serverhost);
}
}
Immutable Classes
25 November 2021
19:12
Immutable class in java means that once an object is created, we cannot change its content. In Java,
all the wrapper classes (like Integer, Boolean, Byte, Short) and String class is immutable. We can
create our own immutable class as well. Prior to going ahead do go through characteristics of
immutability in order to have a good understanding while implementing the same. Following are the
requirements:
// Creating Map object with reference to HashMap Declaring object of string type
Map<String, String> tempMap = new HashMap<>();
this.metadata = tempMap;
}
// Method 1
public String getName() { return name; }
// Method 2
public int getRegNo() { return regNo; }
// Class 2
// Main class
class GFG {
// Calling the above methods 1,2,3 of class1 inside main() method in class2 and
executing the print statement over them
System.out.println(s.getName());
System.out.println(s.getRegNo());
System.out.println(s.getMetadata());
map.put("3", "third");
// Remains unchanged due to deep copy in constructor
System.out.println(s.getMetadata());
s.getMetadata().put("4", "fourth");
// Remains unchanged due to deep copy in getter
System.out.println(s.getMetadata());
}
}
Database
07 December 2021
08:18
Select salary from (Select rownum row_num, salary (Select Salary from employees order by
salary desc) ) where row_num=2;
2. Salary between Range : Display the name, age and address of customers whose salary is
between 9000 and 10000 (inclusive)
4. Display the name, salary and dept ID of the employee who has highest salary of each dept
https://www.edureka.co/blog/interview-questions/sql-query-interview-questions
SQL Notes
07 December 2021
19:45
Indexing
For example:
We could also create an index with more than one field as in the example
below:
We could also choose to collect statistics upon creation of the index as follows:
CREATE INDEX supplier_idx ON supplier (supplier_name, city) COMPUTE
STATISTICS;
https://www.edureka.co/blog/interview-questions/sql-query-interview-questions
REST API
25 April 2022
18:18
WebClient:
@Service
publicclassMyService {
privatefinalWebClient webClient;
publicMyService(WebClient.Builder webClientBuilder) {
this.webClient =
webClientBuilder.baseUrl("https://example.org").build();
}
publicMono<Details> someRestCall(String name) {
returnthis.webClient.get().uri("/{name}/details",
name)
.retrieve().body
ToMono(Details.class);
}
}
While the list is hardly exhaustive, here are some of the most
common HTTP codes you'll be running into:
Interview Programs
21 September 2022
16:10
Rotate An Array :
Array : 1,2,3,4,5
n = 5 : length of array
k time ?
k =1 : 51234
k=2 : 45123
Now, let's modify the final WAR file name to avoid including
version numbers:
<build>
<finalName>${artifactId}</finalName>
...
</build>