Java
Java
Interview Questions.................................................................................................................................................................. 7
ConcurrentHashMap ........................................................................................................................................................... 10
ClassNotFoundException Vs NoClassDefFoundError.......................................................................................................... 10
Optional ............................................................................................................................................................................... 13
Design Patterns.................................................................................................................................................................... 16
Decorator Pattern................................................................................................................................................................ 22
Main..................................................................................................................................................................................... 29
ENUM .................................................................................................................................................................................. 30
Abstraction .......................................................................................................................................................................... 33
Encapsulation ...................................................................................................................................................................... 33
IS - A Relation ...................................................................................................................................................................... 34
Method Signature................................................................................................................................................................ 37
Cohesion .............................................................................................................................................................................. 48
Constructors ........................................................................................................................................................................ 52
Packages .............................................................................................................................................................................. 57
Modifiers ............................................................................................................................................................................. 58
Interfaces ............................................................................................................................................................................. 59
Collections ........................................................................................................................................................................... 64
Arrays............................................................................................................................................................................... 64
ArrayList ........................................................................................................................................................................... 68
LinkedList ......................................................................................................................................................................... 69
Vector .............................................................................................................................................................................. 70
Stack ................................................................................................................................................................................ 71
Cursors ............................................................................................................................................................................. 71
HashSet ............................................................................................................................................................................ 75
LinkedHashSet ................................................................................................................................................................. 76
SortedSet(I) ...................................................................................................................................................................... 77
TreeSet ............................................................................................................................................................................ 77
Map.................................................................................................................................................................................. 81
HashMap ......................................................................................................................................................................... 82
LinkedHashMap ............................................................................................................................................................... 85
IdentityHashMap ............................................................................................................................................................. 85
WeakHashMap ................................................................................................................................................................ 86
TreeMap .......................................................................................................................................................................... 87
HashTable ........................................................................................................................................................................ 87
Queues............................................................................................................................................................................. 88
PiriorityQueue .................................................................................................................................................................. 88
[Link] .............................................................................................................................................................................. 94
[Link] ................................................................................................................................................................ 95
How to manage the inter service communication in java microservices .......................................................................... 178
JSP.......................................................................................................................................................................................... 187
SQL......................................................................................................................................................................................... 193
AJAX....................................................................................................................................................................................... 203
Find The Percentage Of Uppercase Letters, Lowercase Letters, Digits And Other Special Characters In A String ........... 214
In Java, every ClassLoader has a predefined location from where they load class files. There are following types of
ClassLoader in Java:
Bootstrap Class Loader: It loads standard JDK class files from [Link] and other core classes. It is a parent of all class loaders.
It doesn't have any parent. When we call [Link]() it returns null, and any code based on it throws
NullPointerException. It is also called Primordial ClassLoader. It loads class files from jre/lib/[Link]. For example, [Link]
package class.
Extensions Class Loader: It delegates class loading request to its parent. If the loading of a class is unsuccessful, it loads
classes from jre/lib/ext directory or any other directory as [Link]. It is implemented by
[Link]$ExtClassLoader in JVM.
System Class Loader: It loads application specific classes from the CLASSPATH environment variable. It can be set while
invoking program using -cp or classpath command line options. It is a child of Extension ClassLoader. It is implemented by
[Link]$AppClassLoader class. All Java ClassLoader implements [Link].
2. Class (Method) Area: It stores class level data of every class such as the runtime constant pool, field and
method data, the code for methods.
3. Heap: It is used to allocate memory to objects at run time
4. Stack:
• Each thread has a private JVM stack, created at the same time as thread. It is used to store data and
partial results which will be needed while returning value for method and performing dynamic linking.
• Java Stack stores frames and a new frame is created each time at every invocation of the method.
A frame is destroyed when its method invocation completes
5. Program Counter Register: Each JVM thread which carries out the task of a specific method has a program
counter register associated with it. The non-native method has a PC which stores the address of the available
JVM instruction whereas, in a native method, the value of the program counter is undefined. PC register is
capable of storing the return address or a native pointer on some specific platform.
Native method Stacks: Also called as C stacks, native method stacks are not written in Java language. This
memory is allocated for each thread when its created And it can be of a fixed or dynamic nature.
Deep Copy
• Whenever we need own copy not to use default implementation, we call it as deep copy, whenever we
need deep copy of the object we need to implement according to our need.
• So for deep copy we need to ensure all the member class also implement the Cloneable interface an d override
the clone() method of the object class.
Runnable vs callable
public interface Callable<V> {
V call() throws Exception;
}
Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is
because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-
safe iterators.
CopyOnWriteArrayList class is introduced in JDK 1.5, which implements the List interface. It is an enhanced version
of ArrayList in which all modifications (add, set, remove, etc) are implemented by making a fresh copy. It is found
in [Link] package. It is a data structure created to be used in a concurrent environment.
ConcurrentHashMap
• The underlined data structure for ConcurrentHashMap is Hashtable.
• ConcurrentHashMap class is thread-safe i.e., multiple threads can operate on a single object without any
complications.
• At a time, any number of threads are applicable for a read operation without locking the ConcurrentHashMap
object which is not there in HashMap.
• In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level.
• The default concurrency-level of ConcurrentHashMap is 16.
• In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in
the object, the thread must lock the particular segment in which the thread wants to operate. This type of
locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can
be performed by threads.
• Inserting null objects is not possible in ConcurrentHashMap as a key or value.
HashTable vs ConcurrentHashMap:
As opposed to the HashTables where every read/write operation needs to acquire the lock, there is no locking at the
object level in ConcurrentHashMaps and is much finer granular at a hashmap bucket level.
It never locks the whole Map, instead, it divides the map into segments and locking is done on these segments
ConcurrentHashMap allows performing concurrent read and write operation. Hence, performance is relatively better than
the Synchronized Map. In Synchronized HashMap, multiple threads cannot access the map concurrently. Hence, the
performance is relatively less than the ConcurrentHashMap.
What kind of business use cases can be implemented using concurrent hash map?
There are a few different scenarios in which it makes sense to use a ConcurrentHashMap over a regular HashMap. One
common scenario is when you need to support multiple readers and writers simultaneously. This could be the case in a
web application, for example, where multiple users are accessing data at the same time.
ClassNotFoundException Vs NoClassDefFoundError
ClassNotFoundException is an exception that occurs when you try to load a class at run time using
Class. forName() or loadClass() methods and mentioned classes are not found in the classpath.
NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but
was missing at run time.
Sequential Stream:
Sequential Streams are non-parallel streams that use a single thread to process the pipelining. Any stream operation
without explicitly specified as parallel is treated as a sequential stream. Sequential stream’s objects are pipelined in a
single stream on the same processing system hence it never takes the advantage of the multi-core system even though
the underlying system supports parallel execution. Sequential stream performs operation one by one.
stream() method returns a sequential stream in Java.
Parallel Stream:
Parallel stream leverage multi-core processors, which increases its performance. Using parallel streams, our code gets
divide into multiple streams which can be executed parallelly on separate cores of the system and the final result is
shown as the combination of all the individual core’s outcomes. It is always not necessary that the whole program be
parallelized, but at least some parts should be parallelized which handles the stream. The order of execution is not
under our control and can give us unpredictably unordered results and like any other parallel programming, they are
complex and error-prone.
The Java stream library provides a couple of ways to do it. easily, and in a reliable manner.
• One of the simple ways to obtain a parallel stream is by invoking the parallelStream() method
of Collection interface.
• Another way is to invoke the parallel() method of BaseStream interface on a sequential stream.
It is important to ensure that the result of the parallel stream is the same as is obtained through the sequential stream,
so the parallel streams must be stateless, non-interfering, and associative.
Note: If we want to make each element in the parallel stream to be ordered, we can use the forEachOrdered() method,
instead of the forEach() method.
Solution: You can achieve multiple inheritance in Java, using the default methods (Java8) and interfaces.
Must override the default method from the class explicitly specifying the default method along with its
interface name.
interface MyInterface1{
public static int num = 100;
public default void display() {
[Link]("display method of MyInterface1");
}
}
interface MyInterface2{
public static int num = 1000;
public default void display() {
[Link]("display method of MyInterface2");
}
}
public class InterfaceExample implements MyInterface1, MyInterface2{
public void display() {
[Link]();
//or,
[Link]();
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
[Link]();
}
}
Spring Profiles
1. Spring has supported @Profile annotation since version 3.1
2. @Profile is inside [Link]
Spring Boot by default comes with a property file, named [Link]. To segregate the configuration based on
the environments, we will create multiple property files. One for each environment we are targeting.
We will create three property files for the dev, test, and prod environments. Note the naming convention.
[Link]
[Link]
[Link]
The [Link] file will be the master of all properties. Here we will specify which profile is active by using
the property [Link].
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 the value is not
present, and ifPresent() which executes a block of code if the value is present.
[Link]()
[Link](T value)
[Link](T value)
Runtime r = [Link]();
DateFormat df = [Link]();
5) By using deserialization
Dog d2 = (Dog)[Link]();
Security
Assertions
Java 5:
Enum
Var args
Static import
Annotations
Generics
Java 6:
Instrumentation (premain method) (Java 6): The premain is a mechanism associated with
the [Link] package, used for loading "Agents" which make byte-code changes in Java programs.
Java 7:
Java 8:
Java 11:
?????
SOLID Principles
Single responsibility: This principle states that a class should only have one responsibility. Furthermore, it should only
have one reason to change.
How does this principle help us to build better software? Let's see a few of its benefits:
1. Testing – A class with one responsibility will have far fewer test cases.
2. Lower coupling – Less functionality in a single class will have fewer dependencies.
3. Organization – Smaller, well-organized classes are easier to search than monolithic ones.
Open closed: Classes should be open for extension but closed for modification. In doing so, we stop ourselves from
modifying existing code and causing potential new bugs in an otherwise happy application.
Liskov substitution: If class A is a subtype of class B, we should be able to replace B with A without disrupting the
behavior of our program.
Interface segregation: It simply means that larger interfaces should be split into smaller ones. By doing so, we can
ensure that implementing classes only need to be concerned about the methods that are of interest to them.
Dependency inversion: The principle of dependency inversion refers to the decoupling of software modules. This way,
instead of high-level modules depending on low-level modules, both will depend on abstractions. The principle states that
we must use abstraction (abstract classes and interfaces) instead of concrete implementations.
Design Patterns
S.
No Creational Structural Behavioral
11
Visitor Pattern
o Factory Method Pattern allows the sub-classes to choose the type of objects to create.
o It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code. That
means the code interacts solely with the resultant interface or abstract class, so that it will work with any classes
that implement that interface or that extends that abstract class.
o Abstract Factory Pattern isolates the client code from concrete (implementation) classes.
o It eases the exchanging of object families.
o It promotes consistency among objects.
o When the system needs to be independent of how its object are created, composed, and represented.
o When the family of related objects has to be used together, then this constraint needs to be enforced.
o When you want to provide a library of objects that does not show implementations and only reveals interfaces.
o When the system needs to be configured with one of a multiple family of objects.
Singleton
The singleton pattern is one of the simplest design patterns. Sometimes we need to have only one instance of our class for
example a single DB connection shared by multiple objects as creating a separate DB connection for every object may be
costly. Similarly, there can be a single configuration manager or error manager in an application that handles all problems
instead of creating multiple managers. The singleton pattern is a design pattern that restricts the instantiation of a class to
one object.
In other words, to provide the interface according to client requirement while using the services of a class with a different
interface.
o When you don't want a permanent binding between the functional abstraction and its implementation.
o When both the functional abstraction and its implementation need to extended using sub-classes.
o It is mostly used in those places where changes are made in the implementation does not affect the clients.
Composite Pattern
A Composite Pattern says that just "allow clients to operate in generic manner on objects that may or may not represent
a hierarchy of objects".
Procedure:
1. Create an interface.
2. Create concrete classes implementing the same interface.
3. Create an abstract decorator class implementing the above same interface.
4. Create a concrete decorator class extending the above abstract decorator class.
5. Now use the concrete decorator class created above to decorate interface objects.
6. Lastly, verify the output
Behavioral Design Patterns
Chain Of Responsibility Pattern
In chain of responsibility, sender sends a request to a chain of objects. The request can be handled by any object in the
chain.
A Chain of Responsibility Pattern says that just "avoid coupling the sender of a request to its receiver by giving multiple
objects a chance to handle the request". For example, an ATM uses the Chain of Responsibility design pattern in money
giving process.
In other words, we can say that normally each receiver contains reference of another receiver. If one object cannot handle
the request then it passes the same to the next receiver and so on.
o When more than one object can handle a request and the handler is unknown.
o When the group of objects that can handle the request must be specified in dynamic way.
Observer Design Pattern
Definition:
The Observer Pattern defines a one to many dependency between objects so that one object changes state, all of its
dependents are notified and updated automatically.
Explanation:
Language Fundamentals
Identifiers:
➔ A name in java program is called as identifier.
➔ Allowed charters are alphabets, digits, $ and _ only.
➔ Class names are allowed.
Keywords (50):
✓ Used (48)
✓ Unused (2): goto and const
Data Types:
Type checking is done by compiler
Max_value = +127
Min_value = -128
-32768 to 32767
2-31 to 231 -1
Long
Float
double
Char
Boolean
Arrays:
int[] a = new int[100]; //Size is mandatory
int []a;
int a[];
int[] a; //valid
int[5] b; //invalid
[Link](a[1]); //0
int[] a = {10,20,30};
int[] b;
int[] a = {10,20,30};
int[] b = a;
char[] c ={'c'};
int[] d = c; // invalid
[Link](args[i]); //empty
[Link](args[i]);
args= argh;
[Link](args[i]); // A B C
Instance Variable:
✓ Declared with in a class but outside of any method, block and constructor.
✓ Stored in Heap memory
int x =10;
int x;
double y;
boolean b;
String s;
public static void main(String[] args) {
[Link](t.x); // 0
[Link](t.y); // 0.0
[Link](t.b); //false
[Link](t.s); //null
Static variable:
static int x;
static int x;
static double y;
static boolean b;
static String s;
[Link](t.x); // 0
[Link](t.y); // 0.0
[Link](t.b); //false
[Link](t.s); //null
int y =20;
t1.y=30;
int[] x;
[Link](t.x); // null
[Link](t.x[0]); //[Link]
Var args:
Int… x; //valid
Int…x; //valid
M1(int ...d, String s) // not valid var arg should be last parameter
Main:
✓ If main method is not there will get RE:NoSuchMethodException
✓ Inside jvm main method is configured as public static void main(String[] args)
final is allowed
Synchronized is allowed
Strictfp is allowed -> It is used in java for restricting floating-point calculations and ensuring the same result on every
platform while performing operations in the floating-point variable.
inheritance is applicable
ENUM:
✓ 1.5V
✓ To defined our own data types.
✓ Declared inside of the class and outside of the class but not the inside of the method.
package [Link];
FEB,
MAR,
int i =0;
[Link]("test");
}
[Link]([Link]); //KT
KF,
CB
enum Month{
JAN,
FEB,
MAR,
APR
Month m = [Link];
switch(m){
default: [Link]("test");
}
public static void main(String[] args) {
Month m2 = [Link]("MAR");
[Link](m2); //MAR
[Link](x); //0
[Link](x++); //0
[Link](++x); //2
int y=0;
[Link](y);//0
[Link](++y);//1
[Link](y++);//1
int x=0;
int y=0;
[Link](x);//2
[Link](y);//2
[Link](z);//3
Data Hiding:
Every data member/Variable should be declared as private only.
public class Account {
//validation if required
return bal;
Abstraction:
Hides internal implementation of the services but just highlight set of the services available.
If you need to provide a base for a hierarchy of classes or provide a common implementation, you should use abstract
classes.
If you need to define behavior that can be implemented by multiple unrelated classes, you should use interfaces.
Encapsulation:
The process of binding the data members and corresponding methods into single unit is called Encapsulation. Ex: Java
Class
Advantage: security
IS - A Relation
Also known as inheritance using extends keyword.
Advantage: Reusability
Class p {
Sop(“m1”);
Class C extends P{
Sop(“m2”);
}
Class Test{
1) P p= new P();
p.m1(); Valid
2) C c = new C();
c.m1();Valid
c.m2();Valid
P2.m1();Valid
Conclusions:
1) Whatever methods child has by default not available to the parent and hence on the parent reference we can’t
child specific methods.
2) Whatever methods parent has by default available to the child. So on child reference we can call both parent and
child class methods.
3) Parent reference can be to hold child object but by using that reference we can’t call child specific methods. But
we can call methods present in parent class.
4) Parent reference can be used to hold child object but child reference cannot be used to hold parent object.
Multiple Inheritance: Class A extends B, C { } -> A java class can’t extend more than one class at a time. Will get Compile
time error.
Object
A
Class B extends A { } -> B is Child of A and A is child of Object (Multi level inheritance).
Object
Class A {
M1 () {}
Class B {
M1 () {}
But interface can extend any number of interfaces simultantiously hence java provides support multiple inheritance with
respect to interfaces.
CI -> m1 () implementation will provided by the CI and have only unique implementation.
Class A extends B {} and Class B extends A {} -> Cyclic Inheritance -> Not allowed in java
HAS – A Relationship
1) Has –A relationship is used mostly call it is Association.
2) Can achive using composition or Aggregation.
3) No specific keyword. Mostly by using new keyword.
4) Reusability.
Class Car {
Container (University)
Contained (Department)
Aggregation:
Contained (Professors)
Container (Department)
Composition:
Without existing container object, if there is no chance of existing of contained objects then container and contained
objects are strongly associated and this strong association is nothing but composition.
Aggregation:
Without existing container object, if there is a chance of existing of contained objects then container and contained
objects are weakly associated and this weak association is nothing but aggregation.
Method Signature
In java method signature consists of method names followed by argument types.
Public static int m1 (int a, float b); → Method signature: m1 (int, float)
Class Test
M m1 (int)
m2 (String)
Method Table
m1 (10); ->Valid
m1 (10.5); -> CE: cannot find symbol. Symbol: method m1 (double) location: Class Test
In same class, methods with same method signature are not allowed. (CE: m1 (int) is already defined in Test).
Method Overloading
Two methods are said to be overloaded if and only if both methods having same name and different argument types.
M1 (int a);
M2 (double b);
[Link]("int-args");
[Link]("float-args");
}
t. m1 (10); int-args
t. m1 (10.5f); float-args
char
[Link]("String");
[Link]("object");
[Link]("String");
[Link]("StringBuffer ");
}
t. m1 (new Object ()); object
t. m1 (“Santhosh”); String
t. m1 (null); CE: m1 (object) ambiguous for the type t. (with two object (string/integer))
[Link]("int");
[Link]("float");
[Link]("int");
[Link]("args");
class Animal {}
[Link]("animal");
[Link]("monkey");
Method Overriding
Class P {
sop (“land,money”);
Sop (“test”);
}
}
Class C extends P {
Sop (“test54756”);
}}
P p = new P ();
C c =new C ();
P p = new C ();
** In overriding method resolution always take cares by JVM based on runtime object and hence over riding is also
consider as runtime polymorphism or dynamic polymorphism or late binding.
Class C extends P {
public String property () {
sop (“land, money”); } }
A/C to this child class method return type need not be same as parent class method return type. Its child type
also allowed.
Parent Child
Co variant return type concept applicable only for object types but not for Primitive types.
➔ Parent class private methods not available to the child and hence overriding concept not applicable for private
methods.
➢ Based on our requirement exactly same private method in child class. It is valid but not overriding.
In overriding the following modifiers won’t keep any restrictions: synchronized, native, Strictfp
While overriding we can’t reduce scope of access modifier but we can increase the scope.
Class P {
public void property () {
}}
class C extends P {
void property (){}
}
CE: property () in C cannot override property () in P; attempting to assign weaker access; was public
Public public
➔ If child class method throws any checked exception compulsory parent class method should throw the same
checked exception or its parent otherwise will get compile time error but there are no restrictions for unchecked
exceptions.
➔ If both parent and child class methods are static then we won’t get any CE. It’s seems overriding concept is applicable
but it is not overriding, it’s method hiding.
Class P {
}}
Class C extends P {
Method hiding:
P p =new P ();
C c = new C ();
P p1 = new C ();
p. m1 (); -> parent (because of static methods)
Class P {
Sop(“parent”);
}}
Class C extends P {
Sop(“child”);
P p =new P ();
C c = new C ();
P p1 = new C ();
Class P {
Int a= 888;
Class C extends P {
Int a=999;
P p =new P ();
p. x; -> 888
C c = new C ();
P p1 = new C ();
Encapsulation
(security)
Inheritance
(reusability)
Polymorphism OOPS (3 pillars
(flexibility) of oops)
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
➔ private, final and static members (methods and variables) use static binding while for virtual methods (In Java
methods are virtual by default) binding is done during run time based upon the run time object.
➔ The static binding uses Type information for binding while Dynamic binding uses Objects to resolve to bind.
➔ Overloaded methods are resolved (deciding which method to be called when there are multiple methods with the
same name) using static binding while overridden methods use dynamic binding, i.e, at run time.
static binding
When type of the object is determined at compiled time (by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic binding
Coupling
The degree of dependency b/w the component is called coupling.
Cohesion
For every component a clear well-defined functionality is defined then that component is said to be follow high cohesion.
1) Compile time checking 1: the type of ‘d’ and type of ‘H’ must have some relation. Either child to parent or parent
to child or same type, otherwise we will get compile time error saying in convertible types found d required H.
StringBuffer sb = (StringBuffer) o;
2) Compile time checking 2: ‘H’ must be either same or derived (child) type of A otherwise we will get compile time
error saying incompatible types found h required A.
3) Runtime object of ‘d’ must be either same or derived type of ‘H’ otherwise we will get runtime exception saying
ClasscastException.
Object o =new String (“test”);
StringBuffer sb = (StringBuffer) o;
4) Strictly speaking through type casting we are not creating any new object. For the existing object we are
providing another type of reference variable. i.e., we are performing type casting but not object casting.
Class Base {
Static { (2)
M1 (); (8)
Sop (“static”);(10)
M1 (); (13)
s.o.p (main);(15)
Static {(5)
O/P:
static
second block
20
main
Inside a static block if we are trying read a variable is called direct read.
If we are calling a method and with that method if we are trying to read a variable, that read operation is indirect read.
Class Base {
Static {
M1 ();
P static v m1 () {
Examples:
Class Test {
Static {
Sop(x);
Class Test {
Static {
Sop(x);
Constructors
➔ Constructors are used to initialize the object.
➔ Once we create an object compulsory we should perform initialization, then only the object is in a position to respond
properly.
➔ Whenever we are creating an object some piece of the code will be executed automatically to perform initialization
of the object, this piece of the code is nothing but Constructor. Hence the main purpose of constructor is to perform
initialization of the object.
String name;
int rollNo;
[Link] = name;
[Link] = rollNo;
➔ The main purpose of constructor is to perform initialization of an object. But other than initialization if we want to
perform any activity for every object creation then we should go for instance block(like updating one entry in the
database for every object creation or incrementing count value for every creation etc.);
Rules:
Default Constructor:
1) Compiler is responsible to generate default constructor but not JVM.
2) If we are not writing any constructor then only compiler will generate default constructor.
3) It is always no-arg constructor.
4) The access modifier of default constructor is exactly same as access modifier of class.(only public/default)
5) It contains only line (super ();). It’s a no arg call to super call constructor.
6) If are not writing anything(this or super) , then compiler will always place super();
7) Super () or this () must be 1st line. If not CE: call to super must be 1st statement in constructor.
8) Only super or this should be in constructor but not both.
9) We can use super () or this () only in constructor. If not CE: call to super/this must be 1st statement in
constructor.
These are constructor calls to call super call and These are keywords to refer super and current
current call constructor. class instant members.
We can use only in constructors as 1st line. We can use anywhere except static area
We can use only once in constructor. We can use any number of times.
Overloaded constructors:
➔ Only overloading is applicable to constructors.
➔ Every class in java including abstract class can contain constructor but interface cannot contain constructor.
➔ package [Link];
Student(){
this(10);
Student(int i){
this();
Singleton Class
➔ For any java class if we are allowed to create only one object such type of class is called singleton class.
Runtime r1 = [Link]();
We can create our own singleton classes, for this we have to use private constructor and private static variable and public
factory method.
Approach 1:
private Test() {
}
class Test {
private static Test t = null;
private Test() {
}
/**
*
*/
private static final long serialVersionUID = 1L;
private static Singleton singleton;
private Singleton() {
};
@Override
protected Object clone() throws CloneNotSupportedException {
return [Link]();
}
}
Beaking class:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("_________________________________________________");
// Reflection
Class<?> sampleClass = [Link]("[Link]");
Constructor<Singleton> constructor = (Constructor<Singleton>)
[Link]();
[Link](true);
[Link]("_________________________________________________");
// Serialization
ObjectOutputStream outputStream = new ObjectOutputStream(new
FileOutputStream("[Link]"));
[Link](originalSinglton);
[Link]();
[Link]("_________________________________________________");
// Cloneable
Singleton clonableSingleton = (Singleton) [Link]();
[Link]("Orignal Singleton class hashcode: " +
[Link]()); // 1865127310
[Link]("Cloneable Singleton class hashcode: " +
[Link]()); // 1908316405
[Link]("_________________________________________________");
Refelection: To overcome issue raised by reflection, enums are used because java ensures internally that enum value is
instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that
it is not flexible i.e it does not allow lazy initialization.
As enums don’t have any constructor so it is not possible for Reflection to utilize it. Enums have their by-default
constructor, we can’t invoke them by ourselves. JVM handles the creation and invocation of enum constructors internally.
Clone: To overcome this issue, override clone() method and throw an exception from clone method that is
CloneNotSupportedException.
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
Import:
1) Explicit class import -> import [Link]; -> recommended to use (improves readability)
2) Implicit class import -> import [Link].*;
➔ All classes and interfaces present in the following packages are by default available to every java program. Hence we
are not required to write import statement.
o Java. Lang
o Default package ( current working directory)
➔ Import statements is totally compile time related concept. If more number of imports then more will be the compile
time but there is no effect on execution time (Runtime).
➔ C language #include -> Static include -> on translation only it includes all the input output header files at beginning
only. But in the case java import statement no .class will be loaded at the beginning. It is LOAD ON DEMAND or fly.
➔ Explicit import -> current package -> implicit import
➔ current package -> Explicit import -> implicit import (static import)
Packages
➔ To resolve naming conflicts.
➔ Improves modularity of the application.
➔ It improves maintainability of the application.
➔ It provides security for our components.
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Abstract:
Strictfp:
➔ Introduced in 1.2v
➔ Only to classes and methods.
Final:
➔ For instance, variables we are not required to perform initialization explicitly. JVM will always provide default
values.
Static:
[Link]("String");
}
public static void main(int[] args) {
[Link]("int");
o/P: String
➔ Inheritance concept applicable to static methods including main method. Hence while executing child class if child
doesn’t contain main method then parent main method will be executed.
Native:
➔ The methods which are implemented in non-java (mostly c or c++) are called native methods or foreign methods.
Interfaces
Introduction:
Interface methods:
Interface variables:
public interface A {
public interface b {
@Override
//IMPLEMENTATION
➔ Two Interfaces with same name but different argument types. -> implementation for both methods.(overloaded)
public interface A {
public interface b {
@Override
//IMPLEMENTATION
}
@Override
//IMPLEMENTATION
➔ Two Interfaces with same signature but different return types. -> implementation is not possible
public interface A {
public interface b {
public interface A {
int x= 23;
public interface B {
int x= 233;
[Link](A.x);
[Link](B.x);
}
Marker interface:
➔ If an interface doesn’t contain any methods and by implementing that interface if objects get some ability.
Custom annotations
1. To create your own Java Annotation you must use @interface Annotation_name, this will create a new Java
Annotation for you.
2. The @interface will describe the new annotation type declaration.
3. After giving a name to your Annotation, you will need to create a block of statements inside which you may declare
some variables.
Marker Annotation:
@interface books_data
{
// No variable declared here
}
Single-value Annotation
@interface books_data
{
// Single variable declaration
String book_name();
}
Multi-value Annotations
@interface books_data
{
// Multiple variable declarations
String book_name();
int book_price();
String author();
}
Example:
// Class 1
class book_store {
}
// Class 2
class books {
Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is
because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-
safe iterators.
Arrays:
➔ Arrays are limited in size
➔ Homogeneous
➔ Underlying Data Structure is not available.
Collections:
➔ Grow able in nature
➔ Homogeneous and Heterogeneous
➔ Standard Data structure
Arrays Collections
With respect to memory not recommended to use With respect to memory recommended to use
With respect to Performance recommended to use With respect to Performance not recommended to
use
Collection:
If we want to represent a group of individual objects as a single entity, then we should go for Collection.
Collection Framework:
It defines several classes and interfaces which can be used to hold a group of objects as single entity.
List (I):
➔ It is child interface of collection.
➔ If we want to represent a group of individual objects as a single entity where duplicates are allowed and insertion
order preserved then we should go for List.
List (I)
Set (I):
➔ It is child interface of collection.
➔ If we want to represent a group of individual objects as a single entity where duplicates are not allowed and
insertion order is not preserved then we should go for Set.
➔ SortedSet: If we want to represent a group of individual objects as a single entity where duplicates are not allowed
and inserted A/c to some sorted order then we should go for SortedSet.
NavigableSet: It defines several methods for navigation purpose.
Set (I)
Hashset SortedSet(I)
TreeSet
Queue (I):
➔ If we want to represent a group of individual objects prior to processing, then we should go for Queue.
Queue (I)
PriorityQueue BlockingQueue
LinkedBlockingQueue
PriorityBlockingQueue
Note: If we want to represent a group of individual objects as key value pairs then we should go for Map interface.
Map (I):
➔ If we want to represent a group of individual objects as key value pairs then we should go for Map interface.
➔ Duplicates keys are not allowed.
SortedMap (I): If we want to represent a group of individual objects as key value pairs a/c to some sorting order of
keys then we should go for Map interface.
Map Dictionary (Ab)
TreeMap
➔ Enumeration
➔ Iterator
➔ ListIterator
Utility Classes:
✓ Collections
✓ Arrays
Methods:
Boolean isEmpty()
int size()
Object[] toArray ()
Iterator iterator ()
List (I):
✓ We can differentiate duplicates by using index.
ListIterator listIterator ()
ArrayList
✓ Underlying data structure is Resizable Array or grows able Array.
✓ Duplicates are allowed
✓ Insertion order is preserved.
✓ Heterogeneous object are allowed.
✓ Null insertion is possible.
Constructors:
ArrayList al =new ArrayList ();
ArrayList al =new ArrayList (int initial capacity); -> to provide the initial capacity on creation.
ArrayList al =new ArrayList (Collection c); -> to convert other collection object to ArrayList.
✓ Every collection object implements serializable and cloneable interfaces.
✓ ArrayList and vector implements RandomAccess (I). So for frequent retrieval operations ArrayList is the best choice.
ArrayList can use only Iterator to access. Vector list can use Iterator and Enumeration
elements.
LinkedList
➔ LinkedList is best suitable if frequent operation is insertion and deletion.
➔ Doubly linked list
➔ Duplicates are allowed
➔ Insertion order is preserved
➔ heterogonous objects are allowed
➔ null insertion is allowed
Methods:
void addFirst(object o)
void addLast(object o)
Object getFirst()
Object getLast()
Object removeFirst()
Object removeLast()
Constructers:
ArrayList LinkedList
Best choice if frequent operation is Retrieval Best choice if frequent operation is insertion and
deletion
Vector
✓ Resizable array
✓ Duplicates are allowed
✓ Insertion order will be preserved
✓ Null insertion is allowed
✓ heterogeneous objects are allowed
✓ Implements RandomAccess (I)
✓ Best when frequent operation is retrieval.
✓ Synchronized and thread safe.
Constructors:
Initial capacity = 10
Methods:
Cursors
✓ Enumeration
✓ Iterator
✓ ListIterator
Enumeration:
✓ unidirectional
✓ only read access
Methods:
hasMoreElements ();
nextElement ();
E.g.
[Link] ("A");
[Link] ("B");
[Link] ("C");
[Link] ("D");
Iterator:
✓ Unidirectional
✓ Universal cursor.
✓ Read and Remove access.
Methods:
for(int i=0;i<=10;i++)
[Link](i);
[Link](list);
while([Link]()){
Integer n = [Link]();
if(n % 2 ==0)
[Link](n);
else
[Link]();
[Link](list);
ListIterator:
✓ Bidirectional
✓ Read , remove , replace, addition of new objects
Methods:
for(int i=0;i<=10;i++)
[Link](i);
[Link](list);
while([Link]()){
Integer n = [Link]();
if(n==2)
[Link]();
else if(n==4 )
[Link](44);
else if(n==8)
[Link](45);
[Link](list);
Spliterator
trySplit(): Splits this spliterator into two and returns the new one.
Spliterator<String> s = [Link]();
Spliterator<String> s1 = [Link]();
[Link]([Link]::println);
[Link]("-- traversing the other half of the spliterator --- ");
[Link]([Link]::println);
Output:
Banana
Orange
-- traversing the other half of the spliterator ---
Apple
Is it legacy? Yes No No
HashSet
✓ Duplicates are not allowed.
[Link]("A");
[Link]("A");
[Link]("A");
[Link]("A");
[Link](hashSet);
O/P: [A] -> duplicates will not add into the set.
Constructers:
Whenever you insert an element into HashSet using add() method, it actually creates an entry in the internally backing
HashMap object with element you have specified as it’s key and constant called “PRESENT” as it’s value. This “PRESENT” is
defined in the HashSet class as below.
LinkedHashSet
✓ Child class of HashSet.
✓ Duplicates are not allowed and insertion order is preserved.
✓ Hashtable and LinkedList
✓ null is allowed
✓ heterogonous objects are allowed
✓ Cache based applications
[Link]("A");
[Link]("A");
[Link]("A");
[Link](null);
[Link](null);
[Link](hashSet);
TreeSet
✓ Balanced Tree
✓ Duplicates are not allowed.
✓ Insertion order is not preserved.
✓ Heterogeneous objects are not allowed otherwise RE: class cast exception.
✓ Null insertion is not possible (from 1.7V).
✓ All objects will be inserted based on some sorting order. It may be default order or customized sorting order.
Constructors:
[Link]("A");
[Link]("B");
[Link]("a");
[Link](set);
O/P: [A,B,a]
✓ For non-empty TreeSet, if we add null we will get null pointer exception.
✓ Only empty TreeSet will accept null. ( Upto 1.6V) and new versions null is not allowed.
[Link](new StringBuffer("A"));
[Link](new StringBuffer("Z"));
[Link](new StringBuffer("V"));
[Link](new StringBuffer("C"));
[Link](buffers);
RE:ClassCastException
Comparable (I)
It is present in java lang package and it contains only one method (compareTo()).
[Link](obj2):
0 -> equal
String a="A";
String b="B";
[Link]([Link](b));
[Link]([Link](a));
O/P: -1 1
Comparator (I)
It is present in java util package and it contains two methods (compare () and equals ()).
Public int compare (Object obj1 , Object obj2);
0 -> equal
[Link](100);
[Link](45);
[Link](74);
[Link](56);
[Link](0);
[Link](5);
[Link](buffers);
@Override
return 1;
else
return 0;
}
@Override
@Override
@Override
@Override
@Override
@Override
@Override
Map (I):
✓ Used to represent a group of objects as a key value pair.
Methods:
void putAll(Map m)
Object get(Key)
Object remove(key )
Boolean containsKey(k)
Boolean containsValue(value)
Boolean isEmpty()
Int size()
Void clear()
Collection values()
Set entrySet()
Entry (I):
A map is a group of key values pairs and each key value pair is called an Entry. Hence map is considered as a collection of
entry objects.
Without existing map object there is no chance of existing entry object hence entry interface is defined inside map
interface.
Methods:
Object getKey()
Object getValue()
Object setValue(Object o)
HashMap
✓ DS is hashtree
✓ Insertion based on hashcode
✓ Duplicate keys are not allowed and values are allowed.
✓ Null key is allowed once and null values are allowed any number of times.
✓ Best choice for Search operation.
✓ Null keys will store in the zero th index of the bucket internally.
✓ The default load factor is 75% of the capacity.
✓ Number of items in the Map crosses the threshold limit, the capacity of the Map is doubled
Constructors:
Initial capcity = 16
[Link]("A",100);
[Link]("B",200);
[Link]("C",300);
[Link]("D",400);
[Link](buffers);
[Link]([Link]("A",500));
[Link](buffers);
Set<String> s = [Link]();
Collection<Integer> c = [Link]();
[Link]("EntrySet: "+e);
[Link]("Entry Methods:");
while([Link]()){
[Link]([Link]());
[Link]([Link]());
O/P:
100
Entry Methods
500
200
300
D
400
Null is allowed for key and value Null is not allowed for key and value
The iterator in the HashMap is fail-safe (If you change The enumerator for the Hashtable is not fail-safe.
the map while iterating, you’ll know)
[Link]("A",100);
[Link]("B",200);
[Link]("C",300);
[Link]("D",400);
[Link](buffers);
[Link](m);
HashMap Internal Working
LinkedHashMap
✓ Child class of HashMap.
✓ DS is LinkedList and Hashtable
✓ Insertion order is preserved.
✓ 1.4V
✓ Used for developing cache based applications.
[Link]("A",100);
[Link]("C",200);
[Link]("B",300);
[Link]("D",400);
[Link](buffers);
IdentityHashMap
== -> Used to compare reference or objects
✓ It is exactly same as hashmap including methods and constructors expect the following difference.
✓ In the case of normal hashmap jvm will use .equals() methods to identify duplicate keys, which is meant for
content comparison.
✓ In the case of normal IdentityHashMap jvm will use == methods to identify duplicate keys, which is meant for
reference comparison.
[Link](i1, "A");
[Link](i2, "B");
[Link](i3, "A");
[Link](i4, "B");
WeakHashMap
It is exactly same as HashMap expect the following difference.
✓ In the HashMap even though doesn’t have any reference but it is not eligible for gc because it is associated with
HashMap.
✓ In the WeakHashMap even though doesn’t have any reference, it is eligible for gc because it is associated with
WeakHashMap.
[Link](dot, "A");
dot = null;
[Link]();
[Link](5000);
[Link](buffers); // -> {temp=A}
[Link](dot1, "A");
dot1 = null;
[Link](); //Finalize
[Link](5000);
[Link](buffers1); // -> {}
SortedMap (I)
✓ Inserted in some sorting order of keys.
TreeMap
✓ DS is RED – BLACK Tree
✓ Insertion based on some sorting of keys
✓ Duplicates keys are not allowed but values are allowed.
✓ Heterogonous keys are not allowed for default sorting order and allowed for Customized sorting order.
✓ Null is allowed with empty TreeMap (only once). Upto 1.6V
HashTable
✓ DS is hashtable
✓ Insertion order is based on hashcode of the keys.
✓ Duplicates keys are not allowed and values are allowed.
✓ Heterogonous objects are allowed
✓ Null is allowed.
✓ Synchronized
✓ Best choice for search.
Initial capacity = 11
Fill ratio = 0.75
Properties:
Enumeration propertyNames();
Queues
✓ FIFO
Methods:
poll() -> to remove and return head element, if empty returns null
remove() -> to remove and return head element, if empty RE: NoSuchElementException
PiriorityQueue
Init = 11
PriorityQueue q = new PriorityQueue(int initial);
BlockingQueue
The BlockingQueue interface in Java is added in Java 1.5 along with various other concurrent Utility classes
like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList, etc.
BlockingQueue interface supports flow control (in addition to queue) by introducing blocking if either BlockingQueue is
full or empty.
A thread trying to enqueue(add) an element in a full queue is blocked until some other thread makes space in the
queue, either by dequeuing(delete) one or more elements or clearing the queue completely.
Similarly, it blocks a thread trying to delete from an empty queue until some other threads insert an item.
Blocking Queue solves much of the problem of synchronization mechanism handled by wait() and notify() in producer-
consumer problem. The blockingQueue has methods take() and put which uses java. util. concurrent.
Unbounded Queue: The Capacity of the blocking queue will be set to Integer.MAX_VALUE. In the case of an unbounded
blocking queue, the queue will never block because it could grow to a very large size. when you add elements its size
grows.
Bounded Queue: The second type of queue is the bounded queue. In the case of a bounded queue you can create a
queue passing the capacity of the queue in queues constructor:
//Creates a Blocking Queue with capacity 5
✓ ArrayBlockingQueue class is a bounded blocking queue backed by an array. By bounded, it means that the size of the
Queue is fixed. Once created, the capacity cannot be changed.
✓ The LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. It means that the
LinkedBlockingQueue can be bounded, if its capacity is given, else the LinkedBlockingQueue will be unbounded.
import [Link].*;
import [Link].*;
class BlockingQueue<E> {
// constructor of BlockingQueue
public BlockingQueue(int limit) { [Link] = limit; }
return [Link](0);
}
[Link]("A");
[Link]("D");
[Link]("B");
[Link]("B");
[Link]("N");
[Link]("G");
[Link](list);//[A, D, B, B, N, G]
[Link](list);
[Link](list);//[A, B, B, D, G, N]
[Link]([Link](list, "D")); // 3
If-else:
boolean b = true;
if (b = false) {
[Link]("if");
} else {
if(true)
if(true) {
if(true)
if(true)
[Link]("if");
else
Switch:
switch (x) { //for x only byte, short, char and int are allowed up to 1.4V
// Byte, Short , Char, Integer and enum are allowed from 1.5v
case 1:
[Link]("1");break;
case 8:
[Link]("8");break;
[Link]
✓ Every class in java is child class of object.
private static native void registerNatives() -> Internally required for Object class
Default implementation of hashCode() is given in such a way that it returns the Hash Code number for the object based
on the address of the object.
By adding the final keyword to a class variable, we again helped the compiler to perform static code optimization. The
compiler will simply replace all references of final class variables with their actual values.
The final Class in Java provides security as they cannot be inherited by any other classes which means that the classes
that are extended may reveal private and protected information about potential users, but with the use of the final class,
it won't happen.
[Link]
✓ String object are immutable (non changeable) and Stringbuffer objects are mutable.
Why it is immutable:
1) String pool requires string to be immutable otherwise shared reference can be changed from anywhere.
2) Security (File System, Networking, passwords and userid)
[Link]("123");
[Link](s); //test
String s1 = [Link]("123");
[Link](s1); //test123
[Link]("123");
[Link](sb); //test123
[Link]([Link](sb1)); //false
String s = new String("test"); // object created in heap area(referred) and string Constant
pool
[Link](s1); //test789
[Link](s2); //test456
Constructors:
String s = new String();
Methods:
charAt(int index) -> returns the character locating at specified index.
[Link]([Link](5)); // 1
contact(String s)
String s = new String("test");
[Link]("123");
s = s+ "123";
s += "123";
equals(Object o)
equalsIgnoreCase(String s)
[Link]([Link]("Test")); //false
[Link]([Link]("Test")); //true
substring(int index)
[Link]([Link](2)); //st123
[Link]([Link](2,5)); //st1
length()
[Link]([Link]()); //8
[Link](s); //1223
toLowerCase()
toUpperCase()
[Link]([Link]()); //ABC
trim()
[Link](s); // ab c
[Link]([Link]()); //ab c //used to remove blank spaces present at begining and end
of the String
indexOf(char c)
lastIndexOf(char c)
repalce() vs replaceAll()
String s2 = [Link]();
String s4 = [Link]();
The mutable objects are objects whose value can be changed after initialization. We can change the object's values, such
as field and states, after the object is created. For example, [Link], StringBuilder, StringBuffer, etc.
The immutable objects are objects whose value can not be changed after initialization. We can not change anything once
the object is created. For example, primitive objects such as int, long, float, double, all legacy classes, Wrapper class, String
class, etc.
➔ All the wrapper classes like Boolean, Short, Integer, Long, Float, Double, Byte, Char, and String classes are
immutable classes.
Although [Link]() has some design issues but it is still a popular and easy way of copying objects. Following is a list
of advantages of using clone() method:
o You don't need to write lengthy and repetitive codes. Just use an abstract class with a 4- or 5-line long clone()
method.
o It is the easiest and most efficient way for copying objects, especially if we are applying it to an already developed
or an old project. Just define a parent class, implement Cloneable in it, provide the definition of the clone()
method and the task will be done.
o Clone() is the fastest way to copy array.
o To use the [Link]() method, we have to change a lot of syntaxes to our code, like implementing a Cloneable
interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling
[Link]() etc.
o We have to implement cloneable interface while it doesn't have any methods in it. We just have to use it to tell
the JVM that we can perform clone() on our object.
o [Link]() is protected, so we have to provide our own clone() and indirectly call [Link]() from it.
o [Link]() doesn't invoke any constructor so we don't have any control over object construction.
o If you want to write a clone method in a child class then all of its superclasses should define the clone() method in
them or inherit it from another parent class. Otherwise, the [Link]() chain will fail.
o [Link]() supports only shallow copying but we will need to override it if we need deep cloning.
String Buffer
✓ If contents are fixed then go for String.
✓ If contents are changing constantly then go for String buffer.
Methods:
length()
capacity()
charAt(int index)
[Link]([Link]()); // 4
[Link]([Link]()); //20
[Link]([Link](1)); //e
[Link](0, 'b');
[Link](sb); //best
append(String s)
[Link]("123"); //supports String, int, long, double, float, object, char, char[],
StringBuffer,boolean
[Link](sb); //test123
insert(int index,String s)
//supports String, int, long, double, float, object, char, char[], String Buffer,boolean
[Link](sb); //t243est
deleteCharAt(int index)
[Link](sb);//tet
[Link](2);
[Link](sb); //te
reverse()
[Link]();
[Link](sb); //tset
setLength(int index)
[Link](sb); // te
ensureCapacity()
trimToSize()
[Link]([Link]()); //20
[Link]([Link]()); //250
[Link]();
[Link]([Link]()); //4
substring(int index)
[Link]([Link](1)); //est
StringBuilder
✓ Every method present in String Buffer is Synchronized and hence only one thread is allowed to operate on String
buffer object at a time.
✓ StringBuilder is non synchronized and mutable. (1.5V)
Wrapper Classes
✓ To warp primitive into object form so that we can handle primitives also just like objects.
✓ To define several utility methods which are required for the primitives?
char
Byte byte1 = new Byte((byte) 1); // byte and String are allowed
Short short1 = new Short((short) 1);// byte, short and String are allowed
Character character = new Character('a'); // only char is allowed
Integer integer = new Integer(10);// byte, short, char, int and String are allowed
Long long1 = new Long(10l); // byte, short, char, int, long and String are allowed
Float float1 = new Float(10); // byte, short, char, int, long, float, double and String are
allowed
Double double1 = new Double(10d);// byte, short, char, int, long, float, double and String are
allowed
[Link]([Link](boolean2)); // true
Methods:
valueOf(primitive p / String i/ String I , radix r);
[Link]([Link]()); //10
charValue()
[Link]([Link]()); //c
booleanValue()
[Link]([Link]()); //true
String i = "12";
[Link]([Link](i)); //12
Autoboxing:
✓ Automatic conversion of primitive to Wrapper objects by compiler.
// int j = [Link](i);
static Integer i = 0;
static Integer j;
int m = i;
[Link](m); // 0
int n = j;
[Link](n); // [Link]
Integer i = 10;
Integer j = i;
i++;
[Link](i); //11
[Link](j); //10
[Link]("3");
[Link]("2");
[Link]("1");}
{ int i = 10;
m1(i); // 2 // primitives > autoboxing > var args
Clone():
public class Test implements Cloneable{
int i = 10;
int j = 11;
[Link]([Link]());
/* (non-Javadoc)
* @see [Link]#toString()
*/
@Override
String s2 = [Link]();
[Link](s2 == s1); // false because of intern s2 referred to SCP object not to heap
object
String s3 = s1;
String s4 = "test";
[Link](s2 == s4); //true
Exception Handling
Exception vs Error:
• Exceptions are the problems which can occur at runtime and compile time. It mainly occurs in the code written by the
developers. Exceptions are divided into two categories such as checked exceptions and unchecked exceptions.
• Errors are problems that mainly occur due to the lack of system resources. It cannot be caught or handled. It
indicates a serious problem. It occurs at run time. These are always unchecked. An example of errors
is OutOfMemoryError, LinkageError, AssertionError, etc. are the subclasses of the Error class.
✓ The exceptions checked by the compiler for the smooth execution of the program are called checked exceptions.
✓ Checked Exceptions must be handled by try catch or throws.
✓ The exceptions which are not checked by the compiler for the smooth execution of the program are called
unchecked exceptions.
✓ RuntimeExceptions (child classes) and Error (child classes) are unchecked Exceptions and others are Checked
Exceptions
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It means we can't use
try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use
catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is
handled or not.
1. Definition final is the keyword and finally is the block in Java finalize is the method in Java
access modifier which is Exception Handling to which is used to perform
used to apply restrictions on execute the important code clean up processing just
a class, method or variable. whether the exception before object is garbage
occurs or not. collected.
2. Applicable Final keyword is used with Finally block is always related finalize() method is used with
to the classes, methods and to the try and catch block in the objects.
variables. exception handling.
3. Functionality (1) Once declared, final (1) finally block runs the finalize method performs the
variable becomes constant important code even if cleaning activities with
and cannot be modified. exception occurs or not. respect to the object before
(2) final method cannot be (2) finally block cleans up all its destruction.
overridden by sub class. the resources used in try
(3) final class cannot be block
inherited.
4. Execution Final method is executed Finally block is executed as finalize method is executed
only when we call it. soon as the try-catch block is just before the object is
executed. destroyed.
[Link]
✓ File
✓ FileWriter
✓ FileReader
✓ BufferedWriter
✓ BufferedReader
✓ PrintWriter
File:
File f = new File("[Link]"); //It won't create a file, just it will check file is available
or not
if(![Link]()){
try {
} catch (IOException e) {
[Link]([Link]()); //false
[Link]([Link]()); //true
Constructors:
File f = new File(String file/directory); // to create file/directory in the current directory
File f = new File(String directory, String file/directory); //to create file/directory in other
directory
File f = new File(File directory, String file/directory); //to create file/directory in other
directory referred by the file object
Methods:
[Link](); // Used to check the it is file or not (true if it file else false)
[Link](); // Used to check the it is directory or not (true if it directory else false)
FileWriter:
✓ FileWriter will create a new file and writes data into it if file is not exist.
FileWriter fw = new FileWriter(File f,true); // to append the data to already existing data in
the file
Methods:
flush or close is mandatory to write the data to the physically into the file.
FileWriter requires line separators (\n,\t..) to format the data in the file.
while (i != -1) {
[Link]((char) i);
i = [Link]();
[Link]();
[Link](ch);
/*for(char c: ch)
[Link](ch);
}*/
[Link]();
BufferedWriter:
BufferedWriter bw = new BufferedWriter(Writer w);
[Link]("test");
[Link]('c');
[Link]();
[Link]();
BufferedReader: (BEST Reader)
FileReader fileReader = new FileReader("[Link]");
String s = [Link]();
while(s != null){
[Link](s);
s=[Link]();
[Link]();
[Link]("test");
[Link]("dgdfjghjfkh");
[Link]();
[Link]();
String s = [Link]();
while(s != null){
[Link](s);
s = [Link]();
s = [Link]();
while(s != null){
[Link](s);
s = [Link]();
[Link]();
[Link]();
Generics
✓ Need of generic is to provide type safety and to resolve the type casting problems.
public class Test<Dot extends Number & Runnable & Comparable<String>> { //class & interface
only
public void m1(ArrayList<String> arrayList){ // We can call this method by passing any
String of ArrayList
public void m1(ArrayList<?> arrayList){ // We can call this method by passing any type
of ArrayList
public void m1(ArrayList<? extends Number> arrayList){ // We can call this method by
passing Number or child of Number type of ArrayList
public void m1(ArrayList<? super Number> arrayList){ // We can call this method by
passing Number or its super classes type of ArrayList
ArrayList<String> l = new ArrayList<String>(); //Generic code //We can add only Strings
[Link]("test");
[Link]("gh");
[Link](10);
[Link](10.5);
}
Upper bounds and lower bounds are used to restrict the range of types that can be used with a type parameter.
An upper bound restricts the type parameter to a specific type or any of its subtypes, while a lower bound restricts the
type parameter to a specific type or any of its supertypes.
// Upper bound - We can call this method by passing Number or child of Number type of ArrayList
// We can call this method by passing Number or its super classes type of ArrayList
Generics concept is introduced in Java language to provide tighter type checks at compile time and to support generic
programming. The way to implement generics, the Java compiler applies type erasure to:
o Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded.
The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.
o Insert type casts if necessary to preserve type safety.
o Generate bridge methods to preserve polymorphism in extended generic types.
Multi-Threading
Introduction:
Main use of multi-tasking is to improve performance by decrease the response time of the system.
@Override
public void run(){ // Code under run() is called Job of the Thread
for(int i=0;i<10;i++)
for(int i=0;i<10;i++)
@Override
public void run(){ //Recommended to override run() because [Link]() doesn’t have any
implementation
//Overloaded of run() is possible but start() will call only not args run method only
(run())
@Override
public void start(){ //if we override start() new thread will not create and start() is
executed as normal method
[Link]("start method");
@Override
[Link]("run method");
}
public class ThreadDemo {
[Link]();
@Override
[Link]("Run method");
[Link]("Main Thread");
}
Thread class Constructors:
[Link]([Link]()); //Thread-0
[Link]([Link]().getName()); //MyMainThread
Thread Priorities:
Valid range of thread priorities is 1 -10
[Link](Thread.MIN_PRIORITY); //1
[Link](Thread.NORM_PRIORITY); //5
[Link](Thread.MAX_PRIORITY); //10
[Link](); //5
[Link]("main"+[Link]().getPriority()); //5
[Link]("main"+[Link]().getPriority()); //10
Default priority for main thread is 5 and for others it is inherited from parent thread.
Yield(): This method cause’s pause to the current executing thread to give the chance for waiting threads of same
priority. If there is no waiting thread or all waiting threads have low priority then same thread can continue its execution.
Join(): If a thread wants to wait until completing some other thread then we should go for join().
If a thread t1 wants to wait until completing t2 then t1 has to call join() on t2.
Synchronization:
Synchronization is a process of controlling the access of shared resources (like instance variables, static variables etc) by
the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized
multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of
using or updating the object's value. Synchronization prevents such type of data corruption.
Synchronized -> is applicable to only methods/blocks.
If a method/block is declared as synchronized, then at a time only one thread is allowed to execute that method or
block on the given object.
What is the difference when the synchronized keyword is applied to a static method or to a non static method?
When a synch non static method is called a lock is obtained on the object. When a synch static method is called a lock is
obtained on the class, not on the object.
The lock on the object and the lock on the class don’t interfere with each other.
It means, if a thread is accessing a synch non static method, then the other thread can access the synch static method but
can’t access the synch non static method.
Method is only declared as synchronized -> thread will assign with object level locks.
Method is only declared as static synchronized -> thread will assign with class level locks.
synchronized (Object o) {
}
synchronized ([Link]) {
}
Two threads can communicate with each other by wait(), notify() and notifyAll() methods.
The thread which is excepting updation is responsible to call wait method immediately the thread enter into waiting state.
The thread which is responsible to perform updation , after performing updation it is responsible to call notify() then
waiting thread will get that notification and continue its execution with those updated items.
• wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or
notifAll() method is called for the same object. wait() is a method of Object class.
• sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release
the lock. sleep() is a method of Object class.
• notify( ) wakes up the first thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest priority thread will run first
Deadlock
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and
second thread is waiting for an object lock that is acquired by first thread.
Since, both threads are waiting for each other to release the lock, the condition is called deadlock.
Synchronized keyword is the only reason for deadlock situation hence while using synchronized keyword we have to take
special care.
Using [Link]() Method: We can get a deadlock if two threads are waiting for each other to finish indefinitely using
thread join. Then our thread has to wait for another thread to finish, it is always best to use [Link]() method with the
maximum time you want to wait for the thread to finish.
Use Lock Ordering: We have to always assign a numeric value to each lock and before acquiring the lock with a higher
numeric value we have to acquire the locks with a lower numeric value.
Avoiding unnecessary Locks: We should use locks only for those members on which it is required, unnecessary use of
locks leads to a deadlock situation. And it is recommended to use a lock-free data structure and If it is possible to keep
your code free from locks. For example, instead of using synchronized ArrayList use the ConcurrentLinkedQueue.
Executor:
For example, rather than invoking new Thread(new RunnableTask()).start() for each task of a set of tasks, you might use:
In the above sample code runnableTask is a task created using lambda implementation of the run() method of
the Runnable interface.
Runnable runnableTask = () -> {
try {
[Link]("Run method called.");
[Link](2000);
} catch (InterruptedException e) {
[Link]();
}
};
The Executor interface is part of [Link] package and was introduced in java 1.5.
Executor Service
An ExecutorService provides methods to manage termination and methods that can produce a Future for tracking the
progress of one or more asynchronous tasks.
When an ExecutorService is terminated then it has no tasks actively executing, no tasks waiting for execution, and no new
tasks can be submitted.
✓ Java executor framework ([Link]), released with the JDK 5 is used to run the Runnable objects
without creating new threads every time and mostly re-using the already created threads.
✓ The [Link] provide factory methods that are being used to create ThreadPools of worker
threads.
✓ Thread pools overcome this issue by keeping the threads alive and reusing the threads. Any excess tasks flowing in,
that the threads in the pool can’t handle are held in a Queue.
✓ Once any of the threads get free, they pick up the next task from this queue.
✓ This task queue is essentially unbounded for the out-of-box executors provided by the JDK.
1. submit(): this method accepts a runnable or callable task and returns a Future that can be used to wait for completion
and/or to cancel execution.
2. invokeAny(): this method accepts a collection of callable tasks and returns a result if any tasks are successful.
3. invokeAll(): this method accepts a collection of callable tasks and returns a List of Future, which will hold the result
returned by each task when the asynchronous tasks are completed.
What is ThreadPoolExecutor?
The ThreadPoolExecutor is an implementation of ExecutorService and provides a pool of threads that executes the
runnable or callable tasks.
There is also an Executors class that has a set of factory methods to create different types of thread pools.
ExecutorService executorService = new ThreadPoolExecutor(1, 5, 0L,
[Link],
new LinkedBlockingQueue<Runnable>());
corePoolSize — the number of threads to keep in the pool, even if they are idle unless allowCoreThreadTimeOut is set.
keepAliveTime — when the number of threads is greater than the core, this is the maximum time that excess idle threads
will wait for new tasks before terminating.
workQueue — the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks
submitted by the execute.
But the above code can be replaced by a factory method of the Executors class:
1. SingleThreadExecutor
2. FixedThreadPool(n)+
3. CachedThreadPool
4. ScheduledExecutor
Executor 1: SingleThreadExecutor
A thread pool of single thread can be obtained by calling the static newSingleThreadExecutor() method of the Executors
class. It is used to execute tasks sequentially.
Syntax:
Syntax:
Executor 3: CachedThreadPool
Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are
available.
Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will
be created and added to the pool. It uses a SynchronousQueue queue.
Scheduled executors are based on the interface ScheduledExecutorService which extends the ExecutorService interface.
This executor is used when we have a task that needs to be run at regular intervals or if we wish to delay a certain task.
scheduleAtFixedRate: Executes the task with a fixed interval, irrespective of when the previous task ended.
scheduleWithFixedDelay: This will start the delay countdown only after the current task completes.
Syntax:
[Link]
(Runnable command, long initialDelay, long period, TimeUnit unit)
Future Object:
✓ A Future is the result of asynchronous tasks that may be completed in the future.
✓ Future also provides methods to check if the computation is complete, to wait for its completion, and to retrieve the
result of the computation(example get() method).
✓ The future object returned by the executor.
✓ Future can be thought of as a promise made to the caller by the executor.
✓ The future interface is mainly used to get the results of Callable results. whenever the task execution is completed, it
is set in this Future object by the executor.
Syntax:
Serialization in java is a mechanism of writing the state of an object into a byte stream.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
Object graph:
int i = 10;
}
}
}
Customized Serialization:
➔ Jvm will check for writeObject() and readObject() methods present in Serializing object.
➔ If available JVM will execute that
class Cat{
int k =10;
}
}
}
class Animal{
int i =10;
}
}
}
How to restrict child class in serialization
There is no direct way to prevent sub-class from serialization in java. One possible way by which a programmer can
achieve this is by implementing the writeObject() and readObject() methods in the subclass and needs to throw
NotSerializableException from these methods.
Externalization:
➔ Externalization in Java is used to customize the serialization mechanism.
➔ If we want to save some part of the object.
@Override
public void writeExternal(ObjectOutput out) throws IOException {
[Link](s);
[Link](i);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
s = (String) [Link]();
i = [Link]();
//j = [Link](); //[Link]
}
}
}
}
serialVersionUID:
Grabage Collector
When an object doesn’t have any reference then it is eligible for GC.
static Student s1 ;
public static void main(String[] args) {
m1(); -> only 1 object (s2) is eligible for GC.
}
4. Island of isolation: Basically, an island of isolation is a group of objects that reference each other but are not
referenced by any active object in the application. Strictly speaking, even a single unreferenced object is an island
of isolation too.
Scenario one:
O/P: End of main -> GC will call String class finalize method and will not call Test class finalize method
or
Scenario 3:
➔ If execption occurred in finalize() method called by programmer, then it will stop execution.
➔ If exeception occurred in finalize() method called by GC, then JVM will ignore that exception.
Scenario 4:
➔ GC calls finalize() method only once for a particular object even though that object is eligible for garbage
collections multiple times.
Scenario 5:
➔ Most GCs follow mark and swep alogorithm.
Memory leaks: If objects which are not used in the program and not eligible for GC then those objects give memort
leak.
Java 8
Java 8 Lambda Expressions
Functional Interface:
• Lambda expression provides an implementation of the Java 8 Functional Interface. An interface which has
only one abstract method is called a functional interface.
• Java provides an annotation @FunctionalInterface, which is used to declare an interface as a functional
interface.
• It can have any number of default, static methods but can contain only one abstract method. It can also
declare methods of the object class.
• If you have used Runnable, Callable, Comparator, FileFilter, PathMatcher, EventHandler interfaces in your
projects then you can replace its implementation with Lambda Expression.
Note: Default methods of a functional interface cannot be accessed from within lambda expressions.
Java 8 Predefined-Functional Interfaces
Supplier:
Code:
Person p = [Link]();
[Link]("Person Detail:\n" + [Link]() + ", " + [Link]());
Consumer:
Predicate:
1. We need a function for checking a condition. A Predicate is one such function accepting a single argument to
evaluate to a boolean result.
2. It has a single method test that returns the boolean value.
Code:
BiFunction:
BiConsumer:
It represents an operation that accepts two input arguments and returns no result.
Method References
Java provides a new feature called method reference in Java 8.
Each time when you are using a lambda expression to just referring a method, you can replace your lambda
expression with method reference.
Optional Class
Java introduced a new class Optional in JDK 8.
It is a public final class and used to deal with NullPointerException in Java application.
It provides methods that are used to check the presence of a value for the particular variable.
The purpose of the class is to provide a type-level solution for representing optional values instead of using null
references.
Empty() , Of(), ofNullable(), isPresent(), empty(), ifPresent(), orElse(), orElseGet(), orElseThrow(), get()
Stream API
• Stream does not store elements. It simply conveys elements from a source such as a data structure, an array,
or an I/O channel, through a pipeline of computational operations.
• Stream is functional in nature. Operations performed on a stream does not modify its source. For example,
filtering a Stream obtained from a collection produces a new Stream without the filtered elements, rather
than removing elements from the source collection.
• Stream is lazy and evaluates code only when required.
• The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream
must be generated to revisit the same elements of the source.
•
The empty() method should be used in case of the creation of an empty stream:
[Link]()
.filter((product) -> [Link]() > 25000f)
//.collect([Link]())
.forEach([Link]::println);
DoubleSummaryStatistics totalPrice3 =
[Link]().collect([Link](Product::getPrice));
[Link](totalPrice3);
The groupingBy operation returns a map whose keys are the values that result from applying the
lambda expression specified as its parameter (which is called a classification function).
[Link](Product::getPrice, [Link]())));
O/P:
HP Laptop:[25000.0]
Apple Laptop:[90000.0, 90001.0]
Dell Laptop:[30000.0]
Sony Laptop:[28000.0, 287600.0]
Lenevo Laptop:[28000.0]
Reduce:
The map operation allows us to apply a function, that takes in a parameter of one type, and returns something else.
Filter is used for filtering the data, it always returns the boolean value. If it returns true, the item is added to list else it is
filtered out.
reduce is a "fold" operation, it applies a binary operator to each element in the stream where the first argument to the
operator is the return value of the previous operation and the second argument is the current stream element.
collect is an aggregation operation where a "collection" is created, and each element is "added" to that collection.
Collections in different parts of the stream are then added together.
GroupingBy:
ListSorting:
List<Laptop> list = new ArrayList<>();
[Link](new Laptop("lenovo", 45000, 16));
[Link](new Laptop("dell", 56000, 12));
[Link](new Laptop("hp", 25000, 4));
[Link](new Laptop("asus", 49000, 12));
[Link]().sorted([Link](Laptop::getBrand)).forEach(t ->
[Link](t));
Output:
Laptop [brand=asus, price=49000, ram=12]
Laptop [brand=dell, price=56000, ram=12]
Laptop [brand=hp, price=25000, ram=4]
Laptop [brand=lenovo, price=45000, ram=16]
MapSorting:
Map<Laptop, Integer> map = new HashMap<>();
[Link](new Laptop("lenovo", 45000, 16), 123);
[Link](new Laptop("dell", 56000, 12), 345);
[Link](new Laptop("hp", 25000, 4), 456);
[Link](new Laptop("asus", 49000, 12), 567);
map
.entrySet()
.stream()
.sorted([Link]([Link](Laptop::getPrice)))
.forEach(e -> [Link](e));
Output:
Laptop [brand=hp, price=25000, ram=4]=456
Laptop [brand=lenovo, price=45000, ram=16]=123
Laptop [brand=asus, price=49000, ram=12]=567
Laptop [brand=dell, price=56000, ram=12]=345
Map vs FlatMap:
[Link], as it can be guessed by its name, is the combination of a map and a flat operation. That means that
you first apply a function to your elements, and then flatten it.
[Link] only applies a function to the stream without flattening the stream.
To understand what flattening a stream consists in, consider a structure like [ [1,2,3],[4,5,6],[7,8,9] ] which has "two
levels". Flattening this means transforming it in a "one level" structure : [ 1,2,3,4,5,6,7,8,9 ].
Stream vs ParallelStream
Sequential Stream Parallel Stream
Runs on a single-core of the computer Utilize the multiple cores of the computer.
Only a single iteration at a time just like the for- Operates multiple iterations simultaneously in different
loop. available cores.
Employee Stream
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
// Query 1 : How many male and female employees are there in the organization?
method1();
[Link]("\n");
// Query 2 : Print the name of all departments in the organization?
method2();
[Link]("\n");
// Query 3 : What is the average age of male and female employees?
method3();
[Link]("\n");
// Query 4 : Get the details of highest paid employee in the organization?
method4();
[Link]("\n");
// Query 5 : Get the names of all employees who have joined after 2015?
method5();
[Link]("\n");
// Query 6 : Count the number of employees in each department?
method6();
[Link]("\n");
// Query 7 : What is the average salary of each department?
method7();
[Link]("\n");
// Query 8 : Get the details of youngest male employee in the product
// development department?
method8();
[Link]("\n");
// Query 9 : Who has the most working experience in the organization?
method9();
[Link]("\n");
// Query 10 : How many male and female employees are there in the sales and
// marketing team?
method10();
[Link]("\n");
// Query 11 : What is the average salary of male and female employees?
method11();
[Link]("\n");
// Query 12 : List down the names of all employees in each department?
method12();
[Link]("\n");
// Query 13 : What is the average salary and total salary of the whole
// organization?
method13();
[Link]("\n");
// Query 14 : Separate the employees who are younger or equal to 25 years from
// those employees who are older than 25 years.
method14();
[Link]("\n");
// Query 15 : Who is the oldest employee in the organization? What is his age
// and which department he belongs to?
method15();
}
public static void method1() {
[Link]("Query 1 : How many male and female employees are there in the
organization?");
Map<String, Long> noOfMaleAndFemaleEmployees = [Link]()
.collect([Link](Employee::getGender, [Link]()));
[Link](noOfMaleAndFemaleEmployees);
}
.collect([Link]([Link](Employee::getSalary)));
[Link]([Link]().getName());
}
[Link]().collect([Link](Employee::getDepartment,
[Link](Employee::getSalary)));
Employee youngestMaleEmployeeInProductDevelopment =
[Link]();
[Link]("----------------------------------------------");
[Link]("ID :
"+[Link]());
[Link]("Name :
"+[Link]());
[Link]("----------------------------");
[Link]("ID : "+[Link]());
[Link]("Name : "+[Link]());
}
[Link](countMaleFemaleEmployeesInSalesMarketing);
}
[Link](avgSalaryOfMaleAndFemaleEmployees);
}
[Link]().collect([Link](Employee::getDepartment));
[Link]("--------------------------------------");
[Link]().collect([Link](Employee::getSalary));
if ([Link]())
{
[Link]("Employees older than 25 years :");
}
else
{
[Link]("Employees younger than or equal to 25 years :");
}
[Link]("----------------------------");
[Link]("Name : "+[Link]());
[Link]("Age : "+[Link]());
[Link]("Department : "+[Link]());
}
class Employee {
int id;
String name;
int age;
String gender;
String department;
int yearOfJoining;
double salary;
public Employee(int id, String name, int age, String gender, String department, int yearOfJoining, double salary)
{
[Link] = id;
[Link] = name;
[Link] = age;
[Link] = gender;
[Link] = department;
[Link] = yearOfJoining;
[Link] = salary;
}
@Override
public String toString() {
return "Id : " + id + ", Name : " + name + ", age : " + age + ", Gender : " + gender + ", Department : "
+ department + ", Year Of Joining : " + yearOfJoining + ", Salary : " + salary;
}
}
Web Services
Web service is a technology to communicate one programming language with another.
Webservice
REST:
• REST API
• Implementation with JAX-RS
2) SOAP stands for Simple Object REST stands for REpresentational State Transfer.
Access Protocol.
3) SOAP can't use REST because it REST can use SOAP web services because it is a
is a protocol. concept and can use any protocol like HTTP, SOAP.
4) SOAP uses services interfaces REST uses URI to expose business logic.
to expose the business logic.
5) JAX-WS is the java API for SOAP JAX-RS is the java API for RESTful web services.
web services.
6) SOAP defines standards to be REST does not define too much standards like SOAP.
strictly followed.
7) SOAP requires more REST requires less bandwidth and resource than
bandwidth and resource than SOAP.
REST.
8) SOAP defines its own security. RESTful web services inherits security
measures from the underlying transport.
9) SOAP permits XML data format REST permits different data format such as Plain
only. text, HTML, XML, JSON etc.
10) SOAP is less preferred than REST more preferred than SOAP.
REST.
Methods:
Status code:
Format:
Text/xml
Application/json
HTTP PUT:
PUT puts a file or resource at a specific URI, and exactly at that URI.
If there's already a file or resource at that URI, PUT replaces that file or resource.
HTTP POST:
POST sends data to a specific URI and expects the resource at that URI to handle the request.
The web server at this point can determine what to do with the data in the context of the specified resource.
The POST method is not idempotent; however, POST responses are cacheable so long as the server sets the appropriate
Cache-Control and Expires headers.
Stateless: A stateless application does not maintain a connection or store information between requests from the same
client. A client makes a request, the API performs the action defined in the request, and responds. Once the API responds,
it drops the connection and doesn’t maintain any information about the client in active memory. The API treats each
request as the first request.
Cacheable: A REST API should allow caching of frequently requested data. To reduce bandwidth, latency, and server load,
an API should identify cacheable resources, who can cache them, and for how long they can remain in the cache.
Uniform interface: The defined way a client interacts with the server independent of the device or application.
Resource-Based: The API needs to have a specific URI (uniform resource identifier) for each resource, such as
/monitor/{monitorGuid} from Uptrends API version 4.
Self-describing: Includes metadata such as Content-Type that describes how to process the response.
HATEOAS (hypermedia as the engine of application state): The server response includes the URI for additional methods
the client can access using the response data.
Layered system: An API may have multiple layers such as proxy servers or load balancers, and the endpoint server may
deploy additional servers to formulate a response. The client is unaware of which server responds to the request. A
layered system makes an API more scalable.
Code on demand: Optionally, the API may send executable code such as Java applets or JavaScript.
Spring Boot
RoadMap
Spring Boot is basically an extension of the Spring framework which eliminated the boilerplate configurations
required for setting up a Spring application.
The main goal of Spring Boot is to quickly create Spring-based applications without requiring developers
to write the same boilerplate configuration again and again.
Advantages of Spring Boot
➢ The main goal of Spring Boot Framework is to reduce Development, Unit Test and Integration Test time and to ease
the development of Production ready web applications very easily compared to existing Spring Framework.
@EnableWebMvc
✓ Enables default Spring MVC configuration and registers Spring MVC infrastructure components expected by
the DispatcherServlet. Use this annotation on an @Configuration class. In turn that will
import DelegatingWebMvcConfiguration, which provides default Spring MVC configuration.
@Configuration
@EnableWebMvc
@ComponentScan(
basePackageClasses = { [Link] },
excludeFilters = { @Filter(type = [Link], value = [Link]) }
)
public class MyConfiguration {
@EnableWebMvc annotation does some useful things; specifically, in the case of REST, it detects the existence of Jackson
and JAXB 2 on the classpath, and automatically creates and registers default JSON and XML converters. The functionality
of the annotation is equivalent to the XML version <mvc:annotation-driven />.
If we’re using the @SpringBootApplication annotation, and the spring-webmvc library is on the classpath, then
the @EnableWebMvc annotation is added automatically with a default autoconfiguration.
Spring Boot Starters are dependency descript1ors that can be added under the <dependencies> section in [Link].
Spring Boot offers many starter modules to get started quickly with many of the commonly used technologies, like
SpringMVC, JPA, MongoDB, Spring Batch, SpringSecurity, Solr, ElasticSearch, etc. These starters are pre-configured with
the most commonly used library dependencies so you don’t have to search for the compatible library versions and
configure them manually.
For example, the spring-boot-starter-data-jpa starter module includes all the dependencies required to use Spring Data
JPA, along with Hibernate library dependencies, as Hibernate is the most commonly used JPA implementation.
One more example, when we add the spring-boot-starter-web dependency, it will by default pull all the commonly used
libraries while developing Spring MVC applications, such as spring-webmvc, jackson-json, validation-api, and tomcat.
Not only does the spring-boot-starter-web add all these libraries but it also configures the commonly registered beans
like DispatcherServlet, ResourceHandlers, MessageSource, etc. with sensible defaults.
Spring Boot addresses the problem that Spring applications need complex configuration by eliminating the need to
manually set up the boilerplate configuration.
Spring Boot takes an opinionated view of the application and configures various components automatically, by registering
beans based on various criteria. The criteria can be:
For example, if you have the spring-webmvc dependency in your classpath, Spring Boot assumes you are trying to build a
SpringMVC-based web application and automatically tries to register DispatcherServlet if it is not already registered. If you
have any embedded database drivers in the classpath, such as H2 or HSQL, and if you haven’t configured
a DataSource bean explicitly, then Spring Boot will automatically register a DataSource bean using in-memory database
settings.
Spring supports externalizing configurable properties using the @PropertySource configuration. Spring Boot takes it even
further by using the sensible defaults and powerful type-safe property binding to bean properties. Spring Boot supports
having separate configuration files for different profiles without requiring many configurations.
Being able to get the various details of an application running in production is crucial to many applications. The Spring
Boot actuator provides a wide variety of such production-ready features without requiring developers to write much code.
Some of the Spring actuator features are:
Traditionally, while building web applications, you need to create WAR type modules and then deploy them on external
servers like Tomcat, WildFly, etc. But by using Spring Boot, you can create a JAR type module and embed the servlet
container in the application very easily so that the application will be a self-contained deployment unit.
Also, during development, you can easily run the Spring Boot JAR type module as a Java application from the IDE or from
the command-line using a build tool like Maven or Gradle.
@SpringBootApplication annotation indicates a configuration class that declares one or more @Bean methods and also
triggers auto-configuration and component scanning.
@ComponentScan
This annotation enables component-scanning so that the web controller classes and other components you create will be
automatically discovered and registered as beans in Spring's Application Context. All the@Controller classes you write are
discovered by this annotation.
@EnableAutoConfiguration
This annotation enables the magical auto-configuration feature of Spring Boot, which can automatically configure a lot of
stuff for you.
@Autowired
Spring provides annotation-based auto-wiring by providing @Autowired annotation. It is used to autowire spring bean on
setter methods, instance variable, and constructor. When we use @Autowired annotation, the spring container auto-
wires the bean by matching data-type.
@Required
The @Required annotation applies to bean property setter methods.
@Qualifier
The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean
will be wired.
@Bean: It is a method-level annotation. It is an alternative of XML <bean> tag. It tells the method to produce a bean to be
managed by Spring Container.
@Component: It is a class-level annotation. It is used to mark a Java class as a bean. A Java class annotated
with @Component is found during the classpath. The Spring Framework pick it up and configure it in the application
context as a Spring Bean.
@Controller: The @Controller is a class-level annotation. It is a specialization of @Component. It marks a class as a web
request handler. It is often used to serve web pages. By default, it returns a string that indicates which route to redirect. It
is mostly used with @RequestMapping annotation.
@Service: It is also used at class level. It tells the Spring that class contains the business logic.
@Repository: It is a class-level annotation. The repository is a DAOs (Data Access Object) that access the database
directly. The repository does all the operations related to the database.
@RequestMapping: It is used to map the web requests. It has many optional elements like consumes, header, method,
name, params, path, produces, and value. We use it with the class as well as the method.
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a web service endpoint
that fetches It is used instead of using: @RequestMapping(method = [Link])
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create a web service
endpoint that creates It is used instead of using: @RequestMapping(method = [Link])
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a web service endpoint
that creates or updates It is used instead of using: @RequestMapping(method = [Link])
@DeleteMapping: It maps the HTTP DELETE requests on the specific handler method. It is used to create a web service
endpoint that deletes a resource. It is used instead of using: @RequestMapping(method = [Link])
@PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It is used instead of
using: @RequestMapping(method = [Link])
@RequestBody: It is used to bind HTTP request with an object in a method parameter. Internally it uses HTTP
MessageConverters to convert the body of the request. When we annotate a method parameter with @RequestBody, the
Spring framework binds the incoming HTTP request body to that parameter.
@ResponseBody: It binds the method return value to the response body. It tells the Spring Boot Framework to serialize a
return an object into JSON and XML format.
@PathVariable: It is used to extract the values from the URI. It is most suitable for the RESTful web service, where the URL
contains a path variable. We can define multiple @PathVariable in a method.
@RequestParam: It is used to extract the query parameters form the URL. It is also known as a query parameter. It is most
suitable for web applications. It can specify default values if the query parameter is not present in the URL.
@RequestHeader: It is used to get the details about the HTTP request headers. We use this annotation as a method
parameter. The optional elements of the annotation are name, required, value, defaultValue. For each detail in the
header, we should specify separate annotations. We can use it multiple time in a method
@RequestAttribute: It binds a method parameter to request attribute. It provides convenient access to the request
attributes from a controller method. With the help of @RequestAttribute annotation, we can access objects that are
populated on the server-side.
@GetMapping and @PostMapping are specific HTTP method annotations that require more requests. However, using
@RequestMapping will be more helpful as you manage multiple HTTP methods for the same URL.
As there are numerous annotations, it is essential to use SpringBoot annotations that are required and necessary. Because
overusing annotations will make your code harder to read and more challenging to maintain.
For efficient applications using Spring, utilizing the @ConditionalOnProperty will enable or disable configurations based on
the property’s value. It will make your work manageable and configure your applications based on external factors.
4. Integrate Tests With ComponentScan
Using @ComponentScan in integration tests leverages powerful annotations. Also, it ensures that your test is running
accurately based on the behavior of your application and reflects the potential issues that may appear during the run.
The @ControllerAdvice allows you to define global expectation handles that will be implemented to all controllers in the
Spring applications. It helps to resolve this by providing precise and consistent messages to the Spring Boot applications.
Exception Handler
The @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the
client.
@ControllerAdvice
public class ProductExceptionController {
@ExceptionHandler(value = [Link])
public ResponseEntity<Object> exception(ProductNotfoundException exception) {
return new ResponseEntity<>("Product not found", HttpStatus.NOT_FOUND);
}
}
Transactions
Transaction Propagation:
They enable you to control the handling of existing and creation of new transactions. You can choose between:
➔ REQUIRED to tell Spring to either join an active transaction or to start a new one if the method gets called without
a transaction. This is the default behavior.
➔ SUPPORTS to join an activate transaction if one exists. If the method gets called without an active transaction,
this method will be executed without a transactional context.
➔ MANDATORY to join an activate transaction if one exists or to throw an Exception if the method gets called
without an active transaction.
➔ NEVER to throw an Exception if the method gets called in the context of an active transaction.
➔ NOT_SUPPORTED to suspend an active transaction and to execute the method without any transactional context.
➔ REQUIRES_NEW to always start a new transaction for this method. If the method gets called with an active
transaction, that transaction gets suspended until this method got executed.
➔ NESTED to start a new transaction if the method gets called without an active transaction. If it gets called with an
active transaction, Spring sets a savepoint and rolls back to that savepoint if an Exception occurs.
Class:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entitymanager1",
transactionManagerRef = "transactionmanager1",
basePackages = { "[Link]" })
public class PostgresDev {
@Bean(name = "datasource1")
@ConfigurationProperties(prefix = "[Link]")
@Primary
public DataSource datasource() {
return [Link]().build();
}
@Bean("properties1")
@ConfigurationProperties(prefix = "[Link]")
@Primary
public Map<String, String> getProperties() {
return new HashMap<>();
}
@Bean(name = "entitymanager1")
@Primary
public LocalContainerEntityManagerFactoryBean
db1EntityMgrFactory(EntityManagerFactoryBuilder builder,
@Qualifier("datasource1") final DataSource dataSource,
@Qualifier("properties1") Map<String, String> properties) {
[Link]("dev1 prop: " + properties);
return
[Link](dataSource).properties(properties).packages("[Link]")
.persistenceUnit("db1").build();
}
@Bean(name = "transactionmanager1")
@Primary
public JpaTransactionManager transactionManager(@Qualifier("entitymanager1")
EntityManager entityManager) {
return new JpaTransactionManager();
}
ss
Types:
• URI Versioning
• Request Parameter versioning
• Header’s versioning
• Media type versioning (a.k.a “content negotiation” or “accept header”)
URI Versioning
Basic approach to versioning is to create a completely different URI for the new service. Example implementation is shown
below.
Examples
o [Link]
o [Link]
@RestController
public class StudentVersioningController {
@GetMapping("v1/student")
public StudentV1 studentV1() {
return new StudentV1("Bob Charlie");
}
@GetMapping("v2/student")
public StudentV2 studentV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}
[Link]
Response
{
"name": "Bob Charlie"
}
[Link]
Response
{
"name": {
"firstName": "Bob",
"lastName": "Charlie"
}
}
o [Link]
o [Link]
[Link]
Response
{
"name": "Bob Charlie"
}
[Link]
Response
{
"name": {
"firstName": "Bob",
"lastName": "Charlie"
}
}
The third approach to versioning is to use a Request Header to differentiate the versions.
Examples
• [Link]
o headers=[X-API-VERSION=1]
• [Link]
o headers=[X-API-VERSION=2]
The last versioning approach is to use the Accept Header in the request.
Examples
• [Link]
o headers[Accept=application/[Link]-v1+json]
• [Link]
o headers[Accept=application/[Link]-v2+json]
• URI Pollution - URL versions and Request Param versioning pollute the URI space.
• Misuse of HTTP Headers - Accept Header is not designed to be used for versioning.
• Caching - If you use Header based versioning, we cannot cache just based on the URL. You would need take the
specific header into consideration.
• Can we execute the request on the browser? - If you have non technical consumers, then the URL based version
would be easier to use as they can be executed directly on the browser.
• API Documentation - How do you get your documentation generation to understand that two different urls are
versions of the same service?
The list below shows Major API providers using different versioning approaches.
Plan to avoid versioning as far as possible but evaluate and be ready with a versioing strategy before you expose your first
service to your consumer.
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
@Repository
public interface BlogRepository extends PagingAndSortingRepository<Blog, Long> {
}
➔ The preceding repository interface is decorated with the @Repository annotation. By extending from the Spring
PagingAndSortingRepository interface, the BlogRepository interface inherits two methods to paginate data.
➔ Firstly, the findAll(Pageable pageable) method. This method accepts a Pageable object that represents pagination
information. This method returns a Page object meeting the pagination restriction provided in
the Pageable object. Page is a sublist of a list of objects. A Page object provides information about its position in
the containing list.
➔ Next, the findAll(Sort sort) method that accepts a Sort object that represents sorting options for queries. The
method returns an Iterable of all entities sorted by the given options.
➔ On the browser access the REST endpoint localhost:8090/blogPageable?size=2. In this URL, note the size path
variable. It specifies the paging size to the application.
➔ To test the sorting of data, use the sort path variable, like this.
localhost:8090/blogPageable?size=2&sort=blogTitle
We can use it to monitor and manage the application with the help of HTTP endpoints or with the JMX.
To access the ‘Actuator’ services, you will have to use the HTTP endpoint as it becomes reliable to work with. The default
endpoint is ‘/actuator’.
[Link]
[Link]
You can also change the default endpoint by adding the following in the [Link] file.
[Link]-path=/details
what is swagger
The Swagger framework allows developers to create interactive, machine and human-readable API documentation.
API specifications typically include information such as supported operations, parameters and outputs, authorization
requirements, available endpoints and licenses needed.
Overall, Postman is considered easier to install and use, whereas Swagger is more reliable in terms of scalability.
Postman is better for API testing and has good data security features, while Swagger is better for API documentation and
design management.
#first db
[Link] = [url]
[Link] = [username]
[Link] = [password]
[Link] = [Link]
#second db ...
[Link] = [url]
[Link] = [username]
[Link] = [password]
[Link] = [Link]
@Bean
@Primary
@ConfigurationProperties(prefix="[Link]")
public DataSource primaryDataSource() {
return [Link]().build();
}
@Bean
@ConfigurationProperties(prefix="[Link]")
public DataSource secondaryDataSource() {
return [Link]().build();
}
And create 2 entity managers and 2 transaction managers.
API rate
What is API rate limiting?
The basic principle of API rate limiting is fairly simple: if access to the API is unlimited, anyone (or anything) can use the
API as much as they want at any time, potentially preventing other legitimate users from accessing the API.
API rate limiting is, in a nutshell, limiting access for people (and bots) to access the API based on the rules/policies set by
the API’s operator or owner.
To Resolve or Fix CORS issue there are multiple ways. But today we will learn how to define global configuration to Fix
CORS issue.
With Spring Boot, the recommended way to enable global CORS is to declare within Spring MVC and combined with fine-
grained @CrossOrigin configuration as:
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
[Link]("/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}
}
Now, since you are using Spring Security, you have to enable CORS at Spring Security level as well to allow it to leverage
the configuration defined at Spring MVC level as:
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
[Link]().and()...
}
}
Or
If you want to enable CORS without using filters or without config file just add
@CrossOrigin
to the top of your controller and it work.
@OneToMany in JPA
@Entity
@Table(name="CART")
public class Cart {
//...
@OneToMany(mappedBy="cart")
private Set<Item> items;
@Entity
@Table(name="ITEMS")
public class Item {
//...
@ManyToOne
@JoinColumn(name="cart_id", nullable=false)
private Cart cart;
public Item() {}
@ManyToOne In JPA
public class ItemOIO {
// ...
@ManyToOne
@JoinColumn(name = "cart_id", insertable = false, updatable = false)
private CartOIO cart;
//..
}
//..
@OneToMany
@JoinColumn(name = "cart_id") // we need to duplicate the physical information
private Set<ItemOIO> items;
//..
}
@ManyToMany in JPA
@ManyToMany
@JoinTable( name = "course_like",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id"))
Set<Course> likedCourses;
@ManyToMany(mappedBy = "likedCourses")
Set<Student> likes;
We provide the name of the join table (course_like) as well as the foreign keys with the @JoinColumn annotations.
The joinColumn attribute will connect to the owner side of the relationship, and the inverseJoinColumn to the other
side.
Micro Services
Authentication vs Authorization
Authentication is the process of verifying who a user is, whereas authorization is the process of verifying what specific
applications, files, and data a user has access to.
Bounded Context is an independent domain. Let's imagine it as a different department in a company. Something like
separation of concerns. An independent context in which all the stakeholders (Business Analysts, Testers, Developers,
Business Folks) have the same definition of terms used in the Bounded Context. You can then have a separate
microservice corresponding to each Bounded Context.
For Example: If you in Insurance Domain, then you can have bounded context like Customer, Quote, Policy etc. and can
have a micro-service for each of them.
The most popular implementation of a centralized logging solution is Elastic Search, Logstash, Kibana (ELK), AWS
Cloudwatch. However, these can also be replaced with alternatives.
Pros:
✓ All application service and system logs are accessible from one Interface
✓ A single dashboard provides an application-wide view
✓ Provides better monitoring of the whole microservice application
Cons:
Event-sourcing involves using events to persist the data changes. In contrast, event-driven architecture is about
communicating events with data changes between service boundaries
Event Sourcing is ensuring every change to the state of an application is captured in an event object, and that these event
objects are themselves stored in the sequence they were applied for the same lifetime as the application state itself.
• Synchronous communication: In synchronous communication, the calling service waits for a response from the
called service before continuing. This is the simplest way to implement inter-service communication, but it can
lead to performance problems if the called service is slow to respond.
o Can be done using Rest Template and WebClient.
• Asynchronous communication: In asynchronous communication, the calling service does not wait for a response
from the called service. Instead, the called service sends a message to the calling service, and the calling service
processes the message later. This can improve performance, but it can also make it more difficult to track the
progress of a request.
o Can be done using Message brokers (Apache kafka, Rabbit MQ, AWS SNS etc.)
You are using Rest Template to make that http call and in Rest Template how do you pass headers/HTTP
Headers?
HttpHeaders headers = new HttpHeaders();
postForObjects
getForObject
Apart from Rest Template do you know any other way to use http calls?
RestTemplate -> Sync and blocking
WebClient -> Sync and Aync, not blocking.
Monolithic vs Microservices
Disadvantages of Monolithic applications
o Simple to develop relative to microservices, where skilled developers are required in order to identify and
develop the services.
o Easier to deploy as only a single jar/war file is deployed.
o Relatively easier and simple to develop in comparison to microservices architecture.
o The problems of network latency and security are relatively less in comparison to microservices architecture.
o Developers need not learn different applications, they can keep their focus on one application.
Advantages of microservices
Disadvantages of microservices
o Being a distributed system, it is much more complex than monolithic applications. Its complexity increases with
the increase in a number of microservices.
o Skilled developers are required to work with microservices architecture, which can identify the microservices and
manage their inter-communications.
o Independent deployment of microservices is complicated.
o Microservices are costly in terms of network usage as they need to interact with each other and all these remote
calls result in network latency.
o Microservices are less secure relative to monolithic applications due to the inter-services communication over the
network.
o Debugging is difficult as the control flows over many microservices and to point out why and where exactly the
error occurred is a difficult task.
Saga Pattern
• A saga is a sequence of local transactions.
• In this pattern, each transaction updates the database and triggers an event or publishes a message for next
transaction in saga.
• In case, any local transaction fails, saga will trigger series of transactions to undo the changes done so far by the
local transactions.
Coordinated transactions: The SAGA pattern provides a way to coordinate transactions that involve multiple services or
processes. The pattern defines a sequence of steps, each of which can involve a separate service or process, that are
executed in a coordinated manner to complete the transaction.
Compensation and rollback: The SAGA pattern includes a mechanism for compensating or rolling back the transaction if
one of the steps fails. This mechanism ensures that the transaction remains consistent even if one or more of the steps
fail.
Distributed transactions: The SAGA pattern supports distributed transactions that span multiple services or processes.
The pattern provides a way to coordinate the transaction across these services or processes in a consistent manner.
Asynchronous processing: The SAGA pattern can support asynchronous processing, which allows for greater concurrency
and performance. This is especially important in distributed systems where the processing time of different services or
processes may vary.
Error handling: The SAGA pattern provides a standardized way to handle errors that occur during the transaction. The
pattern ensures that errors are handled consistently across all services or processes involved in the transaction.
Scalability: The SAGA pattern can scale to handle large and complex transactions that involve multiple services or
processes. The pattern provides a way to break down the transaction into smaller, more manageable steps, which can be
executed in parallel across different services or processes.
o Choreography
o Orchestration
Choreography is a way to coordinate sagas where participants exchange events without a centralized point of control
With choreography, each microservices run its own local transaction and publishes events to message broker system and
that trigger local transactions in other microservices.
Orchestration is a way to coordinate sagas where a centralized controller tells the saga participants what local
transactions to execute.
The saga orchestrator handles all the transactions and tells the participants which operation to perform based on events.
The orchestrator executes saga requests, stores and interprets the states of each task, handles failure recovery with
compensating transactions.
1. Closed
2. Open
3. Half-Open
Closed state
In this state, the Circuit Breaker routs the requests to the Microservice and counts the number of failures in each period of
time. That means it work without any failures. But if the number of failures in a certain period of time exceeds a threshold,
the circuit will trip and will move to an “Open” state.
Open state
When Circuit breaker moves to the “Open” state, requests from the Microservices will fail immediately, and an exception
will be returned. However, after a timeout, the Circuit Breaker will go to the “Half-Open” state.
Half-Open state
In this state, the Circuit Breaker allows only a limited number of requests from the Microservice, to pass through and
invoke the operation. If these requests are successful, the Circuit Breaker will go back to the “Closed” state. However, if
any request fails again, it goes back to the “Open” state.
Solution
• We can use circuit breaker pattern where a proxy service acts as a circuit breaker.
• Each service should be invoked through proxy service.
• A proxy service maintains a timeout and failures count.
• In case of consecutive failures crosses the threshold failures count then proxy service trips the circuit breaker and
starts a timeout period.
• During this timeout period, all requests will failed.
• Once this timeout period is over, proxy service allows a given limited number of test requests to pass to provider
service. If requests succeed the proxy service resumes the operations otherwise, it agains trips the circuit breaker
and starts a timeout period and no requests will be entertained during that period.
1. The main responsibility of this pattern is that it routes the request means basically provide a road map for how
our request goes, approve or may be canceled, API composition, and app authentication.
2. It basically the entry gate for taking entry in any application by an external source.
Advantages of API gateway pattern
1. It is an important component for every web application means the web application services will be shown only if
the API is up-to-date means updated.
2. It becomes very important for each process for being lightweight because otherwise their time complexity will get
increased because their developer has to wait in the process of updating API.
Hibernate
➔ Best ORM (Object Relational Model) framework for java.
JSP
✓ Java Server pages
✓ JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to
servlet because it provides more functionality than servlet such as expression language, jstl etc.
JSP directives:
The jsp directives are messages that tell the web container how to translate a JSP page into the corresponding servlet.
</jsp:forward>
</jsp:include>
</jsp:useBean>
property="propertyName" param="parameterName" |
/>
codebase= "directoryNameOfClassFile"
</jsp:plugin>
There are many operators that have been provided in the Expression Language. Their precedence are as follows:
[] .
()
* / div % mod
+ - (binary)
== != eq ne
&& and
|| or
?:
There are many reserve words in the Expression Language. They are as follows:
lt le gt ge
eq ne true false
Core tags The JSTL core tag provide variable support, URL management, flow
control etc. The url for the core tag
is[Link] . The prefix of core tag is c.
Function The functions tags provide support for string manipulation and string
tags length. The url for the functions tags
is[Link] and prefix is fn.
Formatting The Formatting tags provide support for message formatting, number
tags and date formatting etc. The url for the Formatting tags
is [Link] and prefix is fmt.
XML tags The xml sql tags provide flow control, transformation etc. The url for the
xml tags is[Link] and prefix is x.
SQL tags The JSTL sql tags provide SQL support. The url for the sql tags
is [Link] and prefix issql.
Core Tags:
<c:out value="${'Welcome to javaTpoint'}"/>
<c:remove var="income"/>
<c:choose>
<c:otherwise>
Income is undetermined...
</c:otherwise>
</c:choose>
<c:forEach var="j" begin="1" end="3">
</c:forEach>
<c:out value="${name}"/><p>
</c:forTokens>
</c:url>
<c:redirect url="[Link]
<p>string-1 : ${fn:escapeXml(string1)}</p>
${fn:toLowerCase(string)}
${fn:toUpperCase(site)}
${fn:toUpperCase(site)}
${fn:substringAfter(string, "Nakul")}
${fn:substringBefore(string, "developed")}
${fn:length(str1)}
</bean>
<bean id="transactionManager"
class="[Link]">
<property name="dataSource" ref="dataSource" />
</bean>
First we will create a datasource object which will take the driver, connection url, username and password from
[Link] file.
[Link]
Spring's using JdbcTemplate class to interact with the database. You would use this class to submit
queries. It reduces boilerplate code significantly.
JdbcTemplate
[Link]
This would be your TransactionManager. TransactionManagers handle all of your transactional activities -
running a query, wrapped in a transaction. As you can see, a DataSource is passed to it as a
property. DataSource would be your DB conneciton.
DataSourceTransactionManager
[Link]
This is a Spring class, that handles your connections to a resource that is acquired by a JNDIname.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/context/*-[Link]</param-value>
</context-param>
<listener>
<listener-class>[Link]</listener-
class>
</listener>
Data Integrity:
There are the following categories of data integrity exist with each RDBMS:
Domain integrity: It enforces valid entries for a given column by restricting the type, the format, or
the range of values.
Referential integrity: It specifies that rows cannot be deleted, which are used by other records.
User-defined integrity: It enforces some specific business rules that are defined by users. These
rules are different from entity, domain or referential integrity.
No. DBMS RDBMS
5) DBMS uses file system to in RDBMS, data values are stored in the
store data, so there will be no form of tables, so arelationship between
relation between the these data values will be stored in the form
tables. of a table as well.
Bit varying BIT VARYING(X) Here, 'x' is the number of bits to store
(length can vary up to x).
Time with time TIME WITH TIME It is exactly same as time but also store an
zone ZONE offset from UTC of the time specified.
- It subtracts right hand operand from left hand a-b will give -50
operand
/ It divides left hand operand by right hand operand b/a will give 2
% It divides left hand operand by right hand operand b%a will give 0
and returns reminder
= Examine both operands value that are equal or not,if yes (a=b) is not
condition become true. true
!= This is used to check the value of both operands equal or not,if (a!=b) is
not condition become true. true
<> Examines the operand?s value equal or not, if values are not (a<>b) is
equal condition is true true
> Examine the left operand value is greater than right Operand, if (a>b) is not
yes condition becomes true true
< Examines the left operand value is less than right Operand, if yes (a<=""
condition becomes true td="">
>= Examines that the value of left operand is greater than or equal (a>=b) is
to the value of right operand or not,if yes condition become true not true
<= Examines that the value of left operand is less than or equal to (a<=b) is
the value of right operand or not, if yes condition becomes true true
!< Examines that the left operand value is not less than the right (a!<=""
operand value td="">
!> Examines that the value of left operand is not greater than the (a!>b) is
value of right operand true
Operator Description
ALL this is used to compare a value to all values in another value set.
AND this operator allows the existence of multiple conditions in an SQL statement.
ANY this operator is used to compare the value in list according to the condition.
BETWEEN this operator is used to search for values, that are within a set of values
NOT the NOT operator reverse the meaning of any logical operator
EXISTS the EXISTS operator is used to search for the presence of a row in a specified table
LIKE this operator is used to compare a value to similar values using wildcard operator
EmployeeID number(10),
FirstName varchar2(255),
LastName varchar2(255),
Email varchar2(255),
AddressLine varchar2(255),
City varchar2(255)
);
But if you do not specify the WHERE condition it will remove all the rows from the table.
TRUNCATE statement: it is used to delete all the rows from the table and free the containing space.
Local temp tables are only available at current connection time. It is automatically deleted when user
disconnects from instances. It is started with hash (#) sign.
User id int,
Global temp tables name starts with double hash (##). Once this table is created, it is like a permanent
table. It is always ready for all users and not deleted until the total connection is withdrawn
User id int,
If you want to add columns in SQL table, the SQL alter table syntax is given below:
If you want to add multiple columns in table, the SQL table will be
column_2 column-definition,
.....
column_n column-definition);
If you want to modify an existing column in SQL table, syntax is given below:
If you want to modify multiple columns in table, the SQL table will be
column_2 column_type,
.....
column_n column_type);
[HAVING Clause]: It selects among the groups defined by the GROUP BY clause.
It will return the total number of names of employee_table. But null fields will not be counted.
The "select count(*) from table" is used to return the number of records in table.
A synchronous request blocks the client until operation completes i.e. browser is not unresponsive. In such case,
javascript engine of the browser is blocked.
An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can perform other
operations also. In such case, javascript engine of the browser is not blocked.
Property Description
onReadyStateChange It is called whenever readystate attribute changes. It must not be used with
synchronous requests.
Method Description
void open(method, URL) opens the request specifying get or post method and
url.
void open(method, URL, async) same as above but specifies asynchronous or not.
void open(method, URL, async, username, same as above but specifies username and password.
password)
Struts1 Vs Struts2:
DSA
LinkedList
public class LinkedList {
class Node {
int data;
Node next;
if(head == null) {
head = newNode;
tail = newNode;
} else {
[Link] = newNode;
tail = [Link];
}
while(n != null) {
[Link]([Link] + " ");
n = [Link];
}
[Link]();
}
return slowNode;
[Link]();
}
}
AWS
ECS vs EC2
ECS - Elastic Container Service
AWS ECS is just a logical grouping (cluster) of EC2 instances, and all the EC2 instances part of an ECS act as Docker host
i.e. ECS can send command to launch a container on them (EC2). If you already have an EC2, and then launch ECS, you'll
still have a single instance. If you add/register (by installing the AWS ECS Container Agent) the EC2 to ECS it'll become the
part of the cluster, but still a single instance of EC2.
An overview
ECS is just about clustering of EC2 instances, and uses Docker to instantiate containers/instances/virtual machines on
these (EC2) hosts.
Simple E-mail Service: It allows sending e-mail using RESTFUL API call or via regular SMTP
Identity and Access Management: It provides enhanced security and identity management for your AWS account
Simple Storage Device or (S3): It is a storage device and the most widely used AWS service
Elastic Compute Cloud (EC2): It provides on-demand computing resources for hosting applications. It is handy in case of
unpredictable workloads
Elastic Block Store (EBS): It offers persistent storage volumes that attach to EC2 to allow you to persist data past the
lifespan of a single Amazon EC2 instance
CloudWatch: To monitor AWS resources, It allows administrators to view and collect keys. Also, one can set a notification
alarm in case of trouble.
Amazon S3 is a REST service, and you can send a request by using the REST API or the AWS SDK wrapper libraries that
wrap the underlying Amazon S3 REST API.
• Spin up a new larger instance than the one you are currently running
• Pause that instance and detach the root webs volume from the server and discard
• Then stop your live instance and detach its root volume
• Note the unique device ID and attach that root volume to your new server
• And start it again
Mention what the security best practices for Amazon EC2 are?
For secure Amazon EC2 best practices, follow the following steps
• Use AWS identity and access management to control access to your AWS resources
• Restrict access by allowing only trusted hosts or networks to access ports on your instance
• Review the rules in your security groups regularly
• Only open up permissions that you require
• Disable password-based login, for example, launched from your AMI
What is VPC?
VPC stands for Virtual Private Cloud. It allows you to customize your networking configuration. It is a network which is
logically isolated from another network in the cloud. It allows you to have your IP address range, internet gateways,
subnet, and security groups.
SQS is distributed queuing system. Messages are not pushed to receivers. Receivers have to poll or pull messages
from SQS
Programs
Patterns
Square pattern:
Triangle Pattern
public class Patterns {
// output:
// * * * *
// * * *
// * *
// *
}
////////////////////////////////////
char c = [Link](i);
if([Link](c)){
[Link](c, ++count);
}else{
[Link](c,1);
////////////////////////////////////
int count = 0;
if([Link](i) == [Link](j)){
count++;
[Link]([Link](i)+":"+count+" ");
String d=[Link]([Link](i)).trim();
s=[Link](d,"");
[Link]("");
////////////////////////////////////
String g = strings[i];
if ([Link](g)) {
[Link](g, ++cnt);
} else {
[Link](g, 1);
////////////////////////////////////
if(strings1[i].equals(strings1[j])){
count++;
}
[Link](strings1[i]+":"+count);
for(char c: chars) {
count += (c-'0');
[Link](count);
String s ="eMail_Address321@[Link]";
int u =0,l=0,n=0,others=0;
for(char c:chars){
if([Link](c)){
u++;
}else if([Link](c)){
l++;
}else if([Link](c)){
n++;
}else{
others++;
[Link]("Avg of Uppercase:"+(u*100)/total);
[Link]("Avg of Lowercase:"+(l*100)/total);
[Link]("Avg of Numbers:"+(n*100)/total);
[Link]("Avg of others:"+(others*100)/total);
Max of two numbers in an array
public static void main(String[] args) {
int maxOne = 0;
int maxTwo = 0;
// [Link](a);
// [Link](a[[Link]-2]+","+a[[Link]-1]);
for (int i : a) {
if (maxOne < i) {
maxTwo = maxOne;
maxOne = i;
maxTwo = i;
[Link](maxOne+" "+maxTwo); }
int count = 0;
int variable = 0;
int[] a = {1,2,4,1,4,2,1,4,4};
for(int i=0;i<[Link];i++){
int temp =0;
for(int j=0;j<[Link];j++){
if(a[i] == a[j]){
temp++;
}
if(temp > count){
variable = a[i];
count = temp;
}
}
}
[Link]("Repeated element is: "+ variable+ " and count is: "+count);
String s = "fgjfgjhdgjkhfgjdjkhgjkfdhgj";
int count = 0;
while([Link]().indexOf("gj") != -1){
s = [Link]().replaceFirst("gj","");
count++;
}
[Link](count);
Factor Program
1 . Find if a number is prime number. prime number is a number divisible by 1 and itself e.g 5 is a
primt number as it has factor only 1,5
import [Link].*;
public class PrimeNum
{
public static void main(String args[])
{
Scanner sc =new Scanner([Link]);
int count=0;
[Link]("enter a number");
int n= [Link]( );
for(int i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
[Link]("Yes");
else
[Link]("No");
}
}
2 . Find if a number is a composite number. Composite number is a number which has more than one
factor(excluding 1 and itself) e.g 8=2, 4=2 factors
import [Link].*;
public class compositeNo
{
public static void main(String args[])
{
Scanner sc =new Scanner([Link]);
int count=0;
[Link]("enter a number");
int n= [Link]( );
for(int i=1;i<=n;i++) { if(n%i==0) count++; } if(count>3)
[Link]("Yes");
else
[Link]("No");
}
}
3 . Find if a number is a perfect number. A perfect number is number which is equal to sum of its
divisor or factor except itself e.g. 6=1+2+3
import [Link].*;
public class perfectNo
{
public static void main(String args[])
{
Scanner sc =new Scanner([Link]);
int sum=0;
[Link]("enter a number");
int n= [Link]( );
for(int i=1;i<n;i++)
{
if(n%i==0)
sum= sum+i;
}
if(sum==n)
[Link]("Yes");
else
[Link]("No");
}
}
4 . Find if a number is an Abundant number. Here sum of factor is greater then the number. itself e.g.
12 factor 1,2,3,4,6=16>12
import [Link].*;
public class AbundantNo
{
public static void main(String args[])
{
Scanner sc =new Scanner([Link]);
int sum=0;
[Link]("enter a number");
int n= [Link]( );
for(int i=1;i<n;i++)
{
if(n%i==0)
sum= sum+i;
}
if(sum>n)
[Link]("Yes");
else
[Link]("No");
}
}
5 . Find if number is a Deficient number. Here sum of factor is less than the no itself. e.g. 21 factor
1,3,7=11<21
import [Link].*;
public class DeficientNo
{
public static void main(String args[])
{
Scanner sc =new Scanner([Link]);
int sum=0;
[Link]("enter a number");
int n= [Link]( );
for(int i=1;i<n;i++)
{
if(n%i==0)
sum= sum+i;
}
if(sum<n)
[Link]("Yes");
else
[Link]("No");
}
}
6 . Find if number is a Pronic number. Pronic No is the product of two consecutive integers, n(n+1).
e.g. 56=7×8
import [Link].*;
public class PronicNo
{
public static void main(String args[])
{
Scanner sc =new Scanner([Link]);
int fact=0;
[Link]("enter a number");
int n= [Link]( );
for(int i=1;i<n;i++)
{
if(i*(i+1)==n)
fact=i;
}
if(fact!=0)
[Link]("Yes");
else
[Link]("No");
}
}
Substrings of a given string
Option1:
O/P:
a
ab
abc
abcd
b
bc
bcd
c
cd
d
Option 2:
Count match
public static void main(String[] args) {
String str = "helloslkhellodjladfjhello";
String findStr = "hello";
[Link]([Link](str,
findStr));
[Link]([Link](str,
findStr));
Option 1:
for(; i<[Link]();i++) {
if([Link](i) == ' ') {
String s = "";
for(int j = start; j < i ; j++) {
s = [Link](j) + s;
}
ans = ans + s + " ";
start = i+1;
}
}
Option 2:
[Link](res);
return res;
if([Link]() == 1) {
res += str;
} else {
char[] c = [Link]();
int i=0;
for(; i < [Link]-1; i++) {
if(c[i] != '*' && c[i] == c[i+1]) {
c[i] = '*';
} else if(c[i] != '*') {
res += c[i];
}
}
res += c[i];
}
return res;
}
return arr3;
int h = Integer.MIN_VALUE;
int sh = Integer.MIN_VALUE;
return sh;
Binary Search
Binary Search is defined as a searching algorithm used in a sorted array by repeatedly dividing the search
interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time
complexity to O(log N).
int s = 0;
int e = [Link] - 1;
while(s <= e) {
int mid = ( s + e ) / 2;
e = mid -1;
s = mid + 1;
} else {
result = mid;
break;
return result;
Selection sort
Selection sort is a simple and efficient sorting algorithm that works by repeatedly selecting the smallest (or largest)
element from the unsorted portion of the list and moving it to the sorted portion of the list.
arr[j] = arr[i];
arr[i] = temp;
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the
wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
public static void bubbleSort(int[] arr, int n) {
sorted = false;
arr[j] = arr[j+1];
arr[j] = temp;
if ([Link](ch[i])) {
[Link](ch[i], [Link](ch[i]) + 1);
} else {
[Link](ch[i], 1);
}
char[] c = [Link]();
import [Link].*;
import [Link].*;
class GFG {
// function to print
// triplets with given sum
static void findTriplets(int[] arr,
int n, int sum)
{
// sort array elements
[Link](arr);
for (int i = 0;
i < n - 1; i++) {
// initialize left and right
int l = i + 1;
int r = n - 1;
int x = arr[i];
while (l < r) {
if (x + arr[l] + arr[r] == sum) {
// print elements if it's
// sum is given sum.
[Link](
x + " " + arr[l] + " "
+ arr[r]);
l++;
r--;
}
// Driver code
public static void main(String args[])
{
int[] arr = new int[] { 0, -1, 2, -3, 1 };
int sum = -2;
int n = [Link];
findTriplets(arr, n, sum);
}
}
int count = 0;
for(int i=0; i < 26; i++) {
if(count1[i] - count2[i] != 0) {
[Link]((char)('a' + i));
count++;
}
}
return count;
Sol2:
int result = 0;
for(int i=0; i < 26; i++) {
if(count[i]!= 0) {
[Link]((char)('a' + i));
result++;
}
}
return result;