You are on page 1of 15

Immutable class

The class must be declared as final (So that child classes can’t be created)
Data members in the class must be declared as private (So that direct access is not
allowed)
Data members in the class must be declared as final (So that we can’t change the
value of it after object creation)
A parametrized constructor should initialize all the fields performing a deep copy
(So that data members can’t be modified with object reference)
Deep Copy of objects should be performed in the getter methods (To return a copy
rather than returning the actual object reference)
No setters (To not have the option to change the value of the instance variable)

//make class as final


class final immutable {

//fields as final
//wrapper classes and strings are immutable so it's okay if we add getter
private final Integer field1;

//for non immutable class we need to send new object

private final Date field2;

public immutable(Integer field, Date field2){


this.field1 = field;
this.field2 = new Date(field2);
}

//only provide getters as setter can set some value and modify it

private Integer getField1(){


return this.field1;
}
-----------------------------------------------------------
hash code and equals

by default all the wrapper classes has overridden hash code and equals method
if we don't have then we can override them
firstly it will check the hascode if both are same then it will go to equals method
if content is same then it will return same

how hash map works

when we put some value in hashmap then it will generate some hashcode and it will
be store in an index by calculating hashcode & n-1
n =16 that will be put in that index
default size is 16
if we have more elements in it as soon as it reaches 13th elements then size will
be doubled 2 power n-1

if two inputs get same index then it will form a linked list

-----------------------------------------------------
singleton class

we can create only one object


class single {
public static void main(String[] args) {
Emp1 e1 = Emp1.getInstance();
}
}
class Empl{
static Empl emp = new Empl();
private Emp1() {
}
private static Empl getInstance(){
return emp;
}
}
--------------------------------------------

three cursors in java to retrieve elements from collection

1. Enumeration
2. Iterator
3. List Iterator

Enumeration came in 1.0 version

it has two methods


public boolean hasmoreelement
public object nextelement

difference between enumeration and iterator is

enum is fast and occupies less memory vice versa


but iterator is thread safe fail-fast throws concurrent modification exception when
threads are chaging values
enum-1.0 (hash table, vector)
iterator - 1.4 (all)
iterator add and iterate
enum-iterate

iterator can traverse only in forward direction .iterator is the only method,
applies both on list and set, cannot add elements,
list iterator can travel in both the directions and works on list objects only

Multi Threading
-------------------------------------------
Thread - sub process

two ways to create a thread


1. extending thread class --run method --create the object and use object.start
method
Empleoyee e1= new Employee();
e1.start();
2. implementing runnable interface
Empleoyee e1= new Employee();
Thread t1= new Thread(e1);
t1.start();

Thread states
new runnable running blocked/waiting terminated/dead

priority states
default -5 (1 to 10)
thread.setpriority()

executive service

excutive service is the new way of executing the thread asyncronously in the
backgroud similarly like thread pool
different ways of creating executive service
ExecutiveService e1 = Executors.newSingleThreadExecutor();
new fixedThreadPool(how many threads);
new scheduledThreadPool(how much time to delay);

with the help of executor service we can actually check whether thread is executed
or not by using Furture

Future f = executoreService.submit(new Runable(){


public void run(){
System.out.println("execute");
}}
f.get();

runnable vs callable

runnable will return void if we want to return some value use callable and use call
method

synchronization
when there are multiple threads want to execute a method can execute it only if it
is not getting executed by oter threads
Synchnized is used on method for safe execution of method

we can synchronize static methods as well

if we have multiple treads running if we want 4th thread to run after 3rd one then
t3.start()
t3.join
t4.start

SOAP VS REST-
----------------------------------------------
SIMPLE OBJECT ACCESS protocal
REPRESENTATIVE STATE TRANSFER

Spring and spring boot and spring mvc


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

we used to have EJB in java


it was hard to manage entites at that time we came across the concept called pojo
spring frame work provides depency injection, pojo,rest, security,batch,mvc and
integrate with other frameworks as well like hibernate and struts

spring boot has everything configured in it we don't need to add anything extra and
focus on coding part (jars and configuration is a big deal) so concept of spring
boot
it has internal tomcat server installed in the system
we can configure everything in application.properties file
Presentation Layer, Data Access Layer, Service Layer, and Integration Layer.

spring mvc
when client sends a request it will go to web.xml and then will go to dispatcher
servlet provided by spring mvc and then it send it respective controller based on
@controller annotation

dependecy injection
---------------------------------------------------
one object may depend on some other object
dependecy injection container to create objects
advantage is loose coupling why bcz we can test that particular object don't need
to depend on other object
@Autowired, @Component

Comparable and comparator


------------------------------
comparable-compareTo
lang pkg
one argument-comapre to
natural order

comparator
comapare
equals
util pkg
customised order

Class Loader
------------------
it is used to load the .class files
there are 3 different types of class loaders
bootstrap-also known as primordial class loader, it doesn't have any parent class
extension-it delegated classes from it's parent class if its unsuccessful t will
load from specified directory.
application classloader-is used to load classes from classpath

List
------------------------
Array List
Linked List

Set
-----------------
Hash Set
Linked hash set

JAVA8-feature
----------------------------------
Lambda expression
------------------------------
lambda expressions are one of the feature implemented by java 8, it is an anonymous
method which does not have any name and uses the abstract method of FI and it
provide some of the imp methods like map, filter and foreach. So because of that
there is code optimzation and this lambda expressions can be written inside an
another method.

(s1,s2) -> s1+s2;

Method Reference
---------------------------
it is similar to the lamba and easy way of using lambda expression. it is used to
refer the method in the functional interface using the symbol (::)

Funcational Interface
---------------------------------
An interface which can have single abstract method and can have multiple static and
default methods are called FI.These are also called as simple abstact method
Interface(sam Iterface).

Streams
-----------------------------
Strems doesn't store any kind of data and it is just used to tranfer data from
particular source through a pipeline and it will not modify the source data for
example if we are filtering based on some condition it will just create a new list
rather than modifying the existing list.

default methods
------------------------------
we can create a method with default implementation using default keyword. methods
which are defined as default methods are not abstract methods. we can also override
default methods to provide more specific implementation.
In the same way we can create static methods also inside interface with some
implemention

after seeing this interface it is similar to abstract method the only difference is
for abstract class we can create a constructor.

foreach method
-----------------------------
this method is used to iterate through the elements and any collection which is
extending iterable interface can use this method and it's return type is void

optional
------------------------------------
optional is used to avoid null pointer exception. if there is any exeption in the
middle, in order to not to terminate in the middle we use optional if we don't have
any value it will not retrun any thing if we have value it wil return that value.

we can check for the element by using isPresent method then we can perform the
operation.

default and static methods both have implementations but default methods can be
overridden and can be accessed by class but static methods cannot be overridden and
can be accessed using interface name.

difference between collections and streams is collections can store the data but
streams is just to transform the data from one source to another.

Hibernate
------------------------
In order to save our data into db we use hibernate which provides Object relational
mapping(ORM) feature which will internally use JDBC api's to connect with the DB
and it provides a specification called JPA(java persistence api) which is used to
store the data into DB.

Equals() method
-------------------------------
equals method is used to compare the two object it will check whether two objects
are equal or not based on the reference if two objects are sharing the common
memory reference then it returns true

hashcode
-----------------------------------
for each object jvm creates an unique id which of 32 bits that is called hashcode.

when we overide equals method then it is important to override hashcode method also

Static variables are stored in premGen which is a section in heap


from java 8 onwards these variables are not stored in premgen now they are stored
in metaSpace which is not a part of heap memory

oops concepts
------------------------------------
Abstraction --
representing the complex things in simple way
eg: switching on TV
it's not required to know how it internally works

Polymorphism: it means many forms


it is the ability to perform a task in multiple ways
eg:talking,barking

overloading and overriding

encapsulation:
wrapping the data into a single unit
eg:capsule

inheritance:
acquiring the properties of parent class
provides code re usability and run time polymorphism
eg:property

comparable and comparator


-----------------------
public int compareTo(Employee o){
return this.property - o.propert;
}

public int compare(Employee t o, Employee o1){


return o.value-o1.value;
}

equals and hashcode


------------------------------
public boolean equals(Object o) {
return this.value == o.value;
}

public int hashCode() {


return this.value;
}

== method compares the references of the objects and equals method checks the
content of the method

when we override equals method inside we will write == method which compares
references of objects.
so fistly we should override hashcode to return single integer if hashcodes are
same then == returns true

what is the use of spring boot application


------------------------------------------------
@SpringBootApplication = @Configuration(java based configurations),
@EnableAutoConfiguration(spring boot configuration), @ComponentScan (component
scanning) from 1.2 version
it is used to launch the application from java main method
It automatically creates applicationContext and scan's the configured class pkg and
launches the application

different kinds of bean scops


-------------------------------------------
singleton
session
prototype
request

custome annotations
-----------------------------------

docker
---------------------------
docker is an open platform to develop and run our applications. It actually frees
us from the infrastructure dependency and make us to develop the application fast.
Using docker we can create containers,
what is a container?
In VM we need to install new OS when we have to run a application so if we have
multiple application which are having different OS then we need to install all, So
we have the concept of docker where we will be installing it then we have
containers in it which will share the same OS
containers can be created using image and we can create an image with the software
we have developed and all the jars and any other os features, with all these we
can create an image and can share it.

Imp points
-------------------
we can't declare constructor as static and final we can inherit super class
constructor and we can use super key word
we can't use super keyword inside static methods

Collections
iterable
collection
list,queue,set

access modifiers
------------------------------
public:any where
private:only in that class
protected:with in the package and in the package of sub class
default:only with in the package

@Component(value = "b") on each object which implements same interface if u are


want to autowire the interface then autowire it and use @Qulifier("b)

why strings are immutable?


Strings are immutable because when we are creating a parameter with string it gets
created in String constant pool so when we are trying to create a string with the
same content then jvm instead of creating a new string it will refer to the same
string which got already created so if we change that string then the second object
which is pointing to old string might gets efected. In order to avoid this problem
strings are made immutable.

if we want to create a mutable string then we can use string buffer or string
builder.

String buffer is synchronized means if two threads wants to access same method then
it can't be done becuase of that it is slow which makes it less efficient.
string builder is not synchronized and is more efficient.

if you doesn't care about any thread safety we can go for string builder.
-------------------------------------
api is just to make the contract between the information provider and information
user

rest api's are used to create restful web services and has certain constraints to
create RWS.they use simple methods like get,post,put,delete,patch.

restful web services? web services that are formed using rest architecture

what is a web service?


it is used to transfer data between the applications using different standards
client requests using web service by submitting xml file and service responsds with
xml response.
--------------------------------------
what is kafka?
distributed and steaming platform used to transfer data from producer to consumer
and is capable of handling trillions of data

why it is distribute is
kafka stands between the producer and consumer
kafka system is called kafka cluster and consists of multiple elements called
nodes.
brokers run inside nodes so it is a distrited system.
data produced from producer is ditributed among the nodes so if any of the cluster
is down it won't loose the data
why do we need kafka?
we can use kafka for fault tolerance that means it can store the data for the give
time period default 7days unlike rabbitMQ
kafka is distributed so when ever it's required we can increase the kafka cluster
just by adding server to kafka cluster.
kafka has low latency which makes it process the data fast.

kafka cluster - > broker1-> topic -> partition1


partition2
broker2
broker3
broker is nothing but the kafka server where kafka runs

zookeeper is must for kafka is used to maintain the brokers and if any of the
broker or partition is down it notifies the kafka and if any cluster is added then
also notified kafka
---------------------------------------------------------------

Exceptions?
it is an abnormal condition
exception handling is nothing but to handle run time exceptions

throwable
exception error (STACK OVERFLOW, OUT OF MEMEMORY, VM
ERROR)
IOEXCEPTION
FILE NOT FOUND
SQL Exceptions
CLASS NOT FOUND
RUN TIME Exceptions
NPE
NUMBER FORMAT
ARTHIMATIC

checked exception : which are checked during compile time


classes that extend the throwable directly except run time exceptions including
error

unchecked: checked during run time

we can have a try block without catch and finally block after java 7, (try using
resource)only constraint is the parameter we are passing to tryblock should
implement autocloseable interface
example:

public class sample {


public static void main(String[] args) {
try(Scanner sc = new Scanner(Systen.in)) {
System.out.println("sample");
}
}
}

------------------------------------------------------
types of injections

1.constructor based
class sample {
private Coach coach;
public Sample(Coach coach) {
coach = coach;
}
}
2.setter based

class sample {
private Coach coach;
public sample() {
}
setCoach(Coach coach) {
coach = coach;
}
}

3.field based
class sample {
@Autowired
private Coach coach;
public sample() {
}
}

it uses the concept of reflection

bean scope
-------------------------
<bean id = "sample" class = "fully qualified class path">
</bean>

so spring will create the object for it and store it in memory and when ever any
other container request for this bean it will share the same reference
basically it's a singleton
we can explicitly specify the bean scope by
<bean id = "sample"
class = "fully qualified class path" scope = "singleton>
</bean>

bean scopes are----


SINGLETON: only one instace is created and shared
<bean id = "sample"
class = "fully qualified class path" scope = "singleton>
</bean>
PROTOTYPE : everytime new instance is created when the request comes to sample
<bean id = "sample"
class = "fully qualified class path" scope = "prototype>
</bean>
REQUEST
SESSION
GLOBAL-SESSION
classpathxmlApplicationcontext
1.<bean ></bean>
2.<component scan>
3.If we don't want to use xml then we can actually go for java configuration by
using @Configuration annotation then there is no need to add XML file
annotationconfigapplicationcontext

bean lifecycle
|

container start -> bean instantiated -> DI -> customer init method ->custom
utility method -> custom destroy method

spring mvc is used to develop web applications


when a request comes from a browser then request goes to front controller which is
dispatcher servlet then it goes to controller where we have the business logic then
the data goes to view part which is view template(jsp,jstl) then response goes to
browser.

@Configuration

it is annotated on a class and contains methods with are annotated with @Bean and
it tells spring IOC that there might be beans which should be configured in
applicationContext
@Bean
return the object which means it should be registered as a bean in application
context

@EnableAutoConfiguration
it tells spring container to create application context without manually creating

@Component
during @Componentscan spring will instantiate such beans and injects any beans
which are required

@RestController- @Controller+@ResponseBody
web application is the general view of HTML+css+JS where rest api returns json or
xml

microservices
--------------
service discovery
---------------------
CSD
here client will query the service registry where the location of services are
avialable then uses any available service to make request
netflix provide eureka registry where it exposes the api's to know what services
are avialble
also netflix ribbon
SSD:here when client makes a request it goes to load balacer here load balancer
calls service registry then service registry routes the request to the avaiable
service.

if we have s1, s2,s3,s4


if s1 wants to communicate with s2 then it will send a request to discovery server
to get the url or address of s2 and then s1 will call s2
this is called client side discovery(CSD)

if the service discovery is at service side then it is called service side


discovery there
s1 calls service discovery to send some message then service discovery will send it

how will service discovery know the service??


spring cloud uses CSD
service discovery uses technoly called Eureka

Threads in java
---------------------------------
multi threads
name itself suggests that multiple threads
In this case multiple threads run simultaneously by sharing common resource to make
the program execution fast, it is one of the important feature provided by java.

uses:

1.improves performance
2.uses cpu effectively and reduce cost of maintenance.
3.threads are independent so one thread will not effect other if there is any
exception.

two types of threads


1.user thread
2.daemon thead
two methods in daemon
.setDaemon
.isDaemon

difference between list and set


list allows duplicates
set doesn't allow duplicates
list maintains insertion order
set doesn't maintain insertion order
list can store multiple null values
set allows null values only once
list implements are array list and linked list
set implements are hash set and tree set

why set doesn't allow duplicates


internally set allows hashmap what ever value we are adding into the set it will
taken as a key in map and value is always hardcoded as present
map.put(e, PRESENT)==null
s.add method returns a boolean value if it is already present it returns false set
will not add into it
difference between hashmap and hashtable
hashmap doesn't maintain insertion order in java

hashmap is non synchronized,


hash table is synchronized
hashmap allows one null key and multiple null values
hashtable doesn't allow null key and value

why hashtable doesn't allow null key and value


in order to store the values and retrieve the values from hash table we need to
implement hash code and equals method
since null is not an object it can't implement these methods

what are the different ways of creating the object


-----------
1.using new keyword
new Employee();
2. using class.newInstance() method

Employee e = Employee.class.newInstance();

3. using constructor newInstance method


public Employee () {
}

Constructor<Employee> c = Employee.class.getInstance();
Employee e1 = c.newInstance();
4.clone() method
@Override
protected Object clone() throws CloneNotFoundException{
return super.clone();
}

Employee e = new Employee();


Employee e2 = (Employee) e.clone();

Difference between hibernate and JPA


--------------------------------------------
JPA is just a specification, to manage the relational data in our java
application.So it needs some framework to implement
ORM is nothing but mapping the object into relational tables
we have different ORM tools available

Hibernate is framework, and hibernate ORM implements JPA


it implements al the javax.persistence classes

@RequestMapping
-------------------------------
It is used to map the incoming request to the specific class or method
when the application starts all the beans are stored in application context, when
the @Controller bean is intialized then it searched for request mapping and store
the mapping/ handler pair in mapping registry. When the http request comes to
dispatcherservlet it searches in application context for the beans which implement
requestmappinghandlermapping and it will internally searches in mapping registry
and solves the request.
@RequestBody
---------------------------
sample(@RequestBody Employee e)

it is used to automaticaly deserialize the json into the object

@ResponseBody
-------------------
object sent is automatically serialized to json

serialization
----------------------
process of converting data into a byte streams

deserialization
-------------------------------
it is the process of converting back to the java object

ci/cd pipeline: continuous integration and continous delivery

ci: using various built in tools and pluging when the code is commited it does
build and unit testing and integration testing
cd: it is used for deploying the code into the production. the goal is the code
should always in develiverable state irrespective of the number of developers doing
the code changes.

jenkins
-----------------------
jenkins is an application used to build, test and deploy the application during the
development. it is used to achieve continuous integration.
continuos integration:
when ever small piece of code is developed and build is done and deploy to any env
to developement is fast and identify bugs at the early stage rather than waiting
for everybody to develop the code and test it once and fix errors if there are any.

jenkins pipeline
----------------------------
It is a series of tasks performed in a specific sequesce like build test deploy on
code to form a software product.

api gateway:
it is used to enroute the client requests to desired services

fail fast: it throws concurrent modification exception when there is a modification


in collection during iteration
fail safe: it doesn't throw the exception, because it works on cloned object not on
the actual object eg: copyonwritearraylist and concurrentHashmap

concurrenthashmap:
--------------------------------
in concurrentHashmap multiple threads can operate at a time. multiple threads can
read the operation and retrieval without locking but for updating it uses lock at
segment level.

difference between hashmap and concurrenthashmap


hashmap:it is not thread safe so performance wise it is fast and it can allow null
key n multiple null values throws concurrent modification exception
concurrentHashmap: it is thread safe for updating it has a lock at segment level.
So performance wise it is less than hashmap. doesn't throw CME.

kong
-------------------------------
request which is coming will come to load balancer and then it routes to kong from
kong it go to microservices
each consumer has unique name and unique key called api key and jwt for
authentication.
all this information is there in vault.

collections are not thread safe, multiple threads perform action at a time, but
concurrent collections are thread safe
we can make collections also thread safe using synchronized. but because of locking
performance wise it becomes slow.
hashmap - concurrent hashmap.
list - copyonwritearraylist
set - copyonwritearrayset

You might also like