0% found this document useful (0 votes)
2 views

? Technical Interview Notes! ?

The document provides an overview of Java, its components (JDK, JRE, JVM), and fundamental concepts of Object-Oriented Programming (OOP) such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism. It also discusses design patterns in software development, SOLID principles for maintainable code, and key differences between Java versions 8, 11, 17, and 21. Additionally, it covers multithreading and core Java concepts with real-time examples.

Uploaded by

asjadzaki2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

? Technical Interview Notes! ?

The document provides an overview of Java, its components (JDK, JRE, JVM), and fundamental concepts of Object-Oriented Programming (OOP) such as classes, objects, encapsulation, abstraction, inheritance, and polymorphism. It also discusses design patterns in software development, SOLID principles for maintainable code, and key differences between Java versions 8, 11, 17, and 21. Additionally, it covers multithreading and core Java concepts with real-time examples.

Uploaded by

asjadzaki2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Credit: Prepared by: Shagun Gujarathi

⚫ What is Java? – A platform-independent, object-oriented programming language.


⚫ Why Java? – Simple, secure, robust, and platform-independent.
⚫ Predecessor of Java: – C++
⚫ Successor of Java: – Kotlin
⚫ Who discovered Java? – James Gosling
⚫ Year of discovery: – 1995

• JDK (Java Development Kit)


o Definition: A software development kit used to write, compile, and run Java
programs.
o Consists of:
▪ JRE (Java Runtime Environment)
▪ Development Tools: javac (compiler), java (launcher), debugger, etc.
▪ Java APIs and Libraries
o Architecture:

▪ Development Tools → Used to write & compile code


▪ JRE → Provides the environment to run compiled code
▪ Java APIs → Provide pre-defined functions
o Real-Time Example:
When a developer writes and compiles Java code in an IDE like IntelliJ or Eclipse, the
JDK is required to develop and run the program.

• JRE (Java Runtime Environment)


o Definition: Provides the runtime environment needed to run Java applications.
o Consists of:

▪ JVM (Java Virtual Machine)


▪ Core Libraries (Java Class Libraries)
▪ Runtime Libraries
o Architecture:

▪ Class Loader → Loads .class files


▪ JVM → Executes bytecode
▪ Libraries → Support runtime functionalities
o Real-Time Example:
When you install and run a Java-based app like Minecraft, the JRE ensures it works
smoothly on your device.

• JVM (Java Virtual Machine)


o Definition: The engine that executes Java bytecode, making Java platform-
independent.
o Consists of:

▪ Class Loader Subsystem → Loads class files


▪ Runtime Data Areas → Stack, Heap, Method Area
▪ Execution Engine → Executes bytecode

1
▪ Native Method Interface (JNI) → Interacts with native code (C/C++)
o Architecture:

▪ Class Loader → Runtime Data Areas → Execution Engine → Native Interface


▪ Converts bytecode → Machine code → Executes
o Real-Time Example:
When you click "Run" on a Java program, the JVM takes the compiled bytecode and
executes it on your machine, whether it's Windows, Linux, or macOS.

• Simple Analogy (Book Example):


o JDK: Like an author’s toolkit (pen, paper, dictionary) to write and publish a book
(develop code).
o JRE: Like a reader’s kit (just the book and reading glasses) to read the book (run
code).
o JVM: Like a translator who translates the book into a language the reader
understands (convert bytecode to machine code).

Class, Object, and OOPs in Java

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

void drive() { // Method


System.out.println("Car is driving");
}
}

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

Definition: An instance of a class. It represents real-world entities with


specific values for properties.

Syntax:

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // Creating an object
myCar.color = "Red"; // Assigning property

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.

3. OOPs (Object-Oriented Programming) Concepts


• Definition: A programming paradigm based on the concept of objects. It helps in organizing
code for better reusability, scalability, and maintenance.

Key Principles of OOP (4 Pillars):

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

public String getName() { return name; } // Getter


public void setName(String name) { this.name = name; } //
Setter
}

• 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
}

