KEMBAR78
Interview Questions | PDF | Class (Computer Programming) | Method (Computer Programming)
0% found this document useful (0 votes)
57 views60 pages

Interview Questions

The document contains a comprehensive list of questions and answers related to Java programming, Spring framework, microservices, and various design patterns. Key topics include thread management, dependency injection, garbage collection, and differences between various data structures and design patterns. It also covers new features in Java 8 and 11, as well as Spring Boot functionalities.

Uploaded by

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

Interview Questions

The document contains a comprehensive list of questions and answers related to Java programming, Spring framework, microservices, and various design patterns. Key topics include thread management, dependency injection, garbage collection, and differences between various data structures and design patterns. It also covers new features in Java 8 and 11, as well as Spring Boot functionalities.

Uploaded by

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

Questions

Can you create immutable class in java? How?

Need of thread

Lifecycle of thread? Use of wait(), join()

Difference between wait() and sleep()

what is yield method.

diffrence between concurrent hash map &


hashmap/hashtable
what is garbage collection
where is object created by new keyword is stored

New addition in java 1.8

default method in interface

Singleton class ; how to break singleton class

Deserializatinon
Design pattern

default scope of bean in spring

dependency injection in spring

Difference between Constructor DI and Setter DI

how does spring support polymorphism

what is advantage of microservices

autoscaling of microservices
can we achieve autoscaling using docker

microservices vs monolithic

stream method
method to convert list into MAP
what is method referencing

what is executor and its methods

Recursion in java

Spring ..why post construct is used


how to read property from application properites

Custom Exceptions in microservices

Explain three annotation of @SpringbootApplication

Classloaders in java
Mocking rest template & repository ( which annotation)

Microservices communication

Delegation principal in Java

Path and class path difference

Transient in Java
how to restrict child class getting serialized when
parent class undergoes serialization
how is garbage collection done
Internal implementation of hashset

Deeep Copy vs shallow copy

Enum in Java

Creating thread by implementing Runnable method and by


extending thread class ( what is difference)
cyclic barrier vs countdown latch

Lock interface and its implementation and its advantage


overr synchronized block

Race condition and deadlocks

Autoboxing in java

executor.submit & executor.execute method

What if one of the microservice not repsonding


Service monitoring & application monitoring

Spring cloud pass


why use Powermockito ( Difference between Mockito and
Powermockito)

Abstraction and encapsulation difference


Static Keyword

Difference between Iterator and list iterator

Fail safe and fail fast iterator

Comparable vs comparator
Singleton vs prototype

Difference @Restcontroller vs @Controller


is springBean thread safe
can private method be overriden

Finally in java
Implementing spring security

What are JWT

Difference between thenReturn and doReturn

Assertions in JUNIT
Difference between spring and spring boot:

Delegation filter proxy

IOC in spring boot

Difference between @Mock and @InjectMocks?

Junit annotations

Difference between assert and verify


Can Junit test methods return strings?
How to enable Mockito Annotations
Mockito.mock() method

How to do authentication against database tables using


Spring Boot Security?
Difference between abstract class and interface

Can Interface extends a class?


is it mandatory to implement all the methods in a class that
implements an interface?
is it mandatory to implement all the abstract methods in a
class that extends abstract class?

IOC vs DI

Difference between list and set

ArrayLilst and Linkded list

Synchronized blocks

HashMAP vs Hashtable
Wrapper classes

String buffer , String, StringBuilder

Abstract class, final class, instance variable

Explain public static void main

Final keyword

Checked and unchecked exceptions

Private, Default, Protected, Public

Why use override


Advantages of rest over soap

Annotation @Scheduler

Spring boot actuators

CrudRepository vs JPA repository

Annotation @Query

In how many ways Rest client can be impletemente?

How to disable specific auto-configuration class :


squash command in GIT

AOP

What are entities

What is JPA

Difference JPA and JDO

How is entity class specified

Property level access and field level access

What is embaddable class

What is Mapped Superclass

Lifecycle of Entity instance


How can exclude some columns to be stored in database
What does @Basic annotation do

What is JPQL

What is spring.jpa.hibernate.ddl-auto=update

How to log SQL statements on console

Advatage of Spring boot over spring

How to use Jetty instead of tomcat server

What is inMemory H2 database

Difference between List and ArrayList

Inbuild functional interfaces


Can you use object in hashmpap
Benefits of generics
Difference between Throw and throws

Difference between @Component and @Bean

What is pojo

Difference between request param and query param


How does Springboot converts Json to java objects

HTTP status codes

What is Dispatcher servlet

Challenges with Microservices


limits service microservice

Spring cloud service config microservice

Eureka naming server

SpringCloudLoadbalancer / Netflix ribbon

Feign client

Resilience 4J / Hystrix
Zuul API gateway vs Spring Cloud Gateway

Zipkin server

Rabbit MQ

Spring cloud seuth

How to implement API gateway

What is spring cloud


What are REST API

What is SpringBoot

what is finalize method on object

Can final array be modified?


It is mandatory to use @Functional interface annotation
Can you overload main() method
Creating custom actuator

New addition to java 11

In how many ways java object can be created


Answers

Yes. The class must be declared as final, data members in the class must be declared as private
and final, a parameterized constructor should initialize all the fields performing a deep copy,
deep Copy of objects should be performed in the getter methods, no setters (To not have the
option to change the value of the instance variable)
Threads allows a program to operate more efficiently by doing multiple things at the same
time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.

1. New 2. Runnable 3. Blocked/Waiting 4. Time waiting 5. Terminated


The method wait() and join() both are used to pause the current thread in Java
The wait() is used for inter-thread communication while the join() is used for adding sequencing
between multiple threads,
Milliseconds. Here, Thread does not lose its ownership of the monitor and resume’s it’s
execution
Wait(): It tells the calling thread to wait until another thread invoke’s the notify() method for
this object, The thread waits until it reobtains the ownership of the monitor and Resume’s
Execution.
yield() basically means that the thread is not doing anything particularly important and if any
other threads or processes need to be run, they should run. Otherwise, the current thread will
continue to run.

In HashMap, if one thread is iterating the object and the other thread wants to modify the
objects, we will get a ConcurrentModificationException runtime exception. But, in
ConcurrentHashMap, one thread can perform modification
while the other thread is running.
In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but
only 16 update can be doen by threads
clean unused object from heap memory. Achieved through system.gc and finally block
in heap memory

function interface : A functional interface is an interface that contains only one abstract
method but can have multiple default methods
Lamda expressions: They implement abstract method and therefore implement functional
interfaces. Anonymous function that can be created without belonging to any class.
optional : By using Optional, we can specify alternate values to return or alternate code to run
to avoid null pointer exception
From Java 8, Interfaces can have implemented methods. These methods are called default
methods.

multiple instances can't be created for the sigleton classs


