0% found this document useful (0 votes)
3 views231 pages

Java

The document provides an extensive overview of Java concepts, including memory areas, object copying methods, thread management, and collections. It covers various topics such as shallow vs deep copy, runnable vs callable interfaces, fail-fast vs fail-safe iterators, and the ConcurrentHashMap class. Additionally, it discusses exceptions like ClassNotFoundException and NoClassDefFoundError, along with other core Java principles and practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views231 pages

Java

The document provides an extensive overview of Java concepts, including memory areas, object copying methods, thread management, and collections. It covers various topics such as shallow vs deep copy, runnable vs callable interfaces, fail-fast vs fail-safe iterators, and the ConcurrentHashMap class. Additionally, it discusses exceptions like ClassNotFoundException and NoClassDefFoundError, along with other core Java principles and practices.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Table of Contents

Interview Questions.................................................................................................................................................................. 7

Memory Areas in java ............................................................................................................................................................ 7

Shallow Copy Vs Deep Copy .................................................................................................................................................. 8

Runnable vs callable .............................................................................................................................................................. 9

FailFast and FailSafe Iterators in Java .................................................................................................................................... 9

ConcurrentHashMap ........................................................................................................................................................... 10

ClassNotFoundException Vs NoClassDefFoundError.......................................................................................................... 10

Stream vs parallel Stream .................................................................................................................................................... 10

Diamond Problem in case of Multiple inheritance .............................................................................................................. 11

Spring Profiles ...................................................................................................................................................................... 12

Optional ............................................................................................................................................................................... 13

How to restrict child class in serialization ......................................................................................................................... 133

Core Java ................................................................................................................................................................................. 15

Java Versions ....................................................................................................................................................................... 15

SOLID Principles ................................................................................................................................................................... 16

Design Patterns.................................................................................................................................................................... 16

Decorator Pattern................................................................................................................................................................ 22

Observer Design Pattern ..................................................................................................................................................... 24

Language Fundamentals ...................................................................................................................................................... 24

Main..................................................................................................................................................................................... 29

ENUM .................................................................................................................................................................................. 30

Increment and Decrement Operators ................................................................................................................................. 32

Data Hiding .......................................................................................................................................................................... 32

Abstraction .......................................................................................................................................................................... 33

Encapsulation ...................................................................................................................................................................... 33

Tightly Encapsulated Class................................................................................................................................................... 34

IS - A Relation ...................................................................................................................................................................... 34

HAS – A Relationship ........................................................................................................................................................... 36

Difference b/w composition and Aggregation .................................................................................................................... 37

Method Signature................................................................................................................................................................ 37

Method Overloading ........................................................................................................................................................... 38

Method Overriding .............................................................................................................................................................. 41

Static Binding and Dynamic Binding .................................................................................................................................... 48


Coupling ............................................................................................................................................................................... 48

Cohesion .............................................................................................................................................................................. 48

Object Type Casting ............................................................................................................................................................. 48

Static control flow ............................................................................................................................................................... 49

Static block .......................................................................................................................................................................... 52

Instance control Flow .......................................................................................................................................................... 52

Constructors ........................................................................................................................................................................ 52

Singleton Class ..................................................................................................................................................................... 54

Java source file structure:.................................................................................................................................................... 57

Packages .............................................................................................................................................................................. 57

Modifiers ............................................................................................................................................................................. 58

Class lever modifiers ............................................................................................................................................................ 58

Interfaces ............................................................................................................................................................................. 59

Method naming conflicts ................................................................................................................................................. 60

Variable naming conflicts ................................................................................................................................................ 61

Marker interface .............................................................................................................................................................. 62

Collections ........................................................................................................................................................................... 64

FailFast and FailSafe Iterators in Java .............................................................................................................................. 64

Arrays............................................................................................................................................................................... 64

Interfaces in Collection Framework................................................................................................................................. 65

ArrayList ........................................................................................................................................................................... 68

LinkedList ......................................................................................................................................................................... 69

Vector .............................................................................................................................................................................. 70

Stack ................................................................................................................................................................................ 71

Cursors ............................................................................................................................................................................. 71

HashSet ............................................................................................................................................................................ 75

LinkedHashSet ................................................................................................................................................................. 76

SortedSet(I) ...................................................................................................................................................................... 77

TreeSet ............................................................................................................................................................................ 77

Comparable (I) ................................................................................................................................................................. 78

Comparator (I) ................................................................................................................................................................. 78

Map.................................................................................................................................................................................. 81

HashMap ......................................................................................................................................................................... 82

LinkedHashMap ............................................................................................................................................................... 85

IdentityHashMap ............................................................................................................................................................. 85
WeakHashMap ................................................................................................................................................................ 86

SortedMap (I) .................................................................................................................................................................. 87

TreeMap .......................................................................................................................................................................... 87

HashTable ........................................................................................................................................................................ 87

Queues............................................................................................................................................................................. 88

PiriorityQueue .................................................................................................................................................................. 88

Flow Control ........................................................................................................................................................................ 92

[Link] .............................................................................................................................................................................. 94

[Link] ................................................................................................................................................................ 95

How to create our own immutable class............................................................................................................................. 99

String Buffer................................................................................................................................................................... 100

StringBuilder .................................................................................................................................................................. 102

Wrapper Classes ................................................................................................................................................................ 102

Autoboxing .................................................................................................................................................................... 103

Clone .............................................................................................................................................................................. 105

Exception Handling ............................................................................................................................................................ 106

[Link] ............................................................................................................................................................................... 109

Generics ............................................................................................................................................................................. 115

Multi-Threading ................................................................................................................................................................. 116

The ways to define a Thread ......................................................................................................................................... 116

Thread Priorities ............................................................................................................................................................ 120

The methods to prevent Thread execution ................................................................................................................... 121

Serialization ....................................................................................................................................................................... 127

Grabage Collector .............................................................................................................................................................. 134

Java 8 ..................................................................................................................................................................................... 138

Java 8 Lambda Expressions ................................................................................................................................................ 139

Java 8 Predefined-Functional Interfaces ........................................................................................................................... 140

Method References ........................................................................................................................................................... 141

Optional Class .................................................................................................................................................................... 142

Default/Static Methods in interfaces ................................................................................................................................ 142

Stream API ......................................................................................................................................................................... 142

Stream Object from Arrays ............................................................................................................................................ 143

Filter and forEach .......................................................................................................................................................... 143

Max, Min, Sorted ........................................................................................................................................................... 144

Reduce ........................................................................................................................................................................... 145


Arrays(Premetive type) to List/Set ................................................................................................................................ 145

GroupingBy .................................................................................................................................................................... 145

ListSorting ...................................................................................................................................................................... 145

MapSorting .................................................................................................................................................................... 146

Map vs FlatMap ............................................................................................................................................................. 146

Stream vs ParallelStream................................................................................................................................................... 147

Employee Stream .............................................................................................................................................................. 147

Web Services ......................................................................................................................................................................... 156

HTTP Methods & Status codes .......................................................................................................................................... 157

REST API Design Best Practices .......................................................................................................................................... 159

What do we mean by REST architectural style? ................................................................................................................ 159

Spring Boot ............................................................................................................................................................................ 160

@EnableWebMvc .............................................................................................................................................................. 162

Spring Boot Key features ................................................................................................................................................... 163

Spring Boot Annotations ................................................................................................................................................... 164

5 Best Practices for Using Spring Boot Annotations .......................................................................................................... 166

Transactions ...................................................................................................................................................................... 167

Versioning in Spring boot .................................................................................................................................................. 169

Pagination in spring boot JPA ............................................................................................................................................ 173

what is spring boot actuator and its advantages............................................................................................................. 173

what is swagger ................................................................................................................................................................. 174

How to config multiple databases in sprin boot? .............................................................................................................. 174

How to load data during startup in Spring Boot? .............................................................................................................. 175

API rate .............................................................................................................................................................................. 175

Cross Origin Requests ........................................................................................................................................................ 175

@OneToMany in JPA ......................................................................................................................................................... 176

@ManyToOne In JPA ......................................................................................................................................................... 176

@ManyToMany in JPA ...................................................................................................................................................... 177

Micro Services ....................................................................................................................................................................... 177

Authentication vs Authorization ....................................................................................................................................... 177

How to manage the inter service communication in java microservices .......................................................................... 178

Monolithic vs Microservices .............................................................................................................................................. 179

Saga Pattern ...................................................................................................................................................................... 180

Circuit Breaker Pattern ...................................................................................................................................................... 182

API Gateway Design Pattern .............................................................................................................................................. 184


Hibernate .............................................................................................................................................................................. 186

JSP.......................................................................................................................................................................................... 187

SQL......................................................................................................................................................................................... 193

AJAX....................................................................................................................................................................................... 203

Struts flow ............................................................................................................................................................................. 205

DSA ........................................................................................................................................................................................ 205

LinkedList ........................................................................................................................................................................... 205

AWS ....................................................................................................................................................................................... 208

ECS vs EC2 .......................................................................................................................................................................... 208

Programs ............................................................................................................................................................................... 211

Patterns ............................................................................................................................................................................. 211

Triangle Pattern ................................................................................................................................................................. 211

Java Program To Find Duplicate Characters In A String .................................................................................................... 212

To Find The Sum Of All Digits Of A Number ...................................................................................................................... 214

Find The Percentage Of Uppercase Letters, Lowercase Letters, Digits And Other Special Characters In A String ........... 214

Max of two numbers in an array ....................................................................................................................................... 215

Max number in an array .................................................................................................................................................... 215

To get count of a String present in a file ........................................................................................................................... 216

Factor Program .................................................................................................................................................................. 217

Substrings of a given string................................................................................................................................................ 220

Count match ...................................................................................................................................................................... 220

Reverse Each Word............................................................................................................................................................ 221

Reverse String Word wise.................................................................................................................................................. 222

Remove Consecutive Duplicates ....................................................................................................................................... 222

Merge 2 arrays in sorting order ......................................................................................................................................... 222

Push Zeros to End .............................................................................................................................................................. 223

Second Largest Element .................................................................................................................................................... 223

Binary Search ..................................................................................................................................................................... 224

Selection sort ..................................................................................................................................................................... 225

Bubble Sort ........................................................................................................................................................................ 225

Find max char in a String ................................................................................................................................................... 226

Get Compressed String ...................................................................................................................................................... 227

Print all triplets with given sum or 3SUM == 0 .................................................................................................................. 228

Sum of 3 consecutive numbers ......................................................................................................................................... 229


Interview Questions
Memory Areas in java
1. Class (Method) Area
2. Heap
3. Stack
4. Program Counter Register
5. Native Method Stack

Let’s see about them in brief:


1. Class Loader: It is a subsystem of JVM which is used to load class [Link] is mainly responsible for three
activities.
• Loading
• Linking
• Initialization
Types of ClassLoader

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.

Shallow Copy Vs Deep Copy


Shallow Copy
• Whenever we use default implementation of clone method, we get shallow copy of object means it creates
new instance and copies all the field of object to that new instance and returns it as object type, we need to
explicitly cast it back to our original object. This is shallow copy of the object.
• clone() method of the object class support shallow copy of the object. If the object contains primitive as well
as nonprimitive or reference type variable in shallow copy, the cloned object also refers to the same object to
which the original object refers as only the object references gets copied and not the referred objects
themselves.
• That’s why the name shallow copy or shallow cloning in Java. If only primitive type fields or Immutable objects
are there then there is no difference between shallow and deep copy in Java.

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;
}

public interface Runnable {


public abstract void run();
}

To summarize few notable Difference are:


1. A Runnable object does not return a result whereas a Callable object returns a result.
2. A Runnable object cannot throw a checked exception wheras a Callable object can throw an exception.
3. The Runnable interface has been around since Java 1.0 whereas Callable was only introduced in Java 1.5.

Few similarities include:


1. Instances of the classes that implement Runnable or Callable interfaces are potentially executed by another
thread.
2. Instance of both Callable and Runnable interfaces can be executed by ExecutorService via submit() method.
3. Both are functional interfaces and can be used in Lambda expressions since Java8.

FailFast and FailSafe Iterators in Java


Iterators in java are used to iterate over the Collection objects.

Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the


collection. Structural modification means adding, removing or updating any element from collection while a thread is
iterating over that collection.
Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.

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.

Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator.

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

What are benefits of using ConcurrentHashMap over synchronized HashMap?

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.

Stream vs parallel Stream


A stream in Java is a sequence of objects which operates on a data source such as an array or a collection and supports
various methods

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.

Diamond Problem in case of Multiple inheritance


public class Super1 {
public void demo() {
[Link]("demo method of super1");
}
}
public class Super2 {
public void demo() {
[Link]("demo method of super2");
}
}

public class SubClass extends Super1, Super2 {


public static void main(String args[]) {
SubClass obj = new SubClass();
[Link](); // multiple inheritance
}
}

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].

The property files are as follows: This is the [Link] file.

• [Link] = Spring Profiles


• [Link] = test
• [Link] = This is the Primary Application Property
Optional
Every Java Programmer is familiar with NullPointerException. It can crash your code. And it is very hard to avoid it without
using too many null checks. So, to overcome this, Java 8 has introduced a new class Optional in [Link] package. It can
help in writing a neat code without using too many null checks. By using Optional, we can specify alternate values to
return or alternate code to run. This makes the code more readable because the facts which were hidden are now visible
to the developer.

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)

In how many ways we can create/get object in java


1) By using new operator.
Test t =new Test ();
2) By using newInstance().

Test t = (Test) [Link](“Test”).newInstance();

3) By using factory method.

Runtime r = [Link]();

DateFormat df = [Link]();

4) By using clone() method

Test t1 = new Test ();

Test t2 = (Test) t1. Clone ();

5) By using deserialization

FileInputStream fis = newFIS(“[Link]”);

ObjectInputStream ois = new OIS(fis);

Dog d2 = (Dog)[Link]();

Java Code Review


Clean Code - Meaningful Names, Comments, Exceptions, Avoid Duplication

Security

Performance - string concatenation, creating unnecessary objects, loops

General- exception handling, JUnit


Core Java
Java Versions
Java 4:

Assertions

Java 5:

For Each loop

Enum

Var args

Static import

Autoboxing and Unboxing

Coverient return types

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:

String in switch statement (Java 7)

Binary Literals (Java 7)

The try-with-resources (Java 7)

Caching Multiple Exceptions by single catch (Java 7)

Underscores in Numeric Literals (Java 7)

Java 8:

Lamda Expressions. Example: Runnable java8Runner = () -> {sop("I am running"); };

Nashorn : javascript engine that enables us to run javascript to run on a jvm

[Link]() function, Streams, functionalInterface, Optional

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

Types of design patterns: There are 3 types of Design Patterns in java.

1. Creational Design Pattern


2. Structural Design Pattern
3. Behavioral Design Pattern

S.
No Creational Structural Behavioral

1 Chain Of Responsibility Pattern


Factory Pattern Adapter Pattern

2 Abstract Factory Pattern Bridge Pattern Command Pattern


3 Singleton Pattern Composite Pattern Interpreter Pattern
4 Prototype Pattern Decorator Pattern Iterator Pattern
5 Builder Pattern Facade Pattern Mediator Pattern
6 Object Pool Flyweight Pattern Memento Pattern
7 Proxy Pattern Observer Pattern
8 State Pattern
9
Strategy Pattern
10
Template Pattern

11
Visitor Pattern

Creational Design Patterns


Factory
A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but
let the subclasses decide which class to instantiate. In other words, subclasses are responsible to create the instance of
the class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design 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.

Usage of Factory Design Pattern:

o When a class doesn't know what sub-classes will be required to create


o When a class wants that its sub-classes specify the objects to be created.
o When the parent classes choose the creation of objects to its sub-classes.
Abstract Factory
Abstract Factory Pattern says that just define an interface or abstract class for creating families of related (or dependent)
objects but without specifying their concrete sub-classes. That means Abstract Factory lets a class returns a factory of
classes. So, this is the reason that Abstract Factory Pattern is one level higher than the Factory Pattern.

An Abstract Factory Pattern is also known as Kit.

Advantage of Abstract Factory Pattern

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.

Usage of Abstract Factory Pattern

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.

// Classical Java implementation of singleton


// design pattern
class Singleton
{
private static Singleton obj;

// private constructor to force use of


// getInstance() to create Singleton object
private Singleton() {}

public static Singleton getInstance()


{
if (obj==null)
obj = new Singleton();
return obj;
}
}

Structural Design Patterns


Adapter Pattern
An Adapter Pattern says that just "converts the interface of a class into another interface that a client wants".

In other words, to provide the interface according to client requirement while using the services of a class with a different
interface.

The Adapter Pattern is also known as Wrapper.

Advantage of Adapter Pattern

o It allows two or more previously incompatible objects to interact.


o It allows reusability of existing functionality.

Usage of Adapter pattern

o When an object needs to utilize an existing class with an incompatible interface.


o When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.
o When you want to create a reusable class that cooperates with classes which don't have compatible interfaces.
Bridge Pattern
A Bridge Pattern says that just "decouple the functional abstraction from the implementation so that the two can vary
independently".

The Bridge Pattern is also known as Handle or Body.

Advantage of Bridge Pattern

o It enables the separation of implementation from the interface.


o It improves the extensibility.
o It allows the hiding of implementation details from the client.

Usage of Bridge Pattern

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".

Advantage of Composite Design Pattern

o It defines class hierarchies that contain primitive and complex objects.


o It makes easier to you to add new kinds of components.
o It provides flexibility of structure with manageable class or interface.

Usage of Composite Pattern

o When you want to represent a full or partial hierarchy of objects.


o When the responsibilities are needed to be added dynamically to the individual objects without affecting other
objects. Where the responsibility of object may vary from time to time.
Decorator Pattern
• Decorator patterns allow a user to add new functionality to an existing object without altering its structure. So,
there is no change to the original class.
• The decorator design pattern is a structural pattern, which provides a wrapper to the existing class.
• The decorator design pattern uses abstract classes or interfaces with the composition to implement the wrapper.
• Decorator design patterns create decorator classes, which wrap the original class and supply additional functionality
by keeping the class methods’ signature unchanged.
• Decorator design patterns are most frequently used for applying single responsibility principles since we divide the
functionality into classes with unique areas of concern.
• The decorator design pattern is structurally almost like the chain of responsibility pattern.

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.