class Bike extends Vehicle {


void start() {
System.out.println("Bike starts with a key");
}
}

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");
}
}

class Car extends Vehicle { // Inheritance using 'extends'


void display() {
System.out.println("Car is displayed");
}
}

• 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;
}
}

// Run-time Polymorphism (Method Overriding)


class Animal {

4
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

• Real-Time Example:
o Overloading: A printer can print documents, images, PDFs using the same print()
method but with different data formats.
o Overriding: The sound() method behaves differently for Dog and Cat classes.

Summary of OOPs Concepts:


OOP Principle How to Achieve Real-Time Example
Private variables +
Encapsulation Bank account security
Getters/Setters
Abstraction Abstract classes, Interfaces Car steering system
extends (for classes), Car inherits features
Inheritance
implements (for interfaces) from Vehicle
Printer handling
Polymorphism Method Overloading & Overriding
different data formats

Design Patterns in Software Development

What Are Design Patterns?

• Design patterns are proven solutions to common software design problems.


• They provide best practices for writing clean, reusable, and maintainable code.
• Purpose: Improve code flexibility, scalability, and reduce redundancy.

Types of Design Patterns

• Creational Patterns: Deals with object creation.


• Structural Patterns: Focuses on object composition.
• Behavioral Patterns: Manages communication between objects.

1. Creational Design Patterns

5
• Purpose: Control the creation process of objects.
• Examples:

o Singleton Pattern: Ensures a class has only one instance.


▪ Real-Time Example: A logging service where only one instance logs
throughout the app.
o Factory Pattern: Creates objects without specifying the exact class.

▪ Real-Time Example: A payment gateway system deciding whether to


process a credit card or UPI payment dynamically.
o Builder Pattern: Builds complex objects step-by-step.
▪ Real-Time Example: Pizza order system where you select base, toppings,
and sauce separately.

2. Structural Design Patterns

• Purpose: Simplify the structure of code by organizing classes and objects.


• Examples:

o Adapter Pattern: Converts one interface into another for compatibility.


▪ Real-Time Example: Mobile charger adapter connecting incompatible
devices.
o Facade Pattern: Provides a simple interface to complex subsystems.

▪ Real-Time Example: A unified dashboard controlling different modules like


reports, users, and analytics.

3. Behavioral Design Patterns

• Purpose: Manage how objects interact and communicate.


• Examples:

o Strategy Pattern: Chooses an algorithm at runtime based on conditions.

▪ Real-Time Example: A navigation app selecting the fastest or shortest route


dynamically.
o Observer Pattern: Notifies multiple objects when a state changes.

▪ Real-Time Example: YouTube notifications alerting subscribers when a new


video is uploaded.

SOLID Principles in the Project

6
What Are SOLID Principles?

SOLID is an acronym for five design principles that help in building robust,
maintainable, and scalable software:

• S - Single Responsibility Principle (SRP)


• O - Open/Closed Principle (OCP)
• L - Liskov Substitution Principle (LSP)
• I - Interface Segregation Principle (ISP)
• D - Dependency Inversion Principle (DIP)

By following SOLID principles, the project became:

• More maintainable
• Easier to scale
• Less prone to bugs when adding new features

Java 8 vs Java 11 vs Java 17 vs Java 21 (Key Differences)

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:

• Java 8: Functional programming (Lambda, Streams).


• Java 11: Better HTTP handling, String API improvements.
• Java 17: OOP enhancements with Sealed Classes, Pattern Matching.
• Java 21: Focus on concurrency (Virtual Threads), cleaner syntax.

Here's an expanded Multithreading & Core Java Concepts Summary with


additional topics, keeping it concise and Word-friendly:

Multithreading & Core Java Concepts

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.

Core Java Concepts

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:

• Multithreading: Boosts performance with parallel task execution.


• Synchronization & Volatile: Manage data consistency in concurrent environments.
• Core Java: Serialization, String handling, and transaction management ensure robust
applications.

Advanced Java Concepts

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:

• OOP Concepts: Drive reusability, modularity, and scalability.


• Advanced Features: Streams, Optionals, and Reflection improve modern Java development.
• Best Practices: Encapsulation, immutability, and annotations ensure clean, maintainable
code.

Comprehensive Java Concepts Summary

Concept Description Example/Use Case


== compares
references, .equa str1.equals(str2) for
== vs .equals()
ls() compares string content check.
values.
Prevents
modification of final int x = 10; (cannot
final Keyword
variables, reassign).
methods, classes.
Executes code
Closing DB connections in
finally Block after try-catch
finally.
regardless of

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

1. Stream API (Java 8)

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

Type Description Real-Time Example


Ordered, allows List<String> names = new ArrayList<>();
List
duplicates. (Employee Names)
Unordered, no Set<Integer> ids = new HashSet<>(); (Unique
Set
duplicates. IDs)
FIFO (First In, Queue<String> tasks = new LinkedList<>();
Queue
First Out). (Task Scheduling)
Map<Integer, String> empMap = new
Map Key-value pairs.
HashMap<>(); (Employee ID to Name)

3. Differences Between Collections

Collection Implementation Key Differences


ArrayList: Fast for random access, slow
ArrayList vs
List for insertion/deletion.LinkedList: Fast
LinkedList
insertion/deletion, slower random access.
HashSet: Unordered, faster (uses hash
HashSet vs
Set table).TreeSet: Sorted order, slower
TreeSet
(uses Red-Black tree).
Queue PriorityQueue vs PriorityQueue: Orders elements based on

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.

4. Garbage Collection (GC)

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.

Optional Additional Java Concepts

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).