Singleton class has all private data members, private consructors, no setters, getinstance
method to check if any instance of class exists,
Spring bean is example of singleton class
Multiple instances of singleton class can be created using reflection methods
Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual Java
object in memory. JPA and hibernate are example of this concept ( by Persistence: If you want
to store the state of a particular operation in a database, it can be easily serialized to a byte
array, and stored in the database for later retrieval.)
Creational patterns:
1. Factory method: The factory method is a creational pattern that deals with Object creation.
It helps in encapsulating an object from the code that depends on it.
After creating a common interface that contains the general behavior , the next step is creating
the different implementations and accordingly decide which one to invoke.
2. Singleton: Singleton is a creational design pattern that lets you ensure that a class has only
one instance, while providing a global access point to this instance. The constructor is made
private to prevent creating a new instance of the class with the new keyword. The getInstance
method will only create a new instance if there isn’t an existing instance thereby obeying the
singleton principle.
Singlton ….This scope implies that Spring container will create an only shared instance of the
class designated by this bean, so each time the getBean is required the same object will be
injected.
Dependency Injection (or sometime called wiring) helps in loosely coupling classes together by
injecting objects of a class into dependent class and at the same time keeping them
independent
Setter Dependency Injection (The bean must include getter and setter methods for the
properties, @Autowired annotation is needed ) and Constructor Dependency Injection (The
bean class must declare a constructor with number of arguments each representeting a
dependency, @Autowire annotation not needed)

Constructor-based DI fixes the order in which the dependencies need to be injected. Setter
based DI does not offer this.

Setter-based DI helps us to inject the dependency only when it is required.

By using the @Qualifier annotation(it is used alongside @Autowired annotation )


There are use cases e.g when we have two beans of same type, for which @Autowired
annotation alone isn't enough for Spring to understand which bean to inject. The Spring
framework will throw a NoUniqueBeanDefinitionException. This is because Spring doesn't
know which bean to inject.

scaling (you can create many instances of a microservice and can run them on different ports)
Faster busines release cycles ( Since you are developing &deploying your application in smaller
components, its much easier to release microservices as compared to monolith applications.
This means you can bring new features, faster to market)
Isolating faulty modules( microservices are independent units hence easier to isolate faulty
microservices and replace)

Kubernetes provides the ability to implement automatic scaling through the use of a Horizontal
Pod Autoscaler (HPA). The criteria for scaling (down or up) is usually based upon the observed
CPU utilization but can take into account other custom metrics.
kubectl autoscale deployment -n --min --max --cpu-percent
No. It is done through kubrnetis or AWS EC2.
Microservices is an architectural software development where software is composed of small
independent services that communicate over well-defined APIs. These services run in their
own processes. With monolithic architectures, all processes are tightly coupled and run as a
single service. Microservices architectures make applications easier to scale and faster to
develop. In monolithik, if one process of the application experiences a spike in demand, the
entire architecture must be scaled. In Monolithic architectures impact of a single process
failure is very significant compared to microservices
Stream takes inputs from collections, arrays or IO and they provide results as per the
intermediate methods. Various intermediate methods can be pipelined and terminal
operations mark the end of stream and return result. Intermediate methods - map, filter,
sorted . Terminal opertions - Collect, forEach, reduce
Collectors.toMap() method
Method reference is used to refer method of functional interface. It is compact and easy form
of lambda expression. Each time when you are using lambda expression to just referring a
method, you can replace your lambda expression with method reference. ( e.g
Class::staticMethod ) Below are the types
Static Method Reference. You can make reference to static method
Instance Method Reference. You can make reference to Instance method
Constructor Method Reference. You can refer a constructor by using the new keyword

Java executor framework is used to run the Runnable objects without creating new threads
every time and mostly re-using the already created threads. Its methods:
SingleThreadExecutor Executor that uses a single worker thread
FixedThreadPool(n) a thread pool that reuses a fixed number of threads
CachedThreadPool Executors class Creates a thread pool that creates new threads as needed
but will reuse previously constructed threads
ScheduledExecutor
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.

The @PostConstruct annotation is used on a method that needs to be executed after


dependency injection is done to perform any initialization.
The @PreDestroy annotation is used on methods as a callback notification to signal that the
instance is in the process of being removed by the container.
Using @Value annotation @Value("${spring.datasource.username}")
by @ControllerAdvice annotation. Create a class extending responseEntityExceptionHandler
and write this annotation on this class. Then write all anticipated exception for this
microservice under annotation @ExceptionHandler(Exception.class) inside this class
Three are : @Configuration :This annotation is used for defining beans using the Java
configuration.
@EnableAutoConfiguration :This annotation enables the application to add the beans using the
classpath definitions.
@ComponentScan : This annotation tells the spring to look for other components,
configurations and services in the specified path.

Classes that needs to be loaded before compiling and running java application
BootStrap ClassLoader: It loads standard JDK class files from rt.jar and other core classes. It is a
parent of all class loaders.
Extension ClassLoader: The Extension ClassLoader is a child of Bootstrap ClassLoader and loads
the extensions of core java classes from the respective JDK Extension library. It loads files from
jre/lib/ext directory
System ClassLoader: It loads application specific classes from the CLASSPATH environment
variable. The Application ClassLoader is a child class of Extension ClassLoader.
Using mock annotation of Mockito
1. Synchronous : Feing & Ribbon
2. Asynchronous: Rest template, httpclient api
Delegation can be an alternative to inheritance.
Delegation means that you use an object of another class as an instance variable, and forward
messages to the instance.
Path - reference for OS to search executable
Classpath - for JVM reference, to locate java binaries
During serialization, if you don’t want some part of code to be not transformed then you mark
it as Transient or static . After deserilization exact values wont be transferred but default values
will be restored

By overriding writeObject and readObject methods. 2. By marking it as @Transient


Using system.gc and defining resources under finally block.
hash set does not allow duplicates. Before adding element, it will check hashcode, and if
present will not add the element. Then it will check equals method and if returns false then it
will add the element to set
In shallow copy, only fields of primitive data type are copied while the objects references are
not copied. Deep copy involves the copy of primitive data type as well as object references.
You can use enum types any time you need to represent a fixed set of constants . They
provide compile time type safety

Thread be created by extending the Thread class and overriding its run() method
Another way to create a thread is to implement the Runnable interface:
The major difference is that when a class extends the Thread class, you cannot extend any
other class, but by implementing the Runnable interface, it is possible to extend from another
class as well
Once the countdown latch goes below 0 you can not reuse thread wheres cycli barrier you can
reuse

Reentrant Locks are provided in Java to provide synchronization with greater flexibility.
ReentrantLock allows threads to enter into the lock on a resource more than once. When the
thread first enters into the lock, a hold count is set to one. Before unlocking the thread can re-
enter into lock again and every time hold count is incremented by one. For every unlocks
request, hold count is decremented by one and when hold count is 0, the resource is unlocked.
Reentrant Locks also offer a fairness parameter, by which the lock would abide by the order of
the lock request i.e. after a thread unlocks the resource, the lock would go to the thread which
has been waiting for the longest time. This fairness mode is set up by passing true to the
constructor of the lock.

A race condition occurs when two or more threads can access shared data and they try to
change it at the same time.
If threads are waiting for each other to finish, then the condition is known as Deadlock.. To
detect deadlock,we have to collect Thread Dump; command is jcmd $PID Thread.print

Related to wrapper class.Autoboxing is the automatic conversion that the Java compiler makes
between the primitive types and their corresponding object wrapper classes. For example,
converting an int to an Integer, a double to a Double, and so on. If the conversion goes the
other way, this is called unboxing.

submit method returns future object whereas execute method does not return anything.
Submit method can accept both callable and runnable tasks whereas execute method accept
only runnable tasks

