1. What is Encapsulation?
Encapsulation means binding data into a single object.
We can achieve encapsulation by making all variables private.
To access private variables, we have to provide getter and setter methods.
A setter method is used to assign a value to private variables.
A getter is used to get the values from private variables.
---
2. What is Inheritance?
Acquiring all properties and functionality of a parent class into a child
class.
We can achieve inheritance using extends and implements keywords.
Purpose: (Code Reusability) We can reuse code.
Disadvantage: Unwanted properties and functionalities may occur in the
child class, whether they are required or not.
Make all unwanted properties and functionalities private in the parent
class.
Types of inheritance :-
i) Single Inheritance
ii) Multilevel Inheritance
iii) Multiple Inheritance:- It is not allowed in Java with the
extends keyword (shows Ambiguity Error).
- Ambiguity Error: The compiler gets confused
about which one to call.
- We can achieve multiple inheritance using the
implements keyword in an Interface.
---
3. Can we override or inherit a private variable or method?
NO, we can't override or inherit private variables or methods.
We can't override main method because it is static method.
---
4. What is Polymorphism?
Polymorphism means same name, different form.
We can achieve polymorphism in two ways:
i) Overriding:
- If we are not satisfied with the parent method's
implementations.
- The method name must be the same.
- The input arguments must be the same.
- The return type must be the same or covariant.
- The access modifier must be the same or we can increase
the scope.
ii) Overloading:
- The method name must be the same.
- The input arguments must be different.
- The access modifier can be anything.
- The return type can be anything.
- private ➡� default ➡� protected ➡� public
- Byte ➡� Short ➡� iNt ➡� Long ➡� Float ➡� Double
- B ➡� s ➡� n ➡� l ➡� f ➡� d.
- ➡� Char ➡� int ➡� Long ➡� Float ➡� Double
---
[Link] is Interface?
We can declare an interface using the interface keyword.
Every variable is public static final.
Every method is public and abstract.
You must override all abstract methods of interface in the child class.
---
[Link] is Abstract class?
We can declare an abstract class with the abstract keyword.
Abstract Method: A method without a body is known as an abstract method.
An abstract class can have abstract methods and non-abstract methods.
An abstract class can have a constructor, but we can't create an object.
[Link] do we declare a class as abstract?
When we don't want to override all abstract methods, we declare the class
as abstract.
---
[Link] is the difference between an Abstract class and an Interface?
Interface
i) Every variable is "public static final."
ii) Every method is "public abstract."
iii) An interface doesn't have a constructor.
iv) We can declare an interface with the help of the "interface" keyword.
Abstract class
i) In an abstract class, it is not mandatory to declare variable "public
static final.
ii) In an abstract class, we can write abstract and non-abstract methods.
iii) An abstract class can have a constructor.
iv) We can declare an abstract class with the "abstract" keyword.
---
[Link] is a Constructor?
It is exactly like a method but without a return type.
The constructor name must be the same as the class name.
Purpose:
i) Creation of an object.
ii) To initialize the state of an object/Variable.
There are mainly 3 types:
i) Default Constructor.
ii) Parameterized Constructor.
iii) Non-Parameterized Constructor.
---
[Link] we create an object of an interface?
No, we can't create an object of an interface.
---
[Link] we create an object of an abstract class?
No, we can't create an object because of incomplete methods.
This: 'This' keyword refers to the current class object and methods.
Super: 'Super' keyword refers to the parent class Constructor.
---
[Link] is the use/need of a Constructor?
Creation of an object.
To initialize the state of an object/variable.
---
[Link] is the static keyword?
It is at the class level.
There is only 1 copy of a static variable.
No need to create an object of static classes.
Static methods are called without creating an object.
---
[Link] is a Factory?
A factory is a creational type of design pattern.
It is used for the creation of an object.
Instead of us creating the object, a factory will create the object for
us.
---
[Link] is Tightly coupling?
When we create an object with the new keyword, it is known as Tightly
Coupling.
---
[Link] are SOLID Principle?
S:- Single Responsibility Principle: A single class can have a single
responsibility.
O:- Open/Close Principle: Open for extension, close for modification.
L:-
I:- Interface Segregation Principle: A single interface can have a single
responsibility.
D:- Dependency Injection.
---
[Link] is Abstraction?
Hiding internal implementation and showing only functionality.
We can achieve this with any method.
Every method is performing abstraction.
We only know the functionality name but don't know the internal logic.
Ex :- SAVE method of repository.
---
[Link] is the Final keyword?
It is a keyword in Java.
We can use the final keyword at the class, method, and variable levels.
- If a class is declared as final, we cannot extend the class.
- If a method is declared as final, we cannot override the method.
- If a variable is declared as final, we cannot change the value of the
variable.
SQL: Used for writing operations. Ex: Print Bank Statements.
NOSQL: Used for reading operations. Ex: Instagram, Facebook.
---
[Link] is Spring Data JPA?
It is powerful feature provided by Spring Boot to help us perform database
operations.
To perform database operations, we need an interface that is extended from
JPA Repository.
Then we can call JPA repository methods in service class.
To execute logic, at runtime, it will create a child class and override
all abstract methods that are present inside JpaRepository.
It also provide Native and JPQL queries.
Internally JPA Repository is using hibernate which is By default and we
can change this to another implementation also.
---
[Link] we have two implementations and we are autowiring the interface in
the controller, how will it work?
It will throw an exception because there are two implementations.
To solve this issue, there are three ways:
- i) @Primary: To inject any specific bean as default (write on the
implemented class).
- ii) @Qualifier: To inject any specific bean (write in the controller
class).
- iii) @Autowired: Change the variable name to the bean name.(Ex:-
DocServiceInt exelServiceImpl) (exelServiceImpl ➡� in Camel Case).
---
We can change the bean name as well:
@Service("New_Name")
➡� @Qualifier("New_Name")
Key ➡� Bean Name.
Value ➡� Stored Object.
---
[Link] is IOC?
IOC is a principle called Inversion Of Control.
Instead of us creating an object, Spring will create the object for us.
So here, the control is inverted because the control is not in our hands
it is in Spring's hands, so it's called IOC.
To achieve this, Spring uses an IOC container and Dependency Injection.
---
[Link] is an IOC Container?
When the application starts, Spring will scan all classes.
It will check for stereotype annotations like @Controller, @Service,
@Component, @Repository and create beans.
It stores that bean in the form of a key and value in logical memory.
And that logical memory is known as the IOC Container.
---
[Link] are the types of IOC containers?
There are 2 types of IOC containers:
i) Application context(Pulling).
ii) Bean Factory(Injecting).
---
Q) What is difference between Application context and Bean factory?
Bean Factory
i) Bean factory is a legacy.
ii) It is used for standalone applications.(Normal core Java not for web
applications).
iii) Loading the beans lazy.(At run time)
Application Context
i) Application context is not legacy.
ii) It is mainly used for web applications.
iii) Loading beans eagerly.(Immediately loads when applications start)
---
[Link] is Dependency Injection?
It is a core feature of Spring.
It helps to make our application loosely coupled.
Because if we create an object with the new keyword, it will become
tightly coupled.
So instead of us creating an object, Spring will create the object inside
the IOC container.
We can then inject that object with the help of Dependency Injection.
---
[Link] are the types of Dependency Injection?
i) Field Injection (@Autowired).
ii) Setter Injection.
iii) Constructor Injection.
iv) Lookup Injection.
---
[Link] dependency Injection is preferred?
This is based on the requirement.
If you want to make it optional, then use Setter Injection.
If you want to make it mandatory, then use Constructor Injection.
Field injection is not preferred because of slow processing because
internally it uses JVM reflection.
---
[Link] is get @getmapping @postmapping?
@getMapping :-
@GetMapping handle the HTTP Get request.
This fetch data from server.
Only retrieve data from server.
@PostMapping :-
@PostMapping handle the HTTP Post request
This send the data to server.
Make changes inside server.
---
[Link] is application context?
Application Context is type of IOC container.
It create, manages and configure beans so we don't need to create bean
manually.
Autowire the application context and inject the bean.
Basically it create beans and stores and provide when required.
---
[Link] is @Entity?
@Enity annotation marks the class as JPA entity.
Basically It represent table in database.
It map the entity class to the table.
By default table name will be same as class name.
To change table name ➡� use @table annotation.
To change column name ➡� use @column annotation.
---
[Link] is automatic promotion?
when we pass parameter it checks for exact match with method parameter
during method call.
If it doesn't found then it will automatically promoted.
Order of promotion is Byte ➡� Short ➡� Int ➡� Long ➡� Float ➡�
Double.
---
[Link] is constructor overloading?
Declaring more than one constructor with different parameter in same
class.
---
[Link] we write database properties?
We write Database properties like USERNAME, PASSWORD and URL in
[Link] file.
---
[Link] is Order by and Group by?
Order by is SQL clause used to sort the data in ascending or descending
order.
Group by is SQL clause used to group same type of data.
we can use aggregate functions with this like SUM, MIN, MAX, AVG, COUNT.
---
[Link] is Template design pattern?
It is behavioral type of design pattern.
It is used for code reusability.
Ex :- If we have interface with multiple implementation and there is
common code inside the implementation.
Then we can write that code inside abstract child class.
---
[Link] is array?
Array is collection homogenous type of data.(same type of data)
Advantage :
- It is very fast because it store data in contagious memory.
Disadvantage :
- Array is fixed in size.
- We can store only same type of element.
---
[Link] is collection?
We can store group of element in collection.
We can store any type of data inside the collection.
Size of the collection is dynamically growable.
It also provide some additional utility methods like add , create.
Collection also have some child implementation like a LIST , SET , QUEUE.
---
.What is List?
List is child of collection.
Duplicates are allowed in list.
Insertion order is maintained.
List is also an interface which have some child implementation like
Arraylist , LinkedList and Vector.
---
[Link] is ArrayList?
Arraylist is an implementation of list interface.
Duplicates are allowed.
Insertion order is maintained.
It is good for reading operation because it can access any element with
same speed.
It is not good for frequent writing operation because it will increase
size of array frequently.
To increase the size it will create array of double size and copy all the
elements of pervious array into new array.
That's why writing operation is not good in arraylist.
Insertion operation is also not good in arraylist.
because we insert anything in the middle of the arraylist then it will
perform N [Link] shifting operations.
---
[Link] is LinkedList?
Linkedlist is an implementation of list interface.
Duplicates are allowed.
Insertion order is maintained.
It will store data in form of nodes.
It is good for frequent writing and insertion operation.
because to ADD and INSERT new data it will just create a new node and it
will just change the address of previous and next node.
It is not good for reading operation because it has travel from first node
to given node which is time consuming.
default size of arraylist is 10. and load factor of it is 0.75 = 75%.
---
[Link] is vector?
It is an implementation of List interface.
Duplicates are allowed.
Insertion order is maintained.
vector is a synchronized, synchronized mean only one thread can access at
one time.
In vector only one thread can access at time so helps us to avoids data
inconsistency.
but the problem is, performance wise vector is not good because only one
thread can access at one time.
---
[Link] between arraylist and vector?
Both are the child implementation of list interface.
In both insertion order is maintained and Duplicates are allowed.
But the main difference is :-
Vector :-
- vector is synchronized, Due to this performance will get slow.
- because vector can access only one thread at a time.
- To solve the performance issue we can go for concurrent collection
Arraylist :-
- Arraylist is not synchronized, So it is faster.
---
[Link] is set?
It is child of collection.
Duplicates are not allowed.
Insertion order is not maintained but if you want to maintain an order
then you can use LinkedHashSet.
Set also have some child implementations like HashSet , LinkedHashSet and
TreeSet.
---
[Link] is HashSet?
It is Implemtation of set interface.
Duplicates are not allowed.
Insertion order is not maintained.
If adding any custom objects we have to override equals and hashcode.
---
[Link] are adding Custom object will it filter or not?
NO, it will not filter. we have to override equals and hashcode method.
---
[Link] is Linkedhashset?
It is an implementation of set interface.
Duplicates are not allowed.
But Insertion order is maintain.
---
[Link] is TreeSet?
It is an implementation of set interface.
Duplicates are not allowed.
Insertion order is not maintained but it provides Sorting order.
It accept only homogenous type of element.
If you are adding custom objects then we should implement it from
comparable.
Inside comparable we should provide sorting order
Then TreeMap will call comparable methods to compare objects and provide
sorting order.
String, Character and integer are by default implemented from comparable.
Sorting ➡� Compare.
Filter ➡� Equal and HashCode.
---
Scenario base
46.I want to sort no of employees by their salary?
We can use TreeSet and inside TreeSet we can use comparator and
comparable.
---
[Link] one is preferred Comparator or Comparable?
We should use Comparator because in comparator we can provide multiple
sorting order.
---
[Link] between Comparator vs Comparable?
Comparator and comparable both are interface.
In Comparator their is compare method and In Comparable their is CompareTo
method.
In Comparator we can provide multiple sorting order but In comparable we
can provide only single sorting order.
In Comparable to change sorting order we modify exiting code but In
Comparator no need to modify code we can write new comparator.
---
[Link] is HashCode Method?
HashCode is unique code provided by JVM for every object.
It is present inside object class.
If you want to print HashCode of any object then we can call HashCode
method.
The main purpose of hashcode is to select the bucket number.
---
[Link] two object have same HashCode?
If you are overriding HashCode then two object can have same HashCode.
---
[Link] is toString method?
It is present inside object class.
By default it is returning class_name @HashCode in from Hexadecimal form
(Student@7125ce12).
If you want print state of object then we can override toString method.
Benefit :- If you want to override State of object to print data.
---
[Link] is equal method?
It is present inside object class.
By default it is using the "==" double equal operator to compare the
string.
But if you want to compare the content then you can override this equal
method.
---
[Link] is difference between Equals and == ?
== :-
- == is operator compares the references.
- It is fast.
.equals :-
- .equal is method present inside object class.
- It is slow.
- By default it is comparing the references with the help of "=="
operator.
- But if you want to compare the content then you should override
the method into child class.
---
[Link] is Map?
If you want to store data in form of key and values then we should use
map.
Duplicate keys are not allowed.
Duplicate values are allowed.
Insertion order is not maintained but if you want to maintain then we can
use LinkedHashMap.
If you want to maintain sorting then you can use TreeMap.
Map also have multiple child implementations HashMap, LinkedHashMap,
TreeMap, IdentityHashMap, WeakHashMap.
---
[Link] is HashMap?
It is child implementation of map.
Stores data in form of key and values.
Duplicate keys are not allowed.
Duplicate values are allowed.
insertion order is not maintained.
If you are adding any custom object then you should override equals and
HashCode method.
---
[Link] happen if we are not overriding equal and hashcode?
In map key will be duplicated because it will select the different bucket.
---
[Link] happen if we are not overriding the hashcode?
custom objects with same data will goes into different bucket because
hashcode is different.
---
[Link] happen if we are not overriding the equal method but override
hashcode?
So it will select the same bucket and inside that their will be duplicates
even two objects are same.
because hashmap uses .equals method to compare the content in the same
bucket.
and it will return false because we haven't overrided the equals method.
Once we override the method then it will filter the duplicates.
---
scenario base
[Link] we are adding e1,e2,e3 as a key in hashmap then what will happen?
It will allow the duplicate because we haven't override the equal and
hashcode method.
In that case we have to override equal and hashcode method and then it
will calculate the bucket for that particular objects.
If the object having the same hashcode it will select the same bucket and
use equal method to compare the content.
---
[Link] HashMap will filter the duplicate objects?/Tell me about the
interns of hashmap?
HashMap is internally using the equals and HashCode to filter the keys.
When we add any element inside HashMap first it will select the bucket
number for that particular key.
It is using one formula : bNo=HashCode/[Link] bucket-1 (36/15=1) and
whatever will be the reminder that will be the bucket number.
It will put that key and value pair inside that particular bucket in form
of node.
Again when we are adding new element it will select the bucket in same
way
unfortunately it will giving the same bucket no in that case it will
create new node in same bucket.
but before creating new node it will compare the key using equal method to
filter the duplicates.
---
[Link] is hash collision?
sometimes different keys have same bucket no.
so all the entries go inside the same bucket that is known as hash
collision.
So to filter the duplicates hashmap using .equals method.
---
[Link] is LinkedHashMap?
It is child of HashMap.
Stores data in form of key and values.
Duplicate keys are not allowed.
Duplicate values are allowed.
Insertion order is maintained.
---
[Link] is TreeMap?
It is child implementation of Map.
Stores data in form of key and values.
Duplicate keys are not allowed.
Duplicate values are allowed.
Insertion order is not maintained but provide Sorting order.
If you are adding custom objects as a key then we should implement it from
comparable.
Inside comparable we can provide sorting order.
Then TreeMap will call compareTo method of comparable to compare object
and then provide sorting order.
---
[Link] is difference between HashMap and hashtable?
HashMap and hashtable both are implementation of map interface.
Hashtable is synchronized, HashMap is not synchronized.
In hashtable only one thread can access at one time and In HashMap
multiple thread can access at one time.
hash table provide thread safety and HashMap does not.
---
[Link] is identityhashmap?
It is implementation of map interface.
we can store data in form of key and value.
Duplicates keys are not allowed.
Duplicate values are allowed.
Insertion order is not maintained.
It is using == operator for comparison instead of .equals that's why it is
fast.
We can go for identityhashmap if it is confirm that the key will be String
or any other wrapper class.
It is not able to filter custom objects.
---
[Link] is contract between equal and hashcode?
If equal is returning true then hashcode should be same.
because it will help to filter duplicate in hashmap if want then i can
explain.(internals answer)
---
[Link] is concurrent Modification Exception?
When we perform reading and writing operation on collection at same time
then it will throw concurrent modification exception.
It is coming because when we perform reading operation it will check size
of collection before and after iteration.
Then it will compare the size, if it is same then fine if it is different
then it will throw concurrent Modification Exception.
---
[Link] is concurrent collection?
It provides thread safety and performance because it maintain two copies
read only and write only.
Read only copy in not synchronized any no of thread can access at same
time and.
Write only copy is synchronized but it provide bucket level lock so no of
thread can access to no of bucket at same time.
Then after specific thresh hold it will update read only copy.
---
[Link] is fail fast iterator?
Normal collection is fail fast because when we perform reading and writing
operation at same time then it will throw exception.
---
[Link] is fail safe iteration?
concurrent collection is fail safe because when we perform reading and
writing operation at same time then there is no issue.
because it is maintaining two different copies read only for reading
operation and write only for writing operation.
---
[Link] is cloning?
Creating exact duplicate copy of object is known as cloning.
To achieve cloning we need to implement our class from clonable interface
and override clone method.
Inside that we call [Link] method then it will return new clone
object.
There are mainly two types of cloning :-
- Shallow Cloning.
- Deep Cloning.
- Shallow Cloning :-
- It will create exact duplicate copy of primitive variables
and both the primitive copies are independent.
- In case of custom object it will not create the duplicate
copy it refers the original custom objects.
- That's why if we make any changes in original or custom
object then it will reflect in each other.
- And this is the problem in shallow cloning and to solve this
issue we can use deep cloning.
- Deep Cloning :-
- fist we have to implement our class from cloneable interface
and override clone method.
- Inside clone method instead of calling just [Link] we
need to create object of content manually.
- And put that new object inside clone object.
---
[Link] is marker Interface?
It is a empty interface, only for Marking.
It is indicating JVM that to provide specific capability to that class.
For ex :- clone, indicate JVM to allow to make that class cloning clone.
If we can't implement it then it will throw class cast exception.
---
* IMP*
[Link] is immutable?
When we create an object that object should not modify in any way that is
called as immutable object.
we have to make class as a final so no one can create child class also
make variables final.
We should not provide setter method provide only getter method and
Constructor.
---
[Link] is Exception?
Exception mean unwanted events happening at the time of execution of the
program.
we can handle that exception with try and catch block but in case of
spring boot we can handle this in another way.
---
Parent of exception is throwable.
We can catch the error also.
Always finally block return statement will preferred.
---
[Link] is difference between run time exception and compile time
exception?
Run time Exception
i) Also known as unchecked exception.
ii) Run time exception is coming on the time of run time.
iii) For ex : - [Link] Exception [Link] Pointer Exception [Link] Of
Bound Exception.
Compile time Exception
i) Also known as checked Exception.
ii) Compile time exception is coming on the time of compile time.
iii) For ex:-[Link] Exception [Link] Exception. [Link] not found Exception.
---
[Link] between Exception and Error?
Exception
i) Exception is occur due to the programmers mistake.
ii) Foe ex :- [Link] Exception [Link] Pointer Exception
Error
i) Error occur due to the lack of resources.
ii) For ex :- [Link] of memory error. [Link] over flow error.
---
[Link] is finally block?
Finally block is come with try, catch or try block.
If you want to execute any mandatory code whether there is exception or
not then we should write in finally block.
---
[Link] there any way to stop finally block Execution?
yes, There are two ways to stop finally block execution:-
1) [Link](0);
2) [Link]().exit(10);
---
[Link] is throw Keyword?
It is used throw the exception, so generally JVM is throwing exception..
But if you want to throw Explicitly exception then you should use throw
Keyword.
---
[Link] is compile time exception?
It also known as checked Exception.
Compile time exception is coming on the time of compile time.
For ex:-[Link] Exception [Link] Exception. [Link] not found Exception.
compulsory we need to provide try catch block.
If you don't want to provide try catch block then you can use throws
keyword.
---
[Link] between throw and throws?
Throw :-
- If you want to throw exception explicitly then you can use throw
keyword.
Throws :-
- In case of compile time exception compulsory we need to provide
try catch block.
- If you don't want to provide then you can use throws keyword.
---
* IMP*
[Link] you handle exception?
We are creating custom exception for every service class.
For example employee service we are creating Employee Service Exception
and we are throwing custom exception.
Inside that custom exception we are throwing appropriate error message and
Status Code.
That will traverse towards the controller and in controller we catch the
exception and returning Response Entity.
Inside that Response Entity we are putting error message and adding the
status code from that custom exception.
In that we are handling the exception in our project.
Internally it is using AOP after throwing advise.
---
[Link] are the status code you know?
200,201,500,400,404,204,403,
---
[Link] is instanceof?
It is a keyword of java.
It is used to check the object is instance of specific class or subclass.
It returns the Boolean values like (true or false).
---
[Link] can we resolve Concurrent Modification Exception?
we can resolve this using copy on write array list and concurrent HashMap.
copy on write arraylist create copy of an array while modification.
concurrent HashMap allow safe writing during iteration.
---
[Link] is dependency pulling?
We can pull the beans using getBean method.
---
[Link] is boiler plate logic?
Lombok is dependency which is used to remove the boiler plate logic like
getter, setter, toString, constructor, equal and hashcode.
So instead this we can use Lombok and there we can use annotations like
@getter, @setter... so that we don't need to write this.
while running the program inside that byte code it will injects logic of
boiler plate code.
---
[Link] is devtool?
It is used to restart the application.
When we save the program then it will automatically restart the
application.
---
[Link] is logger?
It helps in debugging and tracking the flow of application.
There is one interface named SL4J which has multiple implementation
[Link] [Link] util logging 3.LOG4J2 [Link] logging.
by default spring boot support logback.
---
Logger Levels :- TRACE ➡� DEBUG ➡� INFO ➡� WARN ➡� ERROR ➡� OFF .
---
[Link] you see the logs?
We are using spring boot admin and apart from this we are downloading the
log files from the Linux server through winscp.
But we are planning to implements kibana and elastic search.
---
[Link] is microservices?
It is totally loosely couple.
Instead of creating all the functionalities in single application which
makes it tightly couple.
We can create sperate independent applications for different
functionality.
So here if one functionality is down there is no impact on others.
To build microservices we need Eureka server and Api Gateway.
Eureka Server is responsible for Service registry and discovery.
And Api Gateway is single entry point for all the applications and also
responsible for load balancing.
---
Normal application == Monolithic application architecture.
---
[Link] is difference between microservices vs monolithic application?
Size wise monolithic application is very big But Microservice are very
small.
Monolithic application is tightly couple but microservices is loosely
couple.
If there is any problem in monolithic service we have to fix and re-deploy
it because it affect on other service.
In microservices if there is problem in any functionality we need to fix
the bug for that specific microservices no impact on others.
In monolithic debugging is very easy but in microservices debugging is
very hard.
Maintenance wise monolithic is good but microservices are not good.
Monolithic application takes more time for deployment compared to
microservices.
---
[Link] is [Link]?
If you set the private repository then we use [Link].
---
[Link] are Native queries and JPQL Queries?
---
[Link] is Dialect?
Dialect is provided by hibernate.
It is converting JPQL Queries into Native Queries(Database Specific
Queries).
---
[Link] we deploy the code?
Whenever the story is assigned so we have to create Story specific branch
then.
We have to test the code in local if it is working then we can deploy that
story branch into dev branch through the Jenkin pipeline.
If it is working then we have to raise the PR to merge the story branch
code into the dev branch.
Then seniors will review the code if it is ok then we can will deploy that
code on sit environment.
---
[Link] you provide the API documentation to frontend developer or tester?
We are using swagger to provide documentation.
---
[Link] you fetch the millions of record?
We can use spring data JPA repository to do the pagination.
To perform paginations we have to create Pageable object and provide Page
No and size.
Then it will provide the records.
---
[Link] there are 1000 users and we have to fetch those records so it will
work on not?
Yes, It will work we can use pagination.
---
[Link] is difference between PathVariable and RequestParam?
If you want make fields mandatory then we can use PathVariable.
If you want make fields optional then can use RequestParam.
---
[Link] is AOP?
AOP mean Aspect Oriented Programming.
If you want to add or remove cross fitting logic without modifying the
code in that case we can use AOP.
There are 5 key terminologies in AOP :-
[Link] :- Aspect mean a class in which we have add cross
fitting logic.
[Link] :- It's a way to apply the aspect. Ex:- Before, After,
Around, AfterThrowing.
[Link] :- Its a place where we can apply the aspect.(Java
support only one Joinpoint which is method).
[Link] :- It's address which define exact methods where we have
to apply the aspect.
[Link] :- Its a process of applying aspect on the pointcut.
It provides mainly 5 Advice :-
1.@After
2.@Before
3.@Around
4.@AfterReturning
5.@AterThrowing
---
[Link] is exception propagation?
If there is exception, Then JVM will check is there any try catch block or
exception handling code or not.
If not, Then it will terminate that method abnormally and through that
exception towards the caller method.
Then again it will check for exception handling code if not there then
again it will also terminate that method until end.
That how exception propagation work.
---
[Link] is difference between JDK , JRE and JVM?
JDK is Java Development Kit which include JVM and JRE.
Apart from this JDK provide some tools like Debugger and Compiler.
JRE is Java Runtime Environment which contains default libraries of java.
Ex:- String, character, collection.
JVM is Java Virtual Machine responsible for load the classes and execute
the programs.
---
[Link] between 'ClassNotFound' vs 'NoClassDefFound'?
If you want to run any program, then first we need to compile that program
and then it will generate the bytecode.
After that while running that program, if that .class file is not
available then it will through ClassNotFound Exception.
But while running the program the class file is available but it is using
another dependencies and those dependency class path are not available in
class path then it will through NoClassDefFound.
---
[Link] is JVM Architecture?
There are mainly 3 steps in JVM.
[Link] [Link] [Link].
When we compile the code then it will generate the .class file which
contains the Bytecode.
1. class loaders :-
- JVM architecture uses the class loaders to load the class files.
- There are mainly 3 types of class loaders i)Bootstrap CL
ii)Extension CL
iii)Application CL.
- Bootstrap CL is parent of extension CL and it has child called as
Application CL this is the hierarchy.
- Bootstrap CL is build in native language like "C".
- When we start the application then Bootstrap CL will load the classes
from "[Link]" file.
- After this Extension CL is responsible for to load the files from
that ext (extension) folder.
- After this the Application CL is responsible for to load the classes
from the class path.
- But it is using one principal called as delegation principal.
- When we run any class at that time the request goes to the
Application CL and ACL delegate that request towards
the Extension CL and again ECL delegate that request towards the
Bootstrap CL
- Now Bootstrap CL will check that class will available in the [Link]
or not if not, Then again BCL will delegate that request towards the
Extension CL now ECL check that the class file is present inside that ext
folder or not, If not then again that
request will be delegate towards the Application CL and now ACL will
check that class file is present in class path or not.
- If present then it will load the file if not then it will through
class not found exception.
- After that JVM will create the class object for every class and store
all the metadata of the class inside class object.
2. Linking :-
- Linking contains 3 phases. i)Verification.
ii)preparation.
iii)Resolution.
- Verification :- Verify that the Structure of bytecode (.class file)
is validate or not.
- Preparation :- It will allocate the memory to static variable in
method area and assign default value to variables called as 0.
- Resolution :- Inside the resolution phase it will replace symbolic
reference with actual memory references.
3. Initialization :-
- It will assign the actual values to the static variables after this
it will execute the static block.
---
[Link] is static block?
Static block will run before main method.
because while running the program static block will be load within the
linking phase.
[Link] is meta Space / Method area?
JVM stores all the meta data and static variables, methods, blocks inside
method area.
It uses JVM specific memory and it can cause out of memory error before
java 8.
After java 8 they introduced Meta Space which is same as method area and
only difference is it is using native memory.
It help us to avoid out of memory error.
---
[Link] is Heap area?
Whenever objects are created that objects are stored inside the heap area.
In heap area there are mainly 2 parts :- i) Young generation ii) Old
Generation.
Young generation also have 3 spaces i) Eden space ii)Survivor 0 ii)
survivor 1.
Newly created object will move inside the Eden space and Minor GC runs.
So unused objects will be removed from Eden space remaining will be moved
to the S0.
In S0 Minor GC will remove unused objects and remaining will be moved in
S1.
Then in S1 Minor GC will remove unused objects and remaining will moved in
S0.
Again inside S0 Minor GC will remove unused objects and remaining will be
moved to S1.
So Minor GC cycle keep going and objects will flip between S0 to S1 and S1
to S0.
After JVM specific threshold remaining object will be moved to the old
generation.
And inside old generation Major GC will remove remaining unused objects.
Any tread can access heap area that's why it's not thread safe.
---
[Link] is Permanent Generation?
After Java 8 Permanent Generation replaced by Meta Space.
Permanent Generation size was fixed but Meta Space size is not fixed
because it uses the Native Memory
So there less possibility of out of memory error.
---
[Link] program execute without main method?
No code will not execute without main method
But it will execute the static block because it will executed in
initialization phase.
If you want then i can explain JVM architecture.
---
[Link] objects are eligible for garbage collection?
Local objects and the objects created in method are eligible for garbage
collection after execution of the method.
---
[Link] is stack area?
For every thread JVM create one stack and stores stack frames.
For every method call, one frame will created inside the stack.
Each stack frame contains local variables, method parameters and method
call information.
After method execution completed, frame will be removed from stack.
It is thread safe.
---
[Link] is stack overflow error?
This error occurs when stack memory gets full.
This happens because method keep calling itself again and again without
stopping.
---
[Link] is Execution Engine?
Execution Engine is part of JVM responsible for executing the Bytecode.
There are 2 part in execution engine known as Interpreter, Jit Compiler.
Interpreter :- It reads Bytecode line by line convert into Machine
Language so machine can understand and execute the code.
JIT Compiler :- JIT mean "Just In Time", When interpreter executes the
same code again and again then after specific threshold
JIT compiler will stores the converter Bytecode and reuse it.
---
[Link] is Native method interface(JNI) and Native Method Library?
Native method interface(JNI) allows Java code to interact with Native code
written in c,c++.
Native Method Library is a collection of native implementations of these
methods.
---
[Link] is Garbage collection?
Garbage Collection continuously running in the background
It collects the objects without have any references and objects remain
after method execution completed those are eligible for GC.
---
[Link] is Async annotation?
If we are performing multiple independent task then we use @Async
annotation to save the time.
When we write @Async annotation then new thread is created and main thread
does not wait for task to complete.
---
[Link] is Singleton Bean and Singletone Scope?
Singletone Bean means there will be only single object/Bean in IOC
container of particular class.
Bydefault all the classes are Singletone in spring.(classes with
Stereotype annotation)
If you don't want to be class as a scope Singletone then you should write
@Bean(prototype) on class.
---
[Link] you declare class or bean as singletone?
If state of object is shareable or it is state less then we can make it
singletone.
Spring also provide Singletone bean or we can also create class as a
singletone.
---
[Link] is @PostContruct annotation?
After creation of bean it perform the dependency injection and check for
@PostContruct method and then execute that method.
---
scenario
[Link] you want to perform specific task at specific time?
If you want to perform specific task at specific time then you should go
for schedular.
Where we need to use @EnableScheduling annotation and @Schedular
annotation inside that we can provide time as per requirement.
---
[Link] is cron?
To execute specific task at specific time then we can use cron expressions
and schedular annotation in spring boot know as CronJob.
There is also another way known as cords but i don't have idea.
---
[Link] is difference between Singletone Object or Singletone bean?
Singletone Object mean there will be only single object at JVM level.
Singletone Bean mean there will be only single bean at IOC level.
---
[Link] is Singletone?
Singletone is a creational type of design pattern.
If we make any class as a singletone there will be only one object at JVM
level.
To make it singletone we should make a constructor as a private.
In class we have to declare one variable "Public static Singletone
singletone".
After that we have create one factory method whose return type is
Singletone.
Inside the method we need to check that instance variable is null or not
null.
If null then create new object and return if it's not null return existing
object.
In this way we can create singletone design pattern.
---
[Link] to break Singletone?
Multi Threading :- Using this we can break singletone so to avoid this we
can use synchronized block.
Reflection :- Using the reflection we can change private constructor to
public so to avoid this throw exception in constructor.
clonning :- Using cloning we can create the duplicate clone object to
avoid so to avoid this throw exception in clone method.
Sterilization
---
[Link] one is preferred synchronized Block and synchronized Method?
Synchronized Block is preferred because if you want to synchronize POC or
Specific line then we can use block instead of making entire method
synchronized.
---
[Link] there is double check in Synchronized block?
To avoid creating of new object but instead of talking lock and then
checking that the object is there or not so we can check it directly
outside the block.
---
[Link] is transaction?
Transaction is feature of spring boot.
To achieve tx we use annotation called as Transaction.
While performing multiple insertion operation in DB at ones then use
@Transaction annotation.
If any one of the DB operation fails then other insertion operation will
be rollback.
There will multiple scenario so that spring provides i)Propagation Level
ii)Isolation Level.
---
[Link] are the propagation levels in transactions?
Mainly there are 6 propagation levels in transaction :-
[Link] :- If there is no transaction create new transaction.
2.Required_New :- If there is existing tx then pause that tx and create
new tx and ones new tx completed then resume existing.
[Link] :- If there is existing tx then join that tx and if there is
not then execute without tx.
4.Not_Supported :- If there is exiting tx then don't Support/Join that
tx it will pause tx and execute without tx.
[Link] :-If there is tx then directly throw execption.(method with tx
is calling)
[Link] :- Tx is compulsory required and not available then throw
execption.
---
[Link] are the Isolation levels in transaction? Which one is preferred?
There are mainly 4 isolation level in transaction :-
1.Read_uncommitted :- When application is reads Uncommitted data.
2.Read_committed :- When application is reads committed data. (Commonly
Used)
3.Repeatable_Read :- It will lock the entire row.
[Link] :- It will lock the all records so performance is very
low.
---
[Link] is dirty read?
When our application is reading Uncommitted data that is called as Dirty
Read.
To avoid this we should use isolation level = Read_Commited.
---
[Link] is fandom Read?
While performing the multiple reading operation in same tx 1st we get 3
records and 2nd time we get more or less records that is called as Fandom
read.
To avoid this we use isolation level = Serializable.
---
[Link] you improve the performance of application?
There are multiple ways to improve performance one of the way is we should
use Cache.
---
[Link] on which task you worked?
So i worked on caffeine cache 2 months ago.
---
[Link] Service?
There are 2 types of web service.
[Link]
[Link] Full
Q. What is SOAP web service?
- SOAP is a web service, and In SOAP we can transfer data only in form
of XML.
- It's complex and also heavy weight but it is highly secure.
- It's highly secure because to read the XML response then consumer
compulsory need WSDL file without WSDL we can't read XML file.
- WSDL file (WSDL file = XML file) is contract between Consumer and
Producer.
- WSDL file contain all the metadata of that XML, so by using WSDL file
Consumer can write the code to read XML file.
- That's why it's heavy weight not flexible.
- It's also complex because developer should know the XML and also need
to build the infrastructure(= code) of XML, WSDL files.
Q. What is Rest Full web service?
- Rest API is very flexible and light weight.
- We can transfer data in any format in Rest Api.
- It is not secure so they changed HTTP to HTTPS to make it secure.
---
[Link] two application can do the communication?
There are multiple ways SOAP, Rest Api or Asynchronous communication like
Kafka , Rabbit MQ, Web Socket.
So it's totally based on requirement we can choose the technology.
But now a days Rest Api is drastically used.
Also we can use Kafka , Rabbit MQ for Asynchronous communication.(I'm not
worked on it but I'm aware about it)
(using Rest Templates but we are planning to move on Rabbit MQ or Kafka)
Rest Templates :-[Link] is totally synchronized [Link] wait for response and
block the thread
vs
Web client :-[Link] will not wait for response it will call and forget (fire
and forget).
---
[Link] to create Bean?
We can use Stereotype annotation or Bean annotation.
(➡� create bean of spring default class ➡� create Config Package ➡�
@configuration on class
➡� create method ➡� Write @bean on method ➡� Return Object)
---
[Link] is feign client?
It is component of MS architecture.
It's a declarative approach so we don't need to write any boiler plate
logic spring boot will take care of it.
It is well organized, for ex :- if you want any service api so we can get
all the api calls in single interface.
Feign client is able to do the load balancing so it will consume the
metadata and divert request towards instance.
But if you are not using the open feign client then we have to find all
the api's in different places in product.
---
[Link] is Eureka?
It is component of microservices architecture which helps us to make our
application loosely couple.
Eureka Server is responsible for service registry and service discovery of
all microservices.
When services starts then continuously send the heart beats to eureka
server after specific time.
Based on this, ES maintain all the metadata of service like name
,instances, status ,port ,IP address.
So if any service want to call another service in MS then caller service
will take that metadata and divert the request.
[Link] is API Gateway?
It is component of MS.
It single entry point for all the microservices, so it makes that
architecture loosely couple.
It is also able to do the load balancing.
If there is any changes in other service still there is no impact on
client.
---
[Link] if one of a service is down?
If we have multiple instances of service then call go towards the another
instance.
---
[Link] will you do if service is unavailable?
We can go for circuit Breaker which provide fallback mechanism.
So if service is down and call will get fail then it will show alternative
response.
---
[Link] is circuit breaker? If there are 2 service A calling B and B is
not responding ?
We can go for circuit breaker and provide fallback mechanism.
Circuit Breaker provide some configurations.
Sliding Window Size :- A ➡� B and SWS is 10 then CB will count failure
of last 10 calls if it's ⬆�= 50% then it will open circuit.
There are mainly 3 stages in CB [Link] [Link] [Link] OPEN.
Service A hit to B continuously and calls getting fail so after specific
threshold we can open the circuit for specific time.
After specific time it goes into the half open state again it will
configure the threshold for half open state.
If it's not hitting that threshold then we can close the circuit if it
cross that threshold then we change the state to open.
---
[Link] is Actuator?
It is feature of spring boot.
It is used to give the status of our applications.
It provides multiple endpoints(api) ex:- /health, /Bean
---
Q. What are the feature of java 8?
The main feature of java 8 is :
1. Functional interface.
2. lambda expression.
3. Stream API's.
---
[Link] is functional interface?
Functional Interface which contain only single abstract method.
It is used by lambda expression to provide implementation.
We can write static or default method as well which are introduced in java
8.
If you want to declare Functional interface explicitly then use
@FunctionalInterface annotation.
---
[Link] are the predefined functional interfaces present inside the java
8?
Predicate:-(predict true or false) Method (test)
Consumer:- (only have argument but not return type), Method (test)
Supplier:- (Supplier (only supply no argument), Method (get)
Function:- (have input argument and return type),, Method (apply)
BiPredicate.
BiConsumer.
BiFunction.
(@FunctionalInterface is not mandatory but if adding this will indicate to
developer to not change interface to non function.)
---
[Link] is lambda function?
It is a feature of java 8.
It's a function/expression which don't have Return Type , Access
Modifier,and Name.
Main Purpose of lambda function is to provide the implementation for
functional interface.
---
[Link] is Stream Api?
It is representing the sequence of object.
Stream provide wide no of utility methods.
It has two types of operations :-
[Link] operation :-
- Ex:- Filter(predicate), Sorted(Comparator),
Mapping(function).
- Intermediate operation only configure the operation
(lazy operation).
[Link] operation :-
- Ex:- toList, distinct, max, [Link].
- When we call Terminal operation then it fetch actual
result as per configuration.
---
[Link] is difference between collection and Stream?
Collection is holding the actual objects.
Collection provide no of utility methods.
Collection is eager.
vs
Stream represents only the sequence of object.
As compare to collection Stream provide wide no of utility methods.
Stream is lazy.
---
[Link] between Collection and Collections?
Collection :- It is framework which have multiple implementations.
vs
Collections :- It is utility class which provide multiple utility method.
Ex:- Sort.
---
[Link] is Arrays?
Arrays is utility class, have static method .asList which convert input
data into array.
---
[Link] is default method?/What is the use of default method in the
interface?
Default method is used to save the old implementation and provide backward
compatibility.
---
[Link] is Flat Map?
Map is responsible for manipulate the elements.
Sometimes it return the result in list of list format.
So if you want result by flatterning (merge) then we can use Flat Map.
---
[Link] is difference between Sequential Stream and Parallel Stream?
Sequential Stream
If you want output in sequence then you should go for SS.
Elements will be processed one by one i sequential manner.
Parallel Stream
If you don't have concern about sequence and want performance then you
should use PS.
Multiple thread will be used and all elements be processed
parallely.
---
[Link] is spring cloud config?
It's a ecosystem provided by spring to build microservices architecture.
To build it provide some component like API gateway, Eureka server, spring
boot admin dashboard, Spring cloud config.
---
[Link] String is Immutable?
Basically string is used frequently in every project.
So let's take one example :-
We have String userName= "john" and we are using it at 10 places and if
it's not immutable.
If someone modified that userName = "johnbob" at that time it will reflect
at 10 places.
And that places expecting username = "john" but they are getting johnbob.
And i think that's why they made String as immutable and if someone try to
modify they will get new object.
---
[Link] is intern method?
Intern is a method present inside string class.
If you want to point any reference variable to the SCP then we can call
intern method on string object.
---
[Link] is difference between String vs String Builder and String Buffer?
String :- It is immutable(can't modify existing object), It's not
synchronize.
String Builder :- It's not synchronize (Multiple thread's at a time ),
Performance is best, It is not immutable.
String Buffer :- It is synchronize (1 Thread at a time), It is not
immutable.
---
[Link] you apply security on application?
Use JWT (Json Web Token). (only this answer in interview).
---
[Link] is IS-A relationship and HAS-A relationship?
IS-A relationship means inheritance and problem is acquire all the
properties and functionalities weather it is required or not.
But to solve this issue we can use HAS-A relationship.
HAS-A relationship have two types :- [Link] [Link].
[Link] :-
- It is not preferred because of it's tightly coupleness.
- We have to create content object inside the container
object.
- If container object is destroyed then content object also
destroyed.
[Link] :-
- In aggregation we create object outside the container
class.(stored IOC container)
- So even container object is destroyed content object will
remain same.
---
[Link] is SAGA design pattern?
SAGA is a design pattern used to manage distributed transactions across
multiple microservices.
If any service fails, previous transactions are compensated.
There are 2 types of SAGA :-
[Link].
[Link].
[Link]:-
- It has centralize microservice(CS) which coordinate
transaction in all the services.
- Ex :- We have order service(OS) and payment service(PS) and
to manage it we have centralize service(CS).
- CS will call to OS and after successful order CS will call
to PS.
- If PS fails then CS again call to OS for canceling the
order.
[Link] :-
- It don't have centralize microservice.
- Ex:- API Gateway will call OS to order and after successful
order OS will publishes order completed.
- PS will listen and process for payment, if PS fails PS will
publishes Payment Failed.
- So OS will listen and cancel the order.
---
[Link] is spring security?
DOA:-
When we hit any API it will get intercepted by SecurityFilterChain(SFC)
and check that it has session id or not and also validity.
If it's not valid then it will redirect toward the login page and we have
to login with username and password.
Once we login then request will go towards the SFC and it will take that
username and password and create Authentication object(AO).
And AO will be passed toward Authentication manager(AM) and it will call
to DB with the help of UserDetailService(UDS).
UDS will fetch the roles and credentials inside the UserDetailObject(UDO).
Now AM have two objects AO and UDO and it will pass that objects toward
the Authentication Provider(AP).
There can be a multiple types of AP but using Dao AP will validate the
credentials
If it's valid then it will return authenticated object with flag = true.
now AP ➡� AO ➡� AM ➡� AO ➡� SFC.
SFC will check that AO is validated or not if validated then it will allow
to that request.
Apart from this it will save the AO inside SecurityContextHolder(SCH) and
SessionObject(SO).
That's the flow
SCH :- object is stored here for auditing / to get the information of that
users.
---
[Link] is Hibernate?
Hibernate is ORM tool.(ORM = Object Relational Mapping)
If you want to perform DB operation then we use hibernate.
In hibernate we need two files (XML format files):-
[Link] :- hibernate Mapping File :- In HBM file we write the mapping
between the entity class and table.
[Link] :- Config file :- In CFG file we write database specific
configuration(username , password, url).
---
[Link] is difference between Controller and Restcontroller?
Controller is used for Spring MVC.
RestController is for Rest API's.
---
[Link] is ACID Properties?
Atomicity :-
- If you are performing tx then it should be completed or totally
rollback.
- We can achieve this with the help of tx. (if you want i can
explain TX is spring boot)
Consistency:-
- We have to maintain rules, constraints like PK, FK in that way we
can maintain consistency.
Isolationism :-
- One Tx should not interfere with another Tx and we can achieve
this in spring boot with the help of isolation levels.
Durability :-
- It is like a COMMIT.
- Once we save the data in DB then it should not be removed even
application will be crashed.
---
[Link] to improve the performance of application?
We can use Chace, indexing or pagination.
---
In food delivery application for tracking functionality we use OBSERVER
design pattern.
---
[Link] is normalization?
It used to remove the redundancy, duplicity.
---
[Link] is API idempotency?
If we are calling any API and getting same result again and again that is
idempotency.
Ex- Get Api, Delete Api, patch Api.