Spring Framework Concepts

• Spring Framework: A lightweight, open-source framework for building enterprise Java


applications, providing support for dependency injection, transaction management, and
more.
• Dependency Injection (DI): Injects object dependencies automatically, reducing tight
coupling.
• Inversion of Control (IoC): The framework controls object creation and lifecycle instead of
the developer.
• Bean: An object managed by the Spring IoC container.
• ApplicationContext: Advanced IoC container for managing beans and resources.
• Spring MVC: A web framework following the Model-View-Controller pattern for creating web
applications.
• Service Layer: Contains business logic and communicates between controllers and
repositories.
• Repository Layer: Handles data access operations, usually with databases.
• Transaction Management: Ensures data consistency by managing database transactions.
• AOP (Aspect-Oriented Programming): Manages cross-cutting concerns like logging and
security.
• Event Handling: Enables communication between different parts of an application using
events.
• Caching: Improves performance by storing frequently accessed data temporarily.
• External Configuration: Manages app configurations through external files
(like .properties files).
• Profiles: Allows setting up different configurations for different environments (dev, test,
prod).

1. Dependency Injection (DI) in Spring

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.

Types of Dependency Injection

1. Constructor Injection:

Dependencies are provided through the class constructor.

Example:

public class Service {


private Repository repo;

public Service(Repository repo) { // Constructor


Injection
this.repo = repo;
}
}

Setter Injection:

Dependencies are injected via public setter methods.

Example:

public class Service {


private Repository repo;

public void setRepository(Repository repo) { //


Setter Injection
this.repo = repo;
}
}

Field Injection:

Dependencies are injected directly into class fields using @Autowired.

Example:

@Autowired
private Repository repo;

Key Points to Remember:

• Constructor Injection is preferred for mandatory dependencies (ensures immutability).


• Setter Injection is useful for optional dependencies.

23
• Field Injection reduces boilerplate code but is harder to test (not recommended for complex
applications).

2. Inversion of Control (IoC):

A principle where the control of object creation and lifecycle is handled by the Spring
container.

• Types of IoC Containers:


o BeanFactory: Basic IoC container, lazy initialization (creates beans only when
needed).
o ApplicationContext: Advanced container, eager initialization (creates beans at
startup) with extra features like event propagation, AOP support, etc.

3. MVC Architecture (Model-View-Controller):

A design pattern to separate application logic into three interconnected layers.

How MVC Works:

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.

