0% found this document useful (0 votes)
14 views43 pages

Own Java Notes

Uploaded by

ManiKannanCse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views43 pages

Own Java Notes

Uploaded by

ManiKannanCse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

OOPS Concepts

https://www.baeldung.com/java-oop
Object Oriented Programming is the programming technique to write programs
based on real world objects. The states and behaviors of an object are represented as the
member variables and methods.
1.Abstraction,2.Encapsulation,3.Polymorphism,4.Inheritance,5.Composition,
6.Association,7.Aggregation there are OOPS core concepts
Class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.
A class contains:Fields,Methods,Constructors,Blocks,Nested class and interface.
An object is an instance of a class.
Abstraction is a process of hiding the implementation details from the user. Оnly
the functionality will be provided to the user. In Java, abstraction is achieved using abstract
classes and interfaces. There are many ways to achieve abstraction in object oriented
programming, such as encapsulation and inheritance.
Encapsulation defines the permissions and restrictions of an object and its
member variables and methods.It achieve private modifier providing member variables of
a class and providing public getter and setter methods. Java provides four types of access
level modifiers: public, protected, default and private.
Inheritance:A subclass can inherit the states and behaviors of it’s super class is
known as inheritance.We use extends keyword in java to implement inheritance.used for
code reuse.Multiple Inheritance does not support java.Because it faced diamond problem.
Multiple inheritance: A child class inheriting states and behaviors from
multiple parent classes is known as multiple inheritance.
Multiple inheritance is not supported in classes but it’s supported in interfaces. A
single interface can extend multiple interfaces.
Polymorphism can perform a single action in different ways.There are two types of
polymorphism in Java compile-time polymorphism perform method overloading and
runtime polymorphism perform method overriding.
Example multiple draw methods but they have different behavior. This is a case of
method overloading because all the methods name is same and arguments are different.
Here compiler will be able to identify the method to invoke at compile time
Runtime polymorphism is called as method overriding because subclass has to
override the superclass method. If we are working in terms of superclass, the actual
implementation class is decided at runtime. Compiler is not able to decide which class
method will be invoked. This decision is done at runtime.
Association is a relationship between two objects with multiplicity.For example
Teacher and Student objects. There is one to many relationship between a teacher and
students. However both student and teacher objects are independent of each other.These
relationships can be one to one, One to many, many to one and many to many.
Aggregation is a specialized form of Association where all objects have their own
lifecycle but there is no ownership and child objects can not belong to another parent
object. Let’s take an example of the Department and teacher. A single teacher can not
belong to multiple departments, but if we delete the department teacher will not destroy.
Composition is again a specialized form of Aggregation and we can call this a
“death” relationship. It is a strong type of Aggregation. Child objects do not have their life
cycle and if the parent object deletes all child objects will also be deleted. Let’s take again
an example of the relationship between House and rooms. House can contain multiple
rooms. There is no independent life of room and any room can not belong to two different
houses if we delete the house room will automatically delete.

Collections
https://www.javatpoint.com/java-collections-interview-questions
A Collection is a group of individual objects represented as a single unit. Java
provides Collection Framework which defines several classes and interfaces to represent
a group of objects as a single unit.
The Collection interface (java.util.Collection) and Map interface (java.util.Map) are
the two main “root” interfaces of collection classes.Collection framework implements
various interfaces 1.Collection,2.List,4.Set,4.Queue,5.Dequeue,6.Map

Iterator interface provides the facility of iterating the elements in a forward


direction only.
List interface is the child interface of Collection interface and duplicate values.
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 ArrayList class can be randomly
accessed.Manipulation slow shifting is required.
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.
Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not part of the Collection
framework.
Stack is the subclass of Vector. It implements the last-in-first-out data structure.
Queue interface maintains the first-in-first-out order. It can be defined as an
ordered list that is used to hold the elements which are about to be processed.
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, TreeSet.
HashSet class extends Collection implements Set interface.
HashSet class creates a collection that uses a hash table for storage. Hashset only
contain unique elements .Also, it uses a mechanism hashing to store the elements.
LinkedHashSet class is a Hash table and Linked list implementation of the set
interface. It contains only unique elements like HashSet. Linked HashSet also provides all
optional set operations and maintains insertion order.
TreeSet class implements the Set interface that uses a tree for storage. The
objects of this class are stored in the ascending order. In TreeSet class, access and
retrieval time are faster.
The Map interface maps unique keys to values.
There are two interfaces for implementing Map in java: Map and SortedMap
HashMap class extends AbstractMap class and implements Map interface.
HashMap is a hash table based implementation of the Map interface. It permits null
keys and values. Also, this class does not maintain any order.
TreeMap The map is sorted according to the natural ordering of its keys.TreeMap
is not synchronized and thus is not thread-safe.
LinkedHashMap class is a Hash table and Linked list implementation of the Map
interface. It is the same as HashMap instead maintains insertion order.
ConcurrentHashMap is a thread-safe implementation of a hashmap.not allow null
key.
Hashtable class implements a hashtable, which maps keys to values.It may not
have any null key or value.It is synchronized.
Allow Duplicate in set could not override equals and hashcode.

Comparable vs Comparator

Comparable Comparator

Comparable provides a single sorting Comparator provides multiple sorting


sequence. sequences.

Comparable affects the original class, i.e., Comparator doesn't affect the original class,
the actual class is modified. i.e., actual class is not modified.

Comparable provides compareTo() method Comparator provides compare()

Comparable is found in java.lang package. Comparator is found in the java.util package.

Comparable type by Collections.sort(List) Comparator type by Collections.sort(List,


Comparator) method.

A comparable object is capable of A comparator object is capable of comparing


comparing itself with another object. two different objects.

Java provides two interfaces to sort objects using data members of the class:
A comparable object is capable of comparing itself with another object. The class
itself must implement the java.lang.Comparable interface in order to be able to compare its
instances.
A comparator object is capable of comparing two different objects. The class is not
comparing its instances, but some other class’s instances. This comparator class must
implement the java.util.Comparator interface.
1.Comparable(compareTo() method)
this>2 obj = + value
this<2 obj = - value
this= obj = 0 value
2.Comparator (compare() method)
public static Comparator<Student> nameComparator = new Comparator<Student>() {
@Override
public int compare(Student e1, Student e2) {
return (int) (e1.getName().compareTo(e2.getName()));
}
};
Collections.sort(ar, nameComparator);

Collections.sort(ar, (Student s1, Student s2) -> {


return s1.getName().compareToIgnoreCase(s2.getName());
});
@Override
public int compare(Employee o1, Employee o2) {
return new CompareToBuilder()
.append(o1.getJobTitle(), o2.getJobTitle())
.append(o1.getAge(), o2.getAge())
.append(o1.getSalary(), o2.getSalary()).toComparison();
}
}
Collections.sort(listEmployees, new EmployeeComparator());

Fail Fast And Fail Safe Iterator

Fail-Fast iterators immediately throw ConcurrentModificationException.Ex ArrayList,


HashMap.Its Not synchronized.
Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified
while iterating over it.Ex CopyOnWriteArrayList, ConcurrentHashMap.Its synchronized.