You can use hystrix or resilience 4j circuit breaker. Define fall back methods ( giving timeout
period or max number of request failing)
Actuators for service monitoring and zipkin for application monitoring
When changes are made to properties file of any microservice then those changes are
propagate to allframework
instances only public non static methods can be tested; but using
Using mockito
Powermockito framework, one can test static methods, constructors, final classes, private
methods,

Abstractin: Hiding internal details and showing functionality only. Abstraction focus on what
the object does instead of how it does. . Abstract class and interface is example
Encapsulation: Encapsulation: Wrapping code and data together into a single unit.
Class is an example of encapsulation, because it wraps the method and property.
a real world example of calculator.
Encapsulation is the internal circuits, battery, etc., that combine to make it a calculator.
Abstraction is the different buttons like on-off, clear and other buttons provided to operate it.
Abstraction done at design level whereas encapsulation is done at implementation level
When a member (block,variable,method,nested class) is declared static, it can be accessed
before any objects of its class are created, and without reference to any object.
Static block : to initialize your static variables, you can declare a static block that gets executed
exactly once, when the class is first loaded.
Static Method: They can only directly call other static methods. They can only directly access
static data.
Static class : Java doesn't allow you to create top-level static classes; only nested (inner) static
classes. To create instance of nested class, you must make use of parent class
Iterator - Iteration through collections ; listIterator - Iteration through list
Iterator can only traverse in forward direction whereas list iterator can traverse in both forward
direction and backward direction

Fail-Fast iterators immediately throw ConcurrentModificationException if there modification


like 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. Iterator on CopyOnWriteArrayList, ConcurrentHashMap classes are examples
of fail-safe Iterator.
Comparable : natural sorting. Comparto method. When object has primitive types
Comparator : Customized soring Compare method.
Singleton : Get bean will return only one instance . Prototype: GetBean method will return new
object each time it is called
Annotation @RepsonseBody is not not needed at class level when using @RestController
whereas with Controller it is needed
NO
No, we cannot override private or static methods in Java.

The finally block in java is used to put important codes such as clean up code e.g. closing the
file or closing the connection. The finally block executes whether exception rise or not and
whether exception handled or not. A finally contains all the crucial statements regardless of the
exception occurs or not.
Step 1: Add the starter dependency. <artifactId>spring-boot-starter-security</artifactId>
Step 2: Create a config class by extending WebSecurityConfigurerAdapter
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {}
Step 3: Annotate it with @Configuration.
@Configuration
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {}
Step 4: Enable WebSecurity.
@EnableWebSecurity
@Configuration
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {}
Step 5: Override configure method from WebSecurityConfigurerAdapter and provide your
custom logic.
@EnableWebSecurity
@Configuration
public class CustomSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/customURL")
.permitAll()
}}
Step 6: Add dependency <groupId>io.jsonwebtoken</groupId> . Expose a POST API with
mapping /authenticate. On passing the correct username and password, it will generate a JSON
Web Token (JWT). If a user tries to access the GET API with mapping /hello, it will allow access
only if a request has a valid JSON Web Token (JWT).

When the user successfully logs in using their credentials, a JSON Web Token will be returned
by server. After that each subsequent request should include the JWT token, for user to access
routes, services, and resources that are permitted with that token. JWT has three parts, Header
(Encoding algorithm) , Payload (request data), signature. JWT is stateless (tateless means the
state of the service doesn't persist between subsequent requests and response. Each request
carries its own user credentials and is individually authenticated)
with thenReturn you can not return anything other than the return type of method under test;
with doReturn you can return anything.

assertAll() : asserts that all supplied executable do not throw exceptions


assertDoesNotThrow() checks that executable does not throw exception of any type
assertThrows() ; checks that executable throws an exception of expectedType and returns
exception
assertArrayEquals() ; array elements are matched index by index
assertEquals() and assertNotEquals(); checks whether expected and actual objects are equal or
not
assertSame() and assertNotSame() : checks whether expected and actual elements are equal or
not
assertTrue() and assertFalse() : asserts that supplied condition is true or false
assertNull() and assertNotNull() : check if specified object is null or not
starter pom : downloads all required dependencies to dev web applications. Simplifies maven
configuration.
-version management : version is defined only for starter parent; no need to define it for each
dependency
-embedded server : provide tomcat
- In memory H2 DB : for developing POC
- Actuator : To monitor application after deployement

DelegationFilterProxy is a Servlet Filter implementation


Spring Security uses Filter component of Java Servlet API.
Servlets has the concept of FilterChain which has a list of Filters in an ordered manner. An HTTP
request first go through the FilterChain and then proceed to the Controllers and handlers.
We just hook a special Spring Security Filter, called DelegationFilterProxy in the Servlet‘s
FilterChain and then process the security related logic in it.

With Spring IoC, we transfer the control of ‘Object creation and assembling’ to Spring IoC
container. E.g beanfactory is type of IOC container
The @Mock annotation creates mock instances.
@InjectMocks creates class objects. Use @InjectMocks when actual method body needs to be
executed for a given class.

JUnit 5 Annotations
@Test
@DisplayName
@BeforeEach
@AfterEach
@BeforeAll
@AfterAll
@Disabled
@TestMethodOrder
@RepeatedTest
@Tag

The Assert command is used to validate critical functionality. If this validation fails, then the
execution of that test method is stopped and marked as failed.
In the case of Verify command, the test method continues the execution even after the failure
of an assertion statement. The test method will be marked as failed but the execution of
remaining statements of the test method is executed normally.
JUnit test methods are designed to return 'void'. So the execution will fail.
Use @Mockbean and import static org.mockito.Mockito.*;
The Mockito.mock() method allows us to create a mock object of a class or an interface.

Following: @Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
Type of methods: Interface can have only abstract methods. An abstract class can have
abstract and non-abstract methods. From Java 8, it can have default and static methods also.
Final Variables: Variables declared in a Java interface are by default final. An abstract class may
contain non-final variables.
Type of variables: Abstract class can have final, non-final, static and non-static variables. The
interface has only static and final variables.
Implementation: Abstract class can provide the implementation of the interface. Interface can’t
provide the implementation of an abstract class.
Inheritance vs Abstraction: A Java interface can be implemented using the keyword
“implements” and an abstract class can be extended using the keyword “extends”.
Multiple implementations: An interface can extend another Java interface only, an abstract
class can extend another Java class and implement multiple Java interfaces.
A class can extends multiple interfaces but only one abstract class
An interface cannot extend a class but it can extend another interface in the same way that a
class can extend another class. The extends keyword is used to extend an interface, and the
child interface inherits the methods of the parent interface.
Yes, it is mandatory to implement all the methods in a class that implements an interface until
and unless that class is declared as an abstract class.
The subclass of abstract class in java must implement all the abstract methods unless the
subclass is also an abstract class.

IoC is a generic term meaning that rather than having the application call the implementations
provided by a library (also know as toolkit), a framework calls the implementations provided by
the application.
DI is a form of IoC, where implementations are passed into an object through
constructors/setters/service lookups, which the object will 'depend' on in order to behave
correctly.
List allow duplicate whereas set does not allow duplicates
List allow null elements but set will allow only one null element
List is ordered(elments can be accessed based on index) where as set is unordered

How the ArrayList works