Flow in Spring MVC:

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

• Spring Boot: A framework built on top of Spring to create stand-alone, production-ready


applications with minimal configuration.
• Why Use Spring Boot: Simplifies development with auto-configuration, embedded servers,
and easy dependency management.
• Predecessor: Spring Framework
• Successor: Latest version - Spring Boot 3.x with Spring Framework 6

24
Spring Framework vs Spring Boot

Aspect Spring Framework Spring Boot


A tool built on top of
A comprehensive framework
Definition Spring to simplify
for Java applications.
development.
Requires manual XML or Auto-configuration with
Configuration
Java-based configurations. minimal setup.
Embedded servers (Tomcat,
Requires external servers
Deployment Jetty) for easy
like Tomcat.
deployment.
Dependency Manual handling of Uses starter POMs for easy
Management dependencies. dependency management.
More boilerplate code and Reduces boilerplate code,
Complexity
setup required. faster development.
Suitable for complex, Best for microservices and
Use Case
enterprise applications. REST API development.

Spring Boot Components, Architecture, and Annotations

Spring Boot Components:

• Spring Boot Starter: Pre-configured dependencies for quick setup.


• Spring Boot Auto-Configuration: Automatically configures beans based on project
dependencies.
• Spring Boot CLI: Command-line tool for running and testing Spring Boot applications.
• Spring Boot Actuator: Provides production-ready features like monitoring and metrics.
• Spring Initializr: Web-based tool to generate Spring Boot project structures.

Spring Boot Architecture:

1. Internal Architecture:

• Core Container: Manages dependency injection via ApplicationContext.


• Auto-Configuration: Detects project setup and applies default configurations.
• Embedded Servers: Uses Tomcat, Jetty, or Undertow to run apps without external servers.
• Spring MVC: Handles HTTP requests/responses, RESTful APIs.
• Data Access Layer: Integrates with JPA, JDBC, MongoDB, etc.

2. External Architecture:

• Client Layer: User interface or API client (like Angular, Postman).

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).

Spring Boot Annotations

1. Core Annotations:

• @SpringBootApplication: Main entry point for Spring Boot apps (combines


@Configuration, @EnableAutoConfiguration, and @ComponentScan).
• @ComponentScan: Scans specified packages for Spring components.
• @Configuration: Marks a class as a source of bean definitions.
• @Bean: Defines a bean to be managed by the Spring container.
• @EnableAutoConfiguration: Enables automatic configuration based on dependencies in the
classpath.

2. RESTful API Annotations:

• @RestController: Simplifies creating RESTful web services (combines @Controller and


@ResponseBody).
• @GetMapping: Maps HTTP GET requests to specific handler methods.
• @PostMapping: Maps HTTP POST requests to specific handler methods.
• @PutMapping: Maps HTTP PUT requests (for updating resources).
• @PatchMapping: Maps HTTP PATCH requests (for partial updates).
• @DeleteMapping: Maps HTTP DELETE requests to handler methods.
• @RequestMapping: General-purpose annotation for mapping requests to handler methods.
• @RequestParam: Extracts query parameters from the URL.
• @PathVariable: Binds URI template variables to method parameters.
• @RequestBody: Maps the HTTP request body to a Java object.
• @ResponseBody: Converts Java objects to JSON/XML responses.
• @CrossOrigin: Enables Cross-Origin Resource Sharing (CORS) for REST APIs.
• @ResponseStatus: Customizes HTTP response status for exceptions or methods.

3. Dependency Injection & Bean Scope:

• @Autowired: Automatically injects dependencies.


• @Qualifier: Specifies which bean to inject when multiple beans of the same type exist.
• @Value: Injects values from properties files.
• @Scope: Defines the scope of a bean (singleton, prototype, etc.).
• @Lazy: Delays bean initialization until it's needed.

4. AOP (Aspect-Oriented Programming) 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:

• @Scheduled: Schedules tasks to run at fixed intervals.