Compare ArrayList

ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "f"));


ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));
Collections.sort(listOne);
Collections.sort(listTwo);
boolean isEqual = listOne.equals(listTwo);//Compare unequal lists example
ArrayList<String> al3= new ArrayList<String>();
for (String temp : al1)
al3.add(al2.contains(temp) ? "Yes" : "No");
Override equals() and hashCode() method
HashMap and HashSet use the hashcode value of an object to find out how the
object would be stored in the collection, and subsequently hashcode is used to help locate
the object in the collection. Hashing retrieval involves:
First, find the right bucket using hashCode().
Secondly, search the bucket for the right element using equals().

Two object hashcodes are the same using equals method.


The hashCode() method returns the same integer number if two keys
(by calling equals() method) are identical.

Override toString() method

If you want to represent any object as a string, the toString() method comes into
existence.The toString() method returns the string representation of the object.
By overriding the toString() method of the Object class, we can return values of the
object, so we don't need to write much code.

Exception Handling

Exceptions are events that occur during the execution of programs that disrupt the
normal flow of instructions for bad input and connectivity problems.All exception and errors
types are subclasses of class Throwable base class,

throw throws

throw keyword used to explicitly throw throws keyword is used to declare an


exception exception

Throw is followed by an instance. Throws are followed by class.

Throw is used within the method. Throws are used with the method signature.

You cannot throw multiple exceptions. You can declare multiple exceptions
try-catch – We use try-catch block for exception handling in our code. try is the
start of the block and catch is at the end of try block to handle the exceptions. We can
have multiple catch blocks with try catch blocks that require a parameter that should be of
type exception.
finally – finally block is optional and can be used only with try-catch block.we
might have some resources open that will not get closed, so we can use finally block.
finally the block gets executed always, whether an exception occurred or not.

Checked Exception The classes which directly inherit Throwable class


except RuntimeException and Error are known as checked exceptions e.g. IOException,
SQLException etc. Checked exceptions are checked at compile-time.

Unchecked Exception The classes which inherit RuntimeException are known as


unchecked exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError.

Multithreading

Multithreading in java is a process of executing multiple threads simultaneously.


Thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.It is a separate
path of execution.Threads are independent. If there is an exception in one thread, it
doesn't affect other threads. It uses a shared memory area.
Every java application has at least one thread – main thread.
Java Multithreading is mostly used in games, animation, etc.
Two ways to create a thread programmatically.
Implementing Runnable interface
To make a class runnable, we can implement java.lang.Runnable interface
and provide implementation in public void run() method. To use this class as Thread, we
need to create a Thread object by passing the object of this runnable class and then call
start() method to execute the run() method in a separate thread.
Extending Thread class
We can extend java.lang.Thread class to create our own java thread class
and override run() method. Then we can create its object and call start() method to
execute our custom java thread class run method.
Implementing Runnable is preferred because java not supports
implementing multiple interfaces. If you extend Thread class, you can’t extend any other
classes. All synchronized blocks synchronized on the same
object can only have one thread executing inside them at a time. All other threads
attempting to enter the synchronized block are blocked until the thread inside the
synchronized block exits the block.
Constructors

A constructor initializes an object when it is created. It has the same name as its
class and is syntactically similar to a method. However, constructors have no explicit return
type.

String
String is a sequence of characters. But in Java, a string is an object that represents
a sequence of characters. java.lang.String class is used to create string objects.
There are two ways to create a String object:
1. By string literal : Java String literal is created by using double quotes.
For Example: String s=“Welcome”;
2. By new keyword : Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”);
It creates two objects (in String pool and in heap) and one reference variable where
the variable ‘s’ will refer to the object in the heap.
Java String Pool: Java String pool refers to a collection of Strings which are stored
in heap memory. In this, whenever a new object is created, String pool first checks
whether the object is already present in the pool or not. If it is present, then the same
reference is returned to the variable else new object will be created in the String pool and
the respective reference will be returned.
Java has provided StringBuffer and StringBuilder class that should be used for
String manipulation.StringBuffer and StringBuilder are mutable objects in java and provide
append(), insert(), delete() and substring() methods for String manipulation.
String is immutable.In case you reassign the value the new memory reference will
be created.StringBuffer and StringBuilder reassign the value the no memory reference
created.

StringBuffer StringBuilder

StringBuffer is synchronized i.e. thread StringBuilder is non-synchronized i.e. not


safe. It means two threads can't call the thread safe. It means two threads can call
methods of StringBuffer simultaneously. the methods of StringBuilder
simultaneously.

StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.
Serialization And DeSerialization:

Serialization is a mechanism of converting the state of an object into a byte stream.


Deserialization is the reverse process where the byte stream is used to recreate the actual
Java object in memory. This mechanism is used to persist the object. Avoid serialization
using @Transient keyword.

The byte stream created is platform independent. So, the object serialized on one
platform can be deserialized on a different platform.
To make a Java object serializable we implement the
java.io.Serializable interface.
Serializable is a marker interface (has no data member and method).
1.If a parent class has implemented Serializable interface then child class doesn’t need to
implement it but vice-versa is not true.
2. Only non-static data members are saved via the Serialization process.
3. Static data members and transient data members are not saved via Serialization
process.So, if you don’t want to save value of a non-static data member then make it
transient.
4. Constructor of an object is never called when an object is deserialized.
5. Associated objects must be implementing Serializable interface.
SerialVersionUID

The Serialization runtime associates a version number with each Serializable class
called a SerialVersionUID, which is used during Deserialization to verify that sender and
receiver of a serialized object.

JVM

JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM
is the one that actually calls the main method present in a java code. JVM is a part of
JRE(Java Runtime Environment).
Java applications are called WORA (Write Once Run Anywhere). This means a
programmer can develop Java code on one system and can expect it to run on any other
Java enabled system without any adjustment.
When we compile a .java file, a .class file(contains byte-code) with the same
filename is generated by the Java compiler. This .class file goes into various steps when
we run it. These steps together describe the whole JVM.
After loading .class file, JVM creates an object of type Class to represent this file in
the heap memory.
An interpreter as opposed to a compiler does not generate machine code. It has
internal logic for processing the statements or byte code instructions and all machine code
or instructions are already in the compiled interpreter.
Lambda Expressions in Java 8

Lambda expressions basically express instances of functional interfaces (An


interface with single abstract method is called functional interface. An example is
java.lang.Runnable). lambda expressions implement the only abstract function and
therefore implement functional interfaces
lambda expressions are added in Java 8 and provide below functionalities
Enable to treat functionality as a method argument, or code as data.
A function that can be created without belonging to any class
A lambda expression can be passed around as if it was an object ,executed on demand.

Garbage Collection

Garbage collector is the best example of Daemon thread as it is always running in


the background. Main objective of Garbage Collector is to free heap memory by destroying
unreachable objects.

Unreachable objects : An object is said to be unreachable if it doesn’t contain any


reference to it.

1. Nullifying the reference variable


2. Re-assigning the reference variable
3. Object created inside method
4. Island of Isolation
We can also request JVM to run Garbage Collector. There are two ways to do it :
Using System.gc() method : System class contains static method gc() for
requesting JVM to run Garbage Collector.
Using Runtime.getRuntime().gc() method : Runtime class allows the application
to interface with the JVM in which the application is running. Hence by using its gc()
method, we can request JVM to run Garbage Collector.
Just before destroying an object, Garbage Collector calls the finalize() method on
the object to perform cleanup activities. Once the finalize() method completes, Garbage
Collector destroys that object.
finalize() method is present in Object class with the following
prototype. protected void finalize() throws Throwable
Based on our requirement, we can override the
finalize() method for performing our cleanup activities like closing connection from
database.

