You are on page 1of 56

What is functional programming?

Functional programming is a declarative programming paradigm where


programs are created by applying sequential functions rather than
statements.
Each function takes in an input value and returns a consistent output
value without altering or being affected by the program state.
These functions complete a single operation and can be composed in
sequence to complete complex operations. The functional paradigm results
in highly modular code, since functions can be reused across the program
and can be called, passed as parameters, or returned.

JVM, JRE AND JDK:


*****************

Java Runtime Environment:


The JRE software builds a runtime environment in which Java programs can
be executed. The JRE is the on-disk system that takes your Java code,
combines it with the needed libraries, and starts the JVM to execute it.
The JRE contains libraries and software needed by your Java programs to
run. JRE is a part of JDK (which we will study later) but can be
downloaded separately.

Java Development Kit:


The Java Development Kit (JDK) is a software development environment used
to develop Java applications and applets. It contains JRE and several
development tools, an interpreter/loader (java), a compiler (javac), an
archiver (jar), a documentation generator (javadoc) accompanied with
another tool.

source code.java -> Bytecode -> machine code


compiler interpreter(jvm)

What is Bytecode in Java?


Bytecode in Java is the reason java is platform-independent, as soon as a
Java program is compiled bytecode is generated. To be more precise a Java
bytecode is the machine code in the form of a .class file.

Java Virtual Machine:


We can run this bytecode on any other platform as well. But the bytecode
is a non-runnable code that requires or relies on an interpreter. This is
where JVM plays an important part.The bytecode generated after the
compilation is run by the Java virtual machine.While the bytecode is a
non-runnable code generated by compiling a source code that relies on an
interpreter to get executed.

In Java, there is a process of compilation and interpretation.


The code written in Java (Source code), is converted into byte codes
which is done by the Java Compiler.
The byte codes, then are converted into machine code by the JVM.
The Machine code is executed directly by the machine.

-------------------------------------------------------------------------
-------------------------------------------------
CLASSLOADER:
************

The ClassLoader loads the class into the memory.


Bootstrap Class Loader – It loads JDK internal classes. It loads rt.jar
and other core classes for example java.lang.* package classes.
Extensions Class Loader – It loads classes from the JDK extensions
directory, usually $JAVA_HOME/lib/ext directory.
System Class Loader – This classloader loads classes from the current
classpath. We can set classpath while invoking a program using -cp or -
classpath command line option.

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

0.Method Overloading Vs Method Overriding?


Method Overloading will be resolve during compile time where as
Overriding will be resolve at run time
(which method to be invoked)
For Overriding method signature and return type must be same while it
must be different for overloading.
private, static, final methods - Can't be override but can be overload.
Overriding - scope of access modifier we can not reduce - Parent class
has protected method then child class must have
either protected or public method not private/default it will
give compile time error
throws - Child class method throwing exception parent class must throw
the same of parent exception not its sub class exception.Parent need to
throw its ok if child not throw the exception.

1. Why is Java a platform independent language?


Java language was developed in such a way that it does not depend on any
hardware or software due to the fact that the compiler compiles the code
and then converts it to platform-independent byte code which can be run
on multiple systems.
The only condition to run that byte code is for the machine to have a
runtime environment (JRE) installed in it.

2. Why is Java not a pure object oriented language?


Java supports primitive data types - byte, boolean, char, short, int,
float, long, and double and hence it is not a pure object oriented
language.

3.What is WORA? (Write once Run Anywhere)?


Java applications are called WORA because of their ability to run a code
on any platform. This is done only because of JVM. The JVM is a Java
platform component that provides an environment for executing Java
programs. JVM interprets the bytecode into machine code which is executed
in the machine in which the Java program runs.

4.What are the types of memories in Java?


https://www.educba.com/types-of-memory-in-java/
5.Explain about Garbage collection and how it works in the JVM?
Garbage Collection is the process of reclaiming the runtime unused memory
by destroying the unused objects.
Garbage collector works in two simple steps known as Mark and Sweep:
Mark – it is where the garbage collector identifies which piece of memory
is in use and which are not
Sweep – it removes objects identified during the “mark” phase.

The heap memory area in the JVM is divided into two sections:
1.Young Generation:
Newly created objects start in the Young Generation. The Young
Generation is further subdivided into:
a.Eden space - all new objects start here, and initial memory is
allocated to them
b.Survivor spaces (FromSpace and ToSpace) - objects are moved here
from Eden after surviving one garbage collection cycle.When
objects are garbage collected from the Young Generation, it is a minor
garbage collection event.
2.Old Generation:
Objects that are long-lived are eventually moved from the Young
Generation to the Old Generation. When objects are garbage collected
from the Old Generation, it is a major garbage collection event.You can
use the -Xms and -Xmx flags to set the size of the initial and maximum
size of the Heap memory.

When an object is created, it is first put into the Eden space of the
young generation. Once a minor garbage collection happens, the live
objects from Eden are promoted to the FromSpace (Survivor 1). When the
next minor garbage collection happens, the live objects from both Eden
and FromSpace are moved to the ToSpace(Survivor 2).

This cycle continues for a specific number of times. If the object is


still used after this point, the next garbage collection cycle will move
it to the old generation space.

6.List out different ways of creating java objects?

a. Using new keyword.


Tester tester1 = new Tester();

b. Using Class.forName() method


Tester tester2 = (Tester)Class.forName("Tester").newInstance();

c. Using clone method.


Tester tester3 = tester1.clone();

d. Using Constructor.forName() method


Tester tester4 = Tester.class.getConstructor().newInstance();

e. Using Deserialization
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream
);
Tester tester5 = (MyObject) objectInputStream.readObject();
7.What do you understand by an instance variable, class variable and a
local variable?
Instance variables are those variables that are accessible by all the
methods in the class. They are declared outside the methods and inside
the class. These variables describe the properties of an object and
remain bound to it at any cost.
All the objects of the class will have their copy of the variables for
utilization. If any modification is done on these variables, then only
that instance will be impacted by it, and all other class instances
continue to remain unaffected.

Example:
class Athlete {
public String athleteName;
public double athleteSpeed;
public int athleteAge;
}

Local variables are those variables present within a block, function, or


constructor and can be accessed only inside them. The utilization of the
variable is restricted to the block scope. Whenever a local variable is
declared inside a method, the other class methods don’t have any
knowledge about the local variable.

In object-oriented programming with classes, a class variable is any


variable declared with the static modifier of which a single copy exists,
regardless of how many instances of the class exist.

8.Can you tell the difference between equals() method and equality
operator (==) in Java?

This is a method defined in the Object class.It is a binary operator in


Java.
This method is used for checking the equality of contents between two
objects as per the specified business logic.
This operator is used for comparing addresses (or references), i.e checks
if both the objects are pointing to the same memory location.

String a = new String ("a");


String b = new String ("a");
System.out.println (a == b);
Outcome : false

String a = new String ("a");


String b = new String ("a");
System.out.println (a.equals(b));
Outcome : true

9.Java works as “pass by value” or “pass by reference” phenomenon?


Java always works as a “pass by value”. There is nothing called a “pass
by reference” in Java. However, when the object is passed in any method,
the address of the value is passed due to the nature of object handling
in Java. When an object is passed, a copy of the reference is created by
Java and that is passed to the method.

10.Is it mandatory for a catch block to be followed after a try block?


No, it is not necessary for a catch block to be present after a try
block. - A try block should be followed either by a catch block or by a
finally block. If the exceptions likelihood is more, then they should be
declared using the throws clause of the method.

11.Will the finally block be executed if the code System.exit(0) is


written at the end of try block?
NO. The control of the program post System.exit(0) is immediately gone
and the program gets terminated which is why the finally block never gets
executed.

12.Diff between immutable var and final?


final means that you can't change the object's reference to point to
another reference or another object, but you can still mutate its state
(using setter methods e.g). Whereas immutable means that the object's
actual value can't be changed, but you can change its reference to
another one.

13.Why is String immutable? Diff between String,String buffer and String


builder?
In the String constant pool, a String object is likely to have one or
many references. If several references point to same String without even
knowing it, it would be bad if one of the references modified that String
value. That's why String objects are immutable.

14.What do you understand by marker interfaces in Java?


Marker interfaces, also known as tagging interfaces are those interfaces
that have no methods and constants defined in them. They are there for
helping the compiler and JVM to get run time-related information
regarding the objects. Example, serializable and cloneable interface.

15.OOPS : Polymorphism? runtime and compile time

class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

Output:
drawing rectangle...
drawing circle...
drawing triangle...

A method is overridden, not the data members, so runtime polymorphism


can't be achieved by data members.

class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;

public static void main(String args[]){


Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}

class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
}
class BabyDog1 extends Dog{
public static void main(String args[]){
Animal a=new BabyDog1();
a.eat();
}}

Output : Dog is eating

16.What is serialization?
To serialize an object means to convert its state to a byte stream so
that the byte stream can be reverted back into a copy of the object. A
Java object is serializable if its class or any of its superclasses
implements either the java.io.Serializable interface or its subinterface,
java.io.Externalizable. Deserialization is the process of converting the
serialized form of an object back into a copy of the object

17.What is JIT?
The Just-In-Time (JIT) compiler is a component of the Java™ Runtime
Environment that improves the performance of Java applications at run
time. Java programs consists of classes, which contain platform-neutral
bytecodes that can be interpreted by a JVM on many different computer
architectures.The JIT compiler helps improve the performance of Java
programs by compiling bytecodes into native machine code at run time.

18.What is Association, aggregation and composition?


Association is a relation between two separate classes which establishes
through their Objects. Association can be one-to-one, one-to-many, many-
to-one, many-to-many. In Object-Oriented programming, an Object
communicates to another object to use functionality and services provided
by that object.
Composition and Aggregation are the two forms of association.

class Mobile {
private String mobile_no;
}
Class Mobile HAS-A mobile_no object

Aggregation (loose coupling): In Java, the Aggregation association


defines the HAS-A relationship. Aggregation follows the one-to-one or
one-way relationship. If two entities are in the aggregation composition,
and one entity fails due to some error, it will not affect the other
entity.

