Interview Questions
Interview Questions
Need of thread
Deserializatinon
Design pattern
autoscaling of microservices
can we achieve autoscaling using docker
microservices vs monolithic
stream method
method to convert list into MAP
what is method referencing
Recursion in java
Classloaders in java
Mocking rest template & repository ( which annotation)
Microservices communication
Transient in Java
how to restrict child class getting serialized when
parent class undergoes serialization
how is garbage collection done
Internal implementation of hashset
Enum in Java
Autoboxing in java
Comparable vs comparator
Singleton vs prototype
Finally in java
Implementing spring security
Assertions in JUNIT
Difference between spring and spring boot:
Junit annotations
IOC vs DI
Synchronized blocks
HashMAP vs Hashtable
Wrapper classes
Final keyword
Annotation @Scheduler
Annotation @Query
AOP
What is JPA
What is JPQL
What is spring.jpa.hibernate.ddl-auto=update
What is pojo
Feign client
Resilience 4J / Hystrix
Zuul API gateway vs Spring Cloud Gateway
Zipkin server
Rabbit MQ
What is SpringBoot
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.
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.
Constructor-based DI fixes the order in which the dependencies need to be injected. Setter
based DI does not offer this.
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.
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
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
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.
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
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
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
@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
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
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.
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
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
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.
shredding - db concept
Between and IN
Merge
Recursive stored proceducre
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
Transaction controls
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.
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
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
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
. ~/.nvm/nvm.sh
npm install
What is docker
Advantages of docker
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.
What is angular
what is RxJx
Angular Forms:
What is promise
Observables vs Promise
what is protractor
What is Typescript
What is Angular Routing:
Angular pipes
Interpolation binding
Property binding
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)
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.
<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
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.
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
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);
}
}