The ArrayList class has a regular array inside it. When an element is added, it is placed into the
array. If the array is not big enough, a new, larger array is created to replace the old one and
the old one is removed.
How the LinkedList works
The LinkedList stores its items in "containers." The list has a link to the first container and each
container has a link to the next container in the list. To add an element to the list, the element
is placed into a new container and that container is linked to one of the other containers in the
list.
When To Use
It is best to use an ArrayList when: You want to access random items frequently, You only need
to add or remove elements at the end of the list
It is best to use a LinkedList when: You only use the list by looping through it instead of
accessing random items, You frequently need to add and remove items from the beginning,
middle or end of the
list

Only one thread can have access to resources accessed under Synchronized blocks; other
threads can wait till thread finishes with its execution

1. HashMap is non synchronized. It is not-thread safe and can’t be shared between many
threads without proper synchronization code whereas Hashtable is synchronized. It is thread-
safe and can be shared with many threads.
2. HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any
null key or value.
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.
String - Immutable
String buffer - not Immutable - Synchronized - thread safe - Multithreaded enviornment
String builder - not Immutable - Not synchronized - not thread safe - Single thread enviornment

Abstract class can have zero number of abstract methods.


final class can not contain abstract methods
abstract class can contain final methods.
for instance variables, for every object a separate copy of instance variables will be created but
in case of static variable only one copy will be created shared by every object in the class
Abstract class and interface can't be instantiated i.e their objects can not be created
public static void main( String args[]) .. public access modifier, static : accessed without creating
instanc of class, void . return type not returning any value, String args[] - method parameters
final variable value cant change , final method can not be overriden, final class can not be
extended
Checked exception : exception checked at runtime ( try and catch block, IO exception)
Unchecked exception: exceptions not checked at runtime ( Null Pointer exception)

private : accessible within class only


Default : accessible within package only
protected: accessible within package and subpackages
public : accessible across the packages
If programmer makes any mistake wrong parameter or wrong types while overriding, you
would get a compile time error. If you don’t use the annotation then the sub class method
would behave as a new method (not the overriding method) in sub class.
REST let you chose response format whereas in SOAP only xml is allowed

the Spring @Scheduled annotation can be used to configure and schedule tasks.
Can schedule a task by fixed delay or fixed rate @Scheduled(fixed delay=1000)
The scheduled method should typically have a void return type (if not, the returned value will
be ignored)
The scheduled method should not expect any parameters

Spring Boot Actuator provides secured endpoints for monitoring and managing your Spring
Boot application. By default, all actuator endpoints are secured. Some important end points are
listed below
/metrics To view the application metrics such as memory used, memory free, threads, classes,
system uptime etc.
/env To view the list of Environment variables used in the application.
/beans To view the Spring beans and its types, scopes and dependency.
/health To view the application health
/info To view the information about the Spring Boot application.
/trace To view the list of Traces of your Rest endpoints.
Difference : @crudRepository: to perform only crud operations
@JpaRepository: peforms not only crud operations but pagination and sorting

This annotation is used to write custom quries inside repository interface


Below is example :
@Query("SELECT b FROM Book b WHERE b.title = ?1 and b.author = ?2")
Book findBookByTitleAndAuthor(String title, String authorName);

Rest Client can be implemented in three ways:


1. Rest Template 2. Web Client 3. Feign Client
Feign client: Microservices can communicate each other by making API calls without having to
bother about REST internal details

@EnableAutoConfiguration(exclude={DataSourceAutoConfig.class}}
The squash is not any command; instead, it's one of many options available to you under git
interactive rebases. The squash allows us to rewrite history. Suppose we have made many
commits during the project work, squashing all the commits into a large commit is the right
choice before pushing the code.

The application is generally developed with multiple layers. The responsibility of each layer is
different, but there are a few common aspects that apply to all layers are Logging, Security,
validation, caching, etc. These common aspects are called cross-cutting concerns Using AOP,
we define these cross cutting concerns one special class called aspect. We are free to define
how and where this functionality is applied without modifying the class to which we are
applying the new feature.
Aspect: A code unit that encapsulates pointcuts, advices, and attributes.
Advice: It is an implementation of cross-cutting concerns
Pointcut: It defines the set of entry points in which advice is executed.

Entities represent persistent data stored in a relational database. Entities: Entity can be a
person, place, thing, or any identifiable object for which data can be stored in a database.
Entity class can inherit from non entity class or other entity class

JPA - Java persistence API : used to save java objects to relational database table. JPA has
features for DDL generation, Database data manipulation and these can be set up to run on
startup against the database using external property
Hibernate - open source implementation of latest JPA(2.1) specification
JPA specification are only for mpaaing java objects to relational database
To enable JPA in a Spring Boot application, we need the spring-boot-starter and spring-boot-
starter-data-jpa dependencies:
Spring Boot configures Hibernate as the default JPA provider, so it's no longer necessary to
define the entityManagerFactory bean
JPA & JDO - specifications for storing java objects in databases. JPA is for relational databases
whereas JDO describes ORM for any possible bases and repositories ( incuding no SQL)
Entity can be abstract class

Entity class must be annotated with @Entity


Should have getter and setter methods
Should have public or protected constructor with no arguments
Entity class can not be final class
Entity class can not contain final fields or methods
Must contain primary key denoted with @Id

valid attribute type for entity class : Primitiv types, strings, enums, collection, othe entity
Property level access (fields with private modifier, setter and getter methods are considered as
properties) and field level (Variables of a class i.e. instance variables and static variables are
called fields) access
embeddable class - embaddable class is a class that is not used by itself, but only as part of one
or more entity classes. Can be used as keys or map values. Embeddable class must be marked
with Embeddable annotation and need not contain primary
Mapped superclass is a class from which Entity is inherited, it may not cotain JPA annotations,
is not a n Entity and does not have to fulfill all requirement for entity class. It is annotate with
Mapped Superclass

Lifecycle status of an entity instance :


a. new - object created but primary key not generated and not saved in database
b. managed - ojbect create, primary key generated and managed by jpa
c. detached - the object is no longer managed by JPA
d. removed - created, managed but will be deleted in next commit
JPA @Transient annotation - used to indicate that field should not persist in database
The @Basic annotation on a field or a property signifies that it's a basic type and Hibernate
should use the standard mapping for its persistence.

JPQL is java persistence query language


Where SQL works with relational database tables, records and fields, whereas JPQL works with
Java classes and objects. For example, a JPQL query can retrieve and return entity objects
rather than just field values from database tables, as with SQL.

It is used for database schema definition; various property values explain below
create – Hibernate first drops existing tables, then creates new tables
update – the object model created based on the mappings (annotations or XML) is compared
with the existing schema, and then Hibernate updates the schema according to the diff. It
never deletes the existing tables or columns even if they are no more required by the
application
create-drop – similar to create, with the addition that Hibernate will drop the database after all
operations are completed. Typically used for unit testing
validate – Hibernate only validates whether the tables and columns exist, otherwise it throws
an exception
spring.jpa.sql-show
used for logging of SQL statements(while spring application starting) with Spring Boot and
Hibernate
The Spring Boot project is intended to make creating Spring applications much faster and
easier. This is done with the use of starters and auto-configuration for various Spring
functionalities, auto configuring web server liket Tomacat, JPA among them.

Inside spring-boot-starter-web dependecy exclude following Tomcat dependency


<artifactId>spring-boot-starter-tomcat</artifactId>
and include following dependency
<artifactId>spring-boot-starter-jetty</artifactId>

