? Technical Interview Notes! ?
? Technical Interview Notes! ?
1
▪ Native Method Interface (JNI) → Interacts with native code (C/C++)
o Architecture:
1. Class
Definition: A blueprint or template for creating objects. It defines properties
(variables) and behaviors (methods).
Syntax:
class Car { // Class definition
String color; // Property
int speed; // Property
Real-Time Example:
Think of a "Car" class. It defines the general features of all cars, like color,
speed, and the ability to drive.
How to Achieve:
o Use the class keyword to define a class.
o Define properties (fields) and behaviors (methods) inside the class.
2. Object
Syntax:
2
myCar.speed = 120; // Assigning property
myCar.drive(); // Calling method
}
}
Real-Time Example:
If "Car" is the class, then "myCar" is an object. It’s a specific car with
properties like "Red" color and speed "120 km/h".
How to Achieve:
o Create objects using the new keyword.
o Access properties and methods using the dot (.) operator.
1. Encapsulation
• Definition: Binding data (variables) and methods together, restricting direct access to data
for security.
• How to Achieve:
o Declare variables as private.
o Provide getter and setter methods to access and modify the data.
• Syntax:
class Person {
private String name; // Encapsulated field
• Real-Time Example:
In banking apps, your account balance is private. You can check or update it only through
secure methods (getters/setters).
2. Abstraction
• Definition: Hiding complex implementation details and showing only the essential features
to the user.
• How to Achieve:
o Use abstract classes and interfaces.
o Define abstract methods that subclasses must implement.
• Syntax:
abstract class Vehicle {
abstract void start(); // Abstract method
}
3
• Real-Time Example:
A car driver uses the steering wheel without knowing the internal mechanism of how it
works.
3. Inheritance
• Definition: The process where one class inherits properties and methods from another class,
promoting code reusability.
• Types of Inheritance:
o Single Inheritance: One class inherits from another.
o Multilevel Inheritance: A class inherits from a derived class.
o Hierarchical Inheritance: Multiple classes inherit from one base class.
(Note: Java doesn’t support multiple inheritance with classes but supports it with
interfaces.)
• How to Achieve:
o Use the extends keyword for classes.
o Use the implements keyword for interfaces.
• Syntax:
class Vehicle {
void run() {
System.out.println("Vehicle is running");
}
}
• Real-Time Example:
A "Car" class can inherit common properties from a "Vehicle" class.
4. Polymorphism
• Definition: The ability of a method to perform different tasks based on the context,
promoting flexibility in code.
• Types of Polymorphism:
o Compile-time (Static) Polymorphism: Achieved through method overloading (same
method name, different parameters).
o Run-time (Dynamic) Polymorphism: Achieved through method overriding (subclass
provides its own implementation of a superclass method).
• How to Achieve:
o Method Overloading: Define multiple methods with the same name but different
parameters.
o Method Overriding: Override methods in child classes using @Override.
• Syntax:
// Compile-time Polymorphism (Method Overloading)
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) { // Overloaded method
return a + b + c;
}
}
4
void sound() {
System.out.println("Animal makes a sound");
}
}
5
• Purpose: Control the creation process of objects.
• Examples:
6
What Are SOLID Principles?
SOLID is an acronym for five design principles that help in building robust,
maintainable, and scalable software:
• More maintainable
• Easier to scale
• Less prone to bugs when adding new features
Java 21
Java 11 (2018) Java 17
Feature Java 8 (2014) (2023)
[LTS] (2021) [LTS]
[LTS]
Lambda Record
Pattern
Programming Expressions Patterns,
var in Lambda Matching
Style (functional String
(instanceof)
style) Templates
Unnamed
Collections Enhanced
Files.readString Classes,
& Data Streams API switch
() Simplified
Handling expressions
Code
Date & Time New Date & Time
— — —
API API (java.time)
Basic
New HTTP Client
HTTP Client HttpURLConnecti — —
API
on
isBlank(),
String
Basic String lines(), Text Blocks String
Enhancement
Methods strip(), (""") Templates
s
repeat()
Virtual
OOP Default &
Sealed Threads
Enhancement Static Methods —
Classes (Improved
s in Interfaces
Concurrency
7
Java 21
Java 11 (2018) Java 17
Feature Java 8 (2014) (2023)
[LTS] (2021) [LTS]
[LTS]
)
Null
Optional Class — — —
Handling
Strong
Encapsulatio Enhanced
Performance Improved Garbage
Standard GC n of Garbage
& Memory Collection
Internal Collection
APIs
Removed Java EE
Removed
— Modules (JAXB, — —
Features
JAX-WS)
Virtual
Standard Threads for
Concurrency — —
Threads Better
Performance
Summary:
Descriptio Real-Time
Concept Syntax/Example
n Example
Smallest Downloading
Thread t = new Thread();
Thread unit of a files while
t.start();
process. browsing.
Defines
task logic class Task implements Sending emails
Runnable
separately Runnable { public void run() in the
Interface
from {} } background.
thread.
8
Descriptio Real-Time
Concept Syntax/Example
n Example
run() runs
on the
current
start() is used
run() vs thread; thread.start(); // vs
for parallel
start() start() thread.run();
execution.
creates a
new
thread.
New →
Runnable Video buffering
Thread → Running with
Handled by JVM.
Lifecycle → Blocked pausing/resumin
→ g.
Terminated
Prevents
Bank
race
Synchronizati synchronized(obj) { // transactions to
conditions
on critical section } avoid double
in shared
deductions.
resources.
Circular
dependency
Traffic jam
causing
Deadlock Improper nested locks. without
threads to
signals.
block
forever.
Ensures
thread
Volatile volatile boolean flag = Real-time game
visibility
Keyword true; status flag.
of
variables.
Manages
ExecutorService ex = Handling API
Thread Pool threads
Executors.newFixedThreadPool requests
(Executor) efficientl
(5); simultaneously.
y.
Executes
Fetching stock
Callable & tasks and Future<Integer> result =
prices
Future returns executor.submit(task);
concurrently.
results.
Waits for Uploading files
Join one thread thread.join(); before sending
to finish. confirmation.
9
Descriptio Real-Time
Concept Syntax/Example
n Example
Pauses
execution Auto-logout
Sleep Thread.sleep(1000);
for a set timers.
time.
Descriptio
Concept Syntax/Example Real-Time Example
n
Converts
ObjectOutputStream oos
objects to Saving user
Serialization = new
byte sessions.
ObjectOutputStream();
stream.
Converts
byte ObjectInputStream ois =
Deserializati Restoring app data
stream new
on after restart.
back to ObjectInputStream();
object.
Prevents
fields Ignoring sensitive
Transient
from being transient int tempData; data like
Keyword
serialized passwords.
.
Mutable,
thread-
safe StringBuffer sb = new Logging in multi-
StringBuffer
string StringBuffer("Hello"); threaded apps.
operations
.
Mutable,
faster Building strings in
StringBuilder sb = new
StringBuilder (not single-threaded
StringBuilder("Hi");
thread- apps.
safe).
Once
Storing constant
Immutable created, String s = "Test";
values like config
Strings cannot be s.concat("123");
keys.
changed.
Mutable Can be List<String> list = new Modifying shopping
Objects changed ArrayList<>(); cart items.
10
Descriptio
Concept Syntax/Example Real-Time Example
n
after
creation.
Ensures
data
Bank money transfer
Transaction consistenc
@Transactional (Spring) (debit/credit both
Management y in DB
succeed or fail).
operations
.
Enables
Lambda functional Filtering data in
(a, b) -> a + b;
Expressions programmin collections.
g.
Interface
with a Runnable,
Functional
single @FunctionalInterface Comparator
Interface
abstract implementations.
method.
Handles
null Preventing
Optional Optional.ofNullable(val
values NullPointerExceptio
Class ue)
gracefully n.
.
Key Takeaways:
Descriptio
Concept Syntax/Example Real-Time Example
n
Cannot be
instantiat Defining common
Abstract abstract class Vehicle
ed, used properties of
Class { abstract void run(); }
as a base vehicles.
for other
11
Descriptio
Concept Syntax/Example Real-Time Example
n
classes.
Defines a
contract Payment gateways
interface Drivable { void
Interface with implementing
drive(); }
abstract Payable.
methods.
Performing
actions in Print functions
Polymorphi different Vehicle v = new Car(); handling
sm ways using v.run(); different data
the same types.
interface.
Binding
data and
methods User data
Encapsulat private int age; public
together, protection in
ion void setAge(int a)
hiding banking apps.
internal
details.
Acquiring
Employee class
Inheritanc properties
class Dog extends Animal {} inheriting Person
e of parent
details.
class.
Manages
runtime Handling invalid
Exception try { } catch (Exception e)
errors to user inputs in
Handling { } finally { }
prevent forms.
crashes.
Caught at
Checked File reading
compile- throws IOException
Exception errors.
time.
NullPointerExcept
Unchecked Occurs at
int a = 5 / 0; ion when
Exception runtime.
accessing null.
Allows
code
Type-safe
reusabilit List<String> list = new
Generics collections in
y with ArrayList<>();
data structures.
type
safety.
12
Descriptio
Concept Syntax/Example Real-Time Example
n
Provides
Collection data Storing items in
List<Integer> nums = new
s structures an e-commerce
ArrayList<>();
Framework like List, cart.
Set, Map.
HashMap
stores
key-value Employee IDs in
HashMap vs pairs; Map<Key, Value> vs HashSet, data
HashSet HashSet Set<Value> caching with
stores HashMap.
unique
values.
Sorting
objects
Comparable Sorting employee
naturally
vs compareTo() vs compare() data by name or
vs custom
Comparator salary.
sorting
logic.
Defines
Days of the week,
Enum fixed enum Day { MON, TUE, WED }
status codes.
constants.
Belongs to
Static the class, Common counter
static int count;
Keyword not for all objects.
instances.
Prevents
modificati
Final on Defining constant
final int x = 100;
Keyword (variables values like PI.
, methods,
classes).
Refers to Resolving
This the variable
this.name = name;
Keyword current shadowing in
object. constructors.
Calling parent
Refers to
Super class
the parent super(); or super.method()
Keyword constructor/metho
class.
d.
13
Descriptio
Concept Syntax/Example Real-Time Example
n
Checks
Instanceof object Type checking
if (obj instanceof String)
Operator type at before casting.
runtime.
Class
whose
objects final class Person
Immutable String class is
cannot be { private final String
Class immutable.
modified name; }
after
creation.
Inspects
classes,
Dynamic loading
Reflection methods, Class<?> cls =
of plugins or
API and fields Class.forName("ClassName");
modules.
at
runtime.
Provides
Marking
Annotation metadata @Override, @Deprecated,
deprecated
s about @FunctionalInterface
methods in APIs.
code.
Processes
list.stream().filter(e ->
Java collection
e > Filtering data in
Streams s in a
10).collect(Collectors.toLi large datasets.
(Java 8) functional
st());
style.
Handles
null
API responses to
values
Optional avoid
gracefully Optional.ofNullable(value)
(Java 8) NullPointerExcept
to prevent
ion.
exceptions
.
Improved
date-time
Date &
handling LocalDate.now(); Event scheduling
Time API
with LocalDate.of(2024, 2, 9); apps.
(Java 8)
LocalDate,
LocalTime.
Var Local Reducing
var name = "Shagun";
Keyword variable boilerplate code.
14
Descriptio
Concept Syntax/Example Real-Time Example
n
(Java 10) type
inference.
Immutable
data
Records classes record User(String name,
DTOs in APIs.
(Java 14) with less int age) {}
boilerplat
e.
Restricts
Sealed Modeling
class sealed class Shape permits
Classes restricted
inheritanc Circle, Square {}
(Java 15) hierarchies.
e.
Simplifies
Pattern type if (obj instanceof String Simplifying
Matching casting in s) conditional
(Java 16) conditions { System.out.println(s); } logic.
.
Key Takeaways:
15
Concept Description Example/Use Case
exceptions.
Called before
garbage
Releasing resources
finalize() Method collection for
(rarely used now).
cleanup
(deprecated).
Checked at
compile-time;
Checked Exceptions IOException, SQLException.
must be handled
with try-catch.
Runtime
exceptions; not NullPointerException,
Unchecked Exceptions required to be ArrayIndexOutOfBoundsExcep
caught tion.
explicitly.
Ensures
visibility of
Shared flags in multi-
volatile Keyword changes to
threaded apps.
variables across
threads.
Prevents variable Hiding passwords during
transient Keyword
serialization. serialization.
Controls thread
access to Thread-safe method
synchronized Keyword
critical implementation.
sections.
Asynchronous
Fetching data from APIs
Callable & Future programming with
concurrently.
results.
Enables
Lambda Expressions (Java list.forEach(e ->
functional
8) System.out.println(e));
programming.
Interface with a
@FunctionalInterface for
Functional Interfaces single abstract
lambda usage.
method.
Shorthand for
Method References (Java
lambda System.out::println
8)
expressions.
Functional
Predicate, Consumer, Filtering with
interfaces for
Supplier Predicate<Employee>.
data processing.
16
Concept Description Example/Use Case
Convert objects
Serialization/Deserializ Saving user sessions or
to byte streams
ation data transfer.
and vice versa.
Heap, Stack, Optimizing JVM
JVM Memory Model
Metaspace, etc. performance.
Automatic memory
JVM tuning for large-scale
Garbage Collection (GC) management in
apps.
JVM.
Manage memory
Soft, Weak, Phantom efficiently with
Caching mechanisms.
References different
reference types.
Dynamic Binding (Late Method resolution Overridden methods in
Binding) at runtime. polymorphism.
Static Binding (Early Method resolution
Method overloading.
Binding) at compile-time.
Debugging tool to assert age > 18; for
Assertions
test assumptions. validation.
Optimizes
bytecode at Performance improvement in
JIT Compiler
runtime for JVM.
faster execution.
Ensures data
Transaction Management consistency @Transactional for atomic
(Spring) during DB DB transactions.
operations.
Manages object
Dependency Injection
dependencies @Autowired in Spring Boot.
(DI)
automatically.
Creation,
initialization, Using @PostConstruct,
Bean Lifecycle (Spring)
destruction of @PreDestroy.
beans.
Separates cross-
AOP (Aspect-Oriented cutting concerns @Aspect for logging API
Programming) like logging and requests.
security.
17
Java Concepts: Stream API, Collections, Garbage
Collection
Aspect Details
Process collections of data in a functional way
Purpose
(filtering, mapping, sorting).
Basic list.stream().filter(e -> e >
Syntax 10).collect(Collectors.toList());
Filtering employees with salary >
Real-Time
50,000:employees.stream().filter(emp -> emp.getSalary() >
Example
50000).collect(Collectors.toList());
Key
filter(), map(), sorted(), collect(), forEach(), reduce()
Operations
2. Collections Framework
18
Collection Implementation Key Differences
Deque priority.Deque: Double-ended queue,
allows insertion/removal from both ends.
HashMap: Unordered, fast
HashMap vs
performance.TreeMap: Sorted by
Map TreeMap vs
keys.LinkedHashMap: Maintains insertion
LinkedHashMap
order.
Aspect Details
Purpose Automatic memory management in JVM.
Why We Use Prevents memory leaks, improves performance by freeing
It? unused objects.
When It Triggered automatically when JVM detects low memory or
Happens? manually using System.gc().
Serial GC (Simple, single-threaded) Parallel GC
Types of (Multi-threaded, for high performance) CMS (Concurrent
GC Mark-Sweep) (Low-latency apps) G1 GC (Optimized for
large heaps, Java 9+)
Real-Time In large-scale web applications to handle session data and
Example temporary objects efficiently.
Real-Time
Concept Description Basic Syntax (if applicable)
Example
Inspect or Frameworks
modify like
Class<?> clazz =
runtime Hibernate,
Reflection Class.forName("com.example.MyCla
behavior of Spring
API ss");Method method =
classes, (dynamic
clazz.getMethod("methodName");
methods, object
and fields. creation).
Modularize
Enterprise
large
Java application
application module com.example.app
Modules s with
s for { requires java.base; }
(Java 9+) independent
better
modules.
maintainabi
19
Real-Time
Concept Description Basic Syntax (if applicable)
Example
lity and
performance
.
Manage
Thread
complex
coordinatio
multithread CountDownLatch latch = new
Concurrency n in
ing tasks CountDownLatch(1);latch.await();
Utilities banking
with latch.countDown();
transaction
synchroniza
s.
tion tools.
Handle
Real-time
asynchronou
application
Reactive s data Mono<String> mono =
s like chat
Programming streams Mono.just("Hello");mono.subscrib
apps or
(WebFlux) with non- e(System.out::println);
stock
blocking
monitoring.
behavior.
Avoid
NullPointer Handling
Optional Optional<String> opt =
Exception optional
Class (Java Optional.ofNullable(null);opt.or
by handling user data
8) Else("Default Value");
null values in APIs.
gracefully.
Class whose
objects String
Immutable cannot be class in final class Employee { private
Classes modified Java is final String name; }
after immutable.
creation.
Automatic
conversion Simplifies
between collection
Autoboxing/ List<Integer> list =
primitive operations
Unboxing Arrays.asList(1, 2, 3);
types and with
wrapper primitives.
classes.
Shorter Stream
List<String> names =
syntax for operations
Method List.of("A",
calling like
References "B");names.forEach(System.out::p
methods in sorting or
rintln);
lambda filtering.
20
Real-Time
Concept Description Basic Syntax (if applicable)
Example
expressions
.
Metadata
that @Override
provides in method
@Override public String
Annotations information overriding,
toString() { return "Example"; }
to the @Autowired
compiler or in Spring.
runtime.
Interfaces
with a
single Java 8
Functional abstract Streams, @FunctionalInterface interface
Interfaces method used event MyFunc { void execute(); }
for lambda listeners.
expressions
.
Collections
Provides a that
way to use require
Wrapper Integer num =
primitive objects
Classes Integer.valueOf(5);
data types (e.g.,
as objects. ArrayList<I
nteger>).
Describes
how threads
Memory
interact
management
Java Memory through No specific syntax (conceptual
in high-
Model memory understanding)
concurrency
(Heap,
apps.
Stack,
Metaspace).
Built-in
Filtering
Predicate & functional Predicate<Integer> isPositive =
employee
Consumer interfaces num -> num > 0;Consumer<String>
data in
(Java 8) used with printer = System.out::println;
APIs.
Streams.
Converting
Implicit: int a = 10; double b =
one data Implicit:
Typecasting a;Explicit: double d = 9.7; int
type into int to
i = (int) d;
another. double in
21
Real-Time
Concept Description Basic Syntax (if applicable)
Example
Two types: calculation
Implicit s.
(Widening) Explicit:
- Auto Casting
conversion double to
(smaller to int in
larger). finance
Explicit apps.
(Narrowing)
- Manual
conversion
(larger to
smaller).
22
Definition:
Dependency Injection (DI) is a design pattern where the Spring container
automatically injects dependencies into objects, reducing tight coupling and
improving code manageability.
1. Constructor Injection:
Example:
Setter Injection:
Example:
Field Injection:
Example:
@Autowired
private Repository repo;
23
• Field Injection reduces boilerplate code but is harder to test (not recommended for complex
applications).
A principle where the control of object creation and lifecycle is handled by the Spring
container.
1. Model: Represents the data and business logic (e.g., database operations).
2. View: The user interface (e.g., HTML, JSP).
3. Controller: Handles user requests, processes data via the Model, and returns the
View.
1. Client Request →
2. DispatcherServlet (Front Controller) →
3. Controller (Handles logic) →
4. Service Layer (Business logic) →
5. DAO/Repository (Database interaction) →
6. Model (Data) →
7. View Resolver (Determines UI) →
8. Response to Client
Spring Boot
24
Spring Framework vs Spring Boot
1. Internal Architecture:
2. External Architecture:
25
• Controller Layer: Manages HTTP requests with @RestController and
@RequestMapping.
• Service Layer: Business logic using @Service.
• Repository Layer: Database operations using @Repository (JPA, CRUD).
• Database Layer: SQL (MySQL, PostgreSQL) or NoSQL (MongoDB).
1. Core Annotations:
• @Aspect: Defines a class as an aspect for cross-cutting concerns (e.g., logging, security).
• @Before, @After, @Around: Apply actions before, after, or around method execution in
AOP.
• @EnableAspectJAutoProxy: Enables support for handling components marked with
@Aspect.
26
5. Scheduling & Async Annotations:
8. Transaction Management:
27
You can create custom annotations using @interface. Example:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {}
1. application.properties
• Purpose: Defines key-value pairs for application configuration (e.g., server port, database
URL).
• Example:
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/db
logging.level.org.springframework=DEBUG
2. application.yml (YAML)
server:
port: 8082
spring:
datasource:
url: jdbc:mysql://localhost:3306/db
username: user
password: pass
3. bootstrap.properties / bootstrap.yml
• Purpose: Used in Spring Cloud applications for externalized configuration (e.g., connecting to
Config Server).
• Example:
spring.application.name=config-client
spring.cloud.config.uri=http://localhost:8888
4. application-{profile}.properties / .yml
# application-dev.properties
server.port=8083
spring.datasource.username=dev_user
28
5. @Value Annotation
@Value("${server.port}")
private int port;
6. @ConfigurationProperties
• Purpose: Binds external configuration properties to Java objects for easy access.
• Example:
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private String name;
private String version;
}
7. Command-Line Arguments
8. Environment Variables
export SPRING_DATASOURCE_PASSWORD=secret
• Purpose: Legacy support; rarely used as Spring Boot favors annotations and properties.
• Example:
o HTTP: 80
o HTTPS: 443
o MySQL: 3306
29
o PostgreSQL: 5432
o MongoDB: 27017
o Spring Boot (Default): 8080
Localhost URLs:
o HTTP: http://localhost:8080
o HTTPS: https://localhost:8443
o Custom Port Example: http://localhost:3000 (React app),
http://localhost:4200 (Angular app)
Microservices:
An architectural style where applications are built as a collection of small,
loosely coupled, independent services.
o Scalability
o Flexibility in technology stack
o Faster development & deployment
o Improved fault isolation
o Easy maintenance
Microservice Architecture:
30
Microservice Design Patterns:
o API Gateway: Acts as a single entry point for all client requests, handling routing,
authentication, and rate limiting.
o Database per Service: Each microservice manages its own database, ensuring data
isolation and flexibility.
o Circuit Breaker: Prevents cascading failures by stopping calls to a failing service after
repeated failures.
o Service Discovery: Dynamically registers and discovers services, enabling scalability
(e.g., Eureka).
o Saga Pattern: Manages distributed transactions across multiple services to maintain
data consistency.
REST vs SOAP:
RESTful Principles:
31
Real-Time Example:
Employee Management System:
Basic Syntax:
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
@GetMapping
public List<Employee> getAllEmployees() {
return employeeService.getAll();
}
@PostMapping
public Employee createEmployee(@RequestBody Employee emp)
{
return employeeService.save(emp);
}
@PutMapping("/{id}")
public Employee updateEmployee(@PathVariable Long id,
@RequestBody Employee emp) {
return employeeService.update(id, emp);
}
@DeleteMapping("/{id}")
public void deleteEmployee(@PathVariable Long id) {
employeeService.delete(id);
}
}
SQL Concepts -
32
Concept Description Example Basic Syntax
Returns all rows List all SELECT * FROM emp
from the left employees LEFT JOIN proj ON
LEFT JOIN
table, even if with/without emp.id =
there's no match. projects. proj.emp_id;
Returns all rows List all SELECT * FROM emp
from the right projects RIGHT JOIN proj ON
RIGHT JOIN
table, even if with/without emp.id =
there's no match. employees. proj.emp_id;
Returns all rows SELECT * FROM emp
Combine
when there's a FULL JOIN proj ON
FULL JOIN employee and
match in one of the emp.id =
project data.
tables. proj.emp_id;
Combines result
List cities SELECT city FROM A
sets of two
UNION from two UNION SELECT city
queries, removing
tables. FROM B;
duplicates.
Combines result List all cities SELECT city FROM A
UNION ALL sets, including from two UNION ALL SELECT
duplicates. tables. city FROM B;
Groups rows sharing
Count employees SELECT dept,
the same values for
GROUP BY in each COUNT(*) FROM emp
aggregate
department. GROUP BY dept;
functions.
SELECT dept,
Filters groups
Departments COUNT(*) FROM emp
based on conditions
HAVING with more than GROUP BY dept
(used with GROUP
5 employees. HAVING COUNT(*) >
BY).
5;
SELECT * FROM emp
Employees with WHERE salary =
Query within
Subquery the highest (SELECT
another query.
salary. MAX(salary) FROM
emp);
Perform SELECT name,
calculations across salary, RANK()
Window Rank employees
a set of table rows OVER (ORDER BY
Functions by salary.
related to the salary DESC) FROM
current row. emp;
Speeds up data CREATE INDEX
Index on
Indexing retrieval in large idx_emp_id ON
employee ID.
tables. emp(id);
33
Concept Description Example Basic Syntax
Splitting
Organizing data to employee and
Normalization -
reduce redundancy. department
tables.
Merging
Combining tables to
employee and
Denormalization improve read -
department
performance.
tables.
Rules to maintain ALTER TABLE emp
Unique
data integrity ADD CONSTRAINT
Constraints constraint on
(e.g., PRIMARY KEY, unique_email
email.
UNIQUE). UNIQUE (email);
Ensures a set of
SQL operations are Bank transfer
BEGIN; UPDATE A;
Transactions completed between
UPDATE B; COMMIT;
successfully accounts.
together.
MongoDB Concepts -
34
Concept Description Example Basic Syntax
(WHERE) conditions in HR
to queries.
Modify
Update age db.employees.updateOne({ name:
Update existing
for John "John" }, { $set: { age: 35 } })
documents.
Remove
Delete
documents db.employees.deleteOne({ name:
Delete employee
from a "Anna" })
named Anna
collection.
Process
Total
data with db.employees.aggregate([{ $group:
salaries
Aggregation operations { _id: "$dept", totalSalary:
per
like sum, { $sum: "$salary" } } }])
department
avg.
Improve
query Index on db.employees.createIndex({ name:
Indexing
performance name 1 })
.
Select
specific
Get only db.employees.find({}, { name: 1,
Projection fields to
names _id: 0 })
return in
query.
Sort
Sort by db.employees.find().sort({ age:
Sorting documents
age 1 })
by a field.
Restrict
the number
Limit to 5
Limit of db.employees.find().limit(5)
employees
documents
returned.
Skip
specific Skip first
Skip number of 5 db.employees.find().skip(5)
documents employees
in results.
Perform Join db.employees.aggregate([{ $lookup
joins employees : { from: "departments",
Joins
between with localField: "deptId",
(Lookup)
collections department foreignField: "_id", as:
. s "deptInfo" } }])
35
Concept Description Example Basic Syntax
Distribute Shard data
Partitionin data across for large
sh.enableSharding("myDatabase")
g multiple collection
servers. s
Ensure Update
Transaction atomicity salary and
session.startTransaction()
s of multiple log
operations. together
db.createCollection("employees",
Enforce
Validate { validator: { $jsonSchema:
Schema data
age as a { bsonType: "object", required:
Validation structure
number ["name", "age"], properties:
rules.
{ age: { bsonType: "int" } } } })
36
Concept Description Example / Syntax
multiple tables. A.id = B.id;
Divides data for CREATE TABLE emp PARTITION
Partitioning
performance. BY RANGE (emp_id);
CREATE INDEX idx_name ON
Indexes Speeds up data retrieval.
employees(name);
CREATE VIEW emp_view AS
Virtual table based on
Views SELECT name FROM
SELECT queries.
employees;
Executes actions CREATE TRIGGER trg AFTER
Triggers automatically on data INSERT ON employees FOR
changes. EACH ROW ...
Stored Encapsulates business CREATE PROCEDURE
Procedure logic for reuse. proc_name() BEGIN ... END;
CREATE FUNCTION
Returns a value after
Functions func_name() RETURNS INT
performing operations.
BEGIN ... END;
Ensures data integrity
Transactions BEGIN; UPDATE ...; COMMIT;
(ACID properties).
BACKUP DATABASE mydb TO
Backup/Restore Data protection mechanism.
'/backup/path';
Rules to enforce data
Constraints CHECK (salary > 0)
integrity.
WITH temp AS (SELECT *
Creates temporary result
WITH Clause FROM employees) SELECT *
sets.
FROM temp;
Controls the number of SELECT * FROM employees
LIMIT/OFFSET
records fetched. FETCH FIRST 10 ROWS ONLY;
Controls concurrent access LOCK TABLE employees IN
Locking
to data. EXCLUSIVE MODE;
37
• git branch - List all branches.
• git branch <branch_name> - Create a new branch.
• git checkout <branch_name> - Switch to a specific branch.
• git merge <branch_name> - Merge changes from one branch to another.
• git log - View the commit history.
• git diff - Show changes between commits, branches, or working directory.
• git reset --hard <commit_id> - Reset to a specific commit (destructive).
• git revert <commit_id> - Revert changes from a specific commit (non-destructive).
• git stash - Temporarily save changes without committing.
• git stash apply - Reapply stashed changes.
• git remote -v - List remote repositories.
Angular Concepts
Components:
The core building blocks of Angular applications. They define the UI using
HTML, CSS, and TypeScript. Each component consists of:
38
o Class: Contains logic (TypeScript).
o Styles: Manages CSS for the component.
Example: @Component({ selector: 'app-header', templateUrl:
'./header.component.html' })
Modules (@NgModule):
Organize an Angular app into cohesive blocks. Every Angular app has a root
module (AppModule), and you can create feature modules for better
modularity.
Example: imports: [BrowserModule, AppRoutingModule]
Data Binding:
Connects the UI (template) with the component’s data.
o Interpolation: {{ title }}
o Property Binding: [src]="imageUrl"
o Event Binding: (click)="handleClick()"
o Two-way Binding: [(ngModel)]="username"
Directives:
Modify the DOM's structure or appearance.
Routing:
Enables navigation between different views/pages. Defined in app-
routing.module.ts.
Example:
39
HTTPClient:
Used for making API requests (GET, POST, PUT, DELETE).
Example:
this.http.get('https://api.example.com/data').subscribe(respons
e => console.log(response));
Lifecycle Hooks:
Control component behavior during its lifecycle.
o ngOnInit: Called once after the component is initialized (used for API calls, data
fetching).
o ngOnChanges: Called when input properties change.
o ngOnDestroy: Clean up resources before the component is destroyed
(unsubscribe from observables).
Example:
Pipes:
Transform data in templates.
Guards:
Protect routes from unauthorized access. Types include CanActivate,
CanDeactivate.
Example:
40
canActivate(): boolean { return isLoggedIn; }
Interceptors:
Modify HTTP requests globally (add auth tokens, handle errors).
Example:
Lazy Loading:
Load modules only when needed to improve performance.
Example:
Resolvers:
Fetch data before navigating to a route.
Example:
Standalone Components:
Angular 14+ feature allowing components without modules.
Example:
<ng-content></ng-content>
41
Custom Directives:
Create your own directives to manipulate the DOM.
Example:
42