Object class

Object class is the superclass of all Java classes. All Java classes inherited from this
class.

Object class methods Description

boolean equals( Object o ); Gives generic way to compare objects

Class getClass(); The Class class gives us more


information about the object

int hashCode(); Returns a hash value that is used to


search objects in a collection

void notify(); Used in synchronizing threads

void notifyAll(); Used in synchronizing threads

String toString(); Can be used to convert the object to


String

void wait(); Used in synchronizing threads

protected Object clone() throws Return a new object that are exactly
CloneNotSupportedException ; the same as the current object

protected void finalize() throws This method is called just before an


Throwable; object is garbage collected

super and this


Super keyword in java is a reference variable that is used to refer to parent class
objects.
This is a keyword in Java. This keyword in java can be used inside the Method or
constructor of Class. It(this) works as a reference to the current Object, whose Method or
constructor is being invoked.
This can be used to refer to a current class instance variable,invoke the current
class method,invoke the current class constructor,passed as an argument in the method
call,passed as argument in the constructor call,return the current class instance from the
method.
final and finally and finalize

final finally finalize

Final is used to apply Finally, it is used to place Finalize is used to perform


restrictions on class, important code. It will be clean up processing just
method and variable. executed whether an before the object is garbage
Final class can't be exception is handled or not. collected.
inherited, final method can't
be overridden and final
variable value can't be
changed.

Final is a keyword. Finally is a block. Finalize is a method.


Static

Static is a keyword.
Class can not be static.
Method and variable can be static.
If there is a frequent use of a method in a program, then declare that method as
static. The static keyword in java is used for memory management mainly.
Common cases are not going to be changed at any time, so we declare it as static.

Static final

variables, methods Variables, methods, classes

Slower in relative Faster

final variable cannot be reassigned.


do not require an object the final method cannot be overridden.
final class cannot be inherited.

equals() and == difference


== -> is a reference comparison, i.e. both objects point to the same memory
location .equals() -> evaluates the comparison of values in the objects.
We can use == operators for reference comparison (address comparison) and
.equals() method for content comparison. In simple words, == checks if both objects point
to the same memory location whereas .equals() evaluates to the comparison of values in
the objects.

ENUM

1.Enum is a data type that contains a fixed set of constants.


2.Enum declaration can be done outside a Class or inside a Class but not inside a Method.
3.The main objective of enum is to define our own data types(Enumerated Data Types).
4.values() method can be used to return all values present inside enum.
5.valueOf() method returns the enum constant of the specified string value, if it exists.
6.enum may implement many interfaces but cannot extend any class because it internally
extends Enum class.

Generics(Type safety)

1.The Java Generics programming is introduced in JAVA 5 to deal with type-safe objects.
2.We can hold only a single type of objects in generics. doesn’t allow to store other objects
3.There is no need to typecast the object.

public static void main(String args[])

public : Public is an access modifier, which is used to specify who can access this
method. Public means that this Method will be accessible by any Class.

static : It is a keyword in java which identifies it is class based i.e it can be accessed
without creating the instance of a Class.

void : It is the return type of the method. Void defines the method which will not return any
value.

main: It is the name of the method which is searched by JVM as a starting point for an
application with a particular signature only. It is the method where the main execution
occurs.

String args[] : It is the parameter passed to the main method.

Define a Java Class.


A class in Java is a template of an object.
Object is instance of a class
A class in Java is a blueprint which includes all your data.

wrapper classes

Wrapper classes convert the java primitives into the reference types (objects).

Singleton class

Singleton class is a class whose only one instance can be created at any given time, in
one JVM. A class can be made singleton by making its constructor private.
Naming Convention

class and interface name should start with uppercase letter


method should start with uppercase letter
variable name should start with lowercase letter
package name should be in lowercase letter
the constant name should be in uppercase letters.

Marker Interface
It is an empty interface (no field or methods). Examples of marker interface are
Serializable, Clonnable and Remote interface.

Reflection
Reflection is an API which is used to examine or modify the behavior of methods,
classes, interfaces at runtime.

Transient Keyword
Java transient keywords are used in serialization. If you define any data member as
transient, it will not be serialized.
JVM comes across transient keywords, it ignores the original value of the variable
and saves the default value of that variable data type.

Array

Java array is an object which contains elements of a similar data type. It is a data
structure where we store similar elements. We can store only a fixed set of elements in a
Java array.

1.Single Dimensional Array


2.Multidimensional Array
You can use in Java 8 List<Class> myArray= new ArrayList<>();

Ternary Operator

Java ternary operator is the only conditional operator that takes three operands.
Java ternary operator is a one liner replacement for if-then-else statement and used a lot
in java programming.
The first operand in java ternary operator should be a boolean or a
statement with boolean result. If the first operand is true then java ternary operator returns
second operand else it returns third operand.
result = statement ? value1 : value2;
Regex

The Java Regex or Regular Expression is an API to define a pattern for searching or
manipulating strings.
It is widely used to define the constraint on strings such as password and email
validation. // Create a pattern to be searched
Pattern pattern = Pattern.compile("geeks");
// Search above pattern in "geeksforgeeks.org"
Matcher m = pattern.matcher("geeksforgeeks.org");
// Print starting and ending indexes of the pattern in text
while (m.find())

JDBC

Register and Load the Driver: Using Class.forName(), Driver class is registered to
the DriverManager and loaded in the memory.
Use DriverManager to get the Connection object: We get connection object
from DriverManager.getConnection() by passing Database URL String, username and
password as argument.
Class.forName("com.mysql.jdbc.Driver");
// create the connection now
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB","pankaj","pa123");

JAVA VERSIONS
Java SE 8
Lambda Expressions
Default Methods in interface
Java SE 7
Strings in switch Statement
Multiple Exception Handling
Try with Resources
Java nio Package
Java SE 6
Scripting Language Support
J2SE 5.0
Generics
Enhanced for Loop
Typesafe Enums
Varargs
Static Import
J2SE 1.4
XML Processing
Logging API
Assertions
Regular Expressions
J2SE 1.3
Jar Indexing
A huge list of enhancements in almost all the java area.
J2SE Version 1.2
Collections framework.
Java String memory map for constants.
Just In Time (JIT) compiler.
JDK Version 1.1
JDBC (Java Database Connectivity)
Inner Classes
Java Beans
RMI (Remote Method Invocation)
Reflection (introspection only)

Assertion
Assertion is achieved using the assert statement in Java. While executing the
assertion, it is believed to be true. If it fails, JVM throws an error named AssertionError. It
is mainly used for testing purposes during development.
The assert statement is used with a Boolean expression and can be written in two different
ways.
First way : assert expression;
Second way : assert expression1 : expression2;

---------------------------------------------

Spring IOC

https://www.youtube.com/watch?v=suiEGbKf21g
https://www.youtube.com/watch?v=K43qyHJXmWI
https://www.youtube.com/watch?v=IVIhVJJGo68