Advantage of Chain of Responsibility Pattern

o It reduces the coupling.


o It adds flexibility while assigning the responsibilities to objects.
o It allows a set of classes to act as one; events produced in one class can be sent to other handler classes with the
help of composition.

Usage of Chain of Responsibility Pattern

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:

• One to many dependency is between Subject(One) and Observer(Many).


• There is dependency as Observers themselves don’t have access to data. They are dependent on Subject to provide
them data.

Language Fundamentals
Identifiers:
➔ A name in java program is called as identifier.
➔ Allowed charters are alphabets, digits, $ and _ only.
➔ Class names are allowed.

int String = 45;


[Link](String); //45
int Runnable = 45;
[Link](Runnable); //45

Reserved words (53):


Reserved Literals (3) -> true, false, null

Keywords (50):

✓ Used (48)
✓ Unused (2): goto and const

Data Types:
Type checking is done by compiler

Byte (1byte (8bits)):

Max_value = +127

Min_value = -128

short (2 bytes (16 bits)):

-32768 to 32767

Int(4 bytes (32 bits))

2-31 to 231 -1

Long

Float

double

Char

Boolean

int x =10; //decimal //10

int y=010; //octal //8

int z=0X10; //hexadecimal //16


[Link](x+" "+y+" "+z);

Arrays:
int[] a = new int[100]; //Size is mandatory

int[] a; //best options

int []a;

int a[];

int[] a; //valid

int[5] b; //invalid

int[] a[],b[]; //valid

int[] []c,[]d; //invalid

int[] a = new int[-3];

[Link](a); //RE: [Link]

int[] a = new int[3];

[Link](a[1]); //0

int[] a = {10,20,30};

int[] b;

b = {10,20,30}; //not valid

sum(new int[]{10,20,30}) //valid

sum(new int[3]{10,20,30}) //not valid

int[] a = {10,20,30};

int[] b = a;

char[] c ={'c'};

int[] d = c; // invalid