H2database is, in-memory database is volatile, and data will not persist when we restart the
application. Mostly used for Unit testing purpose.
if we want to use an in-memory H2 database in a Spring Boot JPA application, we only need to
add the h2 dependency to the pom.xml file:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.200</version>
</dependency>
H2 database has an embedded GUI console for browsing the contents of a database and
running SQL queries.
To enable it, we need to add spring.h2.console.enabled=true in application.properties

The List is an interface, and the ArrayList is a class of Java Collection framework. The List
creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the
List can not be expanded once it is created but using the ArrayList, we can expand the array
when needed.

1. The Function interface represents a function (method) that takes a single parameter and
returns a single value.
2. The Predicate interface represents a simple function that takes a single value as parameter,
and returns true or false.
3. The Supplier interface is a functional interface that represents an function that supplies a
value of some sorts. It has only get() method
4. The Consumer interface is a functional interface that represents an function that consumes
a value without returning any value. It has only accept() method
yes; but for that you need to override equal() and hashcode() methods
1. Type safety 2. Type casting not required
1) Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to
declare an exception. 2)Checked exception cannot be propagated using throw only. Checked
exception can be propagated with throws. 3) Throw is followed by an instance. Throws is
followed by class. 4) Throw is used within the method. Throws is used with the method
signature.

Below is difference: @Component is a class level annotation whereas @Bean is a method level
annotation and name of the method serves as the bean name. @Component need not to be
used with the @Configuration annotation where as @Bean annotation has to be used within
the class which is annotated with @Configuration

POJO stands for Plain Old Java Object. It is an ordinary Java object, not bound by any special
restriction other than those forced by the Java Language Specification
A POJO should not:
Extend prespecified classes
Implement prespecified interfaces
Contain prespecified annotations
The @RequestParam is used to extract query parameters ( anything after ?) while
@PathVariable is used to extract data right from the URI
By way of @Request body param

Status code 200 (Success)– Success


Status code 301 (Redirectional)– Moved Permanently
Status code 302 – Moved Temporarily
Status code 403 (client side error)– Forbidden
Status code 404 – Not Found
Status code 500 (server side error)– Internal Server Error
Status code 503 ­– Service Unavailable

Spring Boot Auto configurer does dispather servlet configuration


All incoming HTTP request goes through
dispatcher servlet
Dispatcher servlet is the front controller

1. Bounded Context : The number of miscroservices buit at the end of the project might be
much higher than what planned at the start of the project
2. Configuration management : There could as many as 5 enviorments to be managed ( L1, L2,
L3, Prod). Managing configuration files for all these env is big task
3. Visibility : If exceptions occurs at one microservice then difficult to locate this microservice.
( This challenge can be overcomed by using centralized logging system like splunk)
4. Stack of cards: If one microservice goes down then rest all microservices can go down ( can
be solved by provisining for fault tolerance)
for specifying minimum and maximus limits
For maitaing configurations informations for all enviornments like Dev QA. Git repository is
linked which stores configuration on files named after enviornments
Service discovery and registration. For keeping track of running instances of all microservices.
Eureka server default port is 8761
For doing load balancing ( spring cloud load balancer). Service discovery and fault tolerance are
provided by load balancer.
I used for interservice communication.
Using Feign client: Microservices can communicate each other by making API calls without
having to bother about REST internal details To use Feign create an interface and annotate it
with @Feign Client. Annotate main spring class with @EnableFeignClien
For fault tolerance, as a circuit braker. It is generally required to enable fault tolerance in the
application where some underlying service is down/throwing error permanently, we need to
fall back to different path of program execution automatically.
Spring Cloud Gateway is a library for building an API gateway, spring Cloud Gateway is intended
to sit between a requester and a resource that’s being requested, where it intercepts, analyzes,
and modifies every request.
Since Cloud gateway is another Spring Boot application, you have access to the entire Spring
ecosystem including spring security and spring actuators.
Spring cloud Gateway helps in service aggregation: rather rather proving end points for all 10
Api. You can aggregate all 10 Api into one and can give end point to user
Spring Cloud Security allows you to lock down access to your backend services. Since all
requests are going through your gateway, that security propagates to all of your services that
are sitting behind that gateway. For example, you can enable single sign-on (SSO) with your
gateway and then control which role each route requires a user to have.
Spring Boot Actuators actuators are used to monitor any Java application. e.g you could record
each time a route is hit to see trends over time, or measure the latency of each request.

It is used for Distributed tracing. Distributed tracing is a technique used to profile and monitor
applications, especially those built using the microservice architecture.It identifies the failed
microservices or the services having performance issues when there are many services call
within a request. It is very useful when we need to track the request passing through the
multiple microservices. It is also used for measuring the performance of the microservices.

It is a message broker. All rabbitmq does is provide an efficient way to store pending
transactions and requests and forward them on to somewhere else that handles them.
We receive thousands of request during brunch hours, now imagine the situation where users
are placing the order simultaneously and back end servers are not processing the orders as fast
as they should, or some error has occurred at BE side either through code or hardware.
Now in this case since all the request were directly handled by the server, these request will
not be processed and no body would ever come to know if there is any such order placed
because server is not working.
Imagine another situation where I have placed a service in between the two services, i.e Front
end and Back end.
This service is called as Rabbit, what Rabbit will do for us is now consume all messages from
Front end and will only release when BE is ready to process it, in this case even when we have
got some error at Back end either a coding error or infrastructure we always have our
messages a.k.a requests from the users
Assings unique ID to all incoming requests. Then all logs from all request services will be sent
from Sping cloud seuth ( by Rabbit MQ) to Zipking tracing server

Implementing API Gateway:


1. Add starter web, netflix-zuul and eureka client dependency
2. Configure @EnableZuulProxy and @EnableDiscoveryClient annotation at springboot start
class
3. Configure API gateway with Eureka server registration in yml or application.properties
4. Configure routing to access backent services in yml or application.properties

We can quickly develop cloud-based spring application with the help of the Spring Cloud
Framework. Spring Cloud provides tools for developers to build some of the common patterns
in distributed systems like configuration management, service discovery, circuit breakers,
intelligent routing, distributed tracing
RESTful Web Services are basically REST Architecture based Web Services. In REST Architecture
everything is a resource.
RESTful Web Services are fast because there is no strict specification like SOAP. It consumes
less bandwidth and resource.
RESTful web services can be written in any programming language and executed in any
platform.
RESTful web services can use SOAP web services as the implementation.
RESTful web service permits different data format such as Plain Text, HTML, XML and JSON.
Common Rest methods are get, post, put, delete

Spring has become more and more complex as new functionalities have been added. If you
have to start a new spring project, then you have to add build path or add maven
dependencies, configure application server, add spring configuration. So everything has to be
done from scratch.
Spring Boot is the solution to this problem. Using spring boot you can avoid all the boilerplate
code
Basically, Springboot = Spring MVC + Autoconfiguration ( no need for Web.xml for
configuration) + Web server like tomcat
Continuous Integration (CI) is the process of automating the build and testing of code every
time a team member commits changes to version control.
Finalize is called before destroying object. No certainity if it will be called immediately. Close()
method can be used.
So a final array means that the array variable which is actually a reference to an object, cannot
be changed to refer to anything else, but the members of array can be modified.
No
Yes. JVM will called default main method for class
Create class with @Component and @Endpoint annotation