• @EnableScheduling: Enables scheduled tasks in Spring Boot.
• @Async: Executes methods asynchronously.
• @EnableAsync: Enables asynchronous processing.

6. Validation Annotations (Hibernate Validator):

• @Valid / @Validated: Validates request bodies or objects in APIs.


• @NotNull, @Size, @Min, @Max, @Pattern: Used for input validation.

7. Spring Security Annotations:

• @EnableWebSecurity: Enables Spring Security in the project.


• @PreAuthorize, @PostAuthorize: Adds method-level security based on roles.
• @Secured: Restricts access based on roles.
• @RolesAllowed: Specifies allowed roles for a method or class.

8. Transaction Management:

• @Transactional: Manages transactions automatically (rollbacks, commits).

9. Profile & Configuration:

• @Profile: Specifies environment-specific beans (e.g., dev, test, prod).


• @PropertySource: Loads properties from an external .properties file.
• @EnableConfigurationProperties: Binds external configuration properties to Java objects.

10. Persistence Annotations (JPA):

• @Entity → Marks a class as a database entity.


• @Table → Specifies the table name in the database.
• @Id → Defines the primary key.
• @GeneratedValue → Auto-generates primary key values.
• @Column → Maps class fields to database columns.
• @Repository → Indicates a data access layer (DAO).

11. Error Handling:

• @ControllerAdvice: Global exception handling across all controllers.


• @ExceptionHandler: Handles exceptions locally within a specific controller.

12. Testing Annotations:

• @SpringBootTest → Used for integration testing.


• @MockBean → Creates mock objects for testing.

13. Custom Annotations:

27
You can create custom annotations using @interface. Example:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {}

Spring Boot Configuration Overview

Spring Boot provides flexible configuration options to manage application settings.


Here’s a summary:

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)

• Purpose: A hierarchical format for structured configuration, making it more readable


than .properties.
• Example:

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

• Purpose: Profile-specific configuration for different environments (dev, test, prod).


• Example:

# application-dev.properties
server.port=8083
spring.datasource.username=dev_user

28
5. @Value Annotation

• Purpose: Injects configuration values directly into Java classes.


• Example:

@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

• Purpose: Override configuration at runtime.


• Example:

java -jar app.jar --server.port=9090

8. Environment Variables

• Purpose: Configure sensitive data (like passwords) in production environments.


• Example:

export SPRING_DATASOURCE_PASSWORD=secret

9. XML Configuration (Rare in Spring Boot)

• Purpose: Legacy support; rarely used as Spring Boot favors annotations and properties.
• Example:

<bean id="myService" class="com.example.MyService"/>

10. External Configuration Files

• Purpose: Load configuration from files outside the packaged JAR.


• Example:

java -jar app.jar --spring.config.location=/path/to/config/

Common Port Numbers:

o HTTP: 80
o HTTPS: 443
o MySQL: 3306

29
o PostgreSQL: 5432
o MongoDB: 27017
o Spring Boot (Default): 8080

HTTP Status Codes:

o 200 OK: Request successful


o 201 Created: Resource successfully created
o 204 No Content: Request successful, no content to return.
o 400 Bad Request: Invalid request from client
o 401 Unauthorized: Authentication required
o 403 Forbidden: Access denied
o 404 Not Found: Resource not found
o 500 Internal Server Error: Server encountered an error
o 501 Not Implemented: Server doesn't support the request method.
o 502 Bad Gateway: Invalid response from the upstream server.
o 503 Service Unavailable: Server temporarily unavailable (overloaded or down).
o 504 Gateway Timeout: Server didn't get a timely response from another server.

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 - Key Concepts

Microservices:
An architectural style where applications are built as a collection of small,
loosely coupled, independent services.

Why We Use Microservices:

o Scalability
o Flexibility in technology stack
o Faster development & deployment
o Improved fault isolation
o Easy maintenance

Microservice Architecture:

o Description: Each service handles a specific business function and communicates