Composition (tight coupling): A restricted form of the Aggregation where


the entities are strongly dependent on each other. Unlike Aggregation,
Composition represents the part-of relationship. When there is an
aggregation between two entities, the aggregate object can exist without
the other entity, but in the case of Composition, the composed object
can't exist.

19.What is IS-A relationship?

interface I{}
class A{}
class B extends A implements I{}
Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

20.When should we use abstract class and interface(after java 8)?


Abstract classes should be used primarily for objects that are closely
related, whereas interfaces are best suited for providing common
functionality to unrelated classes.

Consider using abstract classes if any of these statements apply to your


situation:

You want to share code among several closely related classes.


You expect that classes that extend your abstract class have many common
methods or fields or require access modifiers other than public (such as
protected and private).
Consider using interfaces if any of these statements apply to your
situation:

You expect that unrelated classes would implement your interface. For
example, the interfaces Comparable and Cloneable are implemented by many
unrelated classes.
You want to specify the behavior of a particular data type, but not
concerned about who implements its behavior.

21.What are the diff object class methods?

hashCode(): returns the hashcode number for this object.


equals(Object obj): compares the given object to this object.
clone(): creates and returns the exact copy (clone) of this object.
toString(): returns the string representation of this object.
notify(): wakes up single thread, waiting on this object's monitor.
notifyAll(): wakes up all the threads, waiting on this object's monitor.
wait(long timeout): causes the current thread to wait for the specified
milliseconds, until another thread notifies (invokes notify() or
notifyAll() method).
protected void finalize(): is invoked by the garbage collector before
object is being garbage collected.

22.Can we overload static method and main method?


yes

23.Why we Cannot override static method?


Static methods cannot be overridden because they are not dispatched on
the object instance at runtime. The compiler decides which method gets
called. Static methods can be overloaded (meaning that you can have the
same method name for several methods as long as they have different
parameter types). Static methods are bonded using static binding at
compile time
method overinding is based on dynamic binding at runtime.
We can't override the static method because they are the part of the
class, not the object.

24.Transient and Volatile variable?


The Volatile keyword is used to mark the JVM and thread to read its value
from primary memory and not utilize cached value present in the thread
stack. It is used in concurrent programming in java.
Transient Variable: The Transient keyword is used with the instance
variable to eliminate it from the serialization process. During
serialization, the value of the transient field or variable is not saved,
default value would be taken.

25.How to solev diamond problem of multiple inheritence after java 8?

To solve the diamond problem, Java 8 proposes 3 rules to follow. They


are,

Rule 1 : Select classes over interfaces


If your class inherit multiple methods with same signature then a method
from super class is selected (Remember a class can inherit only one
class).

Rule 2 : Select most specific interfaces than general interfaces.


If your class doesn’t extend any class and inherit multiple methods with
same signature from multiple interfaces which belong to same hierarchy,
then a method from most specific interface is selected.

Rule 3 : InterfaceName.super.methodName()
If your class doesn’t extend any class and inherit multiple methods with
same signature from multiple interfaces which doesn’t belong to same
hierarchy, then override that method and from within body explicitly call
desired method as InterfaceName.super.methodName().

26.equals() and hashcode()?


If two Objects are equal, according to the equals(Object) method, then
hashCode() method must produce the same Integer on each of the two
Objects.
If two Objects are unequal, according to the equals(Object) method, It is
not necessary the Integer value produced by hashCode() method on each of
the two Objects will be distinct.

If you don't override hashcode() then the default implementation in


Object class will be used by collections. This implementation gives
different values for different objects, even if they are equal according
to the equals() method.
Object.hashcode() is ''typically implemented by converting the internal
address of the object into an integer

26.If there's abstract class then why interface has default methods java
8 onwards?
The reason we have default methods in interfaces is to allow the
developers to add new methods to the interfaces without affecting the
classes that implements these interfaces.

27.equals() and == in String?

public class MyClass {


public static void main(String args[]) {
String s1= new String("java");
String s2= new String("java");
String s3="java";
String s4="java";
System.out.println(s1.equals(s2));
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s3==s4);
String s1= "java";
s1.concat("dd")
System.out.println(s1)
}
}
Output: true
false
false
true
java

The String.intern() method puts the string in the String pool or refers
to another String object from the string pool having the same value.

28.Why is String immutable?

The String is immutable in Java because of the security, synchronization


and concurrency, caching, and class loading. The reason of making string
final is to destroy the immutability and to not allow others to extend
it.

The String objects are cached in the String pool, and it makes the String
immutable. The cached String literals are accessed by multiple clients.
So, there is always a risk, where action performs by one client affects
all other clients. For example, if one client performs an action and
changes the string value from Pressure to PRESSURE, all remaining clients
will also read that value. For the performance reason, caching of String
objects was important, so to remove that risk, we have to make the String
Immutable.

If we don't make the String immutable, it will pose a serious security


threat to the application. For example, database usernames, passwords are
passed as strings to receive database connections

The String is safe for multithreading because of its immutableness.


Different threads can access a single "String instance". It removes the
synchronization for thread safety because we make strings thread-safe
implicitly.

29.final, finally, finalize?

30.What is Reflection API?


Reflection is an API which is used to examine or modify the behavior of
methods, classes, interfaces at runtime. ... reflect package. Reflection
gives us information about the class to which an object belongs and also
the methods of that class which can be executed by using the object.

31.String vs StringBuilder vs StringBuffer in Java?

32.Design a Singelton class -


Only one instance of the class is available at a time.
1. private constructor
2. private static variabal of the class
3. return the instance from the method

1. Eager Instantiation -