Spring boot application starts the application created on object in singleton in spring IOC
container.
@Component -instantiate an object and use it to create a bean in a container.
@Scope(value=”prototype”) -instance created not default.not create complex time is
created runtime.
@Autowire- search byType is a class name.
@Qualifer-search byName
byName= create many object based on bean name
byType-one member variable create and one object created by based on class name.
Autowire annotation first looks for types...only one bean as type is autowire is
possible..multiple beans is the same type autowired is not possible.

Container:
1.core-Bean factory
2.J2EE-ApplicationContext,ConfigurableApplicationContext

wat do:

-Will create instance of class


-mange life cycle of class and spring bean
-do dependencyInjection
-Lightweight and very little overhead of using framework for our development.
-spring container takes care of wiring them together to achieve our work.
-Reducing direct dependencies between different components of the application,
-Spring IoC container is responsible for initializing resources or beans and injecting them
as dependencies. -Writing unit test cases are easy in Spring framework because our
business logic doesn’t have direct dependencies with actual resource implementation
classes.
-We can easily write a test configuration and inject our mock beans for testing purposes.
-Reduces the amount of boiler-plate code, such as initializing objects, open/close
resources.
-Inversion of Control (IoC) is to achieve loose-coupling between Objects dependencies.
-Spring Framework IoC container classes are part of org.springframework.beans and
org.springframework.context packages and provides us different ways to decouple the
object dependencies.
-Some of the useful ApplicationContext implementations that we use are;
AnnotationConfigApplicationContext: For standalone java applications using annotations
based configuration.
-ClassPathXmlApplicationContext: For standalone java applications using XML based
configuration.

Dependency Injection
The act of connecting objects with other objects, or “injecting” objects into other
objects, is done by an assembler rather than by the objects themselves.

Spring Bean
Any normal java class that is initialized by Spring IoC container is called Spring
Bean. We use Spring ApplicationContext to get the Spring Bean instance.
Spring IoC container manages the life cycle of Spring Bean, bean scopes and
injecting any required dependencies in the bean.
You can configure a Spring bean using @Bean annotation. This annotation is used
with @Configuration classes to configure a spring bean

stateless beans: beans that are singleton and are initialized only once. The only
state they have is a shared state. These beans are created while the ApplicationContext is
being initialized. The SAME bean instance will be returned/injected during the lifetime of
this ApplicationContext. .

stateful beans: beans that can carry state (instance variables). These are created
every time an object is required.

five different scopes of Spring Bean?

singleton: Only one instance of the bean will be created for each container. This is the
default scope for the spring beans. While using this scope, make sure spring bean doesn’t
have shared instance variables otherwise.it’s not thread-safe.

prototype: A new instance will be created every time the bean is requested.
request: This is the same as prototype scope, however it’s meant to be used for web
applications. A new instance of the bean will be created for each HTTP request.

session: A new bean will be created for each HTTP session by the container.

global-session: This is used to create global session beans for Portlet applications.

Spring actuator

is internally is a rest endpoint and exposed as rest endpoint.

Monitoring our app, gathering metrics, understanding traffic or the state of our database
becomes trivial with this dependency.

Actuator is mainly used to expose operational information about the running application –
health, metrics, info, dump, env, etc. It uses HTTP endpoints or JMX beans to enable us to
interact with it.
1.Spring boot actuator monitoring the application any production related stuff
2. health- db connection up or down,process up and running
3.metrics-heap size,space available particular jvm,garbage collections,count url
using,session active
4.env-running port,system properties,system environment,application
Config-application.properties.
5.info-is empty response,u can overwrite something in info
6.trace-accessed the url lists and details,and how much time taken,
7.mappings- show available mapping urls
8.beans-show create all beans and dependencies
9.Custom EndPoint creation in actuator

Spring MVC

DispatcherServlet acts as the front controller in the Spring’s MVC module(web.xml).


The DispatcherServlet first receives the request.
The DispatcherServlet consults the HandlerMapping and invokes the Controller
associated with the request.
The Controller processes the request by calling the appropriate service methods
and returns a ModeAndView object to the DispatcherServlet. The ModeAndView object
contains the model data and the view name.
The DispatcherServlet sends the view name to a ViewResolver to find the actual
View to invoke.
Now the DispatcherServlet will pass the model object to the View to render the
result.
The View with the help of the model data will render the result back to the user.
Model view controller is a software architecture design pattern. It provides a solution
to layer an application by separating three concerns: business, presentation and control
flow.

MVC
The Model can be some DAO layer or some Service Layers which give some
information about request or requested information or Model can be a POJO which
encapsulates the application data given by the controller.
The View is responsible for rendering the model data and in general it generates
HTML output that the client's browser can interpret.
The Controller is responsible for processing user requests and building appropriate
models and passes it to the view for rendering.

Spring Modules

● Spring IOC- mange life cycle of class and spring bean


● Spring Context – for dependency injection.
● Spring AOP – for aspect oriented programming.
● Spring DAO – for database operations using DAO pattern
● Spring JDBC – for JDBC and DataSource support.
● Spring ORM – for ORM tools support such as Hibernate
● Spring Web Module – for creating web applications.
● Spring MVC – Model-View-Controller implementation for creating web
applications, web services etc.
● Spring Security- providing both authentication and authorization to Java
applications.

Spring Framework is using a lot of design patterns, some of the common ones are:

1.Singleton Pattern: Creating beans with default scope.


2.Factory Pattern: Bean Factory classes
3.Prototype Pattern: Bean scopes
4.Adapter Pattern: Spring Web and Spring MVC
5.Proxy Pattern: Spring Aspect Oriented Programming support
6.Template Method Pattern: JdbcTemplate, HibernateTemplate etc
7.Front Controller: Spring MVC DispatcherServlet
8.Data Access Object: Spring DAO support
Dependency Injection and Aspect Oriented Programming
We use annotate a method with @Transactional annotation for Declarative transaction
management.

Spring annotations

@Controller – for controller classes in the Spring MVC project.

@RequestMapping – for configuring URI mapping in controller handler methods. This is a


very important annotation, so you should go through Spring MVC RequestMapping
Annotation Examples

@ResponseBody – for sending Objects as response, usually for sending XML or JSON
data as response.

@PathVariable – for mapping dynamic values from the URI to handler method arguments.

@Autowired – for autowiring dependencies in spring beans.

@Qualifier – with @Autowired annotation to avoid confusion when multiple instances of


bean type are present.

@Service – for service classes.

@Scope – for configuring the scope of the spring bean.

@Configuration, @ComponentScan and @Bean – for java based configurations.

AspectJ annotations for configuring aspects and advice, @Aspect, @Before, @After,
@Around, @Pointcut etc.

@Component is used to indicate that a class is a component. These classes are used for
auto detection and configured as bean, when annotation based configurations are used.

@Controller is a specific type of component, used in MVC applications and mostly used
with RequestMapping annotation.

@Repository annotation is used to indicate that a component is used as a repository and a


mechanism to store/retrieve/search data. We can apply this annotation with DAO pattern
implementation classes.

@Service is used to indicate that a class is a Service. Usually the business facade classes
that provide some services are annotated with this.
post-initialization and pre-destroy methods in a spring bean –
InitializingBean/DisposableBean interfaces or init-method/destroy-method attributes.
Spring framework also supports @PostConstruct and @PreDestroy annotations for
defining post-init and pre-destroy methods.
Spring batch-These business operations include automated, complex processing
of large volumes of information that is most efficiently processed without user interaction.
These operations typically include time based events (e.g. month-end calculations, notices
or correspondence),