Java 11 adds a few new methods to the String class: isBlank, lines, strip, stripLeading,
stripTrailing, and repeat.
File class added with new readString and writeString static methods
toArray method added to collection interface
we don't need to compile the Java source files with javac explicitly anymore. can do that with
just java
Support for using the local variable syntax (var keyword) in lambda parameters was added in
Java 11.

Java new Operator


Java Class.newInstance() method
Java newInstance() method of constructor
Java Object.clone() method
Java Object Serialization and Deserialization
Yes; class should be final; data members should be private &
final, constructor should be parametrized performing deep
copy, only getters and no setters

Multithreading helps program by executing multiple things at


same time

new, runnabled, waiting/blocked, terminated.


Wait : for pausing thread execution because certain condition
has occurred Join: To add sequecing between multiple
threads

Sleep : Pauses the execution thread by specified time in


milliseconds. Thread does not lose ownership of Monitor

Hashmap : If one thread is iterating over hashmap and if some


other thread tries to modify hashmap then
cocurrentmodification exception is thrown

data members should be private, constructor should be


private, getInstance method should be defined which will
create ojbect of class only if object does not previously exists.
No setters and getters
After creating interface with general behavior , the next step is
to create its implementation

Helps in loosely coupling two classes by injecting ojbects of


one class into dependent class Setter DI : done through
@Autowired annotation. Bean class must have setter and
getter methods
Constructor DI : Parametrized costtructor needed with
arguments each representing dependency
Del
JwtRequestFilter
The JwtRequestFilter extends the Spring Web Filter
OncePerRequestFilter class. For any incoming request, this
Filter class gets executed. It checks if the request has a valid
JWT token. If it has a valid JWT Token, then it sets the
authentication in context to specify that the current user is
authenticated.
JwtResponse
This class is required for creating a response containing the
JWT to be returned to the user.
JwtRequest
This class is required for storing the username and password
we received from the client.
JwtAuthenticationController
Expose a POST API /authenticate using the
JwtAuthenticationController. The POST API gets the username
and password in the body. Using the Spring Authentication
Manager, we authenticate the username and password. If the
credentials are valid, a JWT token is created using the
JWTTokenUtil and is provided to the client.
JwtTokenUtil
The JwtTokenUtil is responsible for performing JWT operations
like creation and validation. It makes use of the
io.jsonwebtoken.Jwts for achieving this.
The @Component is an annotation that allows Spring to
automatically detect our custom beans
Questions

Left and outer join

delete and truncate and drop

Stored procedurea and function


Difference between primary key and unique key

Difference between primary key and foreign key


Subset of SQL
Difference between Char and Varchar
Can table has two primary keys
Foregin key

Cluster and non cluster index


Entities and relationships
Trigger
Query for selecting employees name starting with A

Different type of relationships

shredding - db concept
Between and IN
Merge
Recursive stored proceducre

Where vs having clause

Order BY

Group BY
Having

Stored procedure

Views

Inner Join

imagine that you are joining the titles and publishers tables to
create a query showing the average book price for a set of
publishers. You want to see the average price for only a
specific set of publishers - perhaps only the publishers in the
state of California. And even then, you want to see the
average price only if it is over $10.00.
Intersect sql

SQL vs PL SQL
Authentication and Authorization

What are entities

What are aggregate functions and scalar functions

How to fetch common records from two tables?


How to fetch alternate records from a table?
How to select unique records from a table?
Query to fetch first 5 characters of the string
Query to find 2nd highest salary

Which operator is used in query for pattern matching?

What are UNION, MINUS, UNION ALL, INTERSECT?


What is database schema

Different clauses in SQL

Transaction controls

How to update view in SQL


What is subquery; how many comparison operators are used
while working with subquery
What is a Cursor?

What are Indexes in SQL?


ACID properties

Constraints in SQL
Views vs tables:
What do you understand by Self Join?
Answers
Inner join returns rows if there is at least one match in both tables. Left join returns all the rows from the left table even if the
right table. Right join returns all the rows from the right table even if no matches exist in the left table. Full join would return r
least one match in the tables.
DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE are DML statements.
DDL stands for Data Definition Language. CREATE, ALTER, DROP, RENAME are DDL statements.
TCL Commit, Rollback
The function must return a value but in Stored Procedure it is optional.
Functions can have only input parameters for it whereas Procedures can have input or output parameters.
Functions can be called from Procedure whereas Procedures cannot be called from a Function
The primary key does not allow ‘NULL’, but the unique key does.
There can be only one primary key for a table There can be more than one foreign key for a table
Primary key attributes cannot have duplicate values in a table Duplicate values are acceptable for a foreign key
Null values are not acceptable for Primary key whereas Null values are acceptable for foreign key
DDL - used to define database schema e.g create table ; DML - used to manipulate data present in database e.g Select , Insert
Char stores strings of fixed length whereas varchar stores string of variable length
NO. For that specify composite key like. 1. PRIMARY KEY (COL1, COL2));
Maintains referential integrety by enforcing a link between data in two tables
Both used to retrieve data from database but clustered index is faster; there can be only one cluster index on a table whereas
non cluster index. Cluster index reorders the physical orders of rows whereas non clustered index does not.
Enitites : Customer, Orders these are example Relationship: Connects two tables. Link between two tables
allows you to execute code after or before insert , delete and update operations
Select * from table_name where Empname like 'A%'
One to One : One record in table A will be related to only single record in table B
Many to One: Many records in table A will be related to only single record in table B
One to Many: Only One record in table A will be related to many records in table B
Shredding or Horizontal partitioning is a design principle whereby rows of a database table are held separately, rather than sp
for normalization). The advantage is the number of rows in each table is reduced (this reduces index size, thus improves searc
Between : Used to display rows based on a range of values . IN : Used to check for values contained in a specific set of values
Allows conditional update or insertion of data into a table
Stored procedure referes to a stored procedure which calls by itself until it reaches some boundry condition

1. WHERE Clause is used to filter the records from the table. Having Clause is used to filter record from the groups
2. WHERE Clause can be used without GROUP BY Clause. HAVING Clause cannot be used without GROUP BY Clause
3. WHERE Clause implements in row operations. HAVING Clause implements in column operation
4. WHERE Clause cannot contain aggregate function. HAVING Clause can contain aggregate function
5. WHERE Clause can be used with SELECT, UPDATE, DELETE statement. HAVING Clause can only be used with SELECT st
6. WHERE Clause is used before GROUP BY Clause. HAVING Clause is used after GROUP BY Clause

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the recor
by default
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in ea
The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG())
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.

CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode nvarchar(10)


AS
SELECT * FROM Customers WHERE City = @City AND PostalCode = @PostalCode
GO;

EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';

In SQL, a view is a virtual table based on the result-set of an SQL statement.

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);

SELECT * FROM [Products Above Average Price];


SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

SELECT titles.pub_id, AVG(titles.price)


FROM titles INNER JOIN publishers
ON titles.pub_id = publishers.pub_id
WHERE publishers.state = 'CA'
GROUP BY titles.pub_id
HAVING AVG(price) > 10
ORDER BY price
INTERSECT statement will return only those rows which will be common to both of the SELECT statements that are being com
SQL allows only single query or execute single insert, delete, update. Whereas PL SQL allows to write full programs having mul
insert/delete/update commands to achieve multiple operation on database
Authentication confirms that users are who they say they are. Authorization gives those users permission to access a resource
Entities represent persistent data stored in a relational database. Entities: Entity can be a person, place, thing, or any identifiab
data can be stored in a database.
Entity class can inherit from non entity class or other entity class