public static void main(String[] args) {


for(int i=0;i< [Link] ;i++){

[Link](args[i]); //empty

for(int i=0;i<= [Link] ;i++){ //[Link]

[Link](args[i]);

String[] argh = {"A","B","C"};

args= argh;

for(int i=0;i< [Link] ;i++){

[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;

public static void main(String[] args) {

[Link](x); //cannot access instance variable from static area

Test t = new Test();

[Link](t.x); // can be accessed by using object reference

public void m1(){

[Link](x); // Accessed from instance area directly

int x;

double y;

boolean b;

String s;
public static void main(String[] args) {

Test t = new Test(); //default values are assigned by JVM

[Link](t.x); // 0

[Link](t.y); // 0.0

[Link](t.b); //false

[Link](t.s); //null

Static variable:

static int x;

public static void main(String[] args) {

[Link](x); //accessed in static block

public void m1(){

[Link](x); // accessed in instance block

static int x;

static double y;

static boolean b;

static String s;

public static void main(String[] args) {

Test t = new Test(); //default values are assigned by JVM

[Link](t.x); // 0

[Link](t.y); // 0.0

[Link](t.b); //false

[Link](t.s); //null

private static int x=10;

int y =20;

public static void main(String[] siva) {


Test t1 = new Test();// x=100 ,y = 30

t1.x=100; // x= 100 for every object

t1.y=30;

Test t2 = new Test(); // x=100 ,y = 20

public static void main(String[] siva) {

final int x=10; //only final is allowed for local variable

int[] x;

public static void main(String[] siva) {

Test t = new Test();

[Link](t.x); // null

[Link](t.x[0]); //[Link]

Var args:

Int… x; //valid

Int …x; //valid

Int…x; //valid

M1(String s,int ...d) //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)

public -> to call by JVM from any where

Static -> to call main method without object of the class.

void -> main() won’t return anything to

main -> name configured in JVM


String[] -> Command line arguments.

modifiers place is optional (like public static or static public)

String[] args / String []args / String args[] any way is valid

args -> args is optional , it can be any name

can replace String[] with String…

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.

public final synchronized strictfp static void main(String... anyname)


overloading is possible but JVM consider String[] method

inheritance is applicable

overriding is not applicable

method hiding 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];

public class Test {//public,default,strictfp,final,abstract,private,protected,static

enum Month{ //public,default,strictfp,private,protected,static

JAN, //public static final

FEB,

MAR,

APR; // semicolon is optional if contains only constants

int i =0;

public static void m1(){

[Link]("test");
}

public static void main(String[] args) {

[Link]([Link]); //JAN is object of the ENUM Month

[Link]([Link]); //KT

enum Beer{ // public,default,stripfp

KF,

CB

enum Month{

JAN,

FEB,

MAR,

APR

public static void main(String[] args) {

Month m = [Link];

switch(m){

case JAN: [Link](m); break;

case FEB: [Link](m); break;

case MAR: [Link](m); break;

case APR: [Link](m); break;

default: [Link]("test");

}
public static void main(String[] args) {

Month[] m = [Link](); //to get all values

for(Month m1: m){

[Link](m1+"...."+[Link]()); //JAN….0 FEB…1 MAR…2 APR….3

Month m2 = [Link]("MAR");

[Link](m2); //MAR

Increment and Decrement Operators:


int x=0;

[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;

int z = ++x + y++ + x++ + y++; // ++x(1) y++(0) x++(1) y++(1)

[Link](x);//2

[Link](y);//2

[Link](z);//3

Data Hiding:
Every data member/Variable should be declared as private only.
public class Account {

private double bal;

public double getBal () {

//validation if required

return bal;

Main advantage of data hiding is security.

Note: Recommended data type for a variable is private.

Default data type: public

Abstraction:
Hides internal implementation of the services but just highlight set of the services available.

Advantages: Security, Easy Enhancement, Easy to use, Maintainability.

By using Abstract class and interfaces we can implement Abstraction.

When should I use abstract class and interface?

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

Encapsulation = data hiding + Abstraction.


public class Account {
private double bal;

public double getBal () {


//validation
return bal;
}

Public void setBal(double bal) {


//validation
[Link] = bal;
}
}

Advantage: security

Disadvantage: It increases length of the code and slow down execution

Tightly Encapsulated Class:


Each and every variable in a class are declared as private. Getters and setters/ declared as public are optional.

Public class Account{

Private double bal;

IS - A Relation
Also known as inheritance using extends keyword.

Advantage: Reusability

Class p {

Public void m1(){

Sop(“m1”);

Class C extends P{

Public void m2(){

Sop(“m2”);
}

Class Test{

Public static void main(String[] args){

1) P p= new P();

p.m1(); Valid

p.m2(); complie time error : Cannot find symbol : method m2 in class P

2) C c = new C();

c.m1();Valid

c.m2();Valid

*Polymorphism 3) P p2 = new C();

P2.m1();Valid

P2.m2();complie time error : Cannot find symbol : method m2 in class P

4) C c2 = new P();Incompatible types found : P required : C

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.

Class A { } -> Direct child of Object.

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 () {}

Class C extends A, B {} -> Not possible

But interface can extend any number of interfaces simultantiously hence java provides support multiple inheritance with
respect to interfaces.

Interface -> PI1 with m1 ()

Interface -> pI2 with m1 ()

CI -> m1 () implementation will provided by the CI and have only unique implementation.

Class A extends A {} -> Cyclic Inheritance -> Not allowed in java

Class A extends B {} and Class B extends A {} -> Cyclic Inheritance -> Not allowed in java

Will get compile time: Cyclic inheritance involving A.

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 {

Engine E = new Engine ();

Car Has-A Engine reference.

Difference b/w composition and Aggregation


composition:

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.

Container object just have the reference of contained objects.

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)

Return type is not part of method signature in java.

Class Test
M m1 (int)

m2 (String)

Method Table

Compiler will use method signature to resolve method calls.

m1 (10); ->Valid

m2 (“Santhosh”); -> 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);

Also known as compile time polymorphism, static polymorphism, early binding.

public class Test {

public void m1(int i){

[Link]("int-args");

public void m1(float i){

[Link]("float-args");
}

Test t = new test ();

t. m1 (10); int-args

t. m1 (10.5f); float-args

t.m1 (‘a’); int-args

t.m1 (10l); float-args

t.m1 (10.5); CE: cannot find symbol double

byte -> short

int -> long -> float-> double.

char

public class Test {

public void m1(String s){

[Link]("String");

public void m1(Object o){

[Link]("object");

public void m1(Integer s){

[Link]("String");

public void m1(StringBuffer s){

[Link]("StringBuffer ");

}
t. m1 (new Object ()); object

t. m1 (“Santhosh”); String

t. m1 (null); String -> because child class will get preference.

t. m1 (null); CE: m1 (object) ambiguous for the type t. (with two object (string/integer))

t. m1 (“string”); -> String

t. m1 (new StringBuffer (“string”)); -> StringBuffer

public class Test {

public void m1(int I,float f){

[Link]("int");

public void m1(float o,int i){

[Link]("float");

t. m1 (10,10.5f) -> int

t. m1 (10.5f,10) -> float

t. m1 (10,10) -> CE: m1 (object) ambiguous for the type t.

t. m1 (10.5f,10.5f) -> CE: cannot find symbol

public class Test {

public void m1(int i){

[Link]("int");

public void m1(int… i){

[Link]("args");

t. m1(); -> args


t. m1(10,20) -> args

t. m1(10) -> int

class Animal {}

class Monkey extends Animal {}

public class Test {

public void m1(Animal a){

[Link]("animal");

public void m1(Monkey m){

[Link]("monkey");

Animal a = new Animal ();

t. m1 (a); -> animal

Monkey m = new Monkey ();

t. m1 (m); -> monkey

Animal a1 = new Monkey ();

t. m1 (a1); -> animal

Method Overriding

Class P {

public void property () {

sop (“land,money”);

Public void marry () {

Sop (“test”);

}
}

Class C extends P {

Public void marry () {

Sop (“test54756”);

}}

P p = new P ();

[Link] (); -> parent method

C c =new C ();

[Link](); -> child method

P p = new C ();

[Link](); -> child method

** 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.

Rules for overriding:

1) Method signatures must be same.


2) Return types must be same (until 1.4V). Co variant return types also allowed (From 1.5V).
Class P {
public Object property () {
sop (“land,money”); } }

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

Object -> object | String | StringBuffer

Number -> Number | Integer|

String -> Object -> not valid

double -> int -> not valid

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.

➔ Overriding the parent class final method is not possible.


➢ CE: m1 in C cannot override in P; overridden method is final.
➔ Parent class abstract method must be override in child class to provide implementation.
➔ We can override non abstract method as abstract method as abstract.
Class P {
public Object property () {
sop (“land,money”); } }

abstract Class C extends P {


Public abstract Object property ();
}

In overriding the following modifiers won’t keep any restrictions: synchronized, native, Strictfp

Parent Method Child Method Valid /invalid

Final non final/final not valid

Non final final valid


Abstract non abstract valid

Synchronized non synchronized valid

Native nonnative valid

Strictfp Strictfp valid

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

Private < default < protected < public

Parent Method Child Method

Public public

Protected protected /public

Default default/ protected /public

Private overriding is not applicable

➔ 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.

Overriding with respect to static methods:

➔ We cannot override a static method as non-static.


Class P {
Public static void m1 () {
}}
Class C extends P {
Public void m1 () {}
}
CE: m1 () in C cannot override m1 ( ) in P; overridden method is static.
➔ We cannot override a non-static method as static.
Class P {
Public void m1 () {
}}
Class C extends P {
Public static void m1 () {}
}
CE: m1 () in C cannot override m1 ( ) in P; overriding method is static.

➔ 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 {

Public static void m1 () {

}}

Class C extends P {

Public static void m1 () {} }

Rules of Method Overriding:

Rule #1:Final and static methods cannot be overridden.


Rule #2: The overriding method must have same argument list.
Rule #3: The overriding method must have same return type (or subtype).
Rule #4: The overriding method must should not decrease the scope
Rule #5: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked
exception but it can declare unchecked exception.
Rule #6: If the superclass method declares an exception, subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent exception.

Method hiding:
P p =new P ();

p. m1 (); -> parent

C c = new C ();

c. m1 (); -> child

P p1 = new C ();
p. m1 (); -> parent (because of static methods)

Method overriding with var-args:

Var-arg method can override only by other var-arg method only.

Class P {

Public void m1 (int… i) {

Sop(“parent”);

}}

Class C extends P {

Public void m1 (int i) {

Sop(“child”);

P p =new P ();

p. m1 (10); -> parent

C c = new C ();

c. m1 (10); -> child

P p1 = new C ();

p. m1 (10); -> parent (because of overloading)

➔ Overriding is applicable to methods not to variables.

Class P {

Int a= 888;

Class C extends P {
Int a=999;

P p =new P ();

p. x; -> 888

C c = new C ();

c.x; -> 999

P p1 = new C ();

P1.x; -> 888

• If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass overridden method cannot declare the
checked exception but it can declare unchecked exception.
• If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method can declare same, subclass
exception or no exception but cannot declare parent exception.

Property Over loading Over riding

Method name Same Same

Method Types Different Same(including order)

Method signature Different Same

Return types No restrictions Same(1.4V) co variant(1.5V)

Private , static, final No restrictions Cannot be over ridden

Access modifiers No restrictions Cant reduce the scope , can increase

Throws No restrictions If child class throws any checked


exception then parent class through same
or its parent exception. NO restriction on
unchecked exceptions.

Method resolution Compiler JVM

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.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late 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

When type of the object is determined at run-time, it is known as dynamic binding.

Coupling
The degree of dependency b/w the component is called coupling.

Loosely coupling is a good programming practice.

Cohesion
For every component a clear well-defined functionality is defined then that component is said to be follow high cohesion.

Object Type Casting


We can use parent reference to hold child object.

Object o =new String (“test”);

We can use interface reference to hold implemented class object.

Runnable r= new Thread ():


A b = (H) d;

A-> class/interface name

B -> name of reference variable

H -> class/interface name

D -> reference variable name

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.

Object o =new String (“test”);

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;

RE: ClassCastException : [Link] cannot cast to [Link]

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.

Static control flow


➔ Whenever are executing a java class the following sequence of steps will be executed as the part of static control
flow.

1) Identification of static member from top to bottom. [1-6]


2) Execution of static variable assignments and static blocks from top to bottom. [7-12]
3) Execution of main method.[13-15]

I=0 [Read indirectly write only]

J=0 [Read indirectly write only]


I=10 [read and write]

J=20 [read and write]

Class Base {

Static int I=10; (1.i=0, 7.i=10)

Static { (2)

M1 (); (8)

Sop (“static”);(10)

P static v main(s [] a){ (3)

M1 (); (13)

s.o.p (main);(15)

P static v m1 (){ (4)

Sop (j); (9,14)

Static {(5)

s.o.p (second block) ; (11)

static int j=20; (6.j=0,12.j=20)

O/P:

static

second block

20
main

Read indirectly write only:

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 int I=10;

Static {

M1 ();

Sop (I); -> direct read

P static v m1 () {

Sop (I); -> indirect read

Examples:

Class Test {

Static int x=10;

Static {

Sop(x);

O/P: 10 RE: nosunchmethodError: main

Class Test {

Static {

Sop(x);

Static int x=10;

O/P: illegal forward reference


Static block
➔ Static blocks will be executed at the time of class loading. Hence at the time of class loading if we want to perform
any activity, we have to define that inside static block.
➔ Whenever we are executing child class the following sequence of events will be executed automatically as the part of
static control flow.
1. Identification of static member from parent to child (top to bottom)
2. Execution of static variable assignments and static blocks from parent to child (top to bottom).
3. Execution of child class main method.

Instance control Flow


➔ Whenever we are executing a java class first static control flow will be executed.
➔ In the static control flow if we are creating an object the following sequence of events will be executed as the part of
instance control flow.
1. Identification of instance members from top to bottom.
2. Execution of instance variable assignments and instance blocks from top to bottom.
3. Execution of constructors.
➔ Whenever we are creating child class object the following sequence of events will be executed automatically as the
part of instance control flow.
1. Identification of instance members from parent to child.
2. Execution of instance variable assignments and instance blocks in parent class.
3. Execution of constructors in parent class.
4. Execution of instance variable assignments and instance blocks in child class.
5. Execution of constructors in child class.

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.

public class Student {

String name;

int rollNo;

Student( String name,int rollNo){ //Constructor

[Link] = name;

[Link] = rollNo;

public static void main(String args[]) {

Student t =new Student ("test", 12);


Student t1 =new Student ("testd", 122);

Difference b/w constructor and instance block:

➔ 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:

1) Name of the class and name of the constructor must be matched.


2) Return Type concept not applicable to the constructor.
3) By mistake if we declare return type for the constructor then we won’t get any compile time error, because
compiler treats it as
4) Only modifier applicable to constructor are public, private, protected and default. For others CE: Illegal modifier
for the constructor in type Student; only public, protected & private are permitted

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.

super () , this () super, this

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];

public class Student {

Student(){

this(10);

Student(int i){

this();

CE: Recursive constructor invocation

Singleton Class
➔ For any java class if we are allowed to create only one object such type of class is called singleton class.

E.g., Runtime, ServiceLocator

Runtime r1 = [Link]();

How to create our own singleton class:

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:

public class Test {


private static Test t = new Test();

private Test() {
}

public static Test getTest() {


return t;
}
}
Approach 2:

class Test {
private static Test t = null;

private Test() {
}

public static Test getTest() {


if (t == null) {
t = new Test();
}
return t;
}
}

➔ By declaring the constructor as private we can’t extend that class.

Ways to break Singleton:

public class Singleton implements Serializable, Cloneable {

/**
*
*/
private static final long serialVersionUID = 1L;
private static Singleton singleton;

private Singleton() {
};

public static Singleton getInstance() {


if (singleton == null)
singleton = new Singleton();
return singleton;
}

@Override
protected Object clone() throws CloneNotSupportedException {
return [Link]();
}
}

Beaking class:

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class BreakingSingleton {

public static void main(String[] args) throws Exception {


Singleton originalSinglton = [Link]();
Singleton duplicateSingleton = [Link]();

[Link]("Orignal Singleton class hashcode: " +


[Link]()); // 1865127310
[Link]("Duplicate Singleton class hashcode: " +
[Link]()); // 1865127310

[Link]("_________________________________________________");
// Reflection
Class<?> sampleClass = [Link]("[Link]");
Constructor<Singleton> constructor = (Constructor<Singleton>)
[Link]();
[Link](true);

Singleton reflectionSingleton = [Link]();


[Link]("Orignal Singleton class hashcode: " +
[Link]()); // 1865127310
[Link]("Reflection Singleton class hashcode: " +
[Link]()); // 1586600255

[Link]("_________________________________________________");

// Serialization
ObjectOutputStream outputStream = new ObjectOutputStream(new
FileOutputStream("[Link]"));
[Link](originalSinglton);
[Link]();

ObjectInputStream inputStream = new ObjectInputStream(new


FileInputStream("[Link]"));
Class<? extends ObjectInputStream> serilizedSingleton = [Link]();
[Link]();

[Link]("Orignal Singleton class hashcode: " +


[Link]()); // 1865127310
[Link]("Serilizable Singleton class hashcode: " +
[Link]()); // 205125520

[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.

public enum Singleton


{
INSTANCE;
}

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.

Serialization: To overcome this issue, we must implement method readResolve() method.

// implement readResolve method


protected Object readResolve() {
return singleton;
}

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();
}

Java source file structure:


➔ A java program can contain any number of classes but at most one class can be declared as public. If there is a public
class then name of the program and name of the public class must be matched otherwise we will get compile time
error.
➔ If there is no public class then, we can use any name and there no restrictions.
➔ If class B is public then name of the program should be [Link], otherwise we will get compile time error saying “the
public type B must be defined in its own file.”
➔ If class B and C are declared as public then name of the program is [Link], then we will get compile time error saying
“the public type C must be defined in its own file.”

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.

➔ Javac –d . [Link] (d -> destination to . (dot) -> current working directory)

➔ If directory not available ,CE: directory not found


➔ If two packages are defined, CE: class, interface or enum excepted
Modifiers
✓ The private access modifier is accessible only within class.
✓ If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within
package.
✓ The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on
the class.
✓ The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

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

Class lever modifiers


➔ Applicable modifiers for top level classes are public, default, final, abstract, strictfp.
➔ For inner classes are public, default, final, abstract, strictfp, private, protected, static.

Abstract:

➔ Applicable to class and method.

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:

➔ Applicable to methods, variables and inner classes (static nested classes).


➔ Instance variables can be access in instance and static blocks and static variables can be accessed from static
block only.
➔ Overloading concept applicable for static methods including main method but jvm will always call string[] main
method only.

public class Test {

public static void main(String[] args) {

[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:

➔ Any service requirement between client and server.


➔ 100% pure abstract class.

Declarations and implementation:

➔ Implements using implements key word

E.g., Class test implements TestInterface

Extends and implements:

➔ A class can extend one class at a time


➔ An interface can extends any number of interfaces simultaneously.
e.g., interface C extends A, B
➔ A class implements any number of interfaces simultaneously.
➔ A class can extend another class and implements any number of interfaces simultaneously.
➔ Extends followed by implements.
E.g., Class test extends Test1 implements TestInterface

Interface methods:

➔ Every method present in interface is public and abstract.

Interface variables:

➔ To define requirement level constants.


➔ It is public static final always
Method naming conflicts:
➔ Two Interfaces with same signature and same return type -> implements only one’s

public interface A {

public abstract void a1();

public interface b {

public abstract void a1();

public class test implements A, B {

@Override

public void a1() {

//IMPLEMENTATION

➔ Two Interfaces with same name but different argument types. -> implementation for both methods.(overloaded)

public interface A {

public abstract void a1();

public interface b {

public abstract void a1(int i);

public class test implements A, B {

@Override

public void a1() {

//IMPLEMENTATION
}

@Override

public void a1(int i) {

//IMPLEMENTATION

➔ Two Interfaces with same signature but different return types. -> implementation is not possible

public interface A {

public abstract void a1();

public interface b {

public abstract int a1();}

Variable naming conflicts:


➔ Variable contains same name then we have to access using the interface name as its static or else will get CE:
ambiguous

public interface A {

int x= 23;

public interface B {

int x= 233;

public class test implements A, B {

public static void main(String[] args) {

[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.

E.g., Serializable, Clonable, RandomAccess.

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:

// Java Program illustrating Use of Custom Annotation

// Importing input output classes


import [Link].*;

// Sample for marker annotation:


// Custom annotation declaration
@interface books_data
{
// Multiple variable declaration
String book_name();
int book_price();
String author();
}

// Using the custom Annotation


@books_data(book_name = "Effective Java", book_price = 30,
author = "Joshua Bloch")

// Class 1
class book_store {
}

// Class 2
class books {

// Main driver method


public static void main(String[] args)
{
// Print statement
[Link]("how to use the annotations");
}
}
Collections

FailFast and FailSafe Iterators in Java:


Iterators in java are used to iterate over the Collection objects.

Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the


collection. Structural modification means adding, removing or updating any element from collection while a thread is
iterating over that collection.
Iterator on ArrayList, HashMap classes are some examples of fail-fast Iterator.

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.

Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe Iterator.

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

Fixed in size Growable in nature

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

Homogeneous Hemo and Hetero

Underlying DS is not available Consists of Standard DS.

Primitives and objects Only objects

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.

Interfaces in Collection Framework:


Collection (I):
➔ Collection interface defines the most common methods which are applicable for any Collection object.

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)

ArrayList LinkedList Vector


Stack

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)

LinkedHashSet NavagableSet (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)

HashMap WeakHashmap IdentityHashMap HashTree SortedMap (I)

LinkedHashmap Properties NavagableMap (I)

TreeMap

➔ Comparable (I): When default sorting is required


➔ Comparator (I): When Customized sorting is required.

Cursors: To get the objects from Collection

➔ Enumeration
➔ Iterator
➔ ListIterator

Utility Classes:

✓ Collections
✓ Arrays

Methods:

boolean add (Object o)

boolean addAll (Collection c)

boolean remove (Object 0)

boolean removeAll (Collection c)

void clear() -> to remove all elements in a collection


boolean retainAll (Collection c)

Boolean isEmpty()

int size()

boolean contains (Object o)

boolean containsAll (Collection C)

Object[] toArray ()

Iterator iterator ()

List (I):
✓ We can differentiate duplicates by using index.

Void add (Object o)

Boolean addAll (int index, Collection c)

Object get (int index)

Object remove (int index)

Object set (int index, Object o)

Int indexOf (Object o)

Int lastIndexOf (Object o)

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.

Note: In TreeMap and TreeSet Heterogeneous object are not allowed.

Constructors:
ArrayList al =new ArrayList ();

➢ Creates empty array list with initial capacity of 10.


➢ New capacity = (currentCapaticy*3/2) +1.

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.

What are the advantages of ArrayList over arrays?


Some of the advantages ArrayList has over arrays are:

• It can grow dynamically


• It provides more powerful insertion and search mechanisms than arrays.

ArrayList and Vector:


ArrayList Vector
Methods are Non Synchronized Methods are Synchronized

Not Thread safe Thread Safe

Performance is relatively High Performance is relatively low

Non Legacy (1.2V) Legacy(1.0V)

ArrayList can use only Iterator to access. Vector list can use Iterator and Enumeration
elements.

How to obtain Array from an ArrayList ?

ArrayList. List arrayList = new ArrayList();


ObjectA a[] = [Link]();

To make ArrayList Synchronized:

ArrayList<String> list = new ArrayList<String> ();


[Link] ("fgdf");
[Link] ("fgdff");
List<String> I = [Link] (list);
[Link] (set);
[Link] (map);
[Link] (I);

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:

1) LinkedList l = new LinkedList();


2) LinkedList l – new LinkedList(Collection c);

ArrayList LinkedList

Best choice if frequent operation is Retrieval Best choice if frequent operation is insertion and
deletion

Resizable array Doubly linked list

Implements Random access Not implements Random Access

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:

1) Vector v = new Vector ();

Initial capacity = 10

New capacity = 2 * current capacity

2) Vector v = new Vector(int capacity);


3) Vector v = new Vector(int initialcapacity, int increment);
4) Vector v = new Vector (Collection c);
Stack
✓ Child class of Vector
✓ LIFO

Methods:

push (Object o) -> insert

pop (Object o) -> removed and return top of the stack

peek () -> return top of the stack

empty () -> to check the stack is empty or not

search (Object o) -> returns offset if available if not -1

Cursors
✓ Enumeration
✓ Iterator
✓ ListIterator

Enumeration:

✓ unidirectional
✓ only read access

Vector v = new Vector ();

Enumeration e =[Link] ();

Methods:

hasMoreElements ();

nextElement ();

E.g.

Vector<String> v = new Vector<String> ();

[Link] ("A");

[Link] ("B");

[Link] ("C");

[Link] ("D");

Enumeration<String> e = [Link] ();

While ([Link] ()) {

[Link] ([Link] ());


}

Iterator:

✓ Unidirectional
✓ Universal cursor.
✓ Read and Remove access.

Public Iterator iterator ();

Iterator iterator = C. iterator ();

Methods:

public boolean hasnext()

public Object next()

public void remove()

List<Integer> list = new ArrayList<Integer>();

for(int i=0;i<=10;i++)

[Link](i);

[Link](list);

Iterator<Integer> iterator = [Link]();

while([Link]()){

Integer n = [Link]();

if(n % 2 ==0)

[Link](n);

else

[Link]();

[Link](list);

ListIterator:

✓ Bidirectional
✓ Read , remove , replace, addition of new objects

Public ListIterator listIterator();


Iterator iterator = l. iterator ();

Methods:

Public boolean hasNext()

Public Object next()

Public int nextIndex()

Public boolean hasPrevious()

Public Object previous()

Public int perviousIndex()

Public void remove(Object o)

Public void set(Object new)

Public void add(Object new)

List<Integer> list = new ArrayList<Integer>();

for(int i=0;i<=10;i++)

[Link](i);

[Link](list);

ListIterator<Integer> iterator = [Link]();

while([Link]()){

Integer n = [Link]();

if(n==2)

[Link]();

else if(n==4 )

[Link](44);

else if(n==8)

[Link](45);

[Link](list);

o/p: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[0, 1, 3, 44, 5, 6, 7, 8, 45, 9, 10]

Spliterator
trySplit(): Splits this spliterator into two and returns the new one.

List<String> list = [Link]("Apple", "Banana", "Orange");

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

tryAdvance() and forEachRemaining()

List<String> list = [Link]("Apple", "Banana", "Orange");


Spliterator<String> s = [Link]();
[Link]([Link]::println);
[Link](" --- bulk traversal");
[Link]([Link]::println);

[Link](" --- attempting tryAdvance again");


boolean b = [Link]([Link]::println);
[Link]("Element exists: "+b);
Output:
Apple
--- bulk traversal
Banana
Orange
--- attempting tryAdvance again
Element exists: false

Property Enumeration Iterator ListIterator

Applicable for Vector All List

Movement Forward Forward Forward/Backward


Accessibility Read Read and remove Read, remove, replace, add

How to get it? Elements() iterator() listIterator()

Is it legacy? Yes No No

HashSet
✓ Duplicates are not allowed.

HashSet<String> hashSet = new HashSet<String>();

[Link]("A");

[Link]("A");

[Link]("A");

[Link]("A");

[Link](hashSet);

O/P: [A] -> duplicates will not add into the set.

✓ Insertion order is not preserved. Insertion based on hashcode.


✓ Hashtable
✓ heterogonous objects are allowed
✓ null is allowed
✓ Frequent operation is search then HashSet is best choice.
✓ Default initial capacity is 16 and fill ratio(Load Factor) : 0.75

Constructers:

HashSet<String> hashSet = new HashSet<String>();

HashSet<String> hashSet = new HashSet<String>(int initialcapacity);

HashSet<String> hashSet = new HashSet<String>(int initialcapacity, float loadFactor);

HashSet<String> hashSet = new HashSet<String>(Collection C);

HashSet Internal Working

✓ HashSet internally uses HashMap to store it’s elements.


✓ Whenever you create a HashSet object, one HashMap object associated with it is also created.
✓ This HashMap object is used to store the elements you enter in the HashSet.
✓ The elements you add into HashSet are stored as keys of this HashMap object.
✓ The value associated with those keys will be a constant.

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.

// Dummy value to associate with an Object in the backing Map


private static final Object PRESENT = new Object();

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

LinkedHashSet<String> hashSet = new LinkedHashSet<String>();

[Link]("A");

[Link]("A");

[Link]("A");

[Link](null);

[Link](null);

[Link](hashSet);

O/P: [A, null]


SortedSet(I)
✓ Duplicates are not allowed.
✓ Insertion based on some sorting order.
100
Methods:
101
First() -> 100
103
Last() -> 115
104
headSet(104) -> 100 101 103
107
tailSet(104) -> 107 110 115
110
subset(103,110) -> 103 104 107
115
comparator() -> null

✓ Ascending order is default sorting order.

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:

TreeSet t = new TreeSet(); -> inserted in default sorting order.

TreeSet t = new TreeSet(Comparator C) -> Customized sorting order

TreeSet t = new TreeSet(Collection C)

TreeSet t = new TreeSet(SortedSet S)

TreeSet<String> set = new TreeSet<String>();

[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.

TreeSet<StringBuffer> buffers = new TreeSet<StringBuffer>();

[Link](new StringBuffer("A"));

[Link](new StringBuffer("Z"));

[Link](new StringBuffer("V"));

[Link](new StringBuffer("C"));

[Link](buffers);

RE:ClassCastException

✓ For Default sorting order should be homogeneous and comparable.

Comparable (I)
It is present in java lang package and it contains only one method (compareTo()).

Public int compareTo(Object o)

[Link](obj2):

-ve -> if obj1 > obj2 (obj1 before obj2)

0 -> equal

+ve -> if obj1 < obj 2 (obj1 after obj2)

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);

-ve -> if obj1 > obj2 (obj1 before obj2)

0 -> equal

+ve -> if obj1 < obj 2 (obj1 after obj2)

public boolean equals (Object obj)

✓ When we implement comparator, we have to provide implementation to compare() method only.

TreeSet<Integer> buffers = new TreeSet<Integer>(new Dot());

[Link](100);

[Link](45);

[Link](74);

[Link](56);

[Link](0);

[Link](5);

[Link](buffers);

public class Dot implements Comparator<Integer>{

@Override

public int compare(Integer i1, Integer i2) {

if(i1 < i2)

return 1;

else if(i1 > i2)

return -1; -> Descending order

else

return 0;

}
@Override

public int compare(Integer i1, Integer i2) {

return ([Link](i2)); -> Ascending order

@Override

public int compare(Integer i1, Integer i2) {

return (-[Link](i2)); -> Descending order

@Override

public int compare(Integer i1, Integer i2) {

return [Link](i1); -> Descending order

@Override

public int compare(Integer i1, Integer i2) {

return -[Link](i1); -> Ascending order

@Override

public int compare(Integer i1, Integer i2) {

return +1;-> Insertion order with duplicates

@Override

public int compare(Integer i1, Integer i2) {

return -1;-> Reverse of Insertion order with duplicates

@Override

public int compare(Integer i1, Integer i2) {

return 0;-> Only 1st element


}

O/P: [100, 74, 56, 45, 5, 0]

Map (I):
✓ Used to represent a group of objects as a key value pair.

Methods:

Object put (Object key, Object value);

Eg: [Link](101,”test1”); -> null

[Link](102,”test2”); -> null

[Link](101,”test3”); -> test1 and 101 key value is test3

void putAll(Map m)

Object get(Key)

Object remove(key )

Boolean containsKey(k)

Boolean containsValue(value)

Boolean isEmpty()

Int size()

Void clear()

Collection views of Maps:

Set keySet() ->to get all keys

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:

HashMap m = new HashMap();

Initial capcity = 16

Fill ratio = 0.75

HashMap m = new HashMap(int initial capcity);

HashMap m = new HashMap(int initial capcity,float fillratio);

HashMap m = new HashMap(Map m);

HashMap<String,Integer> buffers = new HashMap<String,Integer>();

[Link]("A",100);

[Link]("B",200);

[Link]("C",300);

[Link]("D",400);

[Link](buffers);

[Link]([Link]("A",500));

[Link](buffers);
Set<String> s = [Link]();

[Link]("All Keys: "+s);

Collection<Integer> c = [Link]();

[Link]("All Values: "+c);

Set<Entry<String, Integer>> e = [Link]();

[Link]("EntrySet: "+e);

[Link]("Entry Methods:");

Iterator<Entry<String, Integer>> itr = [Link]();

while([Link]()){

[Link]<String,Integer> entry = [Link]();

[Link]([Link]());

[Link]([Link]());

O/P:

{A=100, B=200, C=300, D=400}

100

{A=500, B=200, C=300, D=400}

All Keys: [A, B, C, D]

All Values: [500, 200, 300, 400]

EntrySet: [A=500, B=200, C=300, D=400]

Entry Methods

500

200

300
D

400

HashMap and Hashtable:

Not Synchronized Synchronized

Not Thread safe Thread safe

Relatively performance is high Relatively performance is low

Null is allowed for key and value Null is not allowed for key and value

Not legacy Legacy

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)

HashMap<String,Integer> buffers = new HashMap<String,Integer>();

[Link]("A",100);

[Link]("B",200);

[Link]("C",300);

[Link]("D",400);

[Link](buffers);

Map<String, Integer> m = [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.

LinkedHashMap<String,Integer> buffers = new LinkedHashMap<String,Integer>();

[Link]("A",100);

[Link]("C",200);

[Link]("B",300);

[Link]("D",400);

[Link](buffers);

O/P: {A=100, C=200, B=300, D=400}

IdentityHashMap
== -> Used to compare reference or objects

equals() -> Used to compare values

✓ 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.

HashMap<Integer,String> buffers = new HashMap<Integer,String>();

Integer i1 = new Integer(10);

Integer i2 = new Integer(10);

[Link](i1, "A");

[Link](i2, "B");

//HashMap used equals() to compare the keys on insertion

[Link](buffers); // -> {10=B}

IdentityHashMap<Integer,String> identityHashMap = new IdentityHashMap<Integer,String>();

Integer i3 = new Integer(10);

Integer i4 = new Integer(10);

[Link](i3, "A");

[Link](i4, "B");

//IdentityHashMap used == to compare the keys on insertion

[Link](identityHashMap); // -> {10=A, 10=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.

HashMap<Object,String> buffers = new HashMap<Object,String>();

Dot dot = new Dot();

[Link](dot, "A");

[Link](buffers); // -> {temp=A}

dot = null;

[Link]();

[Link](5000);
[Link](buffers); // -> {temp=A}

WeakHashMap<Object,String> buffers1 = new WeakHashMap<Object,String>();

Dot dot1 = new Dot();

[Link](dot1, "A");

[Link](buffers1); // -> {temp=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

TreeMap t = new TreeMap (); -> inserted in default sorting order.

TreeMap t = new TreeMap (Comparator C) -> Customized sorting order

TreeMap t = new TreeMap (Collection C)

TreeMap t = new TreeMap (SortedMap S)

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.

HashTable h = new HashTable();

Initial capacity = 11
Fill ratio = 0.75

HashTable h = new HashTable(int initialCapacity);

HashTable h = new HashTable(int initialCapacity , float fillRatio);

HashTable h = new HashTable(Map m);

Properties:

✓ Both key and value must be strings

String getProperty(Sting Pname);

String setProperty(String Pname, StringPvalue);

Enumeration propertyNames();

Void load(InputStream i);

Void store(OutputStream out,String comments);

Queues
✓ FIFO

Methods:

offer(Object o) -> to add into queue

poll() -> to remove and return head element, if empty returns null

remove() -> to remove and return head element, if empty RE: NoSuchElementException

peek() -> to return head element, if empty returns null

element() -> to return head element, if empty RE: NoSuchElementException

PiriorityQueue

✓ Inserted with some priority.


✓ Priority is based on default or customized.
✓ Duplicates are not allowed
✓ Heterogonous objects are not allowed (Default sorting order)
✓ Null is not allowed

PriorityQueue q = new PriorityQueue();

Init = 11
PriorityQueue q = new PriorityQueue(int initial);

PriorityQueue q = new PriorityQueue(int initial, Comparator c);

PriorityQueue q = new PriorityQueue(SortedSet S);

PriorityQueue q = new PriorityQueue(Collection C);

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.

What kind of problems can be solved by using blocking queue?

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.

The BlockingQueue are two types:

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.

BlockingQueue blockingQueue = new LinkedBlockingDeque();

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

BlockingQueue blockingQueue = new LinkedBlockingDeque(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.

// Java program that explains the internal


// implementation of BlockingQueue

import [Link].*;
import [Link].*;

class BlockingQueue<E> {

// BlockingQueue using LinkedList structure


// with a constraint on capacity
private List<E> queue = new LinkedList<E>();

// limit variable to define capacity


private int limit = 10;

// constructor of BlockingQueue
public BlockingQueue(int limit) { [Link] = limit; }

// enqueue method that throws Exception


// when you try to insert after the limit
public synchronized void enqueue(E item)
throws InterruptedException
{
while ([Link]() == [Link]) {
wait();
}
if ([Link]() == 0) {
notifyAll();
}
[Link](item);
}

// dequeue methods that throws Exception


// when you try to remove element from an
// empty queue
public synchronized E dequeue()
throws InterruptedException
{
while ([Link]() == 0) {
wait();
}
if ([Link]() == [Link]) {
notifyAll();
}

return [Link](0);
}

public static void main(String []args)


{
}
}
Collections:
Public static void sort(List l);

Public static void sort(List l, Comparator C);

Public static int binarySearch(List l,Object target);

Public static int binarySearch(List l,Object target, Comparator C);

List<String> list = new ArrayList<String>();

[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

[Link]([Link](list, "S")); //-7 insertion point

[Link]([Link](list,"A",new Dot())); // 0 Ascending -


7 descending

Successful result range : 0 to (n-1)

Unsuccessful result range : -(n+1) to -1

Total range : -(n+1) to n-1

public static void reverse(List l)


Flow Control
1) Selective Statements
✓ If-else
✓ Switch ()
2) Iterative Statements
✓ While()
✓ Do-while()
✓ For
✓ For-each loop
3) Transfer Statements
✓ Break
✓ Continue
✓ Return
✓ Try- catch finally
✓ Assert

If-else:
boolean b = true;

if (b = false) {

[Link]("if");

} else {

[Link]("else"); // o/p: else

if(true)

int x = 10; // Invalid - should not be declarative statement

if(true) {

int x = 10; // Valid

if(true)

if(true)

[Link]("if");

else

[Link]("else"); // else is related to nearest if

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

// String also from 1.7V

case 1:

[Link]("1");break;
case 8:

[Link]("8");break;

[Link]
✓ Every class in java is child class of object.

Methods in Object class (11 methods):

public String toString()

public native int hashcode()

public boolean equals(Object o)

protected native Object clone() throws CloneNotSupportedException

protected void finalize() throws Throwable

public final Class getClass()

public final void wait() throws InterrruptedException

public final native void wait(long ms) throws InterrruptedException

public final void wait(long ms,int ns) throws InterrruptedException

public native final void notify()

public native final void notifyAll()

private static native void registerNatives() -> Internally required for Object class

toString() -> to get String representation of Object.

equals() -> Used to check reference comparison.

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.

public boolean equals(Object object) {


return this == object;
}

public int hashCode() {


return [Link](this);
}
how to improve performance by using final keyword

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.

What is the security of the final class in Java?

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)

String s = new String("test");

[Link]("123");

[Link](s); //test

String s1 = [Link]("123");

[Link](s1); //test123

StringBuffer sb = new StringBuffer("test");

[Link]("123");

[Link](sb); //test123

String s = new String("test");

String s1 = new String("test");

[Link](s == s1); //false

[Link]([Link](s1)); //true (.equals() for content comparison for String class)

StringBuffer sb = new StringBuffer("test");

StringBuffer sb1 = new StringBuffer("test");

[Link](sb == sb1); //false

[Link]([Link](sb1)); //false
String s = new String("test"); // object created in heap area(referred) and string Constant
pool

String s = "test"; // object created in string Constant pool(referred)

String s1 = new String("test"); //new object

String s2 = new String("test"); //new object

String s3 ="test"; // new object

String s4 ="test"; // referred to s3 //total 3 objects

String s1 = new String("test"); // new object

[Link]("123"); // new object

String s2 = [Link]("456"); // new object

s1 = [Link]("789"); // new object

[Link](s1); //test789

[Link](s2); //test456

Constructors:
String s = new String();

String s = new String(String literal);

String s = new String(StringBuffer sb);

String s = new String(char[] ch);

String s = new String(Byte[] b);

Methods:
charAt(int index) -> returns the character locating at specified index.

String s = new String("test 123");

[Link]([Link](5)); // 1

[Link]([Link](45)); // [Link]:String index out


of range: 45

contact(String s)
String s = new String("test");

[Link]("123");

s = s+ "123";

s += "123";

equals(Object o)

equalsIgnoreCase(String s)

String s = new String("test");

[Link]([Link]("Test")); //false

[Link]([Link]("Test")); //true

substring(int index)

substring(int beginIndex, int endIndex)

String s = new String("test123");

[Link]([Link](2)); //st123

[Link]([Link](2,5)); //st1

length()

String s = new String("test 123")

[Link]([Link]()); //8

replace(char oldChar,char newChar)

String s = new String("1223");

[Link](s); //1223

[Link]([Link]('2', '5')); //1553

toLowerCase()

toUpperCase()

String s = new String("abc");

[Link]([Link]()); //ABC

String s1 = new String("ABC");


[Link]([Link]()); //abc

trim()

String s = new String(" ab c ");

[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)

String s = new String("abcbc");

[Link]([Link]("b")); //1st occurrence of specified char //1

[Link]([Link]("b")); //last index of char //3

repalce() vs replaceAll()

➔ String replace(char oldChar, char newChar)


Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
➔ String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement
sequence.
➔ String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
➔ String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.

String s1 = new String("abc");

String s2 = [Link]();

String s3 = [Link](); //referred to s1

[Link](s1 == s2); //false

[Link](s1 == s3); //true

String s4 = [Link]();

[Link](s4 == s2); //false

[Link](s1 == s4); //false


//If there is change in content of current object after some modification then only new object
got created

String s1 = new String("abc"); // new object s1

String s2 = [Link](); // referred to s1

String s3 = [Link](); // referred to s1

String s4 = [Link](); // new object s4

String s5 = [Link](); // new object s5 because of change in the content of s4

How to create our own immutable class

What are Mutable Objects

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.

What are Immutable Objects

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.

public final class Test {


private int i;
Test(int i){
this.i = i;
}
public Test modify(int i){
if(this.i == i){
return this;
}else {
return new Test(i);
}
}
@Override
public String toString() {
return "Test [i=" + i + "]";
}
public static void main(String[] args) {
Test t = new Test(10);
[Link]([Link]()); //Test [i=10]
Test t1 = [Link](100);
[Link](t1 == t); //false
Test t2 = [Link](10);
[Link](t2 == t); //true
Test t3 = [Link](10);
[Link](t3 == t); //false
[Link](t3 == t1); //false
}
}

➔ All the wrapper classes like Boolean, Short, Integer, Long, Float, Double, Byte, Char, and String classes are
immutable classes.

Advantage of Object cloning

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.

Disadvantage of Object cloning

Following is a list of some disadvantages of clone() method:

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.

StringBuffer buffer = new StringBuffer();

[Link]([Link]()); // 16 – initial capcity


new capacity = (currentCapacity +1)*2

StringBuffer buffer = new StringBuffer(int initialCapcity);

StringBuffer buffer = new StringBuffer(String s); // Capacity = 16 + [Link]()

Methods:
length()

capacity()

charAt(int index)

StringBuffer sb = new StringBuffer("test");

[Link]([Link]()); // 4

[Link]([Link]()); //20

[Link]([Link](1)); //e

setCharAt(int index,char Ch)

[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)

[Link](1, 243); // used to insert at specified location

//supports String, int, long, double, float, object, char, char[], String Buffer,boolean

[Link](sb); //t243est

delete(int begin,int end)

deleteCharAt(int index)

[Link](2, 3); // deletes from begin value to end value - 1

[Link](sb);//tet

[Link](2);

[Link](sb); //te

reverse()

[Link]();
[Link](sb); //tset

setLength(int index)

[Link](2); //consider only length from argument.

[Link](sb); // te

ensureCapacity()

trimToSize()

[Link]([Link]()); //20

[Link](250); //to increase capcity on fly

[Link]([Link]()); //250

[Link]();

[Link]([Link]()); //4

substring(int index)

substring(int beginIndex, int endIndex)

[Link]([Link](1)); //est

[Link]([Link](1,2)); //e //fetch from start index to end - 1

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?

byte -> short

int -> long -> float-> double.

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

Boolean boolean1 = new Boolean(true); // boolean(true and false) and String(case


insensitive)(“true” is passed true is o/p if not false is o/p) are allowed

Boolean boolean1 = new Boolean("yes"); // false

Boolean boolean2 = new Boolean("no"); //false

[Link]([Link](boolean2)); // true

Methods:
valueOf(primitive p / String i/ String I , radix r);

Integer inte= [Link](10); // int , String

xxxValue() -> to get primitive for the given wrapper object

Integer integer = [Link](10);

[Link]([Link]()); //10

charValue()

Character c = new Character('c');

[Link]([Link]()); //c

booleanValue()

Boolean boolean1 = new Boolean(true);

[Link]([Link]()); //true

parseXXX() -> to convert String to primitive

String i = "12";

[Link]([Link](i)); //12

Autoboxing:
✓ Automatic conversion of primitive to Wrapper objects by compiler.

Integer i = 10; // complier converts int to Integer automatically by auto boxing


// Integer I = [Link](10);

int j = i; // complier converts Integer to int automatically by auto unboxing

// int j = [Link](i);

static Integer i = 0;

static Integer j;

public static void main(String [] args){

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](i == j); //false

public static void m1(Integer i){ // autoboxing

[Link]("3");

public static void m1(long i){ //wideing

[Link]("2");

public static void m1(int... i){ //var args

[Link]("1");}

public static void main(String []args)

{ int i = 10;
m1(i); // 2 // primitives > autoboxing > var args

Clone():
public class Test implements Cloneable{

int i = 10;

int j = 11;

public static void main(String[] args) throws CloneNotSupportedException {

Test t1 = new Test();

Test t2= (Test) [Link]();

[Link]([Link]());

/* (non-Javadoc)

* @see [Link]#toString()

*/

@Override

public String toString() {

return "Test [i=" + i + ", j=" + j + "]";

String s1 = new String("test");

String s2 = [Link]();

[Link](s2 == s1); // false because of intern s2 referred to SCP object not to heap
object

String s3 = s1;

[Link](s3 == s1); // true

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.

Error Exception Exception2


Type Classified as an unchecked type Classified as checked and unchecked
Package It belongs to [Link] It belongs to [Link]
Recoverable/
Irrecoverable It is irrecoverable It is recoverable
It can't be occurred at compile It can occur at run time compile time
time both
Example OutOfMemoryError ,IOError NullPointerException , SqlException
Checked Exceptions and Unchecked Exceptions:

✓ 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

Final: It is a keyword used to define the constant variables.

Finally: it is a block used to do clean up activity if exception is handled or not.

Finalize: it is a method called by GC for the cleaned-up activities.

throw new ArithmeticException(); //Handover the exception manually to JVM

throws ArithmeticException // used to throw the exception to the caller or JVM

//try must be followed by catch or finally

try{ //braces are mandatory


[Link](10/0);
}catch(ArithmeticException e){ //should be with try
[Link]();
[Link](e);
[Link]([Link]());
}catch(NumberFormatException e){
[Link]([Link]());
}finally{ //should be with try
[Link]("exit");
}
----------------------
public class Dot extends RuntimeException{
Dot(String s){
super(s);
}
}

Scanner sc= new Scanner([Link]);


int i = [Link]([Link]());
if(i < 10){
throw new Dot("Should be greater than 10");
}

catch(ArithmeticException | NumberFormatException | Dot e ){ //from 1.7V


[Link]();
[Link](e);
[Link]([Link]());
}

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.

throw The "throw" keyword is used to throw an exception.


throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the
method. It doesn't throw an exception. It is always used with method signature.

Sr. Key final finally finalize


no.

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.

It's execution is not


dependant on the exception.

[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

[Link]([Link]()); //if file exist true else false

if(![Link]()){

try {

[Link](); //is used to create a file physically

} catch (IOException e) {

[Link]("Unable to create a file: "+[Link]());

File f = new File("santhosh");

[Link]([Link]()); //false

[Link](); // is used to create a directory

[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:

File f = new File("[Link]");

[Link](); // it is used to check file/directory is present (true/false)

[Link](); // Used to create new file (true if created else false)


[Link](); // Used to create new directory (true if created else false)

[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)

[Link](); // used to list out the files/directories (String[])

[Link](); // used to find the length of the file (long)

[Link](); // used to delete the file/directory (true/false)

FileWriter:
✓ FileWriter will create a new file and writes data into it if file is not exist.

FileWriter fw = new FileWriter(String name);

FileWriter fw = new FileWriter(File f);

FileWriter fw = new FileWriter(String name,true); // to append the data to already existing


data in the file

FileWriter fw = new FileWriter(File f,true); // to append the data to already existing data in
the file

Methods:

[Link](int/char ch); // write single character to a file

[Link](String s); //write string to a file

[Link](char[] ch); // write character array to a file

[Link](); // to check last byte is also write into the file

[Link](); // to close the fw

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.

FileReader: Read character by character


FileReader fr = new FileReader(String filename);

FileReader fr = new FileReader(File f);


FileReader fr = new FileReader("[Link]");

int i = [Link](); // read each character each time as a unicode value

while (i != -1) {

[Link]((char) i);

i = [Link]();

[Link]();

File f = new File("[Link]");

char[] ch = new char[(int)[Link]()];

FileReader fr1 = new FileReader(f);

[Link](ch); // this will copy all data into char[]

[Link](ch);

/*for(char c: ch)

[Link](ch);

}*/

[Link]();

BufferedWriter:
BufferedWriter bw = new BufferedWriter(Writer w);

BufferedWriter bw = new BufferedWriter(Writer w,int bufferSize);

FileWriter w = new FileWriter("[Link]");

BufferedWriter bw = new BufferedWriter(w); // cannot communicate directly, used ant writer


object

[Link]("test");

[Link](); // used to provide new line in the file

[Link]('c');

[Link]();

[Link]();
BufferedReader: (BEST Reader)
FileReader fileReader = new FileReader("[Link]");

BufferedReader br = new BufferedReader(fileReader);

String s = [Link]();

while(s != null){

[Link](s);

s=[Link]();

[Link]();

PrintWriter: (Best writer)


PrintWriter pw = new PrintWriter("[Link]"); // String s or File F or Writer w

[Link]("test");

[Link]("dgdfjghjfkh");

[Link]();

[Link]();

character data (text data) -> Readers/Writers


binary data(video , audio,..) -> Streams (InputStream, OutputStream)

Merging of two files into single file:

BufferedReader br = new BufferedReader(new FileReader("[Link]"));

PrintWriter pr = new PrintWriter("[Link]");

String s = [Link]();

while(s != null){

[Link](s);

s = [Link]();

br = new BufferedReader(new FileReader("[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 static void main(String[] args) {

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

public static void main(String[] args) {

ArrayList<String> l = new ArrayList<String>(); //Generic code //We can add only Strings

[Link]("test");

[Link]("gh");

m1(l); //Non Generic code // We can add any type

[Link](l); //[test, gh, 10, 10.5]

public static void m1(ArrayList l){

[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.

public void m1(ArrayList<? extends Number> arrayList) {

// Upper bound - 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

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:

Executing several tasks simultaneously is called multitasking.

1) Process Based Multitasking


✓ Executing several tasks simultaneously where each task is a separate independent program.
✓ Best at OS level.
2) Thread Based Multitasking
✓ Executing several tasks simultaneously where each task is a separate independent part of the same
program.
✓ Each part is called Thread.
✓ Best at Programmatic level.

Main use of multi-tasking is to improve performance by decrease the response time of the system.

The ways to define a Thread:


Thread is a light weight separate flow of execution.

By extending Thread class:

public class MyThread extends Thread { //Defining a Thread

@Override

public void run(){ // Code under run() is called Job of the Thread

for(int i=0;i<10;i++)

[Link]("Child Thread"); //Executed by child Thread

public class ThreadDemo { //Every java program will contain 1 thread(main)

public static void main(String[] args) {

MyThread t = new MyThread(); //Thread instantiation

[Link](); //Starting of the thread // Created by Main thread // main thread


creates a child thread //new Thread will be created // start() from Thread class // [Link]()->
new thread is not created and executed by main thread

for(int i=0;i<10;i++)

[Link]("Main Thread"); //Executed by main Thread

The order of execution of the thread is decided by Thread Scheduler.

Thread class start () { //17000 lines code is available

✓ Register this thread with thread scheduler


✓ Perform all other mandatory activates
✓ Invoke run()

public class MyThread extends Thread {

@Override

public void run(){ //Recommended to override run() because [Link]() doesn’t have any
implementation

[Link]("No args run method");


}

//Overloaded of run() is possible but start() will call only not args run method only
(run())

public void run(int i){

[Link]("With args run method");

public class MyThread extends Thread {

@Override

public void start(){ //if we override start() new thread will not create and start() is
executed as normal method

// [Link](); //to call [Link]()

[Link]("start method");

@Override

public void run(){

[Link]("run method");

}
public class ThreadDemo {

public static void main(String[] args) {

MyThread t = new MyThread();

[Link]();

[Link](); // If we try to start a new thread which is already started. //


[Link]

By implementing Runnable implementation: best way to define a Thread

public class MyThread implements Runnable {

@Override

public void run(){

[Link]("Run method");

public class ThreadDemo {

public static void main(String[] args) {

MyThread t = new MyThread();

Thread t1 = new Thread();

[Link](); //[Link]() will be executed

Thread t2 = new Thread(t);

[Link](); //[Link]() will be executed

[Link]("Main Thread");

}
Thread class Constructors:

Thread thread = new Thread();

Thread thread = new Thread(Runnable r);

Thread thread = new Thread(String name);

Thread thread = new Thread(Runnable r,String name);

Thread thread = new Thread(ThreadGroup g,String name);

Thread thread = new Thread(ThreadGroup g,Runnable r);

Thread thread = new Thread(ThreadGroup g,Runnable r,String name);

Thread thread = new Thread(ThreadGroup g,Runnable r,String name,long statcksize);

Getting and Setting Name of thread:

public class ThreadDemo {

public static void main(String[] args) {

[Link]([Link]().getName()); //main // used to get thread


name

MyThread t = new MyThread();

[Link]([Link]()); //Thread-0

[Link]().setName("MyMainThread"); //used to set a name

[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

MyThread t = new MyThread();

[Link](); //5
[Link]("main"+[Link]().getPriority()); //5

[Link]().setPriority(10); // range is 1 - 10 // if other than 1 -10 will get


RE:[Link]

[Link]("main"+[Link]().getPriority()); //10

Default priority for main thread is 5 and for others it is inherited from parent thread.

The methods to prevent Thread execution:


✓ Yield()
✓ Join()
✓ Sleep()

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.

Public static native void yield();

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.

Once t2 completes execution t1 continue its execution.

Public final void join();

Public final void join(long ms);

Public final void join(long ms, int ns);

A thread can interrupt a sleeping/waiting thread by using interrupt () of Thread class

Public void interrupt ();

Interrupt () -> applicable to only waiting/sleeping threads

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 (this){ //only for few lines go with synchronized block


}

synchronized (Object o) {
}

synchronized ([Link]) {
}

Inter thread communication:

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(),notify(), notifyAll() present in Object class. (Only in Synchronized area)

What is the difference between wait() and sleep()?

• 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.

What is difference between notify() and notfiyAll()?

• 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

What is a volatile keyword?


In general each thread has its own copy of variable, such that one thread is not concerned with the value of same variable
in the other thread. But sometime this may not be the case. Consider a scenario in which the count variable is holding the
number of times a method is called for a given class irrespective of any thread calling, in this case irrespective of thread
access the count has to be increased so the count variable is declared as volatile. The copy of volatile variable is stored in
the main memory, so every time a thread access the variable even for reading purpose the local copy is updated each time
from the main memory. The volatile variable also has performance issues.

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.

We can avoid Deadlock situation in the following ways:

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.

Fork Join in Java

Executor:

This interface provides a way to execute submitted Runnable tasks.

An Executor is normally used instead of explicitly creating threads.

For example, rather than invoking new Thread(new RunnableTask()).start() for each task of a set of tasks, you might use:

Executor executor = new ThreadPoolExecutor(1, 10,


0L, [Link],
new LinkedBlockingQueue<Runnable>());
[Link](runnableTask);
execute(): This execute() method executes the given Runnable task at some time in the future. The command(task) may
execute in a new thread, from the pooled thread, or in the calling thread, at the discretion of the Executor implementation
(e.g. ThreadPoolExecutor).

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.

ExecutorService is an extended version of Executor with more methods and features.

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.

Let’s See Some Methods of ExecutorService:

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.

maximumPoolSize — the maximum number of threads to allow in the pool.

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.

unit — the time unit for the keepAliveTime argument.

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:

ExecutorService executorService = [Link](10);

Some types of Java Executors are listed below:

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:

ExecutorService executor = [Link]();


Executor 2: FixedThreadPool(n)
As the name indicates, it is a thread pool of a fixed number of threads. The tasks submitted to the executor are executed
by the n threads and if there is more task they are stored on a LinkedBlockingQueue. It uses Blocking Queue.

Syntax:

ExecutorService fixedPool = [Link](2);

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.

ExecutorService executorService = [Link]();


Executor 4: ScheduledExecutor

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.

ScheduledExecutorService scheduledExecService = [Link](1);

The tasks can be scheduled using either of the two methods:

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:

Future<String> result = [Link](callableTask);


Serialization

Serialization in java is a mechanism of writing the state of an object into a byte stream.

1. Create a fileoutputStream->open ObjectoutputStream->writeObject(Object o)


2. Create a fileintputStream->open ObjectinputStream->readObject(Object o)

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

class Dog implements Serializable //marker interface


{
/**
*
*/
private static final long serialVersionUID = 1L;
int i = 10;
int j = 20;
transient int z = 30; // transient is modifier only applicable to variable
//if a variable is transient on saving default value is saved
transient static int v = 10; //on static variables there will be no effect of transient
because static variables belong to class level
transient final int f = 22; //on final variables there will be no effect of transient
because variable is replaced by the value at compile time only
}

public class Test {


public static void main(String[] args) throws IOException, ClassNotFoundException {
Dog dog = new Dog();
//Serialization - Start
FileOutputStream outputStream = new FileOutputStream("[Link]");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
[Link](dog);
//Serialization - End
//De serialization - Start
FileInputStream inputStream = new FileInputStream("[Link]");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Dog d2 = (Dog) [Link]();
//De serialization - End
[Link](d2.i+" "+d2.j+" "+d2.z+" "+d2.v+" "+d2.f); //10 20 30 10 22//if
z is not transient
[Link](d2.i+" "+d2.j+" "+d2.z+" "+d2.v+" "+d2.f); //10 20 0 10 22//if
z is transient
}
}

Dog dog = new Dog();


Cat cat = new Cat();
Pig pig = new Pig();
//Serialization - Start
FileOutputStream outputStream = new FileOutputStream("[Link]");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
[Link](dog);
[Link](cat);
[Link](pig); //Order is important for di serialization
//Serialization - End
//De serialization - Start
FileInputStream inputStream = new FileInputStream("[Link]");
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Dog d2 = (Dog) [Link]();
Cat d2 = (Cat) [Link]();
Pig d2 = (Pig) [Link](); // In the order of serialzation we have to de
serialize
Object object = [Link](); //If we don’t know the order of serialization
if(object instanceof Dog){
Dog d = (Dog)object;
}

Object graph:

class Dog implements Serializable {


Cat cat = new Cat();
}

class Cat implements Serializable {

Rat rat = new Rat();


}

class Rat implements Serializable {

int i = 10;
}

public class Test {


public static void main(String[] args) throws IOException,
ClassNotFoundException {
Dog dog = new Dog();
FileOutputStream outputStream = new FileOutputStream("[Link]");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
outputStream);
[Link](dog);

FileInputStream inputStream = new FileInputStream("[Link]");


ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Dog object = (Dog) [Link]();
[Link]([Link].i); // 10

}
}

Customized Serialization:
➔ Jvm will check for writeObject() and readObject() methods present in Serializing object.
➔ If available JVM will execute that

class Account implements Serializable {


/**
*
*/
private static final long serialVersionUID = 1L;
String name = "test";
transient String pass = "test123";

private void writeObject(ObjectOutputStream o) throws Exception{


[Link]();
String ePass = "sdf"+pass;
[Link](ePass);
}

private void readObject(ObjectInputStream o) throws Exception{


[Link]();
String epass = (String) [Link]();
pass = [Link](3);
}

public class Test {


public static void main(String[] args) throws IOException,
ClassNotFoundException {
Account account = new Account();
FileOutputStream outputStream = new FileOutputStream("[Link]");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
outputStream);
[Link](account);

FileInputStream inputStream = new FileInputStream("[Link]");


ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
Account object = (Account) [Link]();
[Link]([Link]+"..."+[Link]); // test...null
[Link]([Link]+"..."+[Link]); // test...test123 //customized
serialization
}
}
Serialization with inheritance:

class Animal implements Serializable{


private static final long serialVersionUID = 1L;
int i =10;
}
class Dog extends Animal{
//If parent implements Serializable then there is no need of implementing Serializable
by child class
private static final long serialVersionUID = 1L;
int j = 20;
}

class Cat{
int k =10;
}

class Cat1 extends Cat implements Serializable{


//As we are Serializable cat1(child) then need not to be Serializable Cat(parent)
private static final long serialVersionUID = 1L;
int g =10;
}

public class Test {


public static void main(String[] args) throws IOException, ClassNotFoundException {
Dog dog = new Dog();
Cat1 cat1 = new Cat1();
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](dog);
[Link](cat1);

FileInputStream fis = new FileInputStream("[Link]");


ObjectInputStream ois = new ObjectInputStream(fis);
Dog object = (Dog) [Link]();
[Link](object.i+"...."+object.j); //10....20
Cat1 cat12 = (Cat1) [Link]();
[Link](cat12.k+"...."+cat12.g); // 10....20

}
}

class Animal{
int i =10;
}

class Cat extends Animal implements Serializable{


private static final long serialVersionUID = 1L;
int j =20;
}

public class Test {


public static void main(String[] args) throws IOException, ClassNotFoundException {
Cat cat = new Cat();
cat.i = 100;
cat.j = 200;
[Link](cat.i+"...."+cat.j);//100....200
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](cat); //0....200 //As i is from non serilized parent class

FileInputStream fis = new FileInputStream("[Link]");


ObjectInputStream ois = new ObjectInputStream(fis);
Cat object = (Cat) [Link]();
[Link](object.i+"...."+object.j); //10...200(if parent class is not
Serialized)
//100....200((if parent class is Serialized)

}
}
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.

class Cat implements Externalizable{


//Externalizable interface consists of writeExternal(),readExternal() methods
private static final long serialVersionUID = 1L;
String s;
int i;
int j; //There will be no effect of transient keyword in Externalization

public Cat(String s,int i,int j) {


this.s = s;
this.i = i;
this.j = j;
}

public Cat(){ //mandatory


}

@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]
}
}

public class Test {


public static void main(String[] args) throws IOException, ClassNotFoundException {
Cat cat = new Cat("Test",10,20);
FileOutputStream fos = new FileOutputStream("[Link]");
ObjectOutputStream oos = new ObjectOutputStream(fos);
[Link](cat);

FileInputStream fis = new FileInputStream("[Link]");


ObjectInputStream ois = new ObjectInputStream(fis);
Cat cat2 = (Cat) [Link]();
[Link](cat2.s+".."+cat2.i+".."+cat2.j);//Test..10..0

}
}

serialVersionUID:

private static final long serialVersionUID = -4783347996196016992L; //generated by JVM


private static final long serialVersionUID = 1L; //default

Grabage Collector
When an object doesn’t have any reference then it is eligible for GC.

The ways to make an object eligible for garbage collector:


1. Nullifying the reference variable:
Student s1 = new Student();
s1 = null; -> by this, s1 object will be eligible for GC
2. Reassign the reference variable:
Student s1 = new Student();
Student s2 = new Student();
S1 = new Student(); -> after assigning new object old object is eligible for GC.
3. Objects created inside a method:
public static void main(){
m1(); -> after execution of this method 2 objects created inside this method
are eligible for GC.
}
public static void m1(){
Student s1 = new Student();
Student s2 = new Student();
}
_____

public static void main(String[] args) {


Student s = m1(); -> here only 1 (s2) is eligible for GC.
m1(); -> here 2(s1 and s2) are eligible for GC as we are not using return object.
M1()
}
public static Student m1() {
Student s1 = new Student();
Student s2 = new Student();
return s1;
}
_____

static Student s1 ;
public static void main(String[] args) {
m1(); -> only 1 object (s2) is eligible for GC.
}

public static void m1() {


s1 = new Student();
Student s2 = new Student();
}

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.

The methods for requesting JVM to run GC:


1. [Link]()
2. [Link]().gc() -> recommended to use due to performance is more
Finalization: Just before destroying the object GC will call finalize() method for clean up activities.
Eg: resource deallocation, db connection, network connection.
protected void finalize() throws Throwable {} -> available in Object class

Scenario one:

public class Test {


public static void main(String[] args) {
String s = new String("String");
s = null;
[Link]();
[Link]("End of main");
}

public void finalize() {


[Link]("finalize method called");
}

O/P: End of main -> GC will call String class finalize method and will not call Test class finalize method

public static void main(String[] args) {


Test s = new Test();
s = null;
[Link]();
[Link]("End of main");
}

public void finalize() {


[Link]("finalize method called");
}
}
O/P: End of main
finalize method called

or

finalize method called


End of main

Scenario 2: If finalize() method call explicitly it will run as a normal method.

public class Test {


public static void main(String[] args) {
Test t = new Test();
[Link]();
[Link]();
t = null;
[Link]();
[Link]("End of main");
}

public void finalize() {


[Link]("finalize method called");
}
}

O/P: finalize method called -> as it run a normal method


finalize method called -> as it run a normal method
End of main
finalize method called -> run by GC

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.

(argument-list) -> {body}

Java lambda expression consists of three components.

1. Argument-list: It can be empty or non-empty as well.


2. Arrow-token: It is used to link arguments-list and body of expression.
3. Body: It contains expressions and statements for the lambda expression.

The below diagram shows a few simple lambda expression examples:

Note: Default methods of a functional interface cannot be accessed from within lambda expressions.
Java 8 Predefined-Functional Interfaces
Supplier:

Represents a supplier of results.

Code:

Supplier<Person> supplier = () -> {


return new Person("Ramesh", 30 );
};

Person p = [Link]();
[Link]("Person Detail:\n" + [Link]() + ", " + [Link]());

Consumer:

It represents an operation that accepts a single argument and returns no result.

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:

Predicate <Person> predicate = (person) -> [Link]() > 28;


boolean result = [Link](new Person("ramesh", 29));
[Link](result);
Function:

It represents a function that accepts one argument and returns a result.

BiFunction:

It represents a function that accepts two arguments and returns a result.

BiConsumer:

It represents an operation that accepts two input arguments and returns no result.

Supplier (no arguments, Object result)


Consumer (One argument, no result)
Predicate (one argument, Boolean result)
Function (one argument, Object result)
BiFunction (Two arguments, Object result)
BiConsumener (Two arguments, no result)

Method References
Java provides a new feature called method reference in Java 8.

Method reference is used to refer method of the functional interface.

It is a compact and easy form of a lambda expression.

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()

orElse(Object) -> execute everytime (egar loading)


orElseGet(Supplier) -> executes only if optional is null ( lazy loading)

Default/Static Methods in interfaces


• Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary
compatibility with code written for older versions of those interfaces.

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:

Stream<String> stream = [Link]();


[Link]([Link]::println);

Stream Object from Arrays:

// creating from existing array or of a part of an array:


String[] arr = new String[] { "a", "b", "c" };
Stream<String> streamOfArrayFull = [Link](arr);
[Link]([Link]::println);

Stream<String> streamOfArrayPart = [Link](arr, 1, 3);


[Link]([Link]::println);

Filter and forEach:

[Link]()
.filter((product) -> [Link]() > 25000f)
//.collect([Link]())
.forEach([Link]::println);

Max, Min, Sorted:

Optional<Product> d = [Link]().max((p1,p2) -> [Link]() >


[Link]() ? 1 : -1);
[Link]([Link]().getPrice()); //90000.0

List<Product> products = [Link]().sorted((p1,p2) -> [Link]() >


[Link]() ? 1 : -1).collect([Link]());
[Link]([Link]());

[Link], [Link], [Link]:

DoubleSummaryStatistics totalPrice3 =
[Link]().collect([Link](Product::getPrice));
[Link](totalPrice3);

O/P: DoubleSummaryStatistics{count=5, sum=201000.000000, min=25000.000000, average=40200.000000,


max=90000.000000}

Example: Group members by gender:


The following example groups members of the collection roster by gender:

Map<[Link], List<Person>> byGender =


roster
.stream()
.collect(
[Link](Person::getGender));

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).

Example: Group names by gender:


The following example retrieves the names of each member in the collection roster and groups
them by gender:

Map<[Link], List<String>> namesByGender =


roster
.stream()
.collect(
[Link](
Person::getGender,
[Link](
Person::getName,
[Link]())));
___________________________________________________________________
Map<String, List<Float>> groupByList = [Link]()
.collect(Collectors
.groupingBy(Product::getName,

[Link](Product::getPrice, [Link]())));

[Link]((k,v) -> [Link](k + ":" + v));

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.

float price = [Link]().map(p -> [Link]()).reduce(0f, (a,b) -> a+b);


[Link](price);

Arrays(Premetive type) to List/Set:

int[] arr = {1,2,4,3,4};


Set<Integer> s = [Link](arr).boxed().collect([Link]());
[Link](s + " " + [Link]());

GroupingBy:

List<String> items = [Link]("apple", "apple", "banana", "apple", "orange", "banana",


"papaya");
Map<String, Long> result = [Link]()
.collect([Link]([Link](), [Link]()));
[Link](result);

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](list, (o1, o2) ->


// [Link]().compareTo([Link]()));
// [Link](list);

[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 ].

List<Employee> list = new ArrayList<>();


[Link](new Employee(1, "asd", 133, [Link](987654433, 987654098)));
[Link](new Employee(4, "ert", 163, [Link](567890345, 245678903)));
[Link](new Employee(2, "dcds", 1216, [Link](675834556, 345902134)));
[Link](new Employee(3, "yhuu", 1677, [Link](671234569, 654321177)));

List<String> names = [Link]().map(Employee::getName).collect([Link]());


[Link](names); // [asd, ert, dcds, yhuu]
List<List<Integer>> phoneNumbersMap = [Link]().map(e ->
[Link]()).collect([Link]());

[Link](phoneNumbersMap); // [[987654433, 987654098],


// [567890345, 245678903],
// [675834556, 345902134],
// [671234569, 654321177]]

List<Integer> phoneNumbers = [Link]().flatMap(e -> [Link]().stream())


.collect([Link]()); // [987654433, 987654098,
// 567890345, 245678903,
// 675834556, 345902134,
// 671234569, 654321177]
[Link](phoneNumbers);

Stream vs ParallelStream
Sequential Stream Parallel Stream

Runs on a single-core of the computer Utilize the multiple cores of the computer.

Performance is poor The performance is high.

Order is maintained Doesn’t care about the order

Only a single iteration at a time just like the for- Operates multiple iterations simultaneously in different
loop. available cores.

Each iteration waits for currently running one to


Waits only if no cores are free or available at a given time,
finish,

More reliable and less error Less reliable and error-prone.

Platform independent Platform dependent

List<String> list= [Link]("Hello ","G", "E", "E", "K", "S!");


[Link]().forEach([Link]::print);
//ES!KGEHello

// using parallelStream() method for parallel stream for ordered output


[Link]().forEachOrdered([Link]::print);
//Hello GEEKS!

Employee Stream
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class EmployeeStreamDemo {


static List<Employee> employeeList = new ArrayList<Employee>();

public static void main(String[] args) {

[Link](new Employee(111, "Jiya Brein", 32, "Female", "HR", 2011, 25000.0));


[Link](new Employee(122, "Paul Niksui", 25, "Male", "Sales And Marketing", 2015,
13500.0));
[Link](new Employee(133, "Martin Theron", 29, "Male", "Infrastructure", 2012,
18000.0));
[Link](new Employee(144, "Murali Gowda", 28, "Male", "Product Development", 2014,
32500.0));
[Link](new Employee(155, "Nima Roy", 27, "Female", "HR", 2013, 22700.0));
[Link](new Employee(166, "Iqbal Hussain", 43, "Male", "Security And Transport", 2016,
10500.0));
[Link](new Employee(177, "Manu Sharma", 35, "Male", "Account And Finance", 2010,
27000.0));
[Link](new Employee(188, "Wang Liu", 31, "Male", "Product Development", 2015,
34500.0));
[Link](new Employee(199, "Amelia Zoe", 24, "Female", "Sales And Marketing", 2016,
11500.0));
[Link](new Employee(200, "Jaden Dough", 38, "Male", "Security And Transport", 2015,
11000.5));
[Link](new Employee(211, "Jasna Kaur", 27, "Female", "Infrastructure", 2014, 15700.0));
[Link](new Employee(222, "Nitin Joshi", 25, "Male", "Product Development", 2016,
28200.0));
[Link](new Employee(233, "Jyothi Reddy", 27, "Female", "Account And Finance", 2013,
21300.0));
[Link](new Employee(244, "Nicolus Den", 24, "Male", "Sales And Marketing", 2017,
10700.5));
[Link](new Employee(255, "Ali Baig", 23, "Male", "Infrastructure", 2018, 12700.0));
[Link](new Employee(266, "Sanvi Pandey", 26, "Female", "Product Development", 2015,
28900.0));
[Link](new Employee(277, "Anuj Chettiar", 31, "Male", "Product Development", 2012,
35700.0));

// 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);
}

public static void method2() {


[Link]("Query 2 : Print the name of all departments in the organization?");
[Link]().map(Employee::getDepartment).distinct().forEach([Link]::println);
}

public static void method3() {


[Link]("Query 3 : What is the average age of male and female employees?");
Map<String, Double> averageAgeOfMaleAndFemaleEmployee = [Link]()
.collect([Link](Employee::getGender,
[Link](Employee::getAge)));
[Link](averageAgeOfMaleAndFemaleEmployee);
}

public static void method4() {


[Link]("Query 4 : Get the details of highest paid employee in the organization?");
Optional<Employee> highestPaidEmployeeWrapper = [Link]()

.collect([Link]([Link](Employee::getSalary)));
[Link]([Link]().getName());
}

public static void method5() {


[Link]("Query 5 : Get the names of all employees who have joined after 2015?");
[Link]().filter(e -> [Link]() > 2015).map(Employee::getName)
.forEach([Link]::println);
}

public static void method6() {


[Link]("Query 6 : Count the number of employees in each department?");
Map<String, Long> employeeCountByDepartment = [Link]()
.collect([Link](Employee::getDepartment,
[Link]()));

Set<Entry<String, Long>> entrySet = [Link]();

for (Entry<String, Long> entry : entrySet) {


[Link]([Link]() + " : " + [Link]());
}
}

public static void method7() {


[Link]("Query 7 : What is the average salary of each department?");
Map<String, Double> avgSalaryOfDepartments=

[Link]().collect([Link](Employee::getDepartment,
[Link](Employee::getSalary)));

Set<Entry<String, Double>> entrySet = [Link]();

for (Entry<String, Double> entry : entrySet)


{
[Link]([Link]()+" : "+[Link]());
}
}

public static void method8() {


[Link]
.println("Query 8 : Get the details of youngest male employee in the product
development department?");
Optional<Employee> youngestMaleEmployeeInProductDevelopmentWrapper=
[Link]()
.filter(e -> [Link]()=="Male" && [Link]()=="Product
Development")
.min([Link](Employee::getAge));

Employee youngestMaleEmployeeInProductDevelopment =
[Link]();

[Link]("Details Of Youngest Male Employee In Product


Development");

[Link]("----------------------------------------------");

[Link]("ID :
"+[Link]());

[Link]("Name :
"+[Link]());

public static void method9() {


[Link]("Query 9 : Who has the most working experience in the organization?");
Optional<Employee> seniorMostEmployeeWrapper=
[Link]().sorted([Link](Employee::getYearOfJoining)).findFirst();

Employee seniorMostEmployee = [Link]();

[Link]("Senior Most Employee Details :");

[Link]("----------------------------");

[Link]("ID : "+[Link]());

[Link]("Name : "+[Link]());
}

public static void method10() {


[Link]("Query 10 : How many male and female employees are there in the sales and
marketing team?");
Map<String, Long> countMaleFemaleEmployeesInSalesMarketing=
[Link]()
.filter(e -> [Link]()=="Sales And Marketing")
.collect([Link](Employee::getGender,
[Link]()));

[Link](countMaleFemaleEmployeesInSalesMarketing);
}

public static void method11() {


[Link]("Query 11 : What is the average salary of male and female employees?");
Map<String, Double> avgSalaryOfMaleAndFemaleEmployees=
[Link]().collect([Link](Employee::getGender,
[Link](Employee::getSalary)));

[Link](avgSalaryOfMaleAndFemaleEmployees);
}

public static void method12() {


[Link]("Query 12 : List down the names of all employees in each department?");
Map<String, List<Employee>> employeeListByDepartment=

[Link]().collect([Link](Employee::getDepartment));

Set<Entry<String, List<Employee>>> entrySet =


[Link]();

for (Entry<String, List<Employee>> entry : entrySet)


{
[Link]("--------------------------------------");

[Link]("Employees In "+[Link]() + " : ");

[Link]("--------------------------------------");

List<Employee> list = [Link]();

for (Employee e : list)


{
[Link]([Link]());
}
}
}

public static void method13() {


[Link]("Query 13 : What is the average salary and total salary of the whole
organization?");
DoubleSummaryStatistics employeeSalaryStatistics=

[Link]().collect([Link](Employee::getSalary));

[Link]("Average Salary = "+[Link]());

[Link]("Total Salary = "+[Link]());


}

public static void method14() {


[Link](
"Query 14 : Separate the employees who are younger or equal to 25 years from
those employees who are older than 25 years.");
Map<Boolean, List<Employee>> partitionEmployeesByAge=
[Link]().collect([Link](e -> [Link]() > 25));

Set<Entry<Boolean, List<Employee>>> entrySet =


[Link]();

for (Entry<Boolean, List<Employee>> entry : entrySet)


{
[Link]("----------------------------");

if ([Link]())
{
[Link]("Employees older than 25 years :");
}
else
{
[Link]("Employees younger than or equal to 25 years :");
}

[Link]("----------------------------");

List<Employee> list = [Link]();

for (Employee e : list)


{
[Link]([Link]());
}
}
}

public static void method15() {


[Link](
"Query 15 : Who is the oldest employee in the organization? What is his age
and which department he belongs to?");
Optional<Employee> oldestEmployeeWrapper =
[Link]().max([Link](Employee::getAge));

Employee oldestEmployee = [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;
}

public int getId() {


return id;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

public String getGender() {


return gender;
}

public String getDepartment() {


return department;
}

public int getYearOfJoining() {


return yearOfJoining;
}

public double getSalary() {


return 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.

Web service provides a way to achieve interoperability.

A Web Service can be defined by following ways:

• is a client server application or application component for communication.


• method of communication between two devices over network.
• is a software system for interoperable machine to machine communication.
• is a collection of standards or protocols for exchanging information between two devices or application.

Webservice

SOAP (JAX-WS) REST (JAX-RS)

REST:

REST stands for REpresentational State Transfer.

REST is an architectural style not a protocol.

• REST API
• Implementation with JAX-RS

No. SOAP REST

1) SOAP is a protocol. REST is an architectural style.

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.

HTTP Methods & Status codes


Hyper Text Transfer Protocal

Hyper Text (Structure form of text contains links to other texts)

Resource based URI

Methods:

1. Create NEW record =>POST


2. read=>GET
3. If the record exists then update else create a new record=>PUT
4. update/modify=>PATCH
5. delete=>DELETE

Status code:

200 -> success

500 -> error

404 -> not found

1XX -> information codes

2XX -> success code

201 -> Created

204 -> no content


3XX -> Redirectional codes

302 -> Found

304 -> not modified

307 -> Temporary Redirect

400 -> Bad Request

401 -> unauthorized

403 -> Forbidden

404 -> Not found

415 -> Unsupported Media Types

4XX -> Client error

5XX -> server error

Format:

Header value -> ContentType

Text/xml

Application/json

Resource based URI:

Get a message with ID 10:

Ex: /[Link]?id=10 -> messages/{messageId} or profiles/{profileName}

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.

If there is no file or resource there, PUT creates one.

PUT is idempotent, but paradoxically PUT responses are not cacheable.

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.

REST API Design Best Practices


✓ Use JSON as the Format for Sending and Receiving Data
✓ Use Nouns Instead of Verbs in Endpoints
o [Link] or [Link]
o Instead, it should be something like this: [Link]
✓ Name Collections with Plural Nouns
o Instead of [Link] it should be [Link]
✓ Use Status Codes in Error Handling

STATUS CODE RANGE MEANING


Informational Responses.
100 – 199 For example, 102 indicates the resource is being processed
Redirects
300 – 399 For example, 301 means Moved permanently
Client-side errors
400 – 499 400 means bad request and 404 means resource not found
Server-side errors
500 – 599 For example, 500 means an internal server error

✓ Use Nesting on Endpoints to Show Relationships


o [Link] would make sense.
o You should avoid nesting that is more than 3 levels deep as this can make the API less elegant and readable.
✓ Use Filtering, Sorting, and Pagination to Retrieve the Data Requested
✓ Use SSL for Security
o SSL stands for secure socket layer. It is crucial for security in REST API design. This will secure your API and make it
less vulnerable to malicious attacks.
o [Link] runs on SSL.
o [Link] does not run on SSL.
✓ Be Clear with Versioning
o Semantic versioning is 1.0.0, 2.1.2, and 3.3.4.
o The first number represents the major version, the second number represents the minor version, and the third
represents the patch version.
✓ Provide Accurate API Documentation

What do we mean by REST architectural style?


REST is a set of governing principles that a developer must adhere to before considering their API “RESTful.” The principles
say nothing about how they choose to implement the API.
Client-server architecture: The API‘s clients use HTTP calls to ask for a resource (a GET method) or send data to the server
(a POST method), or any one of the other HTTP methods supported by the API. Although GET and POST are the most
frequently used methods, other methods an API may support include HEAD, PUT, PATCH, DELETE, CONNECT, OPTIONS,
AND TRACE. The API’s documentation shows the available methods supported by the API.

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

✓ It is very easy to develop Spring Based applications with Java or Groovy.


✓ It reduces lots of development time and increases productivity.
✓ It avoids writing lots of boilerplate Code, Annotations and XML Configuration.
✓ It is very easy to integrate Spring Boot Application with its Spring Ecosystem like Spring JDBC, Spring ORM, Spring
Data, Spring Security etc.
✓ It follows “Opinionated Defaults Configuration” Approach to reduce Developer effort
✓ It provides Embedded HTTP servers like Tomcat, Jetty etc. to develop and test our web applications very easily.
✓ It provides CLI (Command Line Interface) tool to develop and test Spring Boot(Java or Groovy) Applications from
command prompt very easily and quickly.
✓ It provides lots of plugins to develop and test Spring Boot Applications very easily using Build Tools like Maven and
Gradle
✓ It provides lots of plugins to work with embedded and in-memory Databases very easily.

➢ 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.

Ways to create spring boot project:

1. Using Spring Boot CLI Tool


2. Using Spring STS IDE
3. Using Spring Initializr Website

@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 Key features


1. Spring Boot starters
2. Spring Boot autoconfiguration
3. Elegant configuration management
4. Spring Boot actuator
5. Easy-to-use embedded servlet container support

Spring Boot Starters:

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 Autoconfiguration:

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:

• Availability of a particular class in a classpath


• Presence or absence of a Spring bean
• Presence of a system property
• An absence of a configuration file

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.

Elegant Configuration Management:

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.

Read more [Link]

Spring Boot Actuator:

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:

• Can view the application bean configuration details


• Can view the application URL mappings, environment details, and configuration parameter values
• Can view the registered health check metrics

Easy-to-Use Embedded Servlet Container Support:

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.

Spring Boot Annotations


@SpringBootApplication:

@SpringBootApplication annotation indicates a configuration class that declares one or more @Bean methods and also
triggers auto-configuration and component scanning.

The @SpringBootApplication annotation is equivalent to using @SpringBootConfiguration, @EnableAutoConfiguration,


and @ComponentScan with their default attributes.
@Configuration

This annotation marks a class as a Configuration class for Java-based configuration.

@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

@RestController: It can be considered as a combination of @Controller and @ResponseBody annotations. The


@RestController annotation is itself annotated with the @ResponseBody annotation. It eliminates the need for annotating
each method with @ResponseBody.

@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.

5 Best Practices for Using Spring Boot Annotations


Following the 5 best practices for using SpringBoot annotations will help to streamline the project process:

1. Use @RequestMapping Instead of @GetMapping

@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.

2. Avoid Unnecessary Annotations Sparingly

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.

3. Implement @ConditionalOnProperty For Simple Conditions

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.

5. Use @ControllerAdvice For Global Exception Handling

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.

How to roll back the Transactions in case of exceptions in spring boot


The @Transactional annotation in Spring Boot implicitly creates a proxy that starts a transaction and commits it if no
errors occur. If an exception occurs, it rolls back the changes. The @Transactional annotation ensures that the
transaction is rolled back if an exception occurs

Spring data JPA:


Properties:
spring:
datasource:
url: jdbc:postgresql://localhost:11000/dev_db
username: app_user
password: app_user
driver-class-name: [Link]
jpa:
show-sql: true
properties:
hibernate:
dialect: [Link]
ddl-auto: update

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

Versioning in Spring boot

First version of Bean

public class StudentV1 {


private String name;
}

Second Version of Bean

public class StudentV2 {


private Name name;
}

Name has firstName and lastName and is used by StudentV2

public class Name {


private String firstName;
private String lastName;
}

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"
}
}

Request Parameter versioning

Next approach to versioning is to use the request parameter to differentiate versions.


Examples

o [Link]
o [Link]

Implementations are shown below:

@GetMapping(value = "/student/param", params = "version=1")


public StudentV1 paramV1() {
return new StudentV1("Bob Charlie");
}

@GetMapping(value = "/student/param", params = "version=2")


public StudentV2 paramV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}

[Link]
Response

{
"name": "Bob Charlie"
}

[Link]
Response

{
"name": {
"firstName": "Bob",
"lastName": "Charlie"
}
}

(Custom) Header’s versioning

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]

Implementations are shown below:

@GetMapping(value = "/student/header", headers = "X-API-VERSION=1")


public StudentV1 headerV1() {
return new StudentV1("Bob Charlie");
}

@GetMapping(value = "/student/header", headers = "X-API-VERSION=2")


public StudentV2 headerV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}

Media type versioning (a.k.a “content negotiation” or “accept header”)

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]

@GetMapping(value = "/student/produces", produces = "application/[Link]-v1+json")


public StudentV1 producesV1() {
return new StudentV1("Bob Charlie");
}

@GetMapping(value = "/student/produces", produces = "application/[Link]-v2+json")


public StudentV2 producesV2() {
return new StudentV2(new Name("Bob", "Charlie"));
}

Factors affecting Versioning Choice

• 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 fact is that there is No Perfect Solution for versioning.

The list below shows Major API providers using different versioning approaches.

• Media type versioning (a.k.a “content negotiation” or “accept header”)


o GitHub
• (Custom) Headers versioning
o Microsoft
• URI Versioning
o Twitter
• Request Parameter versioning
o Amazon

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.

Pagination in spring boot JPA

[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

Pageable paging = [Link](pageNo, pageSize, [Link]("email").ascending());


Page<EmployeeEntity> pagedResult = [Link](paging);

what is spring boot actuator and its advantages


Spring Boot's 'Actuator' dependency is used to monitor and manage the Spring web application.

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.

What is Swagger vs Postman

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.

How to config multiple databases in sprin boot?


Add in your [Link] file:

#first db
[Link] = [url]
[Link] = [username]
[Link] = [password]
[Link] = [Link]

#second db ...
[Link] = [url]
[Link] = [username]
[Link] = [password]
[Link] = [Link]

Add in any class annotated with @Configuration the following methods:

@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.

How to load data during startup in Spring Boot?


If we are working with a relational database, we could simply place a data. sql in our resources folder. This script will be
automatically executed by Spring Boot against the configured DataSource during startup.

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.

Cross Origin Requests


How To Resolve CORS issue in Spring Boot application?

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;

// getters and setters


}

@Entity
@Table(name="ITEMS")
public class Item {

//...
@ManyToOne
@JoinColumn(name="cart_id", nullable=false)
private Cart cart;

public Item() {}

// getters and setters


}

@ManyToOne In JPA
public class ItemOIO {

// ...
@ManyToOne
@JoinColumn(name = "cart_id", insertable = false, updatable = false)
private CartOIO cart;
//..
}

public class CartOIO {

//..
@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.

What is Bounded Context:

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.

What is Centralised logging system?


Centralized logging is all about bringing your data together in one unified platform, so you can manage all the data in
one place. However, providing a single, giant bucket of log data for every team member can create new problems.

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:

✓ Requires significant one-time efforts to set up centralized logging


✓ Not very useful for Monolithic applications

Event sourcing vs Event driven ?

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.

How to manage the inter service communication in java microservices


There are two basic ways to manage inter-service communication in Java microservices:

• 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();

HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);

public ResponseEntity<T> exchange(String url, HttpMethod method,


@Nullable HttpEntity<?> requestEntity, Class<T> responseType)

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 It becomes too large with time and hence, difficult to manage.


o We need to redeploy the whole application, even for a small change.
o As the size of the application increases, its start-up and deployment time also increases.
o For any new developer joining the project, it is very difficult to understand the logic of a large Monolithic
application even if his responsibility is related to a single functionality.
o Even if a single part of the application is facing a large load/traffic, we need to deploy the instances of the entire
application in multiple servers. It is very inefficient and takes up more resources unnecessarily. Hence, horizontal
scaling is not feasible in monolithic applications.
o It is very difficult to adopt any new technology which is well suited for a particular functionality as it affects the
entire application, both in terms of time and cost.
o It is not very reliable, as a single bug in any module can bring down the entire monolithic application.

Advantages 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

o It is easy to manage as it is relatively smaller.


o If there’s any update in one of the microservices, then we need to redeploy only that microservice.
o Microservices are self-contained and, hence, deployed independently. Their start-up and deployment times are
relatively less.
o It is very easy for a new developer to onboard the project as he needs to understand only a particular
microservice providing the functionality he will be working on and not the whole system.
o If a particular microservice is facing a large load because of the users using that functionality in excess, then we
need to scale out that microservice only. Hence, the microservices architecture supports horizontal scaling.
o Each microservice can use different technology based on the business requirements.
o If a particular microservice goes down due to some bug, then it doesn’t affect other microservices and the whole
system remains intact and continues providing other functionalities to the users.

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.

Features of SAGA Pattern

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.

There are two type of saga implementation ways

o Choreography
o Orchestration

What is Choreography Saga Pattern?

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.

• Advantages of Choreography Saga Pattern?


1. Good for simple workflows that require few participants and don't need a coordination logic
2. Doesn't require additional service implementation and maintenance.
3. Doesn't introduce a single point of failure, since the responsibilities are distributed across the saga
participants.
• Disadvantages of Choreography Saga Design Pattern?
1. Workflow can become confusing when adding new steps, as it's difficult to track which saga participants
listen to which commands.
2. There's a risk of cyclic dependency between saga participants because they have to consume each other's
commands.

What is Orchestration Saga Pattern?

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.

• Advantages of Orchestration Saga Pattern


1. Good for complex workflows involving many participants or new participants added over time.
2. Suitable when there is control over every participant in the process, and control over the flow of activities.
3. Doesn't introduce cyclic dependencies, because the orchestrator unilaterally depends on the saga
participants.
4. Saga participants don't need to know about commands for other participants. Clear separation of concerns
simplifies business logic.
• Disadvantages of Orchestration Saga Pattern?
1. Additional design complexity requires an implementation of a coordination logic.
2. There's an additional point of failure, because the orchestrator manages the complete workflow

The orchestrator executes saga requests, stores and interprets the states of each task, handles failure recovery with
compensating transactions.

Circuit Breaker Pattern


The Circuit Breaker pattern is a popular design pattern used in Microservices Architecture, that falls under the Sustainable
Design Patterns category. In Microservices architecture, a service usually calls other services to retrieve data, and there is
the chance that the downstream service may be down. It may be cause by slow network connection, timeouts, or
temporal unavailability. Therefore, retrying calls can solve the issue. However, if there is a severe issue on a particular
microservice, then it will be unavailable for a longer time. In such case, the request will be continuously sent to that
service, since the client doesn’t have any knowledge about a particular service being down. As a result, the network
resources will be exhausted with low performance and bad user experience. Also, the failure of one service might lead
to Cascading failures throughout the [Link], you can use the Circuit Breaker Design Pattern to overcome
this problem.
With the help of this pattern, the client will invoke a remote service through a proxy. This proxy will basically behave as
an electrical circuit breaker. So, when the number of failures crosses the threshold number, the circuit breaker trips for a
particular time period. Then, all the attempts to invoke the remote service will fail within this timeout period. After the
timeout expires, the circuit breaker allows a limited number of test requests to pass through it. If those requests succeed,
the circuit breaker resumes back to the normal operation. Otherwise, if there is a failure, the timeout period begins again.

The Circuit Breaker Design pattern have three states:

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.

API Gateway Design Pattern


✓ In the API Gateway pattern, an additional entity (the API Gateway) is placed between the client and the microservices.
✓ The job of the API Gateway is to aggregate the calls to the microservices.
✓ Rather than the client calling each microservice individually, the client calls the API Gateway a single time.
✓ The API Gateway then calls each of the microservices that the client needs.
Use of the API Gateway Pattern:

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 encloses the whole internal structure of web applications.


2. It never calls a particular service. For example, client interaction with API gateway.
3. It helps in the simplification of code of the client-side.

Disadvantages 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.

The JSP pages follow these phases:

✓ Translation of JSP Page


✓ Compilation of JSP Page
✓ Classloading (class file is loaded by the classloader)
✓ Instantiation (Object of the Generated Servlet is created).
✓ Initialization ( jspInit() method is invoked by the container).
✓ Reqeust processing ( _jspService() method is invoked by the container).
✓ Destroy ( jspDestroy() method is invoked by the container).

JSP Scripting elements:


The scripting elements provide the ability to insert java code inside the jsp.

There are three types of scripting elements:

✓ scriptlet tag (<% java source code %> )


✓ expression tag (<%= statement %>)
✓ declaration tag(<%! field or method declaration %> )

JSP directives:
The jsp directives are messages that tell the web container how to translate a JSP page into the corresponding servlet.

There are three types of directives:

page directive (<%@ page attribute="value" %>)

include directive (<%@ include file="resourceName" %> )

taglib directive (<%@ taglib uri="[Link] prefix="mytag" %>)

JSP Action Tags:


<jsp:forward page="relativeURL | <%= expression %>">

<jsp:param name="parametername" value="parametervalue | <%=expression%>" />

</jsp:forward>

<jsp:include page="relativeURL | <%= expression %>">

<jsp:param name="parametername" value="parametervalue | <%=expression%>" />

</jsp:include>

<jsp:useBean id= "instanceName" scope= "page | request | session | application"

class= "[Link]" type= "[Link]"

beanName="[Link] | <%= expression >" >

</jsp:useBean>

<jsp:setProperty name="instanceOfBean" property= "*" |

property="propertyName" param="parameterName" |

property="propertyName" value="{ string | <%= expression %>}"

/>

<jsp:getProperty name="instanceOfBean" property="propertyName" />

<jsp:plugin type= "applet | bean" code= "nameOfClassFile"

codebase= "directoryNameOfClassFile"

</jsp:plugin>

Syntax for Expression Language (EL): ${ expression }


Precedence of Operators in EL:

There are many operators that have been provided in the Expression Language. Their precedence are as follows:

[] .

()

-(unary) not ! empty

* / div % mod

+ - (binary)

< <= > >= lt le gt ge

== != eq ne

&& and

|| or

?:

Reserve words in EL:

There are many reserve words in the Expression Language. They are as follows:

lt le gt ge

eq ne true false

and or not instanceof

div mod empty null

JSTL (JSP Standard Tag Library):


Tag Name Description

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:import var="data" url="[Link]

<c:set var="Income" scope="session" value="${4000*4}"/>

<c:remove var="income"/>

<c:catch var ="catchtheException"> </c:catch>

<c:if test = "${catchtheException != null}"> </c:if>

<c:choose>

<c:when test="${income <= 1000}">

Income is not good. </c:when>

<c:when test="${income > 10000}">

Income is very good. </c:when>

<c:otherwise>

Income is undetermined...

</c:otherwise>

</c:choose>
<c:forEach var="j" begin="1" end="3">

Item <c:out value="${j}"/><p>

</c:forEach>

<c:forTokens items="Rahul-Nakul-Rajesh" delims="-" var="name">

<c:out value="${name}"/><p>

</c:forTokens>

<c:url value="/[Link]" var="completeURL"/>

<c:param name="trackingId" value="786"/>

<c:param name="user" value="Nakul"/>

</c:url>

<c:redirect url="[Link]

JSTL Function Tags:


<c:if test="${fn:contains(String, 'javatpoint')}"> </c:if>

<c:if test="${fn:containsIgnoreCase(String, 'javatpoint')}"> </c:if>

<c:if test="${fn:endsWith(String, 'programming')}"> </c:if>

<c:if test="${fn:startsWith(String, 'programming')}"> </c:if>

<p>string-1 : ${fn:escapeXml(string1)}</p>

<p>Index-1 : ${fn:indexOf(string1, "first")}</p>

<p>String-1 Length is : ${fn:length(str1)}</p>

<c:set var="str2" value="${fn:split(str1, '-')}" />

<c:set var="str5" value="${fn:join(str2, ' ')}" />

${fn:toLowerCase(string)}

${fn:toUpperCase(site)}

${fn:toUpperCase(site)}

${fn:substringAfter(string, "Nakul")}

${fn:substringBefore(string, "developed")}

${fn:length(str1)}

${fn:replace(author, "Ramesh", "Suresh")}

JSTL Formatting tags:


<fmt:parseNumber var="j" type="number" value="${Amount}" />

<fmt:parseNumber var="j" integerOnly="true" type="number" value="${Amount}" />

<fmt:formatNumber value="${Amount}" type="currency" /></p>

<fmt:formatNumber type="number" groupingUsed="true" value="${Amount}" />

<fmt:formatNumber type="number" maxIntegerDigits="3" value="${Amount}" />

<fmt:formatNumber type="number" maxFractionDigits="6" value="${Amount}" />

<fmt:formatNumber type="percent" maxIntegerDigits="4" value="${Amount}" />

<fmt:formatNumber type="number" pattern="###.###$" value="${Amount}" />

<fmt:parseDate value="${date}" var="parsedDate" pattern="dd-MM-yyyy" />

JSTL XML Tags

JSTL SQL Tags


SQL
Creating connection:

<bean id="dataSource" class="[Link]">

<property name="[Link]" value="[Link]"/>

<property name="[Link]" value="jdbc:mysql://localhost:3306/demoDB"/>

<property name="[Link]" value="root"/>

<property name="[Link]" value="lg225295"/>

</bean>

//<bean id="dataSource" class="[Link]">


//<property name="jndiName" value="java:jboss/datasources/OracleDS" />
//</bean>

<bean id="transactionManager"
class="[Link]">
<property name="dataSource" ref="dataSource" />
</bean>

<bean id="sqlMapClient" class="[Link]">


<property name="configLocation" value="/WEB-INF/config/[Link]" />
<property name="dataSource" ref="dataSource" />
<property name="useTransactionAwareDataSource" value="true" />
</bean>

First we will create a datasource object which will take the driver, connection url, username and password from
[Link] file.

Next create a transactionmanager using datasource.

Next create a sqlMapClient.

[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:

Entity integrity: It specifies that there should be no duplicate rows in a table.

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

1) DBMS applications store data RDBMS applications store data in a


as file. tabular form.

2) In DBMS, data is generally In RDBMS, the tables have an identifier


stored in either a hierarchical called primary key and the data values are
form or a navigational form. stored in the form of tables.

3) Normalization is Normalization is present in RDBMS.


not present in DBMS.

4) DBMS does not apply any RDBMS defines the integrity


security with regards to data constraint for the purpose of ACID
manipulation. (Atomocity, Consistency, Isolation and
Durability) property.

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.

6) DBMS has to provide some RDBMS system supports a tabular structure


uniform methods to access of the data and a relationship between
the stored information. them to access the stored information.

7) DBMS does not support RDBMS supports distributed database.


distributed database.

8) DBMS is meant to be for small RDBMS is designed to handle large


organization and deal with amount of data. it supportsmultiple
small data. it users.
supports single user.

9) Examples of DBMS are file Example of RDBMS


systems, xml etc. are mysql, postgre, sql
server, oracle etc.

✓ SQL is not case sensitive.

SELECT: it extracts data from a database.


UPDATE: it updates data in database.

DELETE: it deletes data from database.

CREATE TABLE: it creates a new table.

ALTER TABLE: it is used to modify the table.

DROP TABLE: it deletes a table.

CREATE DATABASE: it creates a new database.

ALTER DATABASE: It is used to modify a database.

INSERT INTO: it inserts new data into a database.

CREATE INDEX: it is used to create an index (search key).

DROP INDEX: it deletes an index.


Data-type Syntax Explanation

Integer INTEGER The integer data type is used to specify an


integer value.

Smallint SMALLINT The smallint data type is used to specify


small integer value.

Numeric NUMERIC(P,S) It specifies a numeric value. Here 'p' is


precision value and 's' is scale value.

Real REAL The real integer is used to specify a single


precision floating point number.

Decimal DECIMAL(P,S) It specifies a decimal value. Here 'p' is


precision value and 's' is scale value.

Double precision DOUBLE PRECISION It specifies double precision floating point


number.

Float FLOAT(P) It specifies floating-point value e.g. 12.3,


4.5 etc. Here, 'p' is precision value.

Character CHAR(X) Here, 'x' is the character's number to store.

Character VARCHAR2(X) Here, 'x' is the character's number to store


varying

Bit BIT(X) Here, 'x' is the number of bits to store

Bit varying BIT VARYING(X) Here, 'x' is the number of bits to store
(length can vary up to x).

Date DATE It stores year, month and days values.

Time TIME It stores hour, minute and second values

Timestamp TIMESTAMP The timestamp data type is used to store


year, month, day, hour, minute and second
values.

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.

Timestamp with TIMESTAMP with It is same as timestamp but also stores an


time zone TIME ZONE offset from UTC of the time specified.
Generally there are three types of operators in SQL:

1. SQL Arithmetic Operators


2. SQL Comparison Operators
3. SQL Logical Operators

SQL Arithmetic Operators:

Operators Descriptions Examples

+ It is used to add containing values of both a+b will give 150


operands

- It subtracts right hand operand from left hand a-b will give -50
operand

* It multiply both operand?s values a*b will give 5000

/ 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

SQL Comparison Operators:

Operator Description Example

= 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

SQL Logical Operators:

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

IN this operator is used to compare a value to that specified list value

NOT the NOT operator reverse the meaning of any logical operator

OR this operator is used to combine multiple conditions in SQL statements

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

CREATE DATABASE database_name;

DROP DATABASE database_name;

ALTER DATABASE old_name MODIFY NAME = new_name


CREATE TABLE Employee

EmployeeID number(10),

FirstName varchar2(255),

LastName varchar2(255),

Email varchar2(255),

AddressLine varchar2(255),

City varchar2(255)

);

DROP TABLE "table_name";

DELETE FROM table_name [WHERE condition];

But if you do not specify the WHERE condition it will remove all the rows from the table.

DELETE FROM table_name;

TRUNCATE statement: it is used to delete all the rows from the table and free the containing space.

TRUNCATE TABLE employee;

ALTER TABLE table_name RENAME TO new_table_name;

SQL COPY TABLE: SELECT * INTO <destination_table> FROM <source_table>

Local Temp Variable:

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.

CREATE TABLE #local temp table (

User id int,

Username varchar (50),

User address varchar (150)

Global Temp Variable:

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

CREATE TABLE ##new global temp table (

User id int,

User name varchar (50),


User address varchar (150)

SQL ALTER TABLE Add Column:

If you want to add columns in SQL table, the SQL alter table syntax is given below:

ALTER TABLE table_name ADD column_name column-definition;

If you want to add multiple columns in table, the SQL table will be

ALTER TABLE table_name

ADD (column_1 column-definition,

column_2 column-definition,

.....

column_n column-definition);

SQL ALTER TABLE Modify Column:

If you want to modify an existing column in SQL table, syntax is given below:

ALTER TABLE table_name MODIFY column_name column_type;

If you want to modify multiple columns in table, the SQL table will be

ALTER TABLE table_name

MODIFY (column_1 column_type,

column_2 column_type,

.....

column_n column_type);

SQL ALTER TABLE DROP Column:

The syntax of alter table drop column is given below:

ALTER TABLE table_name DROP COLUMN column_name;

SQL ALTER TABLE RENAME Column:

The syntax of alter table rename column is given below:

ALTER TABLE table_name RENAME COLUMN old_name to new_name;

SELECT expressions FROM tables WHERE conditions;

[WHERE Clause]: It specifies which rows to retrieve.


[GROUP BY Clause]: Groups rows that share a property so that the aggregate function can be applied to
each group.

[HAVING Clause]: It selects among the groups defined by the GROUP BY clause.

[ORDER BY Clause]: It specifies an order in which to return the rows.

SELECT DISTINCT column_name ,column_name FROM table_name;

SQL SELECT COUNT(column_name):

SELECT COUNT(name) FROM employee_table;

It will return the total number of names of employee_table. But null fields will not be counted.

SQL SELECT COUNT(*):

SELECT COUNT(*) FROM employee_table;

The "select count(*) from table" is used to return the number of records in table.

SQL SELECT COUNT(DISTINCT column_name):

SELECT COUNT(DISTINCT name) FROM employee_table;

SELECT TOP 2 * FROM employee

SELECT FIRST (CUSTOMER_NAME) AS first_customer FROM CUSTOMERS;

SELECT LAST (CUSTOMER_NAME) AS LAST_CUSTOMER FROM CUSTOMERS;


AJAX
✓ AJAX is an acronym for Asynchronous JavaScript and XML.
✓ AJAX allows you to send and receive data asynchronously without reloading the web page.
So it is fast.

Synchronous (Classic Web-Application Model):

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.

Asynchronous (AJAX Web-Application Model):

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.

AJAX technology includes:

✓ HTML/XHTML and CSS


✓ DOM
✓ XML or JSON
✓ XMLHttpRequest
✓ JavaScript
➢ An object of XMLHttpRequest is used for asynchronous communication between client and server.

Property Description

onReadyStateChange It is called whenever readystate attribute changes. It must not be used with
synchronous requests.

readyState Represents the state of the request. It ranges from 0 to 4.

0 UNOPENED open () is not called.

1 OPENED open is called but send () is not called.

2 HEADERS_RECEIVED send () is called, and headers and status are available.

3 LOADING Downloading data; responseText holds the data.

4 DONE The operations are completed fully.

reponseText Returns response as text.

responseXML returns response as XML

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)

void send() sends get request.

void send(string) send post request.

setRequestHeader(header,value) it adds request headers.


Struts flow

Struts1 Vs Struts2:

Property Struts1 Struts2

Validation Validation Framework Xwork2 (Annotations are also


used)

Action class Not thread safe By default thread safe

View Thechnologies JSP JSP, velocity, facelets..

Front Controller ActionServlet FilterDispatcher

Configuration file name Any name [Link]

DSA
LinkedList
public class LinkedList {

class Node {
int data;
Node next;

public Node(int data) {


[Link] = data;
[Link] = null;
}
}

Node head = null;


Node tail = null;

public void add(int data) {

Node newNode = new Node(data);

if(head == null) {
head = newNode;
tail = newNode;
} else {
[Link] = newNode;
tail = [Link];
}

public void print() {


Node n = head;

while(n != null) {
[Link]([Link] + " ");
n = [Link];
}
[Link]();
}

public Node midNode() {


Node fastNode = head;
Node slowNode = head;

while(fastNode != null && [Link] != null) {


fastNode = [Link];
slowNode = [Link];
}

return slowNode;

public static void main(String[] args) {


LinkedList list = new LinkedList();
[Link](1);
[Link](2);
[Link](3);
[Link](4);
[Link](5);
[Link](6);

[Link]();

[Link]("Mid Node : " + [Link]().data);

}
}
AWS
ECS vs EC2
ECS - Elastic Container Service

EC2 – Elastic Compute Cloud

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

• EC2 - is simply a remote (virtual) machine.


• ECS stands for Elastic Container Service - as per basic definition of computer cluster, ECS is basically a logical grouping
of EC2 machines/instances. Technically speaking ECS is a more configuration for an efficient use and management of
your EC2 instance(s) resources i.e. storage, memory, CPU, etc.

ECS is just about clustering of EC2 instances, and uses Docker to instantiate containers/instances/virtual machines on
these (EC2) hosts.

Mention what the key components of AWS are?


The key components of AWS are

Route 53: A DNS web service

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.

Explain what S3 is?


S3 stands for Simple Storage Service. You can use the S3 interface to store and retrieve any amount of data, at any time
and from anywhere on the web. For S3, the payment model is “pay as you go.

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.

The default storage class is a Standard frequently accessed.

Explain can you vertically scale an Amazon instance? How?


Yes, you can vertically scale on the Amazon instance. For that

• 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.

What are the advantages of auto-scaling?


Following are the advantages of autoscaling

• Offers fault tolerance


• Better availability
• Better cost management
What is SQS?
Simple Queue Service is also known as SQS. It is distributed queuing service which acts as a mediator for two controllers.

What are the different types of Load Balancers in AWS services?


Two types of Load balancers are:

• Application Load Balancer


• Classic Load Balancer

Name some of the DB engines which can be used in AWS RDS


• MS-SQL DB
• MariaDB
• MYSQL DB
• OracleDB
• PostgreDB

What is the difference between Amazon SNS and Amazon SQS?


SNS is a distributed publish-subscribe system. Messages are pushed to subscribers as and when they are sent by
publishers to SNS.

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 {

public static void main(String[] args) {


increasingTriangle(5);
[Link]("__________");
decreasingTriangle(5);
}

static void increasingTriangle(int n) {


for (int row = 1; row <= n; row++) {
for (int col = 1; col <= row; col++) {
[Link]("* ");
}
[Link]();
}
}
// output:
// *
// * *
// * * *
// * * * *

static void decreasingTriangle(int n) {


for (int row = 1; row <= n; row++) {
for (int col = row; col <= n; col++) {
[Link]("* ");
}
[Link]();
}
}

// output:
// * * * *
// * * *
// * *
// *
}

Java Program To Find Duplicate Characters In A String


String s = "dhgfjkdlghfjdkhg";

////////////////////////////////////

Map<Character, Integer> map = new LinkedHashMap<Character, Integer>();

for(int i=0; i < [Link]() ; i++){

char c = [Link](i);

if([Link](c)){

int count = [Link](c);

[Link](c, ++count);

}else{

[Link](c,1);

[Link]("Count using map: "+map);

////////////////////////////////////

[Link]("Count using for loop: ");

for(int i =0; i < [Link](); i++){

int count = 0;

for(int j=0; j < [Link](); j++){

if([Link](i) == [Link](j)){
count++;

[Link]([Link](i)+":"+count+" ");

String d=[Link]([Link](i)).trim();

s=[Link](d,"");

[Link]("");

////////////////////////////////////

String s1 = "test test test 4546";

String[] strings = [Link](s1);

Map<String, Integer> map2 = new LinkedHashMap<String, Integer>();

for (int i = 0; i < [Link]; i++) {

String g = strings[i];

if ([Link](g)) {

int cnt = [Link](g);

[Link](g, ++cnt);

} else {

[Link](g, 1);

[Link]("Count of words using map: "+map2);

////////////////////////////////////

[Link]("Count words using for loop: ");

String s2 = "test test test 4546";

String[] strings1 = [Link](s2);

for(int i=0;i < [Link];i++){

int count =0;

for(int j=0; j < [Link]; j++){

if(strings1[i].equals(strings1[j])){

count++;

}
[Link](strings1[i]+":"+count);

To Find The Sum Of All Digits Of A Number


int i = 45;

char[] chars = [Link](i).toCharArray();

int count =0;

for(char c: chars) {

count += (c-'0');

[Link](count);

Find The Percentage Of Uppercase Letters, Lowercase Letters, Digits And


Other Special Characters In A String

String s ="eMail_Address321@[Link]";

int total = [Link]();

int u =0,l=0,n=0,others=0;

char[] chars = [Link]();

for(char c:chars){

if([Link](c)){

u++;

}else if([Link](c)){

l++;

}else if([Link](c)){

n++;

}else{

others++;

[Link]("Uppercase : "+u+"\nLowercase: "+l+"\nNumbers: "+n+"\nOthers: "+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[] a = new int[] { 10, 3, 20, 5, 6 };

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;

} else if (maxTwo < i) {

maxTwo = i;

[Link](maxOne+" "+maxTwo); }

Max number in an array


public static void main(String[] args) {

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);

To get count of a String present in a file


public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("[Link]");
BufferedReader reader = new BufferedReader(fileReader);
String s = [Link]();
int count = 0;
while(s != null){
//count += [Link]([Link](), "java");

//String tempString = [Link]().replaceAll("java", "");


//count += ([Link]() - [Link]())/"java".length();

while ([Link]().indexOf("java") != -1){


s = [Link]().replaceFirst("java", "");
count++;
}
s = [Link]();
}
[Link](count);
}
public static void main(String[] args) {

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:

public class Sample {

public static void main(String[] args) {


String str = "abcd";
SubString(str, [Link]());
}

// Function to print all substring


public static void SubString(String str, int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
[Link]([Link](i, j));
}
}
}

O/P:

a
ab
abc
abcd
b
bc
bcd
c
cd
d

Option 2:

public class Sample {

public static void main(String[] args) {


String str = "abcd";
SubString(str, [Link]());
}

// Function to print all substring


public static void SubString(String str, int n) {
// First loop for starting index
for (int i = 0; i < [Link](); i++) {
String subStr="";

// Second loop is generating sub-String


for (int j = i; j < [Link](); j++) {
subStr += [Link](j);
[Link](subStr +"\n");
}
}
}
}

Count match
public static void main(String[] args) {
String str = "helloslkhellodjladfjhello";
String findStr = "hello";

[Link]([Link](str,
findStr));
[Link]([Link](str,
findStr));

Reverse Each Word

Option 1:

public static void main(String[] args) {


String ans = "";

String str1="abc def ghi";


int start = 0;
int i = 0;

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;
}
}

String rev = "";


for(int j = start; j < i ; j++) {
rev = [Link](j) + rev;
}
ans = ans + rev;
[Link](ans);
}

Option 2:

public final class Sample {

public static void main(String[] args) {


String str = "abc def ghi";

String[] data = [Link](" ");


String res = "";
for (int i = 0; i < [Link]; i++) {
res += reverse(data[i]);
if (i != [Link] - 1)
res += " ";
}

[Link](res);

public static String reverse(String s) {


String res = "";
for (int i = 0; i < [Link](); i++) {
res = [Link](i) + res;
}
return res;
}

Reverse String Word wise

public static String reverseWordWise(String input) {


// Write your code here

String[] data = [Link](" ");

String res = "";

for(int i = 0; i < [Link]; i++) {


res = data[i] + " " + res;
}

return res;

Remove Consecutive Duplicates


public static String removeConsecutiveDuplicates(String str) {
//Your code goes here

String 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;
}

Merge 2 arrays in sorting order

public static int[] merge(int arr1[], int arr2[]) {


//Your code goes here

int arr1Size = [Link];


int arr2Size = [Link];
int i= 0, j =0, k =0;
int[] arr3 = new int[arr1Size + arr2Size];

while(i < [Link] && j < [Link]) {


if(arr1[i] <= arr2[j]) {
arr3[k] = arr1[i];
i++;
k++;
}
else if(arr1[i] >= arr2[j]) {
arr3[k] = arr2[j];
j++;
k++;
}
}

while(i < arr1Size) {


arr3[k] = arr1[i];
i++;
k++;
}

while(j < arr2Size) {


arr3[k] = arr2[j];
j++;
k++;
}

return arr3;

Push Zeros to End

static void pushZerosToEnd(int arr[], int n)


{
int count = 0; // Count of non-zero elements

// Traverse the array. If element encountered is


// non-zero, then replace the element at index 'count'
// with this element
for (int i = 0; i < n; i++)
if (arr[i] != 0)
arr[count++] = arr[i]; // here count is
// incremented

// Now all non-zero elements have been shifted to


// front and 'count' is set as index of first 0.
// Make all elements 0 from count to end.
while (count < n)
arr[count++] = 0;
}

Second Largest Element

public static int secondLargestElement(int[] arr, int n) {


// Your code goes here

int h = Integer.MIN_VALUE;
int sh = Integer.MIN_VALUE;

for (int i = 0; i < n; i++) {


h = [Link](h, arr[i]);
}

for (int i = 0; i < n; i++) {


if (arr[i] != h)
sh = [Link](sh, arr[i]);
}

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).

public static int search(int []nums, int target) {

int s = 0;

int e = [Link] - 1;

int result = -1;

while(s <= e) {

int mid = ( s + e ) / 2;

if(nums[mid] > target) {

e = mid -1;

} else if(nums[mid] < target) {

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.

public class Solution {

public static void selectionSort(int[] arr) {

for(int i=0; i< [Link]; i++) {

for(int j = i+1; j < [Link]; j++) {

if(arr[i] > arr[j]) {

int temp = arr[j];

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) {

for(int i=0; i < n-1; i++) {

sorted = false;

for(int j=0; j < n-1-i; j++) {

if(arr[j] > arr[j+1]) {

int temp = arr[j];

arr[j] = arr[j+1];

arr[j] = temp;

Find max char in a String

public static void main(String[] args) {

String str = "abdefgbabfba";


char[] ch = [Link]();

Map<Character, Integer> map = new HashMap<>();

for (int i = 0; i < [Link]; i++) {

if ([Link](ch[i])) {
[Link](ch[i], [Link](ch[i]) + 1);

} else {
[Link](ch[i], 1);
}

//To Print all values


[Link]().stream().forEach(e -> [Link]([Link]() + "=" +
[Link]()));

//to get max value char


Character opt =
[Link]().stream().max((e1, e2) ->
[Link]().compareTo([Link]())).get().getKey();

Optional<[Link]<Character, Integer>> opt1 =


[Link]().stream().max([Link]()).stream().findFirst();
[Link]("Max char: " + opt);
[Link]("Max char: " + [Link]().getKey());

// getting the max count from counter map.


Integer maxCharacterCount = [Link]([Link]());
[Link]("Max count: " + maxCharacterCount);

Get Compressed String

public static String getCompressedString(String str) {


// Write your code here.

char[] c = [Link]();

String res = "";

for (int i = 0; i < [Link]; i++) {


int count = 1;
if(c[i] != '*') {
for (int j = i + 1; j < [Link]; j++) {
if (c[i] == c[j]) {
count += 1;
c[j] = '*';
} else if(c[i] != c[j]) {
break;
}
}
}

if(c[i] != '*' && count == 1) {


res += c[i];
} else if(count != 1) {
res += c[i] + "" + count;
}
}
return res;
}

Input: aaabbcddeeeee or aaabbccdsa


O/p: a3b2cd2e5 or a3b2c2dsa

Print all triplets with given sum or 3SUM == 0

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--;
}

// If sum of three elements


// is less than 'sum' then
// increment in left
else if (x + arr[l] + arr[r] < sum)
l++;

// if sum is greater than


// given sum, then decrement
// in right side
else
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);
}
}

Sum of 3 consecutive numbers

public class Test {


public static void main(String[] args) {
int numbers[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int constant = 3;
// o/p: [6,15,24]
for (int i = 0; i < [Link]; i = i + constant) {
int s = sum(numbers, i, constant + i);
[Link]("Sum is: " + s);
}
}

public static int sum(int numbers[], int i, int e) {


int sum = 0;
for (int j = i; j < e; j++) {
sum = sum + numbers[j];
}
return sum;
}
}

Remove minimum number of characters so that two strings become


anagram
Sol1:

public class Sample2 {

final static int CHARS = 26;

static int countDeletions(String str1, String str2) {


int[] count1 = new int[26];
int[] count2 = new int[26];

for(int i=0; i < [Link](); i++) {


count1[[Link](i) - 'a'] = 1;
}

for(int i=0; i < [Link](); i++) {


count2[[Link](i) - 'a'] = 1;
}

int count = 0;
for(int i=0; i < 26; i++) {
if(count1[i] - count2[i] != 0) {
[Link]((char)('a' + i));
count++;
}
}

return count;

static public void main(String[] args) {


String str1 = "bcadeh", str2 = "hea";
[Link](countDeletions(str1, str2));
}
}
Time Complexity : O(n)

Sol2:

public class Sample2 {

static int countDeletions(String str1, String str2) {


int[] count = new int[26];

for(int i=0; i < [Link](); i++) {


count[[Link](i) - 'a']++;
}

for(int i=0; i < [Link](); i++) {


count[[Link](i) - 'a']--;
}

int result = 0;
for(int i=0; i < 26; i++) {
if(count[i]!= 0) {
[Link]((char)('a' + i));
result++;
}
}

return result;

static public void main(String[] args) {


String str1 = "bcadeh", str2 = "hea";
[Link](countDeletions(str1, str2));
}
}
Time complexity: O(n) where n is the total number of characters in both strings.

You might also like