private final Logger logger = LoggerFactory.getLogger(this.getClass());

ApplicationContext ctx = new AnnotationConfigApplicationContext(HelloWorldConf.class);


HelloWorld helloWorld = ctx.getBean(HelloWorld.class);

@SpringBootApplication annotation and invoke SpringApplication.run() method.


@SpringBootApplication=@EnableAutoConfiguration+@ComponentScan+@Configuratio
n

WebMvc implement the extends WebMvcConfigurerAdapter


public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
configurer.enable();

public void addViewControllers(ViewControllerRegistry registry) {


registry.addViewController("/").setViewName("forward:/login.xhtml");
super.addViewControllers(registry);}

public void addResourceHandlers(ResourceHandlerRegistry registry) {


registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");}

ServletInitializer extends SpringBootServletInitializer

implements ApplicationContextAware

implements Filter

public void init(FilterConfig filterConfig) throws ServletException


public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
public void destroy()

Spring Rest:

REST is an architectural style for developing applications that can be accessed


over the network.REST is a stateless client-server architecture where web services are
resources and can be identified by their URIs. Client applications can use HTTP
GET/POST methods to invoke Restful web services.
- REST is a lightweight protocol.
- REST methods can be tested easily over the browser.
- Supports multiple technologies for data transfer such as text, xml, json, image
etc. - Web services are stateless so we can’t maintain user sessions in web
services.

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is


easy for humans to read and write. It is easy for machines to parse and generate.
An object is an unordered set of name/value pairs. An object begins with { (left
brace) and ends with } (right brace). Each name is followed by : (colon) and the
name/value pairs are separated by , (comma).JSON are keys and values.
Types of Values Array,Boolean,Number,Object,String.

Hibernate

Object-relational mapping or ORM is the programming technique to map application


domain model objects to the relational database tables.
Hibernate provides reference implementation of Java Persistence API, that makes it
a great choice as ORM tool with benefits of loose coupling.
Hibernate is an open-source and lightweight ORM tool that is used to store,
manipulate, and retrieve data from the database.
Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care
of managing resources, so we can focus on business logic.
Hibernate persistence API for CRUD operations. Hibernate framework provides an
option to map plain old java objects to traditional database tables with the use of JPA
annotations as well as XML based configuration.
Hibernate provides a powerful query language (HQL) that is similar to SQL.
However, HQL is fully object-oriented and understands concepts like inheritance,
polymorphism and association. Hibernate is easy to integrate with other Java EE
frameworks, it’s so popular that Spring Framework provides built-in support for integrating
hibernate with Spring applications.
Hibernate supports lazy initialization using proxy objects and performs actual
database queries only when it’s required.
Hibernate cache helps us in getting better performance.
It can also execute native sql queries.
Easy to rework while migrating from one database to another.
Hibernation is a development necessity not a performance necessity.

JPA is the interface, Hibernate is implementation of that interface.

The choice of hibernate over jdbc and sql queries is not because of the
performance but because of reasons mainly object persistence and database
independence in terms of not writing database specific queries.
Hibernate has the capability to generate primary keys automatically while we
are storing the records into a database.
HQL is database independent.Getting pagination in hibernate is quite simple.
Hibernate is little slower than pure JDBC, actually the reason being hibernate
used to generate many SQL statements in run time.

The following are some of the reasons why we use hibernate in the place of jdbc.
In a project data flows between the layers in the form of objects. If we transfer
the data from layer to layer in a text format then number of trips are increased
between layers. It decreases the performance of the project.
In data access layer (persistence layer), If we use JDBC technology then it cannot
transfer objects directly to the database.
A developer needs to convert an object into values(text) and then values are
inserted into a database using JDBC.while reading the data also JDBC can read the row
but we need to convert the values into object. It means JDBC can transfer the data
between Java and database in the form of values(text) but not in the form of object. It
increases the burden on developers for converting data from text to object and vice versa.
Internal state of the SessionFactory is immutable, so it’s thread safe.
Multiple threads can access it simultaneously to get Session instances.
The Hibernate Session object is not thread safe, every thread should
get it’s own session instance and close it after it’s work is finished.
Hibernate SessionFactory getCurrentSession() method returns the
session bound to the context. Once the session factory is closed, this session object gets
closed. The Hibernate SessionFactory openSession() method always opens
a new session.We should open a new session for each request in a multi-threaded
environment. session.load() It will always return a “proxy object” without
hitting the database and the given identifier value, its properties are not initialized yet, it
just looks like a temporary fake object.If no row found , it will throw an
ObjectNotFoundException. session.get() it always hits the database
and returns the real object, an object that represents the database row, not proxy.If no row
found , it returns null. Hibernate merge can be used to update
existing values, however this method creates a copy from the passed entity object and
returns it. Criteria can’t be used to run updates or
delete queries or any DDL statements. It’s only used to fetch the results from the
database. It provides Projection that we
can use for aggregate functions such as sum(), min(), max(). It can be used with
ProjectionList to fetch selected columns only. It can be used for joining
queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and
setProjection(). It can be used for fetching
results with conditions, useful methods are add() where we can add Restrictions.
It provides an addOrder()
method that we can use for ordering the results. hibernate generated
sql queries in log files hibernate.show_sql put on application config.
Hibernate uses
proxy object to support lazy loading. Basically when you load data from tables, hibernate
doesn’t load all the mapped objects. As soon as you reference a child or lookup object via
getter methods, if the linked entity is not in the session cache, then the proxy code will go
to the database and load the linked object. It uses javassist to effectively and dynamically
generate sub-classed implementations of your entity objects. Lazy loading in hibernate
improves the performance. It loads the child objects on demand.Since Hibernate 3, lazy
loading is enabled by default, and you don't need to do lazy="true". It means not to load
the child objects when the parent is loaded. First Level Cache is associated
with Session.It is enabled by default. Second Level Cache is associated with
SessionFactory.It is not enabled by default.

FetchType.LAZY = Doesn’t load the relationships unless explicitly “asked for” via getter
FetchType.EAGER = Loads ALL relationships
EAGER: Convenient, but slow
LAZY: More coding, but much more efficient

Pagination: If Hibernate fetches large amounts of data (records) from the database,
Pagination Hibernate is to divide the large result set into a number of pages and fetch one
page at a time.
paginationDto.getFilters()
criteria.add(Restrictions.like // restriction like where statement
projectionList.add(Projections.property("id"));
projectionList.add(Projections.property("name"));
criteria.setProjection(projectionList); //select particular column only
criteria.setProjection(Projections.rowCount()); //get total count
final Integer totalResult = ((Long) criteria.uniqueResult()).intValue();
criteria.setFirstResult(pageNo * pageSize);
criteria.setMaxResults(pageSize);
criteria.addOrder(Order.desc(sortField)); //asc and desc order
List<?> resultList = criteria.list();

@Entity,@Id annotations are mandatory.

Session session = this.sessionFactory.openSession();


Transaction tx = session.beginTransaction();
session.persist(p);
tx.commit();
session.close();
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root@123</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/inventory
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect
<mapping resource="pojo/Location Details.hbm.xml" />
Example.hbm.xml
<hibernate-mapping>
<class name="pojo.Additional Cost" table="additional cost" catalog="inventory">
<id name="sno" type="java.lang.Integer">
<column name="sno" />
<generator class="identity" /> </id>
<property name="name" type="string">
<column name="name" length="100" /> </property>
different states of an entity bean
Transient: When an object is never persisted or associated with any session, it’s in
a transient state. Transient instances may be made persistent by calling save(), persist() or
saveOrUpdate(). Persistent instances may be made transient by calling delete().
Persistent: When an object is associated with a unique session, it’s in
persistent state. Any instance returned by a get() or load() method is persistent.
Detached: When an object is previously persistent but not
associated with any session, it’s in a detached state. Detached instances may be made
persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient
or detached instance may also be made persistent as a new persistent instance by calling
merge().

JSF Life Cycle

<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
Managed beans are lazy by default. It means, bean is instantiated only when a request is
made from the application. @ManagedBean and @ManagedProperty annotation.

The execute phase is further divided into following subphases.

Restore View Phase


Apply Request Values Phase
Process Validations Phase
Update Model Values Phase
Invoke Application Phase
Render Response Phase

lazyDistrictMasterList = new LazyDataModel<DistrictMaster>() {


private static final long serialVersionUID =
8422543223567350599L;

@Override
public List<DistrictMaster> load(int first, int pageSize, String
sortField, SortOrder sortOrder,
Map<String, Object> filters) {

---------------------------------------------

JDK,JRE,JVM

JDK JRE JVM

It stands for Java It stands for Java Virtual


It stands for Java
Development Kit. Runtime Machine.
Environment.
It is the tool JRE refers to a It is an abstract machine. It is a
necessary to runtime specification that provides
compile, environment in run-time environment in which
document and which java bytecode java bytecode can be executed.
package Java can be executed.
programs.
Along with JRE, it It implements the JVM follows three notations:
includes an JVM (Java Virtual Specification(document that
interpreter/loade Machine) and describes the implementation of
r, a compiler provides all the the Java virtual machine),
(javac), an class libraries and Implementation(program that
archiver (jar), a other support files meets the requirements of JVM
documentation that JVM uses at specification) and Runtime
generator runtime. So JRE is a Instance (instance of JVM is
(javadoc) and software package created whenever you write a
other tools that contains what java command on the command
needed in Java is required to run a prompt and run class).
development. In Java program.
short, it contains Basically, it’s an
JRE + implementation of
development the JVM which
tools. physically exists.
SOAP and REST difference
SOAP REST

SOAP stands for Simple Object Access REST stands for REpresentational State
Protocol. Transfer.
SOAP is a protocol. REST is an architectural style.

SOAP can't use REST because it is a REST can use SOAP web services
protocol. because it is a concept and can use any
protocol like HTTP, SOAP.
SOAP uses services interfaces to REST uses URI to expose business logic.
expose the business logic.
JAX-WS is the java API for SOAP web JAX-RS is the java API for RESTful web
services services.
SOAP requires more bandwidth and REST requires less bandwidth and
resources than REST. resource than SOAP.
SOAP permits XML data format only. REST permits different data formats such
as Plain text, HTML, XML, JSON etc.
SOAP is less preferred than REST REST is preferred over SOAP.

Abstract classes and Interfaces difference


https://www.geeksforgeeks.org/interfaces-in-java/
https://www.geeksforgeeks.org/abstract-classes-in-java/

The reason is, abstract classes may contain non-final variables, whereas variables in
interface are final, public and static.
In Java, we can have an abstract class without any abstract method. This allows us to
create classes that cannot be instantiated, but can only be inherited.

Abstract Class Interfaces

An abstract class can provide complete, An interface cannot provide any code at
default code and/or just the details that all,just the signature.
have to be overridden.
In case of abstract class, a class may A Class may implement several
extend only one abstract class. interfaces.Achieve multiple inheritance.
An abstract class can have All methods of an Interface are abstract.
non-abstract methods.Abstract methods
do not have a body.
An abstract class can have instance An Interface cannot have instance
variables. variables
An abstract class can have any An Interface visibility must be public (or)
visibility: public, private, protected. none.
If we add a new method to an abstract If we add a new method to an Interface
class then we have the option of then we have to track down all the
providing default implementation and implementations of the interface and
therefore all the existing code might define implementation for the new method
work properly
An abstract class can contain An Interface cannot contain constructors
constructors.Used for initializing non
static variables.
Abstract classes are fast Interfaces are slow as it requires extra
indirection to find corresponding method
in the actual class
Member variables provide any modifier. Member variable public static final provide
initialization must in member variable jvm Initialization not must in member
variable
The abstract keyword is used to declare Interface keyword used to declare
abstract class. interface
creating a default method in java
interface, we need to use “default”
keyword with the method signature.Java
interface static method is similar to default
method except that we can’t override
them in the implementation classes.

Array List and vector difference

Array List Vector


Array List is not synchronized. Vector is synchronized.

Array List is fast as it’s Vector is slow as it is thread safe.


non-synchronized.
If an element is inserted into the Array Vector defaults to doubling the size of its
List, it increases its Array size by array.
50%.
Array List does not define the Vector defines the increment size.
increment size.
Array List can only use Iterator for Except Hashtable, Vector is the only other
traversing an Array List. class which uses both Enumeration and
Iterator.
Array list and LinkedList difference

Array List LinkedList

ArrayList internally uses dynamic LinkedList internally uses doubly linked list
array to store the elements. to store the elements.
Manipulation with ArrayList is slow
because it internally uses array. If any Manipulation with LinkedList is faster than
element is removed from the array, all ArrayList because it uses doubly linked list
the bits are shifted in memory. so no bit shifting is required in memory.

ArrayList class can act as a list only LinkedList class can act as a list and queue
because it implements List only. both because it implements List and Deque
interfaces.
ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
HashMap and HashTable difference

HashMap HashTable

HashMap is non synchronized. It is Hashtable is synchronized.It is thread-safe


not-thread safe and can't be shared and can be shared with many threads.
between many threads without proper
synchronization code.
HashMap allows one null key and Hashtable doesn't allow any null key or
multiple null values. value.
HashMap is a new class introduced Hashtable is a legacy class.
in JDK 1.2.

HashMap is fast. Hashtable is slow.

We can make the HashMap as Hashtable is internally synchronized and


synchronized by calling this code can't be unsynchronized.
Collections.synchronizedMap(hmap);

HashMap is traversed by Iterator. Hashtable is traversed by Enumeration and


Iterator.
Iterator in HashMap is fail-fast. Enumerators in Hashtable are not fail-fast.

HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

Heap and Stack Memory difference

Features Stack Heap

Memory Stack memory is used only by one Heap memory is used by all the parts of
thread of execution. the application.
Access Stack memory can’t be accessed Objects stored in the heap are globally
by other threads. accessible.
Lifetime Exists until the end of execution of Heap memory lives from the start till the
the thread. end of application execution.
Usage Stack memory only contains local Whenever an object is created, it’s
primitive and reference variables to always stored in the Heap space.
objects in heap space.

Modifiers

List,Set,Map

Principal Base class Base Allow Ordere Sort Thread


collection interfaces duplica d ed -safe
class te
elemen
ts?

ArrayList<E> AbstractList<E> List<E> Yes Yes No No

LinkedList<E> AbstractSequenti List<E>; Yes Yes No No


alList<E> Deque<E>

Vector<E> AbstractList<E> List<E> Yes Yes No Yes

HashSet<E> AbstractSet<E> Set<E> No No No No

LinkedHashSet HashSet<E> Set<E> No Yes No No


<E>

TreeSet<E> AbstractSet<E> Set<E>; No Yes Yes No


NavigableSet
<E>;
SortedSet<E
>

HashMap<K, AbstractMap<K, Map<K, V> No No No No


V> V>
LinkedHashMa HashMap<K, V> Map<K, V> No Yes No No
p<K, V>

Hashtable<K, Dictionary<K, V> Map<K, V> No No No Yes


V>

TreeMap<K, V> AbstractMap<K, Map<K, V>; No Yes Yes No


V> NavigableMa
p<K, V>;
SortedMap<
K, V>

Property java.util.List java.util.Set java.util.Map

Duplicate List allows to Set does not allow Map stores data in the form
elements store duplicate to store duplicate of a key-value pair. It does
elements in java. elements in java. not allow to store duplicate
keys but allows duplicate
values in java.

Insertion java.util.List is an Most of the Most of the java.util.Map


order ordered collection. java.util.Set implementation does not
It maintains implementation maintain insertion order.
does not maintain HashMap does not maintain
insertion order in
insertion order. insertion order in java.
java.
HashSet does not Thought LinkedHashMap
maintain insertion maintains insertion order of
order in java. keys in java.
Though TreeMap is sorted by
LinkedHashSet natural order of keys in java.
maintains insertion
order in java.
TreeSet is sorted
by natural order in
java.
Null keys List allows you to Most of the Set Let's look at Map
store many null implementations implementations -
keys in java. allow you to add HashMap allows one null
only one null in key and many null values.
java. LinkedHashMap allows one
TreeSet and
null key and many null
ConcurrentSkipLi
values.
stSet do not allow
you to add null in TreeMap doesn't allow null
java. keys but allows many null
values.
Hashtable doesn't allow null
key or null values.
ConcurrentHashMap
doesn't allow null key or null
values.
ConcurrentSkipListMap
doesn't allow null key or null
values.

Getting List Set Map implementations do not


element implementations implementations do provide any such get
on specific provide a method not provide any method to get elements on
index such get method to specified index in java.
to get elements on
get elements on
a specific index in
specified index in
java. java.
ArrayList, Vector,
copyOnWriteArray
List and LinkedList
provides -
get(int index)
Method returns
element on
specified index.
Get method
directly gets the
element on the
specified index.
Hence, offering
O(1) complexity.

Implement ArrayList, HashSet,


HashMap, Hashtable,
ing LinkedList, CopyOnWriteArra
ConcurrentHashMap,
classes Vector, ySet,
LinkedHashSet, LinkedHashMap,
CopyOnWriteArra
TreeSet, TreeMap,
yList classes
ConcurrentSkipLi ConcurrentSkipListMap,
implements List stSet, EnumSet IdentityHashMap,WeakHa
interface in java. classes implements shMap, EnumMap classes
Set interface in
implements Map interface in
java.
java.

listIterator listIterator method Set does not Map provides three type of
returns listIterator provide anything iterators -
to iterate over like a listIterator. It map.keySet().iterator()
simply returns the method returns iterator to
elements in List in
Iterator in java. iterate over keys in
java.
listIterator HashMap
provides map.values().iterator()
additional methods method returns iterator to
as compared to iterate over keys in
iterator like HashMap in java.
hasPrevious(),
map.entrySet().iterator()
previous(),
method returns iterator to
nextIndex(),
previousIndex(), iterate over keys in
add(E element), HashMap.
set(E element)

Structure List are Set uses Map for Map uses hashing
and Resizable-array their technique for storing
resizable implementation of implementation. key-value pairs.
Hence, structure is
the java.util.List
map based and
interface in java.
resizing depends
on Map
implementation.
Example >
HashSet internally
uses HashMap.

Index As ArrayList uses Set is not an index Map is not index based
based array for based structure at structure at all in java.
structure implementation it is all in java.
/RandomA
index based
ccess
structure, hence
provides random
access to
elements.
But LinkedList is
not indexed based
structure in java.

unsynchro ArrayList, HashSet,


HashMap,
nized LinkedList LinkedHashSet,
LinkedHashMap,
implement TreeSet, EnumSet
ations TreeMap,
IdentityHashMap,
WeakHashMap,
EnumMap

synchroniz Vector, CopyOnWriteArra


Hashtable,
ed CopyOnWriteArra ySet,
ConcurrentHashMap,
implement yList ConcurrentSkipLi
ations stSet ConcurrentSkipListMap,

gradle and maven difference

gradle maven

Build.gradle is a Groovy script which has Maven build.xml is an xml document that
syntax similar to Java. includes start and end tags.
Single build tools to support multiple
languages.

throw throws

Difference between String, StringBuilder, and StringBuffer.

Factor String String Builder String Buffer

Storage Area Constant String Pool Heap Area Heap Area

Mutability Immutable Mutable Mutable

Thread Safety Yes Yes No

Performance Fast Slow Fast

Differentiate between static and non-static methods in Java.

Static Method Non-Static Method


1. The static keyword must be used before 1. No need to use the static keyword
the method name before the method name

2. It is called using the class 2. It is can be called like any general


(className.methodName) method

3. They can’t access any non-static 3. It can access any static method
instance variables or methods and any static variable without
creating an instance of the class

What is abstraction in Java?


Abstraction refers to the quality of dealing with ideas rather than events. It basically deals

with hiding the details and showing the essential things to the user. Thus you can say that

abstraction in Java is the process of hiding the implementation details from the user and

revealing only the functionality to them. Abstraction can be achieved in two ways:

1. Abstract Classes (0-100% of abstraction can be achieved)


2. Interfaces (100% of abstraction can be achieved)

What do you mean by an interface in Java?


An interface in Java is a blueprint of a class or you can say it is a collection of abstract

methods and static constants. In an interface, each method is public and abstract but it

does not contain any constructor. Thus, interface basically is a group of related methods

with empty bodies. Example:

public interface Animal {


public void eat();
public void sleep();
public void run();
}
Why do we use interfaces ?

● It is used to achieve total abstraction.


● Since java does not support multiple inheritance in case of class, but by using
interface it can achieve multiple inheritance .
● It is also used to achieve loose coupling.
● Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas
variables in interface are final, public and static.

There are four different ways to create objects in java:

A. Using new keyword

This is the most common way to create an object in java. Almost 99% of objects are created in
this way.

MyObject object = new MyObject();

B. Using Class.forName()

If we know the name of the class & if it has a public default constructor we can create an
object in this way.

MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

C. Using clone()

The clone() can be used to create a copy of an existing object.

MyObject anotherObject = new MyObject(); MyObject object = (MyObject)


anotherObject.clone();

D. Using object deserialization

Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream ); MyObject
object = (MyObject) inStream.readObject();

List<String> collect =
alpha.stream().map(String::toUpperCase).collect(Collectors.toList());

unidirectional vs bidirectional relationship hibernate


https://stackoverflow.com/questions/5360795/what-is-the-difference-between-unidirectional
-and-bidirectional-jpa-and-hibernat

The main difference is that bidirectional relationship provides navigational access in both
directions, so that you can access the other side without explicit queries. Also it allows you
to apply cascading options to both directions.

1. Profile-specific application properties outside of your packaged jar


(application-{profile}.properties and YAML variants).
2. You can also use YAML ('.yml') files as an alternative to '.properties'.

Spring BOOT:
Spring Boot is the best Java framework for microservices.
Bootstrap your application with Spring Initializr.
Spring Boot is a way to ease the creation of stand-alone applications with minimal
or zero configurations.
● Create stand-alone Spring applications
● Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
● Provide opinionated 'starter' dependencies to simplify your build configuration
● Automatically configure Spring and 3rd party libraries whenever possible
● Provide production-ready features such as metrics, health checks and
externalized configuration
● Absolutely no code generation and no requirement for XML configuration

Spring Data
● Prerequisite : Java 8 Optional Class

Optional is a container object which may or may not contain a non-null value. You
must import java.util package to use this class. If a value is present, isPresent() will
return true and get() will return the value. Additional methods that depend on the
presence or absence of a contained value are provided, such as orElse() which
returns a default value if value not present and ifPresent() which executes a block of
code if the value is present.

------------------------------------------------------------------------------------------------------------
What are Annotations?
One word to explain Annotation is Metadata. Metadata is data about data. So Annotations
are metadata for code.
Annotations help to associate metadata (information)

SELECT name (NVL(name,-)) FROM Sales_Data;

the COALESCE function returns the first non-null expression in the list. If all expressions
evaluate to null, then the COALESCE function will return null.

how to create annotation

custom exception

Java String objects are immutable; it is only possible to create modified copies of the
original string. When we need to modify strings in-place, we use StringBuilder.

StringBuilder has methods such as append(), insert(), or replace() that allow you to modify
strings.

@PropertySource({"classpath:inventory.properties"})
@Value("${ntsm.cometServerUrl}")

1.Where you will use encapsulation and abstraction


2.Linkedhaset vs hashset
3.Hashset,hashmap work internally
4.Overload main method.yes.-
https://www.geeksforgeeks.org/how-to-overload-and-override-main-method-in-java/
5.Threadpool executor.
6.fam-https://www.geeksforgeeks.org/how-to-overload-and-override-main-method-in-java/
7.Functional interface &
A functional interface is an interface that contains only one abstract method.,any number
of default methods.-https://www.baeldung.com/java-8-functional-interfaces
Name of functional interface.Consumer,producer,
8.Dynamic method dispatch- overriding
https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/
9.@Qualifier
10.Automicinteger-https://howtodoinjava.com/java/multi-threading/atomicinteger-example/
11.Matrics param-@MatrixParam,@PathParam
@MatrixParam, @HeaderParam, @CookieParam, @FormParam obey the same rules as @QueryParam.
@MatrixParam-https://stackoverflow.com/questions/10183875/whats-the-difference-bet
ween-queryparam-and-matrixparam-in-jax-rs
12.Hibernate vs JPA
13.save and persist
14.How many Generator have hibernate
15.@SCheduled
16.group-id,com.example.
artifact-id-like jemini main folder name

https://www.geeksforgeeks.org/difference-between-abstract-class-and-interface-in-java/
https://www.geeksforgeeks.org/difference-between-abstraction-and-encapsulation-in-java-
with-examples/

@EnableWebMvc
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(
ResourceHandlerRegistry registry) {

registry.addResourceHandler("/static/**")
.addResourceLocations("/WEB-INF/view/react/build/static/");
registry.addResourceHandler("/*.js")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.json")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/*.ico")
.addResourceLocations("/WEB-INF/view/react/build/");
registry.addResourceHandler("/index.html")
.addResourceLocations("/WEB-INF/view/react/build/index.html");
}
}

@Configuration
@EnableWebSecurity
@Profile("!https")
public class SecSecurityConfig
extends WebSecurityConfigurerAdapter {

//...

@Override
protected void configure(final HttpSecurity http)
throws Exception {
http.csrf().disable().authorizeRequests()
//...
.antMatchers(
HttpMethod.GET,
"/index*", "/static/**", "/*.js", "/*.json", "/*.ico")
.permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/index.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html",true)
.failureUrl("/index.html?error=true")
//...
}
}

Abstract Class vs Interface


The table below lists out the key differences between abstract class and interface.

Parameter Abstract Class Interface

Default Method It can have default method Interfaces provide pure

Implementation implementation abstraction & can not have

implementation at all

Variables It may contain non-final Variables declared in an

variables. interface are by default

final

Keyword Used An abstract class can be The interface should be

extended using the implemented using

keyword “extends keyword ïmplements

Access Modifiers Can have public, Interface methods are by

protected, private and default public. you can not

default modifier use any other access

modifier with it

Speed of Implementation It is faster than the An Interface is somewhat

interface slower & require extra

indirection
Normal Class It can extend only one Can implement multiple

abstract class interfaces

Constructors An abstract class can An interface can not have

have constructors constructors

Multiple Inheritance An abstract class can The interface can extend

extend another class and another Java interface

can implement multiple only

Java interfaces

@EnableAutoConfiguration in spring boot tells how you want to configure spring, based on
the jars that you have added in your classpath. For example, if you add
spring-boot-starter-web dependency in your classpath, it automatically configures Tomcat
and Spring MVC.

https://javarevisited.blogspot.com/2012/07/hibernate-get-and-load-difference-interview-que
stion.html
Since load() throws exception when data is not found, we should use it only when we know
data exists.

https://thoughts-on-java.org/ultimate-guide-association-mappings-jpa-hibernate/

list of all immutable classes in java

https://stackoverflow.com/questions/5998031/complete-list-of-immutable-jdk-classes

java.lang.String The wrapper classes for the primitive types:


java.lang.Integer
java.lang.Byte
java.lang.Character
java.lang.Short
java.lang.Boolean
java.lang.Long
java.lang.Double
java.lang.Float

put post difference:


POST should be used to create a resource, and PUT should be used to modify one
PUT should be used to create a resource, and POST should be used to modify one
@RestControllerAdvice
public class GenericExceptionHandler {
@ExceptionHandler({ GenericNtsmValidationException.class })

@Target({ METHOD, FIELD, CONSTRUCTOR, PARAMETER, TYPE_USE })


@Retention(RUNTIME)
@Documented
public @interface Valid {
}

@PropertySource({"classpath:ntsmConfig.properties"})

@Value("${ntsm.hibernate.save.chunk.size}")

Hashmap vs WeakHashMap in Java

https://www.baeldung.com/java-executor-service-tutorial

https://javahungry.blogspot.com/2015/09/difference-between-weakhashmap-and-hashmap
-with-exmaple.html?m=1

● Duplicate remove

List<Person> distinctPersons = list.stream()


.filter(distinctByKeys(Person::firstName, Person::lastName))
.collect(Collectors.toList())

https://howtodoinjava.com/java8/stream-distinct-by-multiple-fields/

https://www.baeldung.com/java-stream-filter-lambda

https://www.baeldung.com/java-8-collectors

The volatile modifier is used to let the JVM know that a thread accessing the variable
must always merge its own private copy of the variable with the master copy in the
memory. Accessing a volatile variable synchronizes all the cached copied of the variables
in the main memory

You might also like