Aggregate functions are used to evaluate mathematical calculation and return single values. This can be calculated from the co
Scalar functions return a single value based on the input value.
Aggregate – max(), count() - Calculated with respect to numeric.
Scalar – UCASE(), NOW() – Calculated with respect to string

Common records result set can be achieved by intersect -.


Select studentID from student INTERSECT Select StudentID from Exam
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0
Select DISTINCT StudentID, StudentName from Student
Select SUBSTRING(StudentName,1,5) as studentname from student
select
DISTINCT(salary)
from employee
order by salary desc
limit 1,1
Note:
limit 0,1 - Top max salary
limit 1,1 - Second max salary
limit 2,1 - Third max salary
limit 3,1 - Fourth max salary

LIKE operator is used for pattern matching,


Select * from Student where studentname like 'a%'

MINUS – returns all distinct rows selected by the first query but not by the second.
UNION – returns all distinct rows selected by either query
UNION ALL – returns all rows selected by either query, including all duplicates.
INTERSECT – returns all distinct rows selected by both queries.
In a relational database, the schema defines the tables, fields, relationships, views, indexes, packages, procedures, functions, q

Select, from, where, orderBy, GroupBy, Having, Join, Using

In simple words, we can say that a transaction means a group of SQL queries executed on database records.
There are 4 transaction controls such as
COMMIT: It is used to save all changes made through the transaction.
ROLLBACK: It is used to roll back the transaction. All changes made by the transaction are reverted back and the database rem
SET TRANSACTION: Set the name of the transaction.
SAVEPOINT: It is used to set the point where the transaction is to be rolled back.

Answer: SQL CREATE OR REPLACE can be used for updating the view.
Execute the below query to update the created view.
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
Query is query written inside a query ( usually after where clause followed by comparison operator). There are 3-row compari
used in subqueries such as IN, ANY and ALL. Subquery result serve as input for main query
Answer: A cursor is a database object which is used to manipulate data in a row-to-row manner.
Answer: The index can be defined as the way to retrieve the data more quickly. We can define indexes using CREATE statemen
Syntax:
CREATE INDEX index_name ON table_name (column_name)
The full form of ACID is Atomicity, Consistency, Isolation, and Durability. To check the reliability of the transactions, ACID prop
NOT NULL: That indicates that the column must have some value and cannot be left NULL.
UNIQUE: This constraint is used to ensure that each row and column has a unique value and no value is being repeated in any
PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE constraints such as on one or the combination
column to identify the particular record with a unique identity.
FOREIGN KEY: It is used to ensure the referential integrity of data in the table. It matches the value in one table with another u
KEY.
CHECK: It ensures whether the value in columns fulfills the specified condition.
It is a virtual table that is extracted from a database. A table is structured with a set number of columns and a boundless numb
Views do not hold data themselves.A table contains data and stores the data in databases.
Self Join in SQL is used for joining a table with itself.
Create Amazon EC2 instance

There is Security Group option under instance Menu.Add custom routes with desirable
ports. See example to right. Custom port of 8080 and 4000 have been added

Installing node js on ec2


curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash

. ~/.nvm/nvm.sh

nvm install node


node -e "console.log('Running Node.js ' + process.version)"

To change to super user


Sudo -su

Installing git on ec2


sudo yum install git -y
Clone project repository on ec2
git clone https://github.com/self-tuts/express-todo-app

npm install

Run the backend application


npm start
Deploy microservices on AWS using docker

1. Build the project using maven

2. Create a docker file


3. Build docker file
docker build -t /springboot-docker-aws
4. Push this build to docker repository
docker push abhagat2/springboot-docker-aws
5. Create EC2 instance if not already done

6. Create security group and enable inbound SSH from


anywhere

7. Assign newly created security group to the instance


8. install docker…sudo yum install docker
9. Start docker .. Sudo service docker start
10. Run the docker image

Upload springboot app to github


1. Create github repository
2. Open terminal in IntelliJ
3. Type git init
4. Type gid add .
5. Type git commit -m "first commit"

6. Then copy paste


7. git push -u origin master

Integrating Springboot + Github + Jenkins + dockerhub

Most used docker commands


docker build
docker create
docker images
docker kill
docker pull
docker push
docker restart
docker rm
docker run
docker start
docker stop

What is docker

Advantages of docker

What is AWS EC2

How does EC2 do autoscaling

What is continues integration


This docker file can be built using Jenkins. While creating build, Jenkins also create docker image
and pushes it to docker hub
Build an image from a Dockerfile
Create a new container
List images
Kill one or more running containers
Pull an image or a repository from a registry
Push an image or a repository to a registry
Restart one or more containers
Remove one or more containers
Create and start a container
Start one or more stopped containers
Stop one or more running containers

Docker container packages your application and all its dependencies together to ensure that
your application works seamlessly in any environment.
Docker enables application portability
Docker enables more efficient use of system resources
Docker very suitable for microservices architecture
EC2 stands for Amazon Elastic Compute Cloud. Amazon Ec2 is a basic virtual machine with
customizable hardware components and an OS. The system allows you to run various virtual
computers and manage the same with a single hardware.

Monitor the health of running instances and repairing unhealthy ones


Amazon EC2 Auto Scaling ensures that your application is able to receive traffic and that EC2
instances are working properly. Amazon EC2 Auto Scaling periodically performs health checks to
identify any instances that are unhealthy.
Balance capacity across Availability Zones
Amazon EC2 Auto Scaling can automatically balance instances across zones, and always launches
new instances so that they are balanced between zones as evenly as possible across your entire
fleet.
Amazon EC2 Auto Scaling enables you to follow the demand curve for your applications closely,
reducing the need to manually provision Amazon EC2 capacity in advance. For example, you can
use target tracking scaling policies to select a load metric for your application, such as CPU
utilization. Or, you could set a target value using the new “Request Count Per Target” metric
from Application Load Balancer, a load balancing option for the Elastic Load Balancing service.
Amazon EC2 Auto Scaling will then automatically adjust the number of EC2 instances as needed
to maintain your target.
Continuous Integration (CI) is the process of automating the build and testing of code every time
a team member commits changes to version control.
Questions

What is angular

What is angular material


Angular CLI
Angular Universal
Angular Ivy :
What is bazel:
How to run angular app to different port
In build testing tool inside angular
How to execute test scripts
Where are unit tests and end to end tests are placed in
angular app

What is lazy loading

Use of Ng ling command


how to call service method in component
how to optimize angular app
What is ngZone

What are angular modules

what is RxJx

What are components

Differnce between constructor and ngOnit intialization


What is angular service

Angular Forms:

What is promise

Observables vs Promise

What is multicasting observables

what are utility functions provided by RxJS:

What are matchers in Jasmine


headless browser

what is protractor

What is Typescript
What is Angular Routing:

What are angular directives

Difference between Component and directive

What is angular http

Angular pipes

Pure pipe vs Impure Pipe:

What is angular template


what are different types of data bindings in angular

Interpolation binding

Property binding

When to use Interpolation and when to use property binding

Event binding in angular

Two way binding

Two way binding program