with other services via APIs (REST, gRPC, etc.).
o Key Components:
▪ Client: Sends requests to the application.
▪ API Gateway: Manages and routes requests to the correct microservice.
▪ Microservices: Independent units for specific functionalities.
▪ Database: Each service has its own database (Database per Service
pattern).
▪ Service Discovery: Helps locate other services dynamically.
▪ Load Balancer: Distributes traffic evenly among services.
▪ Monitoring & Logging: Tracks performance, errors, and activity logs.

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.

Basic Microservices Concepts:

o Service Registry & Discovery (e.g., Eureka): Maintains a registry of available


services for dynamic discovery.
o Load Balancing (e.g., Ribbon, Zuul): Distributes incoming traffic across multiple
service instances to optimize performance.
o Communication:
▪ REST: HTTP-based synchronous communication.
▪ gRPC: High-performance, contract-based communication.
▪ Messaging Queues (RabbitMQ, Kafka): Asynchronous communication for
event-driven architecture.
o Fault Tolerance (Hystrix, Resilience4j): Ensures system resilience by handling
failures gracefully.
o Containerization (Docker, Kubernetes): Deploys microservices in isolated
containers, simplifying scaling and management.
o Logging & Monitoring (ELK Stack, Prometheus, Grafana): Tracks logs, system
metrics, and application health for performance monitoring.

REST API Concepts

What is a REST API?


REST (Representational State Transfer) API allows communication between
client and server over HTTP by performing operations on resources using
standard HTTP methods.

REST vs SOAP:

1. REST: Lightweight, flexible, uses HTTP, supports JSON, XML, etc.


2. SOAP: Heavyweight, uses XML, has strict standards, better for enterprise-level
security.

RESTful Principles:

1. Statelessness: No client data is stored on the server between requests.


2. Statefulness: Server maintains the client state across multiple requests (less
common in REST, more in traditional systems).
3. Client-Server Architecture: Separation of concerns between client and server.
4. Cacheable: Responses can be cached for better performance.
5. Uniform Interface: Standardized way to interact with resources.
6. Layered System: Multiple layers handle requests without the client knowing.

31
Real-Time Example:
Employee Management System:

1. GET /api/employees - Fetch employee list


2. POST /api/employees - Add new employee
3. PUT /api/employees/1 - Update employee details
4. DELETE /api/employees/1 - Delete employee record

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 -

Concept Description Example Basic Syntax


Dividing a large
table into smaller Partition sales
Partitioning PARTITION BY year
parts for better data by year.
performance.
Restricts the
number of rows Get top 5 SELECT * FROM
LIMIT
returned by a employees. employees LIMIT 5;
query.
SELECT * FROM emp
Returns matching Join employees
INNER JOIN dept ON
INNER JOIN rows from both with
emp.dept_id =
tables. departments.
dept.id;

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 -

Concept Description Example Basic Syntax


Holds
Database collections myDatabase use myDatabase
in MongoDB.
Group of
MongoDB
Collection documents employees db.createCollection("employees")
(like
tables).
Basic unit
{ name:
of data db.employees.insertOne({ name:
Document "John",
(JSON-like "John", age: 30 })
age: 30 }
structure).
Add data to Add
db.employees.insertOne({ name:
Insert a employee
"Anna", dept: "HR" })
collection. data
Retrieve
Find documents Find all
db.employees.find()
(Query) from a employees
collection.
Filter Apply Employees db.employees.find({ dept: "HR" })

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" } } } })

DB2 Database Concepts -

Concept Description Example / Syntax


IBM's relational database
DB2 management system for -
high-performance data.
Organized collection of
Database CREATE DATABASE mydb;
data.
Stores data in rows and CREATE TABLE employees (id
Table
columns. INT, name VARCHAR(50));
Logical grouping of
Schema CREATE SCHEMA hr;
database objects.
Unique identifier for each
Primary Key PRIMARY KEY (id)
record.
FOREIGN KEY (dept_id)
Foreign Key Links two tables together.
REFERENCES departments(id)
INSERT INTO employees
Insert Data Adds new data to a table.
VALUES (1, 'John Doe');
Retrieves data from a
Select Data SELECT * FROM employees;
table.
UPDATE employees SET
Update Data Modifies existing data. name='Jane Doe' WHERE
id=1;
DELETE FROM employees
Delete Data Removes data from a table.
WHERE id=1;
Joins Combines rows from SELECT * FROM A JOIN B ON

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;