public class Singelton{


private static Singelton instance = new Singelton();
private Singelton(){

public static Singelton getInstance(){


return instance;
}
}

Thread safe

2. Classis Implementation

public class Singelton{


private static Singelton instance = null;

private Singelton(){

public static Singelton getInstance(){


if(instance = null){
instance = new Singelton();
}
return instance;
}
}

But this is not thread safe.

3.Thread Safe singelton class

public class Singelton{


private static Singelton instance = null;

private Singelton(){

public static synchronized Singelton getInstance(){


if(instance = null){
instance = new Singelton();
}
return instance;
}
}

using synchronized evert time is expensive and may decrease


performance.

4.Double checked locking -

public class Singelton{


private static volatile Singelton instance = null;

private Singelton(){

public static synchronized Singelton getInstance(){


if(instance = null){
synchronized(Singelton.class){
if(instance = null){
instance = new Singelton();
}
}
}
return instance;
}
}

best way

Various ways to break singelton -


1. By Using serialization -
Serialization - Object - convert and save it to file.
Serilizing and deserializing will give two instances of the
singelton class - Breaking of singelton.

To Overcome this issue, implement readResolve() method and return


the instace from this method

2. By using clonable interface -


Clonning is the process to create the duplicate objects.

To overcome this
Need to override clone method and throw clone not supported
exception.
So when we try to clone the singelton it will throw the exception.
If you don;t wont to return the exception then return the same
instace from the method.

33. Design an immutable class?

Immutable class -
Once we create an object of a class we are not able to change the object.
If we are trying to change then we can get a new object.

1. Declare class as final so that no other class can overriden it.


We can't make child class of final class.
2. Don't provide setter methods. Setter methods are meant to change
the state of an object.
3. Make all fields private and final.
4. If there are mutable fields then -
A. Collection objects -
for getter method return
Collection.unModifiable****(collection)
B. Date objects -
from the getter method return new
Date(DateObject.getTime)

final Employee e = new Employee(); - What will happen?

e.setSalary(20K) - This can be done

e = new Employee(); - not possible


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

COLLECTION FRAMEWORK: (have a basic understanding of collection framework


before going through the notes)
*********************

Collection is an interface and Collections is an utility class containing


only static methods which operate on Collection objects.

List : Arraylist, linkedlist, vector, Stack

List <data-type> list1= new ArrayList();


List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

diff betw arraylist, vector and linkedlist?

AL:It uses a dynamic array to store the duplicate element of different


data types. The ArrayList class maintains the insertion order and is non-
synchronized. Elements stored in Contiguous memory location.
Whenever an instance of ArrayList in Java is created then by default the
capacity of Arraylist is 10

LL:It uses a doubly linked list internally to store the elements. It can
store the duplicate elements. It maintains the insertion order and is not
synchronized. Elements stored in non Contiguous memory location.

Vector: Vector uses a dynamic array to store the data elements. It is


similar to ArrayList. However, It is synchronized

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

Set : HashSet, LInkedHashset, TreeSet

Set<data-type> s1 = new HashSet<data-type>();


Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();

Diff between hashset, linkedhashset and treeset?


HashSet class implements Set Interface. It represents the collection that
uses a hash table for storage.
LinkedHashSet : Like HashSet, It also contains unique elements. It
maintains the insertion order and permits null elements.
TreeSet: the access and retrieval time of TreeSet is quite fast. The
elements in TreeSet stored in ascending order.

Internal working of HashSet?


Whenever we create a HashSet, it internally creates a HashMap and if we
insert an element into this HashSet using add() method, it actually call
put() method on internally created HashMap object with element you have
specified as it’s key and constant Object called “PRESENT” as it’s value.
So we can say that a Set achieves uniqueness internally through HashMap.

Diff between list and set?


List type data structure is in which we can store the ordered collection
of objects. It can have duplicate values.
Set represents the unordered set of elements which doesn't allow us to
store the duplicate items. We can store at most one null value in Set.

Queue : Priority Queue, Deque, ArrayDeque


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

Map: HashMap, LinkedHashMap, and TreeMap.


A Map doesn't allow duplicate keys, but you can have duplicate values.
HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't
allow any null key or value.

A Map can't be traversed, so you need to convert it into Set using


keySet() or entrySet() method.

Internal working of HashMap?


https://www.geeksforgeeks.org/internal-working-of-hashmap-java/?ref=rp
In HashMap, hashCode() is used to calculate the bucket and therefore
calculate the index of the node of the array where the element has to be
put. equals method is used to check that 2 objects are equal or not. This
method is provided by Object class. For example,

map.put(new Key("vishal"), 20);

Steps:
Calculate hash code of Key {“vishal”}. It will be generated as 118.
Calculate index by using index method it will be 6.
Create a node object as :

Place this object at index 6 if no other object is presented there.


In this case a node object is found at the index 6 – this is a case of
collision.
In that case, check via hashCode() and equals() method that if both the
keys are same.

String is used as key in hashmap since the hashcode of string is stored


in cache memory, so when map.get(key) is called it doesnt caluculate
hashcode again, it just fetches from cache memory

Diff between hashmap, hashtable, synchronized hashmap and concurrent


hashmap?
--------------------
A Hashtable is an array of a list. Each list is known as a bucket. The
position of the bucket is identified by calling the hashcode() method. A
Hashtable contains values based on the key.
Java Hashtable class contains unique elements.
Java Hashtable class doesn't allow null key or value.
Java Hashtable class is synchronized.
The initial default capacity of Hashtable class is 11 whereas loadFactor
is 0.75.
Hashtable class declaration

why HashTable doesn’t allow null and HashMap do?

In order to successfully store and retrieve objects from a HashTable, the


objects used as keys must implement the hashCode method and the equals
method. Since null is not an object, it can’t implement these methods.
HashMap is an advanced version and improvement on the Hashtable. HashMap
was created later.

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

public class MyDistElementEx {

public static void main(String a[]){

HashSet<Price> lhm = new HashSet<Price>();


lhm.add(new Price("Banana", 20));
lhm.add(new Price("Apple", 40));
lhm.add(new Price("Orange", 30));
for(Price pr:lhm){
System.out.println(pr);
}
Price duplicate = new Price("Banana", 20);
System.out.println("inserting duplicate object...");
lhm.add(duplicate);
System.out.println("After insertion:");
for(Price pr:lhm){
System.out.println(pr);
}
}
}

class Price{

private String item;


private int price;

public Price(String itm, int pr){


this.item = itm;
this.price = pr;
}

public int hashCode(){


System.out.println("In hashcode");
int hashcode = 0;
hashcode = price*20;
hashcode += item.hashCode();
return hashcode;
}

public boolean equals(Object obj){


System.out.println("In equals");
if (obj instanceof Price) {
Price pp = (Price) obj;
return (pp.item.equals(this.item) && pp.price == this.price);
} else {
return false;
}
}
}

Output: In hashcode
In hashcode
In hashcode
item: Apple price: 40
item: Orange price: 30
item: Banana price: 20
inserting duplicate object...
In hashcode
In equals
After insertion:
item: Apple price: 40
item: Orange price: 30
item: Banana price: 20

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

public class test {


public static void main(String a[]){

HashSet<Price> lhm = new HashSet<Price>();


lhm.add(new Price("Banana", 20));
lhm.add(new Price("Apple", 40));
lhm.add(new Price("Orange", 30));
System.out.println(lhm);
Price duplicate = new Price("Banana", 70);
System.out.println("inserting duplicate object...");
lhm.add(duplicate);
System.out.println(lhm);

}
}

class Price{

private String item;


private int price;
public Price(String itm, int pr){
this.item = itm;
this.price = pr;
}

@Override
public String toString() {
return "Price{" +
"item='" + item + '\'' +
", price=" + price +
'}';
}
public int hashCode(){
System.out.println("In hashcode");
int hashcode = 0;
hashcode = price*20;
hashcode += item.hashCode();
return hashcode;
}

public boolean equals(Object obj){


System.out.println("In equals");
if (obj instanceof Price) {
Price pp = (Price) obj;
return (pp.price == this.price);
} else {
return false;
}
}
}

[Price{item='Apple', price=40}, Price{item='Orange', price=30},


Price{item='Banana', price=20}]
inserting duplicate object...
In hashcode
[Price{item='Apple', price=40}, Price{item='Orange', price=30},
Price{item='Banana', price=70}, Price{item='Banana', price=20}]

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

Some set insertion prblems:

Set<String> set= new HashSet<>();


set.add("ghf");
set.add("Test");
set.add(null);
System.out.println(set);

output: [null, ghf, Test]


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

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


set.add("ghf");
set.add("Test");
set.add(null);
System.out.println(set);

output: Exception in thread "main" java.lang.NullPointerException


at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at HelloWorld.main(HelloWorld.java:17)

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

Set set= new TreeSet();


set.add("ghf");
set.add(1);
set.add(null);
System.out.println(set);

Exception in thread "main" java.lang.ClassCastException: java.lang.String


cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at HelloWorld.main(HelloWorld.java:16)

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

Set set= new HashSet();


set.add("ghf");
set.add(1);
set.add(null);
System.out.println(set);

output: [null, 1, ghf]


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

If you need to search an elememt in a list of 1000 unique numbers, how


will you procees?
list.contains will compare all elements with the input, so time
complexity is O(n)
set.contains will get the hashcode of the input and find the element in
the set, time complexity is O(1)

In for-each loop, we can’t modify collection, it will throw a


ConcurrentModificationException on the other hand with iterator we can
modify collection.

Comparable and Comparator Interfaces:


https://www.javatpoint.com/difference-between-comparable-and-comparator
---------------------------------------------

fail Fast 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 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
addingnd that’s why they are called fail-safe iterators. Iterator on
CopyOnWriteArrayList, ConcurrentHashMap classes are examples of fail-safe
Iterator.

How Fail Fast Iterator works ?


To know whether the collection is structurally modified or not, fail-fast
iterators use an internal flag called modCount which is updated each time
a collection is modified.Fail-fast iterators checks the modCount flag
whenever it gets the next value (i.e. using next() method), and if it
finds that the modCount has been modified after this iterator has been
created, it throws ConcurrentModificationException.

Note : If you remove an element via Iterator remove() method, exception


will not be thrown. However, in case of removing via a particular
collection remove() method, ConcurrentModificationException will be
thrown.

Not Fail Fast : These iterators require extra memory for cloning of
collection. Ex : ConcurrentHashMap, CopyOnWriteArrayList

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

JAVA 8 FEATURES: (Read and understand each feature in detail)


****************

1.Functional Interfaces and Lambda Expressions


2.Java Stream API for Bulk Data Operations on Collections
3.forEach() method in Iterable interface
4.default and static methods in Interfaces
5.Optional keyword for handling null pointer exception
6.Method references ( ClassName::methodName)
7.Java Time API
8.Improvement in HashMap implementation (LinkedList converted to Binary
tree)
9.Java Spliterator
10.Memory management changes
11.Concurrent hashmap
------------------------------

Java Spliterator is an interface in Java Collection API.


Spliterator is introduced in Java 8 release in java.util package.
It supports Parallel Programming functionality.
We can use it for both Collection API and Stream API classes.

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


names.add("Rams");
names.add("Posa");
names.add("Chinni");

// Getting Spliterator
Spliterator<String> namesSpliterator = names.spliterator();

// Traversing elements
namesSpliterator.forEachRemaining(System.out::println);
-----------------------------------

Memory management changes:

Permanent Generation:
Metadata such as classes and methods are stored in the Permanent
Generation. It is populated by the JVM at runtime based on classes in use
by the application. Classes that are no longer in use may be garbage
collected from the Permanent Generation.
You can use the -XX:PermGen and -XX:MaxPermGen flags to set the initial
and maximum size of the Permanent Generation.

MetaSpace in java 8:
Starting with Java 8, the MetaSpace memory space replaces the PermGen
space. The implementation differs from the PermGen and this space of the
heap is now automatically resized.
This avoids the problem of applications running out of memory due to the
limited size of the PermGen space of the heap. The Metaspace memory can
be garbage collected and the classes that are no longer used can be
automatically cleaned when the Metaspace reaches its maximum size.

The biggest disadvantage of PermGen is that it contains a limited size


which leads to an OutOfMemoryError.

PG: Contiguous Java Heap Memory.


MS: Native Memory(provided by underlying OS).
PermGen has been completely removed in Java 8. In the place of PermGen,
a new feature called Meta Space has been introduced. MetaSpace grows
automatically by default. Here, the garbage collection is automatically
triggered when the class metadata usage reaches its maximum metaspace
size.

The JVM keeps track of loaded class metadata in the PermGen.


Additionally, the JVM stores all the static content in this memory
section. This includes all the static methods, primitive variables, and
references to the static objects.
With its limited memory size, PermGen is involved in generating the
famous OutOfMemoryError. Simply put, the class loaders weren't garbage
collected properly and, as a result, generated a memory leak.

Therefore, we receive a memory space error; this happens mostly in the


development environment while creating new class loaders.
------------------------------------------------------
Lambda expression provides implementation of functional interface. An
interface which has only one abstract method is called functional
interface. Java provides an anotation @FunctionalInterface, which is used
to declare an interface as functional interface.

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

Stream API hands on: https://javaconceptoftheday.com/solving-real-time-


queries-using-java-8-features-employee-management-system/

Map vs FlatMap -

Map -
1. It applies a function on each element of stream and stores the
value returned by the function into a new Stream. This way one stream is
transformed into another e.g. a Stream of String is transformed into a
Stream of Integer where each element is length of corresponding Stream.
2. Key thing to remember is that the function used for
transformation in map() returns a single value

Ex - List listOfIntegers = Stream.of("1", "2", "3", "4")


.map(Integer::valueOf)
.collect(Collectors.toList());

FlatMap -
1. If map() uses a function, which, instead of returning a
single value returns a Stream of values than you have a Stream of Stream
of values, and flatmap() is used to flat that into a Stream of values.

List evens = Arrays.asList(2, 4, 6);


List odds = Arrays.asList(3, 5, 7);
List primes = Arrays.asList(2, 3, 5, 7, 11);

List numbers = Stream.of(evens, odds, primes)


.flatMap(list -> list.stream())
.collect(Collectors.toList());

System.out.println("flattend list: " + numbers); // [2, 4, 6, 3,


5, 7, 2, 3, 5, 7, 11]

Diff -

1. The function you pass to map() operation returns a single value.


2. The function you pass to flatMap() opeartion returns a Stream of
value.
3. flatMap() is combination of map and flat operation.
4. map() is used for transformation only, but flatMap() is used for both
transformation and flattening.

1.Given a list of students, write a Java 8 code to partition the students


who got above 60% from those who didn’t?
Map<Boolean, List<Student>> studentspartionedByPercentage =
studentList.stream().collect(Collectors.partitioningBy(student ->
student.getPercentage() > 60.0));
2.Given a list of students, write a Java 8 code to get the names of top 3
performing students?
List<Student> top3Students =
studentList.stream().sorted(Comparator.comparingDouble(Student::getPercen
tage).reversed()).limit(3).collect(Collectors.toList());

3.Given a list of students, how do you get the name and percentage of
each student?
Map<String, Double> namePercentageMap =
studentList.stream().collect(Collectors.toMap(Student::getName,
Student::getPercentage));

4.Given a list of students, how do you get the subjects offered in the
college?
Set<String> subjects =
studentList.stream().map(Student::getSubject).collect(Collectors.toSet())
;

5.Given a list of employees, get the details of the most youngest


employee in the organization?
Optional<Employee> youngestEmployee =

employeeList.stream().min(Comparator.comparingInt(Employee::getAge));

6.Map<BlogPostType, Optional<BlogPost>> maxLikesPerPostType =


posts.stream()
.collect(groupingBy(BlogPost::getType,
maxBy(comparingInt(BlogPost::getLikes))));

7. // The lambda expression passed to


// reduce() method takes two Strings
// and returns the longer String.
// The result of the reduce() method is
// an Optional because the list on which
// reduce() is called may be empty.
Optional<String> longestString = words.stream()
.reduce((word1, word2)
-> word1.length() > word2.length()
? word1 : word2);

// Displaying the longest String


longestString.ifPresent(System.out::println);
---------------------------------------------------------

Name three important classes of Java 8 Date and Time API?

java.time.LocalDate, java.time.LocalTime and java.time.LocalDateTime

How do you get current date and time using Java 8 features?

LocalDateTime currentDateTime = LocalDateTime.now();


-------------------------------------------------------------
In Java 8 there are 4 main functional interfaces are introduced which
could be used in different scenarios. These are given below.
- Consumer - 2 types Consumer - Bi-consumer
- Predicate - 2 types predicate - Bi predicate
- Function - 4 types BiFunction, UnaryOperator,
BinaryOperator
- Supplier

1. Consumer :
The consumer interface accepts one argument but there is
no return value.
The name of function inside this interface is accept.
The below consumer is accepting one argument and print
it in upper case. But there is no return value.

@FunctionalInterface
Public interface Consumerr<T>{
void accept(T t);
}
Consumer<String> ucConsumer = (s) ->
System,out.println(s.toUpperCase());

2. Bi Consumer :
The extension of the Consumer which is BiConsumer
accepts two arguments and return nothing.

@FunctionalInterface
Public interface BiConsumerr<T,U>{
void accept(T t,U u);
}
BiConsumerr<String,String> biConsumer = (x,y) ->
System,out.println("x : "+x+"y : "+y);

3. predicate :
Predicate will accept one argument, do some processing
and then return boolean

@FunctionalInterface
Public interface Predicate<T>{
void test(T t);
}
Predicate<Integer> p = (i) -> {return i % 2 == 0});

4. Bi Predicate :
Instead of one argument BiPredicate will accept two
arguments and return nothing.

5. Function :
This interface accepts one argument and return a value
after the required processing. It is defined as below. The required
processing logic will be executed on invocation of the apply method.
In the below example, the Function is accepting one
string and also returns one string.
@FunctionalInterface
Public interface Function<T,R> {
R apply(T t);
}
static Function <String,String> upperCase = (name) ->
name.toUpperrCase();

6. BIFUNCTION :
The BiFunction is similar to Function except it accepts
two inputs whereas Function accepts one argument. The sample code for the
BiFunction interface is given below. In the below interface code T, U are
the inputs and R is the single output.

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

EXCEPTION HANDLING:
*******************

What Is the Purpose of the Throw and Throws Keywords?


The throws keyword is used to specify that a method may raise an
exception during its execution.
The throw keyword allows us to throw an exception object to interrupt the
normal flow of the program.

The block of code in which an exception may occur is enclosed in a try


block. This block is also called “protected” or “guarded” code.

If an exception occurs, the catch block that matches the exception being
thrown is executed, if not, all catch blocks are ignored.

The finally block is always executed after the try block exits, whether
an exception was thrown or not inside it.

What Is the Difference Between a Checked and an Unchecked Exception?


A checked exception must be handled within a try-catch block or declared
in a throws clause; whereas an unchecked exception is not required to be
handled nor declared.

Checked and unchecked exceptions are also known as compile-time and


runtime exceptions respectively.

All exceptions are checked exceptions, except those indicated by Error,


RuntimeException, and their subclasses.

OutOfMemoryError – thrown when the JVM cannot allocate more objects


because it is out memory, and the garbage collector was unable to make
more available
StackOverflowError – occurs when the stack space for a thread has run
out, typically because an application recurses too deeply

// class representing custom exception

class InvalidAgeException extends Exception


{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
----
static void validate (int age) throws InvalidAgeException{
if(age < 18){

// throw an object of user defined exception


throw new InvalidAgeException("age is not valid to vote");
}
else {
System.out.println("welcome to vote");
}
}
}

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

What is constructor chaining in Java?

In Java, constructor chaining is a sequence of invoking constructors upon


initializing an object.

class ParentClass{
int a;
ParentClass(int a){
System.out.println("Inside ParentClass parameterized
constructor!");
this.a = a;
}
ParentClass(){
System.out.println("Inside ParentClass default
constructor!");
}
}
class ChildClass extends ParentClass{

ChildClass(){
System.out.println("Inside ChildClass constructor!!");

}
}
public class ConstructorInInheritance {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

}
}

Output:
Inside ParentClass default constructor!
Inside ChildClass constructor!!

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

SOLID PRINCIPLES:
*****************

SOLID Principle -
Single Responsibility Principle (SRP)
Open-Closed Principle (OCP)
Liskov Substitution Principle (LSP)
Interface Segregation Principle (ISP)
Dependency Inversion Principle (DIP)

O - Open/Closed principle - Open for extension but closed for


modification which means any new functionality should be implemented by
using new classes, attributes and methods.

What if we do not follow this -


if a class or function always allow addition of new logic we need to test
an entire functionality
not following this we are also not following SRP.
Maintanance of the class become difficult.

Ex. We need to calculate the bonus of an employee.


as per this req we will create an employee POJO class and service layer
class which calculate the bonus by using calculateBonus() method.
We are done with everything and then there is an enhancement that
permanent employee will have 10% bonus and temporary will have 5%.
Now rather than changing the logic in the calculateBonus method we will
have that class as an abstract and the method as well
We will provide two implementation of the main abstract class one is for
permanent and other for contact.

L - Liskov Substitution Principle -


S is a subtype of T, then objects of typr T may be replaced
with object of type S.
Derived type must be completly substituable for their base
type

I - interface segeration - larger interface to split in smaller ones. so


that implementing classes only needs to concern about methods that
interest them

D - dependency inversion - refers to decouple software modules. high-


level modules should not depend upon low-level modules; they should
depend on abstractions.
-------------------------------------------------------------------------
---------------------------------------------

DESIGN PATTERNS:
****************

Creational Design Pattern


|- Singleton Pattern : Singleton pattern restricts the
instantiation of a class and ensures that only one instance of the class
exists in the Java virtual machine.
|- Factory Pattern : The factory design pattern is used when
we have a superclass with multiple sub-classes and based on input, we
need to return one of the sub-class.
|- Abstract Factory Pattern : we get rid of if-else block and
have a factory class for each sub-class and then an Abstract Factory
class that will return the sub-class based on the input factory class.
|- Builder Pattern: solve some of the problems with Factory
and Abstract Factory design patterns when the Object contains a lot of
attributes.
|- prototype Pattern

Structural Design Pattern


|- Adapter Pattern
|- Composite Pattern
|- proxy Pattern
|- flyway Pattern
|- Facade Pattern
|- Bridge Pattern
|- Decorator Pattern

Behavioural Design Pattern


|- Temolate method Pattern
|- Meditator Pattern
|- Chain of Responsibility Pattern
|- Observer Pattern
|- Strategy Pattern
|- Command Pattern
|- State Pattern
|- Visitor Pattern
|- Interpretor Pattern
|- Iterator Pattern
|- Momento Pattern

Miscellaneous Design Patterns


|- DAO design Patterns
|- Dependency Injection Patterns
|- MVC Patterns

1 Singleton Pattern:
Eager initialization :
public class EagerInitializedSingleton
{
private static final
EagerInitializedSingleton instance = new EagerInitializedSingleton();
// eager
private
EagerInitializedSingleton(){}
public static
EagerInitializedSingleton getInstance(){
return instance;
}
}

Static block initialization


public class StaticBlockSingleton {
private static StaticBlockSingleton
instance;
private StaticBlockSingleton(){}
static{
try{
instance = new
StaticBlockSingleton();
}catch(Exception e){
throw new
RuntimeException("Exception occured in creating singleton instance");
}
}
public static StaticBlockSingleton
getInstance(){
return instance;
}
}
Lazy Initialization
public class LazyInitializedSingleton {
private static LazyInitializedSingleton
instance;
private LazyInitializedSingleton(){}
public static
LazyInitializedSingleton getInstance(){
if(instance == null){
instance = new
LazyInitializedSingleton();
}
return instance;
}
}
Thread Safe Singleton

public class ThreadSafeSingleton {


private static ThreadSafeSingleton
instance;
private ThreadSafeSingleton(){}
public static synchronized
ThreadSafeSingleton getInstance(){ // same as lazy
loading just used synchronized
if(instance == null){
instance = new
ThreadSafeSingleton();
}
return instance;
}
}
Bill Pugh Singleton Implementation
public class BillPughSingleton {
private BillPughSingleton(){}
private static
class SingletonHelper{
private
static final BillPughSingleton INSTANCE = new BillPughSingleton();
// Inner class is created and is loaded inly when getInstance is called.
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
Using Reflection to destroy Singleton Pattern
Enum Singleton
Serialization and Singleton
-------------------------------------------------------------------------
-----------------------------------

MULTITHREADING:
***************

Two ways to use threads in Java?


There are two ways to start a new Thread – Subclass Thread and implement
Runnable.

Which one is preferred and Why?


What is the actual need to use join() method when we are working with
threads?
How does this differ from sleep() and yield()?

Can you explain the Java thread lifecycle?

Java thread life cycle is as follows:


New – When the instance of the thread is created and the start() method
has not been invoked, the thread is considered to be alive and hence in
the NEW state.
Runnable – Once the start() method is invoked, before the run() method is
called by JVM, the thread is said to be in RUNNABLE (ready to run) state.
This state can also be entered from the Waiting or Sleeping state of the
thread.
Running – When the run() method has been invoked and the thread starts
its execution, the thread is said to be in a RUNNING state.
Non-Runnable (Blocked/Waiting) – When the thread is not able to run
despite the fact of its aliveness, the thread is said to be in a NON-
RUNNABLE state. Ideally, after some time of its aliveness, the thread
should go to a runnable state.
A thread is said to be in a Blocked state if it wants to enter
synchronized code but it is unable to as another thread is operating in
that synchronized block on the same object. The first thread has to wait
until the other thread exits the synchronized block.
A thread is said to be in a Waiting state if it is waiting for the signal
to execute from another thread, i.e it waits for work until the signal is
received.
Terminated – Once the run() method execution is completed, the thread is
said to enter the TERMINATED step and is considered to not be alive.

What is concurrency and multithreading in Java?


Multitasking - Multiple tasks/processes running concurrently on a single
CPU. The operating system executes these tasks by switching between them
very frequently.

Is multithreading concurrent or parallel?


Multithreading on multiple processor cores is truly parallel. Individual
microprocessors work together to achieve the result more efficiently.
There are multiple parallel, concurrent tasks happening at once

Multiprocessing - Multiple Processors/CPUs executing concurrently. The


unit of concurrency here is a CPU.

Multitasking - Multiple tasks/processes running concurrently on a single


CPU. The operating system executes these tasks by switching between them
very frequently. The unit of concurrency, in this case, is a Process.

Multithreading - Multiple parts of the same program running concurrently.


In this case, we go a step further and divide the same program into
multiple parts/threads and run those threads concurrently.

start() and run():

start method can't be invoked more than once on same object otherwise it
will throw java.lang.IllegalThreadStateException.
As already stated that in case of calling start method a new thread is
created along with the current thread so atleast two threads are there
and hence multithreading is introduced.

run method on other hand do not throws any type of exception if it is


being get called more than once.So multiple invocation is possible in
case of run method.
On other hand in case of direct calling of run method no new thread is
created and task is made to be executed on same current thread so only
one thread is there and hence no multithreading is introduced.
----------------

Can you tell which thread is going to sleep after calling


myThread.sleep(5000) in the below program? is it main thread or myThread?

class MyThread extends Thread


{
@Override
public void run()
{
for (int i = 0; i <= 10000; i++)
{
System.out.println(i);
}
}
}

public class JavaThreadsInterviewQuestions


{
public static void main(String[] args)
{
MyThread myThread = new MyThread();

myThread.start();

try
{
myThread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
It is the main thread which is going to sleep not myThread. Because, when
you call sleep() method, it is currently executing thread which is going
to sleep, not on which you have called it.

To sleep myThread in the above program, call Thread.sleep() inside the


run() method of MyThread class.
-------------------------------------------------

The TheadLocal construct allows us to store data that will be accessible


only by a specific thread.

Let's say that we want to have an Integer value that will be bundled with
the specific thread:

ThreadLocal<Integer> threadLocalValue = new ThreadLocal<>();

Java ThreadLocal is used to create thread local variables. We know that


all threads of an Object share it’s variables, so the variable is not
thread safe. We can use synchronization for thread safety but if we want
to avoid synchronization, we can use ThreadLocal variables.
Every thread has it’s own ThreadLocal variable and they can use it’s
get() and set() methods to get the default value or change it’s value
local to Thread.

Constructor - ThreadLocal tl = new ThreadLocal();

Methods -
1. Object get() - returns the value of thread local variable associated
with current Thread.
2. Object initialValue() - returns the initial value of thread local
variable associated with current thread. (default value NULL)
3. void set(Object newValue) - to set a new value to thread local
4. void remove() -to remove the value of thread local variable associated
with current thread
---------------------------------------------------------

Runnable and Callable Interface:

A task that returns a result and may throw an exception. Implementors


define a single method with no arguments called call. The Callable
interface is similar to Runnable , in that both are designed for classes
whose instances are potentially executed by another thread.
Runnable cannot return the result of computation which is essential if
you are performing some computing task in another thread, and Runnable
cannot throw checked exceptions

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

Java Concurrency API: Java executor framework


(java.util.concurrent.Executor), 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.

Java Concurrency API defines the following three executor interfaces that
covers everything that is needed for creating and managing threads -

Executor - A simple interface that contains a method called execute() to


launch a task specified by a Runnable object.

ExecutorService - A sub-interface of Executor that adds functionality to


manage the lifecycle of the tasks. It also provides a submit() method
whose overloaded versions can accept a Runnable as well as a Callable
object. Callable objects are similar to Runnable except that the task
specified by a Callable object can also return a value. We’ll learn about
Callable in more detail, in the next blog post.

ScheduledExecutorService - A sub-interface of ExecutorService. It adds


functionality to schedule the execution of the tasks.

Some types of Java Executors are listed below:

SingleThreadExecutor: ExecutorService executor =


Executors.newSingleThreadExecutor();

FixedThreadPool(n)+ : ExecutorService fixedPool =


Executors.newFixedThreadPool(2);

CachedThreadPool: ExecutorService executorService =


Executors.newCachedThreadPool();
ScheduledExecutor: ScheduledExecutorService scheduledExecService =
Executors.newScheduledThreadPool(1);

Creating a thread is an expensive operation and it should be minimized.


Having worker threads minimizes the overhead due to thread creation
because executor service has to create the thread pool only once and then
it can reuse the threads for executing any task.

how we decide on the size of threadpool?


int numOfCores = Runtime.getRuntime().availableProcessors();
Number of threads = Number of Available Cores * (1 + Wait time / Service
time)

Java provides a Callable interface to define tasks that return a result.


A Callable is similar to Runnable except that it can return a result and
throw a checked exception.

The submit() method of executor service submits the task for execution by
a thread. However, it doesn’t know when the result of the submitted task
will be available. Therefore, it returns a special type of value called a
Future which can be used to fetch the result of the task when it is
available.

Future<String> future = executorService.submit(callable);

// This line executes immediately


System.out.println("Do something else while callable is getting
executed");

System.out.println("Retrieve the result of the future");


// Future.get() blocks until the result is available
String result = future.get();

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

// Java program to demonstrate the use of wait() method

class GunFight {
private int bullets = 40;

// This method fires the number of bullets that are


// passed it. When the bullet in magazine becomes zero,
// it calls the wait() method and releases the lock.
synchronized public void fire(int bulletsToBeFired)
{
for (int i = 1; i <= bulletsToBeFired; i++) {
if (bullets == 0) {
System.out.println(i - 1
+ " bullets fired and "
+ bullets + " remains");
System.out.println(
"Invoking the wait() method");
try {
wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(
"Continuing the fire after reloading");
}

bullets--;
}
System.out.println(
"The firing process is complete");
}

// reload() increases the bullets by 40 everytime it is


// invoked and calls the notify() method which wakes up
// the thread that was sent to sleep using wait() inside
// of fire() method
synchronized public void reload()
{
System.out.println(
"Reloading the magazine and resuming "
+ "the thread using notify()");
bullets += 40;
notify();
}
}

public class WaitDemo extends Thread {


public static void main(String[] args)
{

GunFight gf = new GunFight();

// Creating a new thread and invoking


// our fire() method on it
new Thread() {
@Override public void run() { gf.fire(60); }
}.start();

// Creating a new thread and invoking


// our reload method on it
new Thread() {
@Override public void run() { gf.reload(); }
}.start();
}
}

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

JAVA CONCEPT AND CODING QUESTIONS:


**********************************
1. Given a String Paragrah, calculate the number of words which are
repeating thrice.
-- Brute Force is with two loops. -- Optimised - Str.split(" ") and then
put this data in HashMap and return value > 3. 2.

2. Design a Singleton class for me. - Lazy loading vs Eager Loading -


Will it always be thread safe? If not make the change to make it always
thread safe.

3. Wrtie bubble sort for strings.

4. What is immutability ? How will you design an immutable class? Deep


cloned?

5. When should we use LinkedHashMap? What is the internal data structure


for this? Is it thread Safe? - When insertion order needs to be
preserved. - HashTable + Double Linked List

6. Two ways to use threads in Java? Which one is preferred and Why? --
What is the actual need to use join() method when we are working with
threads? -- How does this this differ from sleep() and yield()?

7. Can I use synchronized keyword with Static methods? If not, then why?
If yes, what is the consequence?

8. Find all possible pairs from a given integer array whose sum is equal
to a pre-defined integer x. - [1, 2, 3, 4, 5, 6] & x = 7 SO ANS = [(1,
6), (6, 1), (2, 5), (5, 2), (3, 4), (4, 3)] - Brute Force & Hashing

9. Revere a String without using StringBuilder or reverse(). - Use


toCharArray() and loop.

10. Given an integer array - remove all the duplicates. - Brute Force and
Hashing.

11. How to identify the from the random char array , whether it is
palindrom or not.

12. what are the OOPS concept with example?


13. what is encapsulation?
14. What is serialization ? What is the way to not include a object to be
serialized?
15. What is Relfection API?
16. Desgin patterns , any design patterns you have used , expalin them.
17. Scenario based questions on constructor , method overloading & method
overriding - with indepth reasoning
18. Design a singleton class
------------------------------

How to get distinct characters and their count in a String?


We can create the character array from the string. Then iterate over it
and create a HashMap with the character as key and their count as value.

String str1 = "abcdABCDabcd";


char[] chars = str1.toCharArray();

Map<Character, Integer> charsCount = new HashMap<>();

for(char c : chars) {
if(charsCount.containsKey(c)) {
charsCount.put(c, charsCount.get(c)+1);
}else
charsCount.put(c, 1);
}

System.out.println(charsCount); // {a=2, A=1, b=2, B=1, c=2, C=1, d=2,


D=1}

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

Consider the following program to remove negative values from an


arraylist:
List&lt;Integer&gt; numbers = new ArrayList&lt;&gt;(Arrays.asList(1,24,-
1,8,-3,0)); for (Integer i:
numbers) If (i&lt;0) numbers.remove(i); } } What is likely to happen?
Follow up with a
discussion on what this kind of iterator is called and how to resolve
this issue.

Design a class such that only one instance of the class and any of its
sub-classes can
be created. To clarify: Assume A is such a class and B is derived from A.
B does not
have any special code apart from extending A new A(); // works fine. new
A(); // causes
an exception new B(); // works fine as this is the first instance of B
new B(); // causes an
exception.

Design a new implementation of the Map interface which will also keep a
count of all the
calls to add a key value pair in the Map. It should count the calls to
put, putAll and
putIfAbsent methods. The implementation should also be able to provide
all the features
of any Map implementation that user wants. (e.g. HashMap, TreeMap etc)

You have received a csv file from stock exchange in following format:
timestamp,
symbol, price, qty, account, buy/sell This file may have millions of
records and
represents the trading activity for the day. The file is not sorted You
need to choose the
most optimal collections for holding this data in order to provide
analytics efficiently.
Write a Unix command to give the names of 10 last modified files in the
current
directory.

We have two tables - T1 and T2. Both have a VARCHAR column called ID in
both the
tables. Write a query to get the count of each ID across both the tables.
e.g. T1: | T2: ID
| ID --- | --- A | B B | C C | D Expected output: ID ---- A, 1 B, 2 C, 2
D, 1

Create two threads A and B, each printing numbers from 1 to 100 in a


sequence. Put a
constraint that thread B cannot go ahead of thread A at any point. The
threads should
operate independently apart from this constraint.

Design a Fixed Thread Pool ExecutorService

Can one use an Employee class as a key in a HashMap? (This is a very


important question. If this is not answered satisfactorily, mark the
candidate as knowledge gap as best case scenario irrespective of answers
to other questions / scenarios) You are using a class from a library (say
Student). You have a list of Student objects. You need to sort this list
based on first name. How will you do it? Constraint: (You do not have the
ability to change the source code of the Student class)

Consider a class Person with two attributes - String name and


List&lt;String&gt; degrees. How will you make this class immutable. Ask
what are the advantanges of immutable classes. (If candidate is unable to
answer atleast 2 of below questions,they should be marked as knowledge
gap irrespective of answers to other questions / sceanrios)

Consider a class A with a synchronized method class A { public void


synchronized m1() {Thread.sleep(5000);} } We create two objects of this
class - o1 and o2. We call o1.m1() on one thread and o2.m1() on another
thread, at the same time. What will be the behaviour? Follow up with -
how will you force these calls to execute one after the other

We have a Parent class with 2 methods walk and run. We have a child class
which overrides both the methods. Both child class methods just call
their respective Super implementation. Parent class run method calls
walk(). class Parent Parent p = new Child(); p.run(); Tell the order in
which each method is called

Given a List of integers (List&lt;Integer&gt;), write code in Java 8


style to get the sum of the squares of all the odd numbers in the array.

Explain what the following command does on Unix: chmod 764 file1

We have a table called BookAuthor. It has two columns Book and Author,
Book being unique column. Write a query to find the names of the authors
who have written more than 10 books.
Given an array of n integers and a number k, find the pairs of numbers in
the array such that the difference between the pair is k. Find the
optimal solution with and without extra storage

write a fibonacci without loop

Given an integer array - remove all the duplicates.

How to reverse a String in Java?

public class StringPrograms {

public static void main(String[] args) {

String str = "123";


System.out.println(reverse(str));
}

public static String reverse(String in) {


if (in == null)
throw new IllegalArgumentException("Null is not valid
input");

StringBuilder out = new StringBuilder();

char[] chars = in.toCharArray();

for (int i = chars.length - 1; i >= 0; i--)


out.append(chars[i]);

return out.toString();
}
}

Q.inputArr[] = {3,1,5,2,7,1}
S >= 7 (sum of subarray)
Write a program which returns the size of the smallest subarray whose sum
is equal to or greater than S.

Q.String NUM1 = "68358695869862424242409857564738299";


String NUM2 = "127869654298765433681";
find sum by putting these values in stack

top 50 coding q: https://javarevisited.blogspot.com/2017/07/top-50-java-


programs-from-coding-Interviews.html#axzz7iNEiPZeJ

array questions: https://medium.com/techie-delight/huge-collection-of-


array-interview-questions-e87ac7c34e62

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

jpa is specification for persisting java obj in rdbms, hibernate is ORM


Hibernate is a Java framework that simplifies the development of Java
application to interact with the database. It is an open source,
lightweight, ORM (Object Relational Mapping) tool. Hibernate implements
the specifications of JPA (Java Persistence API) for data persistence.

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

MICROSERVICES:
**************

Microservice architecture, is an architectural style that structures an


application as a collection of small autonomous services, modeled around
a business domain. In a Microservice Architecture, each service is self-
contained and implements a single business capability.

https://www.edureka.co/blog/microservices-design-patterns

1.diff between microservice and monolithic? which one is preferred and


when?
2.different microservice design patterns

API gateway: it acts as a proxy between client and backend services and
routes the requests to the corres microservice. it can decompose a single
client req to multiple requests to backend services.
auth,authenticationa nd SSl certification can be done in api gateway

API Gateway ->


- is the single entry point for all clients
- Acts as an entry point for our APIs

Fallback provides an alternative solution during a service request


failure. When the circuit breaker trips and the circuit is open, a
fallback logic can be started instead. The fallback logic typically does
little or no processing, and return value.

Service discovery : The Service Discovery mechanism helps us know where


each instance is located. In this way, a Service Discovery component acts
as a registry in which the addresses of all instances are tracked. A
microservice needs to know the location (IP address and port) of every
service it communicates with.

Service discovery and service registration -

1. Interactions between microservices and the registry (registration)


A. Self-registration
B. Third-party registration
2. Interactions between clients and the registry (discovery)
A. Client-side discovery
B. Server-side discovery

Service registry -

Self registration ->


Self-registration forces microservices to interact with the registry by
themselves.
When a service goes up, it notifies the registry. The same thing happens
when the service goes down.
Whatever additional data is required by the registry must be provided by
the service itself.

Microservice -> (When service goes up/dpwn) ->


Service registry

Third-party registration ->


Third-party registration is normally used in the industry. In this case,
there is a process or service that manages all other services.
Third-party registration is commonplace in architectures that use tools
such as Apache ZooKeeper or Netflix Eureka and other service managers.

Microservice -> (When service goes up/dpwn) -> Service Manager ->
Service registry

Client side service discovery

Step1 - client ask service discovery abt service2


Step2 - Service discovery provides the address of service 2
Step3 - Client will call service2

phone book

Server side service discovery

Step1 - client will told service discovery abt he wants to connect with
service2
Step2 - Service discovery will connect with service2 and told it abt
client.

- Microservices Arcitecture
-- SAGA Pattern

-- Service Discovery
-- Netflix Eureka etc.
-- Client Side
-- Server Side
-- Pros and Cons of the above

-- Load Balancer
-- Nginx etc.

-- API Gateway
-- Kong etc.

-- Centralized Configuration
-- Consul
-- Ansible
-- Chef
-- Caching Mechanism
-- Redis

-- Containerization
-- Docker
-- Kubernetes

-- Centralized Logging
-- Zipkin etc.

-- Migration
-- Things to consider when migrating a Monolith application to
Microservices.
---------------------

ResponseEntity<User> response
= new RestTemplate().getForEntity(
"http://localhost:8080/users/{userId}",
User.class, params);

circuit breaker : The Circuit Breaker pattern is a popular design pattern


used in Microservices. 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 application.

Therefore, 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:


Closed
Open
Half-Open

Microservice | Centralize Logging using ELK - Stack| PART-6 | Javatechie


https://www.youtube.com/watch?v=9g-h1biMn2E&ab_channel=JavaTechie

hibernate
design patterns

SQL:
****

1.Types of join
2.diff between delete, drop and truncate
3.DDL and DML
4.cluster and non cluster index
5.What is a Schema? schema is a logical collection of database objects
such as tables, views, stored procedures, indexes, triggers, functions.

SELECT P.name Child, p2.name mother, p3.name father


FROM relation R
JOIN people P ON R.cid = P.id
JOIN people P2 ON R.pid = P.id
AND P.gender = 'F'
JOIN people P3 ON R.pid = P.id
AND P.gender = 'M'

1.7th highest Salary


2.Pros and Cons of using Indexing.
3.INNER JOIN vs FULL OUTER JOIN

SELECT OrderID, COUNT(OrderID)


FROM Orders
GROUP BY OrderID
HAVING COUNT(OrderID)>1

Q11. Write a query find number of employees whose DOB is between


02/05/1970 to 31/12/1975 and are grouped according to gender
1
SELECT COUNT(*), Gender FROM EmployeeInfo WHERE DOB BETWEEN '02/05/1970 '
AND '31/12/1975' GROUP BY Gender;

GRANT & REVOKE are the popular members of the SQL family. These are the
types of DCL commands that are used to assign permission to the users to
perform a different task. The GRANT command is used for permitting the
users whereas the REVOKE command is used for removing the authorization.

how rollback works after we delete?

Table :
ID FName SName LName Salary
1 Har preet Singh 30000
2 Ashu NULL Rana 50000
3 NULL Vinay Thakur 40000
4 NULL Vinay NULL 10000
5 NULL NULL Rajveer 60000
6 Manjeet Singh NULL 60000

Find name of employee?


-> SELECT ID, COALESCE(FName, SName, LName) as Name FROM
employees; ( COALESCE() function which will return first Non Null
values)
------------------------------------------------------------

SPRINGBOOT:
***********

spring provide 2 imp method to every bean:


1. init()
2. destroy()

1.starting point of spring boot application?


2.different Springboot annotations?
3.Dependency injection and IOC
4.Exception handling in spring,
https://www.youtube.com/watch?v=hLlGAQ5NfTE&ab_channel=CodeDecode
5.diff between controller and rest controller
6.what framework we used for rest api? jersey
7.how to handle a response with 1000 entries? pagination
8.how to handle authentication and authorizarion
9.diff between spring and spring boot
10.how to create SB app? initialzr
13.how to handle communication bw them? rest or GRPC

When do you need @ResponseBody annotation in Spring MVC? (answer)


The @ResponseBody annotation can be put on a method to indicates that the
return type should be written directly to the HTTP response body (and not
placed in a Model, or interpreted as a view name).

For example:

@RequestMapping(path = "/hello", method = RequestMethod.PUT)


@ResponseBody
public String helloWorld() {
return "Hello World";
}

Alternatively, you can also use @RestController annotation instead of


@Controller annotation. This will remove the need for using @ResponseBody
because as discussed in the previous answer, it comes automatically with
@RestController annotation.

Read more: https://javarevisited.blogspot.com/2018/02/top-20-spring-rest-


interview-questions-answers-java.html#ixzz7k1xKq5xi

Spring Boot Actuators ->

The spring-boot-actuator module provides all of Spring Boot’s production-


ready features.
The simplest way to enable the features is to add a dependency to the
spring-boot-starter-actuator ‘Starter’.'
Actuator endpoints let you monitor and interact with your application. -
actuator/health, actuator/info

Add Spring boot actuator started dependancy and enable the below
properties
management.security.enabled=true
security.basic.enabled=true
security.user.name=admin
security.user.password=admin
-------------

@transaction
spring security
spring mvc
asynch in spring
exception handling
spring AOP
ioc and DI
jwt token
flat map
restcontroller
@componentScan exclude
rest template
microservcie comm
CompletableFuture interface
elasticsearch
hashing
kafka
deployment
authentication and authorization
why apigateway
design patterns

how authen auth handled in spring, why setter based di is prefered?

why elastic search nOt sql?

JAVA OOPS QUESTION:

Cricket World Cup:


ICC wants to maintain the Team and Player statistics of all the ODI and
T20 cricket world cups.
They should able to identify ODI and T20 cricket world cups separately.
Each world cup finalist and the winning team should be identified
separately (For e.g., India and SL were finalists for 2011 ODI WC and
India was winner).

Based on the above definitions, provide API (method signature) for,


Highest run scorer for a particular formats in cricket world cups till
date.
Winners of last 3 T20 cricket world cups

Deliverables
• List of classes/objects that you see in the problem
• Just include class declaration, member variables and method
signatures (do not provide method implementation)
• Types of relationships in these classes
• No need of getter, setter and default constructors
• Do not write any DAO and Controllers
• No need write any annotations

spring security:
https://www.youtube.com/watch?v=rBNOc4ymd1E&ab_channel=JavaTechie

What is Spring Boot Auto-configuration?


Spring Boot auto-configuration attempts to automatically configure your
Spring application
based on the jar dependencies that you have added.

Why do we need Spring Boot Auto Configuration?


-> Spring based applications have a lot of configuration.
-> When we use Spring MVC, we need to configure
- Component scan,
- Dispatcher Servlet
- View resolver
- Web jars(for delivering static content) among other things.
----------------
Spring MVC:

As displayed in the figure, all the incoming request is intercepted by


the DispatcherServlet that works as the front controller.
The DispatcherServlet gets an entry of handler mapping from the XML file
and forwards the request to the controller.
The controller returns an object of ModelAndView.
The DispatcherServlet checks the entry of view resolver in the XML file
and invokes the specified view component.

https://www.javatpoint.com/spring-mvc-tutorial
https://www.geeksforgeeks.org/spring-boot-spring-data-jpa/

@Query("select e from Employee e where se.name = ?1") List<Employee>


getEmployees(String name);

The findById() is available in CrudRepository while getOne() is available


in JpaRepository.

If you are using spring profiles, you can have multiple profiles in one
single .yml file
While retrieving the values from .yml file we get the value as whatever
the respective type (int, string etc.) is in the configuration

Each profile need one separate .properties file


While in case of the .properties files we get strings regardless of what
the actual value type is in the configuration

xml based spring config


<bean id="testBean" class="org.springframework.beans.TestBean"
scope="prototype">
<property name="age" value="10"/>
<property name="spouse">
<bean class="org.springframework.beans.TestBean">
<property name="age" value="11"/>
</bean>
</property>
</bean>

Spring vs Spring Boot -

What is Spring?
=> The Spring framework provides comprehensive infrastructure support
for developing Java applications.
=> Spring framework has some best feature like Dependency Injection,
Inversion of Control
=> By using spring framework most of the bioler plate code will get
removed

scopes in spring:
singleton : This scopes the bean definition to a single instance per
Spring IoC container (default).
prototype : This scopes a single bean definition to have any number of
object instances.
request : This scopes a bean definition to an HTTP request. Only valid in
the context of a web-aware Spring ApplicationContext.
session : This scopes a bean definition to an HTTP session. Only valid in
the context of a web-aware Spring ApplicationContext.
global-session : This scopes a bean definition to a global HTTP session.
Only valid in the context of a web-aware Spring ApplicationContext.

Spring boot -

1. Developer don't care about the configuaration part.


As in spring MVC we need to configure web.xml (dispatcher servlet) then a
view resolver, web jars etc which consumes a lot of time of developer
If we are using hibernate/JPA, we need to configure a datasource, an
entity manager factory, a transaction manager and lot of other things
By using @AutoConfiguaration - Spring boot provides basic configuaration
needed to configure the application with these frameworks - This is auto-
configuaration.

2. Spring boot starter project.


If suppose we want to develop a web application then first we need
identify the frameworks we want to use, which versions of the frameworks
we want to use and how to connect them together.
For typical web application we required spring MVC, jackson Databind,
hibernate, logging etc dependancies.
So by using spring boot starter project we will get all these
dependancies and their compatible versions with each other.
We get a one-stop-shop for all the Spring and related technology that you
need, without having to hunt through sample code and copy paste loads of
dependency descriptors
3. Embedded tomcat server

4. Production ready code

annotations -

@SpringBootApplication -> @Configuration, @EnableAutoConfiguration,


and @ComponentScan'

@SpringBootApplication is a composite application that combines three


other annotations:

@SpringBootConfiguration— Designates this class as a configuration class.


Although there’s not much configuration in the class yet, you can add
Java-based Spring Framework configuration to this class if you need to.
This annotation is, in fact, a specialized form of the @Configuration
annotation.
@EnableAutoConfiguration— Enables Spring Boot automatic configuration.
We’ll talk more about autoconfiguration later. For now, know that this
annotation tells Spring Boot to automatically configure any components
that it thinks you’ll need.
@ComponentScan— Enables component scanning. This lets you declare other
classes with annotations like @Component, @Controller, @Service, and
others, to have Spring automatically discover them and register them as
components in the Spring application context.

2. @RequestMapping -
- Can be applied over a class or method
@RequestMapping("path", Method=httpmethod)

3. @RequestParam and @PathVariable -

http://localhost:8080/springmvc/hello/101?param1=10

@RequestMapping("/hello/{id}")
public String getDetails(
@PathVariable(value="id") String id,
@RequestParam(value="param1", required=true) String
param1,
@RequestParam(value="param2", required=false) String
param2){
.......
}

4. @Component/@Service/@Repository/@Controller -

@Component - During initial release of the Spring all beans are


sued to be declared in XML file.
For large project this become a massive task and
the solution for the is use of annotations.
In later version Spring provides annotation based
dependancy injection which automatically scans and register
classes as spring bean which is annoted using
@Component.
No need to declare <Bean> tag and inject
dependancy into it. It will be done automatically by spring.
Just add <context:component scan> tag.

------@Controller ------------
@RestController
|
@Component ---
-------@Service
|
------@Repository
-------------------------------------------------------------------------
-------------

@Autowired and @Qualifier -

public class Vehicle{

Engine engine = new Engine(); // Tight coupling


//For loose coupling -
1.Create an instace of Engine - @Component
2. Give that dependency to Vehicle class -
@Autowired
Above steps are done by spring IoC container.
@Autowired
Engine engine;

public void getEngine(){


engine.carEngine();
}
}

@Component
public class CarEngineImpl implements Engine{

public String carEngine(){


return "Car Enigne returned";
}
}

@Component
public class BikeEngineImpl implements Engine{

public String bikeEngine(){


return "Bike Enigne returned";
}
}

-- Excaption - Trying to find one matching bean but found two


- CarEngineImpl, BikeEngineImpl
How to resolve -
1. @Autowired
Engine bikeEngineImpl - Bad Way
2. @Autowired
@Qualifier(value="bikeEngineImpl")
Engine engine;

public class Vehicle{

@Autowired
BikeEngineImpl engine; - will work fine but we are
using implement

public void getEngine(){


engine.carEngine();
}
}

7. @RequestBody & @ResponseBody


@RequestBody - JSON - convert (automatic deserialization) -
POJO JAVA object
@ResponseBody - POJO JAVA object - JSON
-------------------------------------------------------------------------
-------------------------

BeanFactory VS ApplicationContext -
Spring provides two kinds of IOC container - one is BeanFactory and
other is ApplicationContext.
Both are Java Interfaces and ApplicationContext extends
BeanFactory.
BeanFactory provides basic IOC and DI feature while
ApplicationContext provides enhanced feature.
BeanFactory does not support internationlization but
applicationContext provides support for it.
ApplicationContext have an ability to publish the events for beans
which are registered as listners.
ApplicationContext uses eager initilization while BeanFactory uses
lazy intilization.
Go for applicationContext as it give some enhanced feature but if
there is memory issue (applet apps)
and you don't wont enhanced feature then use beanfactory

BeanFactory -
The root interface for accessing a Spring bean container

ApplicationContext -
Central interface to provide configuration for an application.
Provides -
1. Bean factory methods for accessing application components
2. The ability to load file resources in a generic fashion
3. The ability to publish events to registered listeners
4. The ability to resolve messages, supporting
internationalization

Ex - If you are using the standalone application then -


For XML based application -
ApplicationContext ctx = new
ClassPathApplicationContext("applicationcontext.xml");
HelloWorld hello = (HelloWorld) ctx.getBean("helloWorld"); -
In getBean specify the Bean Id from XML file

<bean id="helloWorld"
class="net.javaguides.spring.ioc.HelloWorld">
<property name="message" value="Hello World!" />
</bean>

For annotation based Application -


1. Create a spring configuartion class and annote it
with @Configuartion
and declare the beans inside it by using @Bean

@Configuartion
public class ApplicationConfiguartion{
@Bean
public HelloWorld hello{
return new HelloWorld();
}
}

2. To run the application -

ApplicationContext ctx = new


AnnotationConfigApplicationContext(ApplicationConfiguartion.class);
HelloWorld hello = (HelloWorld)
ctx.getBean("helloWorld");

ApplicationContext Vs WebApplicationContext -
Web Application context extended Application Context which is
designed to work with the standard javax.servlet.ServletContext
so it's able to communicate with the container.

public interface WebApplicationContext extends ApplicationContext {


ServletContext getServletContext();
}
For Web Application -
WebApplicationContext webctx =
WebApplicationContextUtils.getWebApplicationContext(getServletContext())
HelloWorld hello = (HelloWorld)
webctx.getBean("helloWorld");

BeanPostProcessor -
Allows custom modification for newly created spring bean instances.
If you want to implement some custom logic once spring container
finishes instantiating, configuring and initilizing a bean
we can plug in one or more spring bean post processor. In case of
multiple we can control the order by using Ordered interface.

BeanPostProcessor interface consists of exactly two callback


methods
i.e. postProcessBeforeInitialization() and
postProcessAfterInitialization().

registerShutdownHook -
In spring, registerShutdownHook() method is used to shut down IoC
container in non-web applications.
It shuts down IoC container gracefully.
In non-web Based application we need to call this but in web based
application, application context takes care of this.

Spring Bean LifeCycle -

Spring framework provides following 4 ways for controlling life cycle


events of a bean:
1. InitializingBean and DisposableBean callback interfaces
2. *Aware interfaces for specific behavior
3. Custom init() and destroy() methods in bean configuration file
4. @PostConstruct and @PreDestroy annotations - Best Way

Constructor vs Setter Based Injection -


1. As the name implies is How dependancies are injected is one of
the fundamental difference.
Setter Injection uses setter method while constructor uses
constructor to inject dependancies.
2. Code is more readable in case of Setter Injection.
3. Stter Injection does not ensure dependancy injection.There is no
guarantee that dependancy is injected or not.
Constructor injection does not allow injection if
dependancies are not ready.
4. Constructor based injection may result in cyclic dependancies.
To avoid can use setter bases injection.

Spring Exception Handling -


1.@ExceptionHandler - We can define exception handler method in
controller class by annoting the method with @ExcaptionHandler
2.@GlobalExceptionHandler - When controller class is not able to
handle the exception then we can define a contoller class and annote it
with @GlobalExceptionHandler
3. HandlerExceptionResolver -
-------------------------------------------------------------------------
----------------------------------

KAFKA:
******

Kafka is publish/subscribe messaging system


Queue - record will go to the one consumer
Publish/subscriber - record will go to the multiple consumer

Kafka Components -
Topic - group of message belonging to the same type
Publisher - that can publish the message to the topic
Brokers - set of server where publish message are copied
Consumer - that subscribe to the various topic and pulls the data
from broker.

A message is just an array of bytes for Kafka. In this example, we are


sending a string Key and a string value. But Kafka accepts only an array
of bytes. So, we need a class to convert our message key and value into
an array of bytes. The activity of converting Java objects into an array
of bytes is called serialization. So those two properties are to specify
an appropriate serializer class for the key and value. In this example,
we are using string serializer for both key and value.

current offset-sent records


commited offset- processed records
earliest offset-if committed offset not present and new consumer added
then it will start reading from the beginning
latest offset
https://www.youtube.com/watch?v=twvdT6A1eeE&ab_channel=LearningJournal

PRODUCER API:

String key = "Key1";


String value = "Value-1";
String topicName = "SimpleProducerTopic";

Properties props = new Properties();


props.put("bootstrap.servers", "localhost:9092,localhost:9093");
props.put("key.serializer",
"org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer",
"org.apache.kafka.common.serialization.StringSerializer");

Producer<String, String> producer = new KafkaProducer<>(props);


ProducerRecord<String, String> record = new
ProducerRecord<>(topicName, key, value);
producer.send(record);
producer.close();
---------------------

CONSUMER API:
Properties props = new Properties();

props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", "test");
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
props.put("key.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer",
"org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer
<String, String>(props);
//Kafka Consumer subscribes list of topics here.
consumer.subscribe(Arrays.asList(topicName))

//print the topic name


System.out.println("Subscribed to topic " + topicName);
int i = 0;

while (true) {
ConsumerRecords<String, String> records = con-sumer.poll(100);
for (ConsumerRecord<String, String> record : records)

// print the offset,key and value for the consumer records.


System.out.printf("offset = %d, key = %s, value = %s\n",
record.offset(), record.key(), record.value());
}

If we have multiple consumers reading data in parallel from the same


topic, don't you think that all of them can read the same message?
The answer is no. Kafka provides a very simple solution for this problem.
Only one consumer owns a partition at any point in time.

We have one topic, and there are four partitions. So, if we have only one
consumer in a group, it reads from all four partitions. If you have two,
each of them reads two partitions. If you have three, the arrangement may
be something like a single consumer reading two partitions and others own
a single partition each. So, the fundamental concept is that the
consumers do not share a partition. There is no way we can read the same
message more than once.

Writing records to partitions.


How does a producer decide to which partition a record should go? There
are three ways a producer can rule on that.

Using a partition key to specify the partition


A producer can use a partition key to direct messages to a specific
partition. A partition key can be any value that can be derived from the
application context. A unique device ID or a user ID will make a good
partition key.

By default, the partition key is passed through a hashing function, which


creates the partition assignment.

Relication factor in kafka is number of copies of partition. rf is


defined for a topic

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

There are two primary Elasticsearch use cases:

Text search
You want Elasticsearch when you're doing a lot of text search, where
traditional RDBMS databases are not performing really well (poor
configuration, acts as a black-box, poor performance). Elasticsearch is
highly customizable, extendable through plugins. You can build robust
search without much knowledge quite fast.

Logging and analysis


Another edge case is that a lot people use Elasticsearch to store logs
from various sources (to centralize them), so they can analyze them and
make sense out of it. In this case, Kibana becomes handy. It lets you
connect to Elasticsearch cluster and create visualisations straight away.
For instance, Loggly is built using Elasticsearch and Kibana.

One of the Elasticsearch Architects I spoke with said that 80% of the
data Elasticsearch works with in companies is unstructured, while 20% is
structured. It's the unstructured data that companies are looking at to
discover rare or unusual data patterns.

bool query
The default query for combining multiple leaf or compound query clauses,
as must, should, must_not, or filter clauses.

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

APPLICATION LOGIN:
******************

authentication mechanism: Basic auth-client side

username:password --------> sjgfsdgfks9767sdfkj=


base 64 encoder

Authorization: Basic sjgfsdgfks9767sdfkj=

The password is not to be decrypted. In fact it is not encrypted but


'hashed'. When the user enters the password , hash it and compare with
the hashed password stored in the database. If both the strings match ,
then the password is correct.

What may be easier, and even more secure, is using an SHA-256 hash as
"encryption". Simply hash the password, store it in the server, and when
the user tries to log in again, compare the hash stored by the server to
the hash of the password he attempted to use. That way, the password is
never sent through the network, and its almost impossible to reverse-hash
SHA-256!

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

DOCKER:
*******

Docker - Docker is a tool designed to make it easier to deploy and run


the application by using container

Container - Container allow developer to package up an application with


all parts it needs such as libraries
and other dependencies and ship it out as one package
Ex. Transportation - A is manufacturer and want to sell items to the
city. Factory is at X place and city is at Y place.
A need - transportation medium - Truck/ship/air - Skilled labour to
pack this
But by using container A just need to package its item into the conatiner
and don't need to worry abt anything else.

Design -> Development -> Deployment -> Test

How Docker works?

Developer -> Docker File -> Docker Imgae -> Docker Hub (cloud) --> Pull
Image

Docker Image

Docker is container platform

Docker Architecture -

Docker client - (Comman line interface) ---- Docker server -


(Containers)

---------------------------Docker Engine --------------------------------


---------
'
Docker solved the problem abt app running in one platform and not on
other.

Benefits of Docker -
1. Build app only once and run any where (Docker image is same)
2. Portability
3. Version Control
4. Isolocation - app runs in single container and not interfear with
other apps
5. Deployments made easy
-------------------------------------------------------

What is Agile method methodology?


The Agile methodology is a way to manage a project by breaking it up into
several phases. It involves constant collaboration with stakeholders and
continuous improvement at every stage. Once the work begins, teams cycle
through a process of planning, executing, and evaluating.

-------------------------------------------------------------------------
----------------------
REST AND SOAP:
**************

REST - Representational State Transfer


SOAP - Simple Object Access Protocol

SOAP is a protocal whereas REST is an architecture style.

SOAP we can use with any application layer protocol such as HTTP, SMTP,
TCP or UDP
SOAP retuns data to the receiver in XML format.

REST uses HTTP protocol for data transmission. REST returns data in JSON,
XML, HTML, YAML,
Plain text or any other format.

Apporch for SOAP is function driven (getUser()-data available as


services)
Approch for REST is data drivern (user- data available as resource)

REST API calls can be cached but not SOAP.

----------------------------------------------------END------------------
-----------------------------------------

Hope that these notes were helpful in some way :p


All the best!!

You might also like