Answers

Typescript based open source web application framework and has feature likes dependency injection, end to end
tooling, declarative templates
Angular application is made of Component, Modules, templates, services
Angular has inbuild support for routing and unit testing.
Package.json - manages the dependenices in the project ( dependencies like "jasmine-core":
"@angular/core": "@angular/forms": "@angular/common": "@angular/router":
Tsconfig - manages typescript configuration
UI component library ( helps in creating consistent, attractive and full functional web pages)

Command line interface to scaffhold and build angular apps


Server side rendering module
New rendering engine for Angular
Build tool to keep track of dependencies between different packages and build targets
Ng serve -port=7899
Jasmine - unit testing ( supports BDD and does not require a DOM) and protractor - end to end scripts
Karma - is test runner and execution framework ( for running tests on broswers,
ng test for unit testing, Ng e2e for end to end tests

unit tests are placed under src -> app folder ( spec.ts files) , end to end tests are placed under e2e folder
Lazy loading allows Angular to load components and modules as and when they're needed. Implemented by using
angular routing and module declarations
Ng lint command will find syntax issue with typescript and if code is implemented correctly
First inject service as dependency in component ( in constructor of component class), then you can use method in
component templates
avoid un necessary imports, lazy loading, 3rd party libry if not used then remove from applicatoin,
angular dependency for encapsulating and intercepting asynchronus activities in browser

Modules are logical boundries in application; Angular application is divided into separate modules to separate the
functionality of application
NgModule decorator denotes a module and has three otions, 1. imports ( for importing dependent modules) 2.
Declartions ( used to define components in that module). 3. Bootstrap option
Default module bundler is webpack
Ng module class describes how the applicatoin parts fit togethers
creatin new module - Ng g m module_name
To make a component available for import outside the module, include it under exports array

RxJs is a library for composing asynchronus and callback based code using observables
Many API like HttpClient produce and consume RxJS Observable
e.g import {Observalbe, throwerros} from 'rxjs'
Subscribing: Observable instance begins publishing values only when someone subscribes to it.

Components:
Components are building blocks of angular application. For e.g. for ecommerce site, Navbar could be a component,
Cart could be a separate module
structure of component:
1. Selector : define name of HTML element which our compoenent will live in
2. template: defines view for component and allows us to tie logic from compoenent to view
3. Styles: styles for specific component
for creating component : ng g c
Every angular application has at least one component e.g app.component
Angular component lifecycle: ( ngOnit, ngOnChanges, ngDoCheck, ngOnDestroy,)
Typescript classes had default method called construcotr for initialization purpose ( where you could initialize
service instace), ngOnit is specific to angular and define bindings of service methods e.g getEmployees()
Service is typically a class with a narrow, well-defined purpose such as fetching data from the server, validating
user input, or logging directly to the console. You inject service into components and bind service methods in
component template to fetch data from server.
service should be registered as a provider in Ngmodule
Angular provides forms module to capture user input events from the view, validate the user input in Reactive
template driven way

A promise is a JavaScript object that may produce a value at some point in time. A promise may be in one of 4
possible states: fulfilled, rejected, pending or settled.

observable: computation does not start until subscription


Promise: execute immediately on creation
Observable: provide multiple values over time
Promise: Provide only one value
Observable: Subscription method is used for error hadling
promise: Push errors to the child promises
Multicasting is the practice of broadcasting to a list of multiple subscribers in a single execution. With a multicasting
observable, you don't register multiple listeners on the document, but instead re-use the first listener and send
values out to each subscriber.

Iterating through the value in a straem


Mapping values to different types
Filtering streams
Composing multiple streams
Matchers in Jasmine: toBeArray(), toBeArrayOfBooleans(),toBeFalse(),
toBeOddNumber(), toBeEmptyObject()
browser without any kind of graphical user interface

Protractor - end to end test framework for antular and Angular JS


To run protractor, we need to have Selenium webdriver and node js
Protractos is wrapper around Webdriver JS and supports BDD and works in conjuction with sellenium
In conf file of protractor, you set up sellenium server, define which browser to use and which testing framework to
use.
To exclude a spec file in protractor: add them in exclude tag of conf.js file
Protractor support Jasmine, mocha
Mocha: Javascript framework for node.js programs, featuring browswer support asynchronus testing, test coverage
reports
super set of Jaavascript developed by microsoft
strongly typed, object oriented, compiled laguage
During build, typescript is transpled into equivalent javascript code
Routing in Angular helps us navigate from one view to another as users perform tasks in web apps.
RouterMoudule and Routes needs to be imported in routing module/app module and routes needs to be definedd

<base href="/">
RouterOutlet directive acts like a placeholder that indicates spot in the template where router should diplay the
components. You can have multiple router outlest

routerLink directive which replaces the href attribute in the <a> tags to create links and routerLinkActive for
marking the active link.

Activated routed: contains information about a route associated with componenet loaded in outlet
the activated route will be injected as router service to access the information

Wild card routes : when no route matches

Angular Directives add behavior to an existing DOM element. Below are some of the angular directives
Attribute directives
Ngclass- You can add or remove multiple CSS classes simultaneously with ngClass
Ngmodel- You can use the NgModel directive to display a data property and update that property when the user
makes changes.
Structural directives:
NgIf—conditionally creates or disposes of subviews from the template.
NgFor—repeat a node for each item in a list.
NgSwitch—a set of directives that switch among alternative views.

Difference between Component and directive:

Components are used to create UI widgets; Directives use to add behavior to existing DOM element
components are used to break up application into smaller components; Directive are used to design reusable
components

helps in making calls to backend api's over http proctocol


- provides typed request and response objects
- intercepts request and response
- supports observables API
- supports streamlined error handling
Using http:
- import httpclientmodule into root module
- inject as dependecny into service, then define a method in service for accessing data over api
- then inject the service as dependecy into component and invoke the service methods

It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and
display the same in the browser.
E.g {{ Welcome to Angular 4 | lowercase}} --- this converts Welcome to Angular 4 to lowercase
Custom pipe can be created using @Pipe decorator

Pure pipe : A pure pipe is called only when angular detects a change in value
Impure pipe: called no matter if value changes or not
An Angular HTML template renders a view, or user interface, in the browser,
One-way Data Binding. 1.Interpolation 2.Property Binding 3. Event Binding
Two-way Data Binding
Interpolation binding is used to return HTML output from TypeScript code i.e. from the components to the views.
Here, the template expression is specified within double curly braces.
In Property binding, value flows from a component’s property into the target elements property.
In the above example, the src property of the image element is bound to a component’s image property.
when you need to set element properties to non-string data values, you must use Property binding and not
Interpolation.
In Angular 8, event binding is used to handle the events raised by the user actions like button click, mouse
movement, keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls the
specified method in the particular component.
In two-way databinding, automatic synchronization of data happens between the Model and the View. Here,
change is reflected in both components. Whenever you make changes in the Model, it will be reflected in the View
and when you make changes in View, it will be reflected in Model.
var promise = new Promise((resolve, reject) => {
resolve("Promise Resolved");
})

promise.then((success) => {
console.log(success);
})
.catch(function(error) => {
console.log(error);
});
Custom Pipe:
import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
name : 'sqrt'
})
export class SqrtPipe implements PipeTransform {
transform(val : number) : number {
return Math.sqrt(val);
}
}

You might also like