Git Basic Commands -

• git init - Initialize a new Git repository.


• git clone <repo_url> - Clone an existing repository.
• git status - Check the status of files in the working directory.
• git add <file> - Add specific file(s) to the staging area.
• git add . - Add all changes to the staging area.
• git commit -m "message" - Commit staged changes with a message.
• git push - Push commits to the remote repository.
• git pull - Fetch and merge changes from the remote repository.
• git fetch - Download changes from the remote repository without merging.

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:

o Template: Defines the view (HTML).

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.

o Structural Directives: Add or remove elements (*ngIf, *ngFor)


Example: <div *ngIf="isLoggedIn">Welcome!</div>
o Attribute Directives: Change the behavior or style ([ngClass], [ngStyle])
Example: <p [ngClass]="{active: isActive}">Hello</p>

Services & Dependency Injection (DI):


Services provide reusable logic (e.g., API calls, business logic). DI allows
Angular to inject dependencies automatically.
Example:

@Injectable() export class DataService { getData() { return [1,


2, 3]; } }
constructor(private dataService: DataService) {}

Routing:
Enables navigation between different views/pages. Defined in app-
routing.module.ts.
Example:

const routes: Routes = [ { path: 'home', component:


HomeComponent }, { path: 'about', component: AboutComponent } ];

Forms (Reactive & Template-Driven):

o Template-Driven Forms: Simple, using [(ngModel)].


Example: <input [(ngModel)]="name" required>
o Reactive Forms: More robust, using FormGroup,
FormControl.
Example:

this.form = new FormGroup({ name: new FormControl('') });

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:

ngOnInit() { console.log('Component initialized'); }


ngOnDestroy() { console.log('Component destroyed'); }

Pipes:
Transform data in templates.

o Built-in Pipes: date, uppercase, currency, etc.


Example: {{ today | date:'shortDate' }}
o Custom Pipes: Create custom transformations.
Example:

@Pipe({ name: 'capitalize' })


export class CapitalizePipe implements PipeTransform {
transform(value: string): string { return
value.charAt(0).toUpperCase() + value.slice(1); }
}

Additional Angular Concepts

Observables & RxJS:


Used for handling asynchronous data streams (API calls, events).
Example:

this.http.get('api/data').subscribe(data => console.log(data));

Event Binding & Event Emitters:


Pass data from child to parent components using @Output and EventEmitter.
Example:

@Output() notify = new EventEmitter<string>();


this.notify.emit('Data from child');

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:

intercept(req: HttpRequest<any>, next: HttpHandler) {


const cloned = req.clone({ headers:
req.headers.set('Authorization', 'Bearer token') });
return next.handle(cloned);
}

Lazy Loading:
Load modules only when needed to improve performance.
Example:

{ path: 'admin', loadChildren: () =>


import('./admin/admin.module').then(m => m.AdminModule) }

Resolvers:
Fetch data before navigating to a route.
Example:

resolve() { return this.dataService.getData(); }

Standalone Components:
Angular 14+ feature allowing components without modules.
Example:

@Component({ standalone: true, selector: 'app-standalone',


template: '<p>Standalone!</p>' })

TrackBy Function (in *ngFor):


Optimizes performance by tracking items efficiently.
Example:

<div *ngFor="let item of items; trackBy:


trackById">{{ item.name }}</div>

Change Detection Strategy:


Controls how Angular detects and updates the UI.
Example:

@Component({ changeDetection: ChangeDetectionStrategy.OnPush })

Content Projection (ng-content):


Pass dynamic content into components.
Example:

<ng-content></ng-content>

41
Custom Directives:
Create your own directives to manipulate the DOM.
Example:

@Directive({ selector: '[appHighlight]' })

42

You might also like