0% found this document useful (0 votes)
2 views115 pages

Notes

The document provides a comprehensive overview of Java and Object-Oriented Programming (OOP) concepts, including principles like encapsulation, inheritance, polymorphism, and abstraction, along with examples. It discusses key Java features such as interfaces, abstract classes, exception handling, multithreading, and memory management. Additionally, it touches on HTML basics and semantic elements, making it a valuable resource for understanding core programming concepts and interview preparation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views115 pages

Notes

The document provides a comprehensive overview of Java and Object-Oriented Programming (OOP) concepts, including principles like encapsulation, inheritance, polymorphism, and abstraction, along with examples. It discusses key Java features such as interfaces, abstract classes, exception handling, multithreading, and memory management. Additionally, it touches on HTML basics and semantic elements, making it a valuable resource for understanding core programming concepts and interview preparation.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java and OOPs

05 November 2024 21:20

Core Java and OOP Concepts: Sample Answers


1. What are the four main principles of OOP, and can you explain each with an example?
Ans: In Object-Oriented Programming, we work with four main principles: Encapsulation, Inheritance,
Polymorphism, and Abstraction.
• Encapsulation is about wrapping data and methods together in a single unit , typically a class,
and also it promotes data security and abstraction.
○ For example, in an application where customer data is handled, we might make fields like
customerID and accountBalance private and provide public getter and setter methods to
control access.
○ This ensures that sensitive data is managed securely and prevents unauthorized access.
• Inheritance allows one class to acquire properties from another classes, promoting code
reusability.
○ For instance, if we have a User class with basic attributes like name and email, and a
Customer class that extends User, the Customer class automatically inherits these properties,
reducing redundancy and centralizing common code.
• Polymorphism enables flexibility by allowing methods to take on different forms based on the
object that invokes them.
○ For example, a Notification system could have a send method in the parent class, which is
overridden in subclasses such as EmailNotification and SMSNotification. Each subclass would
implement send method differently, depending on the notification type.
• Abstraction is about showing only the essential details and hiding complex implementation. This
can be achieved through interfaces or abstract classes.
○ For instance, a PaymentGateway interface could define methods like processPayment() and
refund(), without specifying how each payment provider (such as PayPal, Stripe, etc.)
implements them.

2. What’s the difference between an interface and an abstract class in Java?


Ans:
• An interface defines a set of methods that must be implemented by any class that uses it, and all
methods in an interface are by default public and abstract.
○ For example, in a company that manages various payment methods, we might have an
interface called PaymentMethod. This interface could declare methods like
processPayment(), refund(), and validate(), which classes like CreditCardPayment and
UPIPayment would implement to define their specific behaviors.
• On the other hand, an abstract class can have both abstract methods(without implementation)
and concrete methods(with implementation). It can also contain fields and constructors.
○ For instance, an abstract class PaymentProcessor might implement a concrete method for
handling transaction logs while declaring an abstract method calculateFees() that its
subclasses like CreditCardPayment or UPIPayment would need to implement.
.

Notes Page 1
Notes Page 2
3. How does Java achieve polymorphism, and why is it useful?
Ans:
• In Java, polymorphism is achieved primarily through method overloading and method
overriding.
• Method overloading happens when we define multiple methods with the same name
but different parameters, enabling flexibility in how we call methods.
○ Compile-Time Binding (Static Binding): The decision on which overloaded method
to call is made by the compiler based on the method signature at compile
time. It's
also known as static polymorphism

• Method overriding occurs when a subclass provides a specific implementation of a


method already defined in its superclass, allowing for dynamic method resolution at
runtime.
Run-Time Binding (Dynamic Binding): The decision on which overridden
method to
call is made at runtime based on the actual object type by jvm. It's also
known as dynamic polymorphism

• Polymorphism is useful because it enables us to write code that can operate on objects
and methods of different types in a consistent way, making it easier to scale and
maintain.
• Method overloading: For instance, in a company’s PaymentProcessor class, we might
have multiple versions of a processPayment() method — one version that takes a credit
card number and expiry date, another that accepts a UPI ID, and another accepts a bank
account Number. This flexibility helps make the code easier to use in different scenarios
without changing the method name.
• Method overriding: For example, a Notification class might define a generic send()
method, while subclasses like EmailNotification and SMSNotification each have their
own send() implementations. By using a Notification reference, we can call send(), and
Java will automatically select the right method based on whether the object is an email
or SMS notification.

Notes Page 3
4. Explain method overloading and method overriding with examples.
• Method overloading in Java allows us to have multiple methods with the same name but
different parameters within the same class.
○ Compile-Time Binding (Static Binding): The decision on which overloaded method
to call is made by the compiler based on the method signature at compile time. It's
also known as static polymorphism
○ For instance, in a company’s PaymentProcessor class, we might have multiple versions of a
processPayment() method — one version that takes a credit card number and expiry date,
another that accepts a UPI ID, and another accepts a bank account Number. This flexibility
helps make the code easier to use in different scenarios without changing the method
name.

• Method overriding allows a subclass to provide its specific implementation of a method that is
already defined in its superclass.
○ Run-Time Binding (Dynamic Binding): The decision on which overridden method to
call is made at runtime based on the actual object type. It's also known as dynamic
Polymorphism.
○ For example, a Notification class might define a generic send() method, while subclasses like
EmailNotification and SMSNotification each have their own send() implementations. By
using a Notification reference, we can call send(), and Java will automatically select the right
method based on whether the object is an email or SMS notification.

5. What is the significance of final, finally, and finalize in Java?


“final, finally, and finalize each have distinct roles in Java:
• final: The final keyword can be used in different contexts:
○ for variables, it means their values cannot change;
○ for methods, they cannot be overridden; and
○ for classes, they cannot be inherited or extended by another classes.
• finally: The finally block is used with try and catch statements and always executes,
regardless of whether an exception is thrown. It’s mainly used to release resources
like closing files or freeing memory.
• finalize: finalize is a method that the garbage collector calls before an object is
removed from memory. Although it’s rarely used, it can handle cleanup tasks if
needed, though it doesn’t guarantee the object’s immediate removal.”

6. What are static variables and methods in Java?


• In Java, static variables and methods belong to the class rather than instances of the
class.
• A static variable is shared among all instances, meaning changes in one instance reflect
across others.
• Similarly, a static method can be called without creating an instance of the class, but it
can only directly access other static data.
• For instance, if we have a Counter class with a static variable count, every time an
object of Counter is created, count would increment, and this count would be shared
across all instances.

7. What is an Exception in Java, and how is it different from Error?


"An Exception in Java is an event that interrupt's normal program flow, but it’s something we can
usually handle within the code.
• For example, if a file is missing, we can catch a FileNotFoundException and respond to it,
allowing the program to continue without crashing.

Notes Page 4
In contrast, an Error is a more severe issue that usually arises from the system environment, like an
OutOfMemoryError or StackOverflowErrror.
• These Errors are generally beyond the program's control and aren’t meant to be handled by
the code."

• Exceptions are Conditions that a program might want to catch and handle.
• Errors: Serious issues that are usually not recoverable and should not be
caught by the application.

8. Explain the purpose of try, catch, throw, throws, and finally.


Java provides several keywords to handle exceptions:
• try: Surrounds code that may throw an exception.
• catch: Catches exceptions that occur in the try block.
• throw: Used to explicitly throw an exception.
• throws: Declares that a method can throw exceptions.
• finally: Executes after try and catch, even if an exception is not caught, typically
used for closing a file or database connection, ensuring they’re closed even if an
exception occurs..
• try: Wraps code that might throw an exception. For example, reading from a file within a try
block handles any potential errors during file access.
• catch: Catches and handles exceptions that occur within the try block. If we try to open a file
that doesn’t exist, a FileNotFoundException can be caught here to prevent a crash.
• throw: Explicitly throws an exception. For instance, we can throw a new
IllegalArgumentException if invalid data is passed to a method.
• throws: Used in method signatures to declare that the method might throw certain
exceptions. If a method performs file reading, it might declare throws IOException.
• finally: Executes after try and catch, regardless of whether an exception was caught. It's
often used to release resources, like closing a file or database connection, ensuring they’re
closed even if an exception occurs."

9. Can you explain how String, StringBuilder, and StringBuffer differ?


“In Java, String is immutable, meaning any modification creates a new String object.
StringBuilder and StringBuffer, on the other hand, are mutable, allowing modifications without creating
new objects. StringBuilder is faster but not synchronized, while StringBuffer is thread-safe, making it
suitable for concurrent environments.

10. What is the purpose of the Collections framework in Java?


“The Collections framework in Java provides standardized classes and interfaces for storing and managing
groups of objects, improving the efficiency and reusability of data handling.
It includes interfaces like List, Set, and Map, and classes like ArrayList, HashSet, and HashMap that make data
manipulation simpler and more consistent.”

16. Explain the concept of multithreading in Java. Why is it useful?


“Multithreading in Java allows multiple threads to run concurrently within a program, sharing the same
memory space. Each thread can perform a separate task independently, improving efficiency by making
better use of CPU resources.
For example, a web server could use multiple threads to handle multiple client requests
simultaneously.
Multithreading is useful for tasks like:
1. Background Processing: Running non-blocking tasks like file downloads or UI animations.
2. Parallelism: Dividing complex computations across threads to speed up processing.
3. Responsive Applications: Keeping applications responsive by delegating(dividing) time-consuming tasks
to background threads.
In Java, we can implement multithreading by either extending the Thread class or implementing the
Runnable interface.”

Notes Page 5
17. How does Java handle synchronization between threads?
“Java handles synchronization to prevent concurrent threads from causing
data inconsistency. The synchronized keyword can be used to ensure that only
one thread can access a critical section at a time. Here are ways
synchronization works:
1. Synchronized Methods: Declaring a method as synchronized ensures that
only one thread can access it at a time. For example, if a method
increment() is synchronized, only one thread can execute it at once.
2. Synchronized Blocks: Synchronized blocks are used to synchronize specific
sections of code within a method, reducing the scope of synchronization.
For instance:

java Counter Class: This class contains a count variable that


Copy code is shared by both threads. The increment() method is
synchronized(this) { marked as synchronized, meaning only one thread can
// code to synchronize access it at a time.
}
3. Locks: Java provides more advanced locking mechanisms through Lock
interface classes, such as ReentrantLock, which offers more control over
synchronization than synchronized methods and blocks.
This ensures data consistency and avoids issues like race conditions when
multiple threads access shared resources.”

Notes Page 6
1. What is a Constructor in Java?
Constructor is a special method which is invoked automatically
at the time of object creation. It is used to initialize the data members of
new objects generally.
Unlike regular methods, constructors have the same name as the class and do not have
a return type.

2. Types of Inheritance in Java


Inheritance in Java is a mechanism where one class (subclass) acquires the
properties and behaviors (methods) of another class (superclass). This promotes
code reuse and establishes a relationship between classes.

Notes Page 7
In object-oriented programming, hybrid inheritance combines two or more
types of inheritance patterns, such as single, multiple, multilevel, or
hierarchical inheritance.

this keyword in Java


• In Java, the this keyword refers to the current instance of a class, helping us
avoid ambiguity and simplifying code.

• For example, if a constructor or method has a parameter with the same


name as an instance variable, this is used to clarify that we’re referring to
the instance variable.
• It’s also useful in calling one constructor from another within the same
class, known as constructor chaining, which makes initializing objects more
flexible.

It’s also useful in calling one


constructor from another within the
same class,

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They
are as follows: In Java, exception handling is a way to manage runtime
1) A scenario where ArithmeticException occurs errors gracefully without unexpectedly terminating the
If we divide any number by zero, there occurs an ArithmeticException. program. The main keywords for this are try, catch, throw,
int a=50/0;//ArithmeticException throws, and finally.
• try surrounds code that might throw an exception.
2) A scenario where NullPointerException occurs • catch handles the exception, providing a solution or an
If we have a null value in any variable, performing any operation on the variable alternative path.
throws a NullPointerException. • throw is used to explicitly throw an exception.
String s=null;
• throws declares that a method might throw certain
[Link]([Link]());//NullPointerException
exceptions.
3) A scenario where NumberFormatException occurs • finally executes regardless of whether an exception is
If the formatting of any variable or number is mismatched, it may result into caught or not, typically used for resource cleanup.
NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.
String s="abc";

Notes Page 8
String s="abc";
int i=[Link](s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.
there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider
the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException

Notes Page 9
Stack Memory Vs Heap Memory
Stack and heap memory are two areas used to store data in memory.
• Stack memory is used for static memory allocation, such as primitive data types and
references to objects. It follows a Last In, First Out (LIFO) structure and is faster, but it
has limited space. Stack memory is automatically managed, meaning variables are
removed when they go out of scope.
• Heap memory, on the other hand, is for dynamic memory allocation, where objects
and instance variables are stored. It has more space than the stack but requires more
management. In Java, heap memory is managed by the garbage collector, which
removes unreferenced objects over time.
The main difference is that the stack is used for method execution and is faster, while the
heap holds larger data for objects and supports dynamic memory, though with a
performance cost."

Notes Page 10
Notes Page 11
Notes Page 12
Notes Page 13
HTML
16 November 2024 22:42

Top 123 TCS Ninja Interview Questions and Answers 2024 - Page 2 | AmbitionBox

HTML Interview Questions


1. What is HTML?
○ HTML stands for Hyper Text Markup Language.
○ It is used to define the structure of the web pages using
elements and tags.

2. What are Semantic elements in HTML?

The Semantic elements in HTML are the elements that contain


content that is related to their names or reflects their names.
These are the some of semantic HTML elements are listed below:
• Header (contains Navbar)
• Main (contains main content)
• Section (one section in the web page)
• Footer (contains footer content like copy rights, Social media
links).

3. What are the Empty elements in HTML?

1. The empty elements in HTML are the elements that don’t


require a closing tag followed by the opening tag.
2. These elements are also known as self-closing elements.
Example: <img>, <input>, <br>, <hr> etc.
What are void elements in HTML?
• Void elements are self-closing tags that do not require a closing tag.

Examples:
○ <img>, <br>, <input>, <hr>.

4. Differentiate between the Inline and the Block elements in


HTML.

The Inline elements in HTML are the elements that do not start
from a new line every time and take up the same space and width
as acquired by the content. Examples:<span>, <a>, <strong>,
<img>, <input> etc.
The Block elements automatically starts from a new line and takes
up the whole view-port width irrespective of the contained content.
Examples: <div>, <h1> to <h6>, <p>, <table> etc.

5. What is list in HTML? Explain different types of list available


in HTML.

In HTML, the lists are used to represent a collection of different


items. There are two types of lists available in HTML as listed
below:
1. Unordered List: It is defined using the <ul> and the <li> tags. By
default, it represents the items with a bulleted dot.
<ul>
<li>List Item 1</li>
<li>List Item 3</li>
<li>List Item 3</li>
</ul>
2. Ordered List: It is defined using the <ol> and <li> tag. By
default, it represents the list items with numeric digits.
<ol>
<li>List Item 1</li>
<li>List Item 3</li>

Notes Page 14
<li>List Item 3</li>
<li>List Item 3</li>
</ol>

6. What is the basic structure of an HTML document?

The basic structure of an HTML document in HTML5 is shown below:


<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body></body>
</html>

7. Explain the elements used in the basic structure of an HTML


document.

The elements used in the basic structure of an HTML document are


explained below:
• <!DOCTYPE html>: It represents the HTML5 version of the HTML.
• <html>: It is the root element of the HTML document.
• <head>: It contains the meta data i.e. the data about the data. The
content contained by this tag is not visible on the web page.
• <title>: It contains the title of the document which will be visible in the
browser tab.
• <body>: It contains the content of the web page in the form of the HTML
tags like <div>, anchor<a>, paragraph<p>, headings<h1>, etc.

8. Explain tags in HTML.

The HTML tags are used to define the elements on the web page.
Basically, they are the keywords that are enclosed inside the angle
brackets(<>). The examples of HTML tags are <div>, <p>, <a>, <span>,
<img> etc.

9. Why ‘alt’ attribute is used with the <img> tag in HTML?

The alt attrbute provides a alternative content that is related to the


image which will be shown on the web page if the image does not gets
loaded.

[Link] the difference between <div> and <span>.


○ <div>: A block-level element used to group larger sections of content.

○ <span>: An inline element used to style or manipulate small chunks of

content.

11. Why the <meta charset = “UTF-8”> tag is used?

It is used to set the character encoding of the charaters for the document
to UTF-8 to properly display the text and the special characters on the
web page.

[Link] is the purpose of the <meta> tag?


• The <meta> tag provides metadata about the HTML document.

Common uses:
○ Setting character encoding: <meta charset="UTF-8">.

○ Setting viewport for responsiveness:

<meta name="viewport" content="width=device-width,


initial-scale=1.0">.

12. What is the purpose of using the ‘role’ attribute in HTML?

The role attribute defines the functionality and the purpose of an


element mainly the accessibility. It provides the additional information
for the screen readers, to convey the exact meaning of the element to
the users with disabilities.
What are data attributes in HTML?
Notes Page 15
What are data attributes in HTML?
• Data attributes are custom attributes that store additional data

directly in HTML elements.


• Syntax:

<div data-id="123" data-role="user">John Doe</div>


• Access them via JavaScript:

const id = [Link]('div').[Link]; // "123"

13. Differentiate between the GET and the POST methods in HTML
forms.

The below table will explain the differences between the GET and
POST methods in HTML forms:

GET Method POST Method


It is a insecure way to send data It is a secure way of sending the form
on the server. data.
All the form data parameters None of the parameters are visible
are visible in the URL. anywhere.
It has a URL length limit that It has a bigger URL length limit as
varies for different browsers. compare to the limit of the GET
method.
Results are cached by the Does not caches the responses in the
browser by default. browser by default.

14. What is the use of the <iframe> tag?

The <iframe> tag is used to embed the external documents or the web
pages inside the current document by specifying its link inside it. It is
mainly used to embed the external videos, maps and other external
content.

15. Explain the features of HTML5?

HTML5 introduced some new features that are listed below:


1. Introduced new semantic elements
like: <header>, <footer>, <nav>, <aside>, <article>, <section> etc.
2. New form input types such as email, url, number, date, etc.
3. It introduced the <audio> and <video> tags to embed audios and
videos and reduces the dependence on the third party libraries.
4. <canvas> element to draw graphics and animations using JavaScript.
5. Introduces the browser storage
as localStorage and sessionStorage to store data in the browser.

16. What is localStorage?

localStorage is a client-side web storage mechanism that Stores data with


no expiration time; data will be persists even after the browser is closed.

17. What is sessionStorage?

It is also a web storage API provided by the web browsers to Stores data
for the session; data is cleared when the browser is closed.

19. What is the purpose of using <figure> and <figcaption> elements


in HTML5?

The <figure> element is used to display the media content on the web
page like audios, videos etc. While, the <figcaption> element is used to
give a caption to the content shown by the <figure> element.

20. Write the HTML code to create a table with 3 columns and 3 rows.

The below code creates a table with 3 rows and 3 columns:


<table border="1px">

Notes Page 16
<table border="1px">
<thead>
<tr>
<th>col 11</th>
<th>col 12</th>
<th>col 13</th>
</tr>
</thead>
<tbody>
<tr>
<td>col 21</td>
<td>col 22</td>
<td>col 23</td>
</tr>
<tr>
<td>col 31</td>
<td>col 32</td>
<td>col 33</td>
</tr>
</tbody>
</table>

21. How you can merge the rows and columns of a HTML table?

You can use the colspan and the rowspan attributes with
the <td> element and specify the number of rows and columns to be
merged by passing a numerical value to the defined attributes.
The colspan attribute can be used to merge columns while
the rowspan to merge the rows.

1. How do you implement responsive design using HTML?


○ Use the <meta> viewport tag: <meta name="viewport"

content="width=device-width, initial-scale=1.0">.
○ Combine with CSS media queries to adjust layout for different screen

sizes.
2. What is the difference between id and class attributes?
id: Used to uniquely identify a single element. It must be unique on

Notes Page 17
○ id: Used to uniquely identify a single element. It must be unique on
the page.
○ class: Used to apply styles or behaviors to multiple elements.

3. What is the difference between <link> and <script> tags?


• <link>: Links external resources like stylesheets.

○ Example: <link rel="stylesheet" href="[Link]">.

• <script>: Embeds or links JavaScript code.

○ Example: <script src="[Link]"></script>.

4. What is the purpose of the <canvas> element?


• <canvas> is used to draw graphics on the web page via JavaScript,

such as charts, games, or animations.

5. How would you optimize an HTML page for SEO?


• Use semantic tags like <article>, <header>, <footer>.

• Include a descriptive <title> and <meta> description.

• Use proper heading hierarchy (<h1> to <h6>).

• Use alt attributes for images.

• Optimize URLs and include relevant keywords.

6. What are the different types of input fields in HTML forms?


• Common input types:

a. Text: <input type="text">


b. Password: <input type="password">
c. Email: <input type="email">
d. Number: <input type="number">
e. File upload: <input type="file">
f. Date: <input type="date">
g. Checkbox: <input type="checkbox">
h. Radio button: <input type="radio">

7. What are the differences between <b> and <strong>, and <i> and
<em>?
• <b> and <i>: Apply visual styling (bold and italic) without semantic

meaning.
• <strong> and <em>: Indicate importance or emphasis and also

provide semantic meaning.(doing same thing with semantic meaning)

8. What are HTML5 Web Storage APIs?


• APIs that allow storing key-value pairs in the browser:

○ localStorage: Persistent storage. Avails after we close and reopen

the browser.
○ sessionStorage: Temporary storage. Data is removed after we

close the browser.


○ Example:

9.

Notes Page 18
DBMS
12 November 2024 10:18

• Data: Data is statically raw and unprocessed information. For example – name, class,
marks, etc

• Database(DB): A database is a collection of organized related data, which is also called structured
data. It can be accessed or stored in a computer system by DBMS.

• DBMS: A Database Management System (DBMS) is a software system that is designed to manage
and organize data in a structured manner.
○ It provides an environment to store and retrieve data in convenient and efficient manner.

• Database management systems were developed to handle the following difficulties:


○ Data redundancy
○ Difficulty in accessing data
○ Concurrent access by multiple users
○ Security problem

• DBMS architecture depends upon how users are connected to the database to get their
request done.

1. One-Tier Architecture:
• Definition: In this architecture, the database is directly accessible to the user without the need for
an application or client/server interface.
• Example: Local databases, such as Microsoft Access or SQLite, where both the database and the
application reside on the same system.
• Use Case: Primarily used for development or testing purposes, not for production due to limited
scalability and security.
2. Two-Tier Architecture (Client-Server Architecture)
• Definition: In this structure, the client acts as an interface between user and database. The user
sends requests to the database server through client, which then processes and returns the
requested data.
• Components:
• Client: The interface where users interact, generally containing the application logic.
• Server: Hosts the DBMS and manages data storage, handling requests and responses.
• Example: A system where a desktop application (client) communicates with a centralized database
server, such as MySQL or Oracle. ś
• Use Case: Offers better data management and separation, allowing multiple clients to connect to a
single server.

3. Three-Tier Architecture
• Definition: This architecture contains three layers—presentation, application, and data layers—
adding a middle layer between the client and server.
• Components:
• Presentation Layer (Client): The user interface, like a web browser or mobile app.
• Application Layer (Middle Tier): Contains the business logic, processing data received from the

Notes Page 19
adding a middle layer between the client and server.
• Components:
• Presentation Layer (Client): The user interface, like a web browser or mobile app.
• Application Layer (Middle Tier): Contains the business logic, processing data received from the
database, and sending it to the client.
• Data Layer (Database Server): Manages the actual database and data storage.
• Example: A web application where the user interacts with a front-end (UI), which communicates
with a back-end server to access a remote database (e.g., an online shopping platform).
• Use Case: Common in large-scale, web-based applications as it provides scalability, easier
maintenance, and better security.

• The application on the client-


end interacts with an
application server which
further communicates with
database and processing data
received from the database, and
sending it to the client.

What are the Data Models in DBMS?


In a database management system, data models are often used to show how data is
connected, stored, accessed, and changed.
Types of Data Models in DBMS.
1. Hierarchical Model- stores data in tree structure
a. Used a Hierarchical tree structure to organize the data.
b. The hierarchy begins at the root, which contains root data, and then grows into a tree
as child nodes are added to the parent node

2. Network Model - store data in graph structure


a. Any record can have several parents in the network model.
b. It uses a graph instead of a hierarchical tree.

c.

3. Entity-Relational Model:
a. An E-R model is the logical representation of database structure.
b. It shows all the constraints and Relationships among different components in
database.

4. Relational Model:

Notes Page 20
4. Relational Model:
a. The data in this model is stored in the form of a rows and columns within a table.
b. Tables are also Called Relations.
c. This model uses Tables for representing data and in-between relationships.

d.

ER diagram:
1. ER diagram is the logical representation of database structure.
2. It shows all the constraints and Relationships among different components in database.
• An ER diagram is mainly composed of following three components- Entity Sets,
Attributes and Relationship Set.

• Roll_no is a primary key that can identify each entity uniquely.

[Link] Set: An Entity Set is a collection of similar types of entities.


1. Strong Entity Set: A strong entity set is an entity set that contains primary key to
uniquely identify all its entities.
2. Weak Entity Set: A weak entity set is an entity set that does not contain primary key
○ An entity that depends on another entity called a weak entity.

2. Attribute
The attribute is used to describe the property of an entity. Eclipse is used to represent an
attribute.
For example, id, age, contact number, name, etc. can be attributes of a student.

a. Key Attribute
The key attribute is used to represent the main characteristics of an entity. It represents a
primary key. The key attribute is represented by an ellipse with the text underlined.

b. Composite Attribute
An attribute that composed of many other attributes is known as a composite attribute. The

Notes Page 21
b. Composite Attribute
An attribute that composed of many other attributes is known as a composite attribute. The
composite attribute is represented by an ellipse, and those ellipses are connected with an
ellipse.

c. Multivalued Attribute
An attribute can have more than one value. These attributes are known as a multivalued
attribute. The double oval is used to represent multivalued attribute.
For example, a student can have more than one phone number.

d. Derived Attribute
An attribute that can be derived from other attribute is known as a derived attribute. It can be
represented by a dashed ellipse.
For example, A person's age changes over time and can be derived from another attribute
like Date of birth.

[Link]
○ A relationship is used to describe the relation between entities.
○ Diamond or rhombus is used to represent the relationship.

Types of relationship are as follows:


a. One-to-One Relationship
When only one instance of an entity is associated with the relationship, then it
is known as one to one relationship.
For example, A female can marry to one male, and a male can marry to one
female.

b. One-to-many relationship
When only one instance of the entity on the left, and more than one instance of
an entity on the right associates with the relationship then this is known as a
one-to-many relationship.
For example, Scientist can invent many inventions, but the invention is done
by the only specific scientist.

c. Many-to-one relationship
When more than one instance of the entity on the left, and only one instance of
an entity on the right associates with the relationship then it is known as a
many-to-one relationship.
For example, Student enrolls for only one course, but a course can have
many students.

d. Many-to-many relationship
When more than one instance of the entity on the left, and more than one
instance of an entity on the right associates with the relationship then it is

Notes Page 22
instance of an entity on the right associates with the relationship then it is
known as a many-to-many relationship.
For example, Employee can assign by many projects and project can have
many employees.

Keys: A key is a set of attributes that can identify each tuple uniquely in
the given relation.
Types of Keys:
1. Super Key- A super key is a set of any no of attributes that can
identify each tuple uniquely in the given relation.
2. Candidate Key- A set of minimal attribute(s) that can identify each
tuple uniquely in the given relation is called a candidate key.
3. Primary Key- A single attribute that can identify each tuple uniquely
in the given relation. It is also a Candidate Key. Primary Keys are unique
and NOT NULL.
4. Alternate Key- An Alternate Key is a candidate key that is not chosen as the
primary key.
5. Foreign Key- A Foreign Key is a key in one table that refers to the primary
key of another table, establishing a relationship between the two tables.
6. Composite Key- A Composite Key is a primary key that consists of more than
one attribute to uniquely identify each row.
7. Unique Key- A Unique Key constraint ensures that all values in a column are
different. Unlike primary keys, unique keys can accept NULL values.

1. Trivial Functional Dependency


A functional dependency X→Y is said to be trivial if and only if Y⊆X, meaning that all attributes
in Y are also present in X.
• Trivial Dependency: Adds no new information, like:
• {StudentID, Name} → StudentID (since StudentID is already part of the left side).

Notes Page 23
2. Non-Trivial Functional Dependency
A functional dependency X→Y is said to be non-trivial if Y⊈X, meaning that Y has at least one
attribute that is not part of X.
• Non-Trivial Dependency: Provides constraints, like:
• EmployeeID → Department (this tells us that EmployeeID uniquely identifies
Department in the Employee table).

Normalization: In DBMS, database normalization is a process of


making the database consistent by
● Reducing the redundancies
Lossless Decomposition- Lossless decomposition ensures -
● Ensuring the integrity of data through lossless decomposition • No information is lost from the original relation during
decomposition.
• 1NF (First Normal Form): A table is in 1NF ,if the attributes of every tuple is • When the sub relations are joined back, the same relation is
either single valued or a null value. obtained that was decomposed.

• 2NF (Second Normal Form): A table is in 2NF if it is in 1NF and has no partial
dependencies.
• Partial Dependency: In a relation, a dependency A → B is called a partial
dependency if A is a subset of some candidate key and B is a non-prime
attribute (not part of any candidate key).

Identifying Partial Dependencies


Now let’s identify the dependencies:
1. {StudentID, CourseID} → StudentName:
○ This dependency implies that StudentID and CourseID together determine StudentName.
○ This dependency is not a partial dependency because StudentID and CourseID together
form the candidate key, and there is no subset involved here.
2. StudentID → StudentName:
○ This dependency shows that StudentID alone determines StudentName.
○ This is a partial dependency because:
▪ StudentID is a subset of the candidate key {StudentID, CourseID}.
▪ StudentName is a non-prime attribute.
○ Because of this partial dependency, the relation is not in 2NF.
3. CourseID → CourseName:
○ This dependency shows that CourseID alone determines CourseName.
○ This is also a partial dependency because:
▪ CourseID is a subset of the candidate key {StudentID, CourseID}.
▪ CourseName is a non-prime attribute.

Notes Page 24
Third Normal Form (3NF)- A given relation is called in Third Normal Form (3NF) if
and only if
• Relation already exists in 2NF.
• has No transitive dependencies. (changes in one cell may leads to change in
another).
• A→B is called a transitive dependency if and only if- A is not a super key and
B is a non-prime attribute (not part of any candidate key) .

In the context of databases, anomalies refer to problems


that can arise when data is inserted, updated, or deleted
in a relational database that isn’t properly normalized.
● Boyce-Codd Normal Form- A given relation is called in BCNF if Anomalies occur due to data redundancy or improper
and only if organization of data, and they can lead to inconsistencies
and errors in the database.
• Relation already exists in 3NF.
• For each non-trivial functional dependency ‘A → B’, A is a super
key of the relation.

Notes Page 25
Now, each table is in 2NF with no partial dependencies.

Notes Page 26
Normalization: In DBMS, database normalization is a process of
making the database consistent by
Lossless Decomposition- Lossless decomposition ensures -
● Reducing the redundancies No information is lost from the original relation during decomposition.
● Ensuring the integrity of data through lossless decomposition
When the sub relations are joined back, the same relation is obtained that was
decomposed.
1NF (First Normal Form): A table is in 1NF ,if the attributes of every
tuple is either single valued or a null value.
2NF (Second Normal Form): A table is in 2NF if it is in 1NF and has no
partial dependencies.
Partial Dependency: In a relation, a dependency A → B is called a
partial dependency if A is a subset of some candidate key and B is a
non-prime attribute (not part of any candidate key).

Third Normal Form (3NF)- A given relation is called in Third Normal Form ● Boyce-Codd Normal Form- A given relation is called
(3NF) if and only if in BCNF if and only if
Relation already exists in 2NF. • Relation already exists in 3NF.
has No transitive dependencies. (changes in one cell may leads to • For each non-trivial functional dependency ‘A → B’,
change in another).
A must be a super key of the relation.
A→B is called a transitive dependency if and only if- A is not a
super key and B is a non-prime attribute (not part of any
candidate key).

ACID Properties: To ensure the consistency of the database, certain properties are
followed by all the transactions occurring in the system. These properties are called as
ACID Properties of a transaction.
• Atomicity :
○ This property ensures that either the transaction occurs completely or it does
not occur at all.
○ In other words, it ensures that no transaction occurs partially.
• Consistency :
○ This property ensures that integrity constraints are maintained.
○ In other words, it ensures that the database remains consistent before and
after the transaction.
• Isolation :
○ This property ensures that multiple transactions can occur simultaneously
without causing any inconsistency.
○ The resultant state of the system after executing all the transactions is the
same as the state that would be achieved if the transactions were executed
serially one after the other.
• Durability :

Notes Page 27
• Durability :
○ This property ensures that all the changes made by a transaction after its
successful execution are written successfully to the disk.
○ It also ensures that these changes exist permanently and are never lost even if
there occurs a failure of any kind

Example Scenario: Online Bank Transfer


Consider a simple scenario where Alice wants to transfer $100 from her account to Bob's account.
1. Atomicity
• Explanation: Atomicity means that the transaction occurs completely or it does not occur at all.
• Example: Alice’s bank account is debited by $100, and Bob’s bank account is credited by $100. If
there is an error after the debit but before the credit, the entire transaction is rolled back, and
Alice’s account balance remains unchanged. This prevents Alice’s account from losing $100
without Bob receiving it.
2. Consistency
• Explanation: Consistency ensures that the database want to be in a valid state before and after
Transaction.
• Example: If Alice’s account balance before the transaction was $500, after the transaction, her
balance will be $400, and Bob’s balance will increase by $100. This maintains the database
consistency rule that the total balance (Alice’s and Bob’s combined) before and after the
transaction remains the same.
3. Isolation
• Explanation: Isolation ensures that transactions do not interfere with each other, and each
transaction is isolated from others.
• Example: Suppose while Alice’s transfer is processing, another transaction is also accessing her
account for a different purpose, like a balance check. Isolation ensures that the other transaction
will see Alice’s balance as $500 until her transfer to Bob is fully completed. This way, no other
transaction sees a partial state, and they execute as if they were completed serially.
4. Durability
• Explanation: Durability ensures that once a transaction is committed, the changes made by it are
permanent, even in the event of a system failure.
• Example: After the transaction successfully completes, Alice’s balance is $400, and Bob’s balance
is increased by $100. Even if there is a sudden system crash right after the transaction is
completed, the database will remember the final balances ($400 for Alice and the updated
amount for Bob) when it comes back online.
Summary
These ACID properties ensure that:
• Atomicity: The whole transfer either happens completely or not at all.
• Consistency: The database remains valid before and after the transaction.
• Isolation: Other transactions do not see intermediate states.
• Durability: Changes are permanently saved after the transaction’s success.
This combination of properties ensures reliable and accurate transaction processing in database
systems, which is especially crucial in scenarios involving financial transactions, inventory
management, or other critical systems.

Notes Page 28
SQL notes
13 November 2024 23:19

SELECT:
The SELECT statement is used to select data from a database.
Syntax
● SELECT column1, column2, ...
FROM table_name;
● Here, column1, column2, ... are the field names of the table you want
to select data
from. If you want to select all the fields available in the table, use the
following syntax:
● SELECT * FROM table_name;
Ex
● SELECT CustomerName, City FROM Customers

SELECT DISTINCT:
The SELECT DISTINCT statement is used to return only distinct (different)
values.
Syntax
● SELECT DISTINCT column1, column2, ...
FROM table_name;
Ex
● SELECT DISTINCT Country FROM Customers

WHERE :
The WHERE clause is used to filter records.
Syntax
● SELECT column1, column2, ...
FROM table_name
WHERE condition;
Ex
● SELECT * FROM Customers
WHERE Country='Mexico'

AND, OR and NOT:


The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one
condition:
● The AND operator displays a record if all the conditions separated by AND are
TRUE.

Notes Page 29
TRUE.
● The OR operator displays a record if any of the conditions separated by OR is
TRUE.
• The NOT operator displays a record if the condition(s) is NOT TRUE

Syntax
● SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
● SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
● SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Ex
● SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
● SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR
City='München');

ORDER BY:
The ORDER BY keyword is used to sort the result-set in ascending or
descending order.
The ORDER BY keyword sorts the records in ascending order by
default. To sort the records in
descending order, use the DESC keyword.
Syntax
● SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Ex
● SELECT * FROM Customers
ORDER BY Country;
● SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;

Notes Page 30
INSERT INTO:
The INSERT INTO statement is used to insert new records in a table.
Syntax
● INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
● INSERT INTO table_name
VALUES (value1, value2, value3, ...);
*In the second syntax, make sure the order of the values is in the same order
as the columns in
the table.
Ex
● INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode,
Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006',
'Norway');

NULL Value:
It is not possible to test for NULL values with comparison
operators, such as =, <, or <>.
We will have to use the IS NULL and IS NOT NULL operators
instead.
Syntax
● SELECT column_names
FROM table_name
WHERE column_name IS NULL;
● SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;
Ex
● SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL

Notes Page 31
Ex
● SELECT CustomerName, ContactName, Address
FROM Customers
WHERE Address IS NULL

UPDATE:
The UPDATE statement is used to modify the existing records in a
table.
Syntax
● UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Ex
● UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;

DELETE:
The DELETE statement is used to delete existing records
in a table.
Syntax
● DELETE FROM table_name WHERE condition;
● DELETE FROM table_name;
In 2nd syntax, all rows are deleted. The table structure,
attributes, and indexes will be intact
Ex
● DELETE FROM Customers WHERE Customer
Name='Alfreds Futterkiste';

SELECT TOP:
The SELECT TOP clause is used to specify the number of
records to return.
Syntax
● SELECT TOP number| percent column_name(s)
FROM table_name
WHERE condition;
● SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
● SELECT column_name(s)
FROM table_name
ORDER BY column_name(s)
FETCH FIRST number ROWS ONLY;
● SELECT column_name(s)
FROM table_name
WHERE ROWNUM<=number;
*In case the interviewer asks other than the TOP, rest are also
correct. (Diff. DB Systems)
Ex
● SELECT TOP 3 * FROM Customers;
● SELECT * FROM Customers

Notes Page 32
● SELECT * FROM Customers
LIMIT 3;
● SELECT * FROM Customers
FETCH FIRST 3 ROWS ONLY;
• Select * from Customers
Where rownum<=3;
Aggregate Functions:
MIN():
The MIN() function returns the smallest value of the selected column.
Syntax
● SELECT MIN(column_name)
FROM table_name
WHERE condition;
Ex
● SELECT MIN(Price) AS SmallestPrice
FROM Products;
MAX():
The MAX() function returns the largest value of the selected column.
Syntax
● SELECT MAX(column_name)
FROM table_name
WHERE condition;
Ex
● SELECT MAX(Price) AS LargestPrice
FROM Products;
COUNT():
The COUNT() function returns the number of rows that matches a
specified criterion.
Syntax
● SELECT COUNT(column_name)
FROM table_name
WHERE condition;
Ex
● SELECT COUNT(ProductID)
FROM Products;
AVG():
The AVG() function returns the average value of a numeric column.
Syntax
● SELECT AVG(column_name)
FROM table_name
WHERE condition;
Ex
● SELECT AVG(Price)
FROM Products;
SUM():
The SUM() function returns the total sum of a numeric column.
Syntax
● SELECT SUM(column_name)
FROM table_name
WHERE condition;
Ex
● SELECT SUM(Quantity)
FROM OrderDetails;

LIKE Operator:
The LIKE operator is used in a WHERE clause to search for a
specified pattern in a column.
There are two wildcards often used in conjunction with the
LIKE operator:
● The percent sign (%) represents zero, one, or multiple
characters
● The underscore sign (_) represents one, single character
Syntax
● SELECT column1, column2, ...
FROM table_name
WHERE column LIKE pattern;

Notes Page 33
IN Operator :
The IN operator allows you to specify multiple values in a
WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
Syntax
● SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
● SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Ex
● SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
● SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM
Suppliers);

BETWEEN:
The BETWEEN operator selects values within a given range. The
values can be numbers, text, or
dates.
The BETWEEN operator is inclusive: begin and end values are
included.
Syntax
● SELECT column_name(s)

Notes Page 34
The BETWEEN operator is inclusive: begin and end values are
included.
Syntax
● SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Ex
● SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;

Joins:
A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.
INNER JOIN:
The INNER JOIN keyword selects records that have matching values in both
tables.
Syntax
● SELECT column_name(s)
FROMtable1
INNER JOIN table2
ONtable1.column_name = table2.column_name;
Ex
● SELECT [Link], [Link]
FROM Orders
INNER JOIN Customers ON [Link] =
[Link]

LEFT (OUTER) JOIN:


The LEFT JOIN keyword returns all records from the left table
(table1), and the matching records
from the right table (table2). The result is 0 records from the
right side, if there is no match.
Syntax
● SELECT column_name(s)
FROMtable1
LEFT JOIN table2
ONtable1.column_name = table2.column_name;
Ex
● SELECT [Link], [Link]
FROMCustomers
LEFT JOIN Orders ON [Link] =
[Link]
ORDER [Link];

RIGHT (OUTER) JOIN:


The RIGHT JOIN keyword returns all records from the right table
(table2), and the matching records from the left table (table1).
The result is 0 records from the left side, if there is no match.
Syntax
●SELECT column_name(s)

Notes Page 35
(table2), and the matching records from the left table (table1).
The result is 0 records from the left side, if there is no match.
Syntax
●SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ONtable1.column_name = table2.column_name;
Ex
● SELECT [Link], [Link], [Link]
FROM Orders.
RIGHT JOIN Employees ON [Link] =
[Link]
ORDER BY [Link];

FULL (OUTER) JOIN :


The FULL OUTER JOIN keyword returns all records when
there is a match in left (table1) or right(table2) table records.
Syntax:
● SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ONtable1.column_name = table2.column_name
WHERE condition;
Ex
● SELECT [Link], [Link]
FROM Customers
FULL OUTER JOIN Orders ON
[Link]=[Link]
ORDER BY [Link];

UNION:
The UNION operator is used to combine the result-set of two or
more SELECT statements.
● Every SELECT statement within UNION must have the same
number of columns
● The columns must also have similar data types
● The columns in every SELECT statement must also be in the
same order
The UNION operator selects only distinct values by default. To
allow duplicate values,
use UNION ALL
Syntax
● SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
● SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
Ex
● SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;

GROUP BY :
The GROUP BY statement groups rows that have the same
values into summary rows, like "find the number of
customers in each country".
The GROUP BY statement is often used with aggregate
functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to
group the result-set by one or more columns.
Syntax :
● SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Ex
Notes Page 36
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Ex
● SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

HAVING:
The HAVING clause was added to SQL because the
WHERE keyword cannot be used with
aggregate functions.
*WHERE is given priority over HAVING.
Syntax
● SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Ex
● SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

CREATE DATABASE:
The CREATE DATABASE statement is used to create a new SQL
database.
Syntax
● CREATE DATABASE databasename;

DROPDATABASE:
The DROPDATABASE statement is used to drop an existing SQL
database.
Syntax
● DROP DATABASE databasename;

CREATE TABLE:
The CREATE TABLE statement is used to create a new table in a
database.
Syntax
● CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

DROPTABLE:
The DROPTABLE statement is used to drop an existing table in a
database.
Syntax
● DROP TABLE table_name;

TRUNCATE TABLE:
The TRUNCATE TABLE statement is used to delete
the data inside a table, but not the table itself.
Syntax
Notes Page 37
Syntax
● TRUNCATETABLE table_name;

ALTER TABLE:
The ALTER TABLE statement is used to add, delete, or modify
columns in an existing table.
The ALTER TABLE statement is also used to add and drop
various constraints on an existing
table.
Syntax
● ALTER TABLE table_name
ADD column_name datatype;
● ALTER TABLE table_name
DROP COLUMN column_name;
● ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Ex
● ALTER TABLE Customers
ADD Email varchar(255);
● ALTER TABLE Customers
DROP COLUMN Email;

● ALTER TABLE Persons


ALTER COLUMN DateOfBirth year

Notes Page 38
SQL(Qs)
13 November 2024 09:24

Notes Page 39
3. GROUP BY and COUNT
Question: Find the number of employees in each
department

Notes Page 40
4. ORDER BY
Question: Retrieve the names and salaries
of employees, ordered by salary in
descending order.

5. DISTINCT
Question: Get a list of unique job titles from the Employees table.

Notes Page 41
Update:

Delete:

SubQuery:

Having Clause :

Notes Page 42
Self Join :

Inner Join Vs Left Join :

Notes Page 43
Aggregate Functions : (Sum,Avg,min,max)

Notes Page 44
Notes Page 45
Networking
14 November 2024 19:08

What is a Network? • Networking is the practice of connecting two or more


• Answer: A network is a group of two or more devices linked together to computing devices together to share resources, exchange
share resources, exchange data, and communicate. data, and communicate.
• It enables devices like computers, servers, and printers to
interact over a network using established protocols.

1-3 NETWORK TOPOLOGIES


1.4 Categories of Topology
Network topology refers to the arrangement of devices and communication links
within a network. Here are some common categories of network topologies:

High redundancy means that a system can continue to operate


even when some components fail, with only a minor effect on
Fully Connected Mesh Topology: the overall system. This is achieved by duplicating critical
○ All devices are directly connected to every other device. components or systems, such as hardware, networks, power,
○ High redundancy and fault tolerance. and applications
○ Complex and expensive to implement.
Fault tolerance is the ability of a system to keep operating even
○ !Figure 1.5: Fully connected mesh topology (five devices) when there is a failure or malfunction in one or more of its
components. It's a key concept in ensuring that systems are
dependable and available, even when there are disruptions like
security incidents or service outages.

Star Topology:
○ All devices connect to a central hub.
○ If the central device is damaged, then the whole network fails.
○ Easy to manage and troubleshoot.
○ Hub acts as a single point of failure.
○ !Figure 1.6: Star topology connecting four stations

Bus Topology:
○ Devices are connected in a linear fashion along a single communication
channel (the bus).
○ As if the bus is damaged then the whole network fails.
○ Simple and cost-effective.
○ Allowing cable failures.
○ !Figure 1.7: Bus topology connecting three stations

Ring Topology:
○ Each device is connected to exactly two other devices and forms a closed
loop.
○ Data travels in one direction around the ring.
○ Difficult to troubleshoot and expand.
○ !Figure 1.8: Ring topology connecting six stations

Hybrid Topology:

Notes Page 46
Hybrid Topology:
○ Combines elements of different topologies (e.g., star backbone with bus
networks).
○ Offers flexibility and scalability.
○ !Figure 1.9: Hybrid topology with a star backbone and three bus networks

Remember, understanding network topologies helps in designing efficient and


reliable communication networks!

Different Types of Networks : (Imp) - Networks can be divided on the basis of area of
distribution. For example:
● PAN (Personal Area Network): Its range limit is up to 10 meters. It is created for
personal use. Generally, personal devices are connected to this network. For
example computers, telephones, fax, printers, etc.
● LAN (Local Area Network): It is used for a small geographical location like office,
hospital, school, etc.
● HAN (House Area Network): It is actually a LAN that is used within a house
and used to connect homely devices like personal computers, phones, printers,
etc.
● CAN (Campus Area Network): It is a connection of devices within a campus
area which links to other departments of the organization within the same
campus.
● MAN (Metropolitan Area Network ):It is used to connect the devices which span
to large cities like metropolitan cities over a wide geographical area.
● WAN (Wide Area Network): It is used over a wide geographical location that may
range to connect cities and countries.
● GAN (Global Area Network): It uses satellites to connect devices over the global
area
VPN (Virtual Private Network) : VPN or the Virtual Private Network is a private WAN
(Wide Area Network) built on the internet.
• It allows the creation of a secured tunnel (protected network) between different networks
using the internet (public network).
• By using the VPN, a client can connect to the organization’s network remotely.
● Advantages of VPN :
1. VPN is used to connect offices in different geographical locations remotely and is
cheaper when compared to WAN connections.
2. VPN is used for secure transactions and confidential data transfer between
multiple offices located in different geographical locations.
3. VPN keeps an organization’s information secured against any potential threats by using
virtualization.
4. VPN encrypts the internet traffic.
● Types of VPN:
● Access VPN: Access VPN is used to provide connectivity to remote mobile users and
telecommuters. It serves as an alternative to dial-up connections or ISDN (Integrated
Services Digital Network) connections. It is a low-cost solution and provides a wide
range of connectivity.
● Site-to-Site VPN: A Site-to-Site or Router-to-Router VPN is commonly used in large
companies having branches in different locations to connect the network of one office to
another in different locations. There are 2 sub-categories as mentioned below:
○ Intranet VPN: Intranet VPN is useful for connecting remote offices in different
geographical locations using shared infrastructure (internet connectivity and servers)
with the same accessibility policies as a private WAN (wide area network)
○ Extranet VPN: Extranet VPN uses shared infrastructure over an intranet, suppliers,
customers, partners, and other entities and connects them using dedicated connections.

Differences between IPv4 and IPv6:


1. Address Length:
○ IPv4: 32-bit address, supports around 4.3 billion unique addresses
(e.g., [Link]).
○ IPv6: 128-bit address, provides approximately 340 undecillion addresses
(e.g., 2001:0db8:85a3:0000:0000:8a2e:0370:7334).
2. Address Format:
IPv4: Decimal format, separated by periods.

Notes Page 47
○ IPv4: Decimal format, separated by periods.
○ IPv6: Hexadecimal format, separated by colons.
3. Header Complexity:
○ IPv4: complex with 12 header fields.
○ IPv6: Simplified with 8 header fields, improving performance.
4. Security:
○ IPv4: Security depends on external solutions (e.g., IPSec).
○ IPv6: IPSec is built-in for encryption and authentication.
5. Fragmentation:
○ IPv4: Performed by sender and routers.
○ IPv6: Only sender performs fragmentation, reducing router load.
6. Broadcasting vs. Multicasting:
○ IPv4: Uses broadcasting.
○ IPv6: Uses multicasting; no broadcasting, improving efficiency.
These differences show IPv6's enhancements over IPv4 in scalability, security, and
performance, making it more suitable for the growing internet.

1. Routing Efficiency:
○ IPv6: Has a simpler, more streamlined header structure, which speeds up
processing and improves efficiency in routing.
○ IPv4: Slightly slower in comparison due to a more complex header, which
requires more processing power from routers.
2. Network Speed:
○ IPv6: Generally faster in theory because of the simplified header and lack of
NAT (Network Address Translation), which reduces processing time and
overhead.
○ IPv4: Relies on NAT to accommodate the limited address space, which can
introduce latency and slow down data transmission.
3. Address Configuration:
○ IPv6: Supports auto-configuration (stateless address auto-configuration or
SLAAC), allowing devices to automatically obtain IP addresses, which can
reduce setup times and improve connection times.
○ IPv4: Typically requires either manual configuration or relies on DHCP, which
can be slower and more complex for large networks.
4. Security and Packet Processing:
○ IPv6: Inbuilt IPsec, which helps to encryption and secure data transfer
○ IPv4: Requires external IPsec configuration, which can add complexity and
slight delays in secure transmissions.
5. Multicasting Efficiency:
○ IPv6: Supports efficient multicasting (sending data to multiple destinations),
which can improve network performance in applications like video streaming
and conferencing.
○ IPv4: Uses broadcasting, which is less efficient as it sends packets to all nodes
in the network, potentially causing congestion.
Overall Summary: IPv6 provides performance improvements over IPv4, especially in
terms of routing speed, security handling, and connection configuration, which can
make it better suited for modern high-traffic networks.

2. Explain the OSI Model and its layers.


• Answer: The OSI (Open Systems Interconnection) model is a framework
used to understand and implement network communication in seven
layers:
1. Physical Layer – Transmits raw bit streams.
2. Data Link Layer – Manages node-to-node data transfer and error
checking.
3. Network Layer – Manages data routing and packet forwarding.
4. Transport Layer – Ensures reliable data transmission.
5. Session Layer – Manages sessions between applications.
6. Presentation Layer – Translates, compresses, and encrypts data.
7. Application Layer – Interface for end-user applications.

The OSI Model


The Open Systems Interconnection (OSI) model, developed by the
International Standards Organization (ISO) in 1984.
The OSI model divides the Networking into seven layers.
Each layer has its own functionalities.

Notes Page 48
1. Physical Layer (Layer 1)
• The Physical layer is responsible for the actual bits transfer between devices.
• It Transmits actual bits from one node to the another node.
• Functions:
○ Bit synchronization
○ Bit rate control

2. Data Link Layer (Layer 2)


• The Data Link layer is responsible for Frame Creation and error free data transfer.
• It is also responsible for Error Detection and Correction.
• Functions:
○ Frame creation and transmission.
○ Error detection and correction.

3. Network Layer (Layer 3)


• The Network layer is Responsible for routing and forwarding data packets.
• Determines the best path for data transmission.
• Functions:
○ Routing decisions.
○ Packet forwarding.

4. Transport Layer (Layer 4)


• The transport layer is responsible for the delivery of a message from one process
to another.
• Segments data into smaller units (segments).
• Functions:
○ Flow control.
○ Segmentation.

5. Session Layer (Layer 5)


• The main responsibility of the session layer is beginning, maintaining and ending
the communication between the devices
• Establish sessions between devices.
• Functions:
○ Session establishment.
○ Session termination.

6. Presentation Layer (Layer 6)


• The Presentation layer is responsible for:
○ Data translation.
○ Data compression

7. Application Layer (Layer 7)


• The Application layer Provides network services directly to end-users and
applications.
• Functions:
○ User authentication.
○ File transfer.
Remember, the OSI model serves as a universal language for computer networking,
allowing devices and software from different vendors to communicate effectively!

Notes Page 49
TCP/IP Model
The TCP/IP model is widely used in real-world networking. It
consists of four layers:
1. Network Interface Layer: responsible for physical
transmission of data over a network.
2. Internet Layer: responsible routing of data packets across
the network.
3. Transport Layer: Ensures reliable data transmission
between devices, using protocols like TCP and UDP.
4. Application Layer: Provides protocols for specific data
communication services on a process-to-process level, such
as HTTP, FTP, and SMTP.

HTTP:
1. HTTP is the Hyper Text Transfer Protocol which defines the set of
rules and standards on how the information can be transmitted on
the World Wide Web (WWW).
2. It helps the web browsers and web servers for communication.
3. It is a ‘stateless protocol’ where each command is independent
with respect to the previous command.
HTTPS :
1. HTTPS (Hyper Text Transfer Protocol Secure) adds a layer of
security with SSL/TLS encryption.
2. It enables secure transactions by encrypting the communication.

DNS (Imp):
1. DNS is an acronym that stands for Domain Name System. DNS was introduced
by Paul Mockapetris and Jon Postel in 1983.
2. It is a naming system for all the resources over the internet which includes
physical nodes and applications. It is used to locate resources easily over a
network.
3. DNS is an internet which maps the domain names to their associated IP
addresses.
4. Without DNS, users must know the IP address of the web page that you wanted
to access.

● Working of DNS (Imp): If you want to visit the website of "shaurya", then the user will
type "[Link] into the address bar of the web browser. Once the
domain name is entered, then the domain name system will translate the domain name
into the IP address which can be easily interpreted by the computer. Using the IP
address, the computer can locate the web page requested by the user.
● DNS Forwarder : A forwarder is used with a DNS server when it receives DNS queries
that cannot be resolved quickly. So it forwards those requests to external DNS servers
for resolution. A DNS server which is configured as a forwarder will behave differently
than the DNS server which is not configured as a forwarder.

DNS stands for Domain Name System, which is a system that


translates domain names into IP addresses:
• Domain names: Human-readable names, such as "[Link]"
• IP addresses: Machine-readable addresses, such as "[Link]"
DNS works like a phone book, allowing users to search for a
website by its name and retrieve the corresponding IP address:
Working Of DNS:

Notes Page 50
DNS works like a phone book, allowing users to search for a
website by its name and retrieve the corresponding IP address:
Working Of DNS:
1. A user enters a domain name into their browser, such as
"[Link]"
2. A DNS server finds the correct IP address for that site.
3. The browser uses that IP address to communicate with the website's
origin servers.
DNS is essential for web browsing and most other internet
activities. Without DNS, users would need to remember the IP
address for each website they visit.
DNS Forwarder forwards the DNS Queries to another DNS server
when it is not responds quickly for DNS Queries.

Difference Between TCP (Transmission Control Protocol) and UDP


(User Datagram Protocol):
TCP (Transmission Control Protocol) is a connection-oriented
protocol that ensures reliable data transmission with error checking
and acknowledgments.
UDP (User Datagram Protocol) is connectionless protocol.
It is faster, and suitable for applications that don’t need reliability,
like streaming.

SMTP Protocol : SMTP stands for Simple Mail Transfer Protocol, which is
a communication protocol that allows users to send and receive emails
over the internet.

FTP: FTP is a File Transfer Protocol. It is an application layer protocol used to transfer
files and data reliably and efficiently between hosts.

DHCP: DHCP is the Dynamic Host Configuration Protocol. It is an application layer


protocol used to automatically assigns IP addresses to devices on a network, reducing
the need for manual configuration.

22. What is ARP, and how does it work?


• Answer: ARP (Address Resolution Protocol) resolves IP addresses to MAC addresses. When
a device knows another device's IP address but not its MAC address, it uses ARP to find the
MAC address by broadcasting a request to the network.
RIP:RIP stands for Routing Information Protocol. It is accessed by the routers to
send data from one network to another.

• MAC Address: A hardware-based physical address that uniquely


identifies a device on a local network. It is provided by the NIC
(Network Interface Card) manufacturer.(Nearby Share)
• IP Address: A logical address assigned by the Internet Service
Provider (ISP) to identify a device's connection on a network,
primarily used for routing and transmitting data packets over the
internet.

Notes Page 51
internet.

Ipconfig and Ifconfig :


1. Ipconfig : Internet Protocol Configuration, It is a command used in
Microsoft operating systems to view and configure network interfaces

2. Ifconfig : Interface Configuration, It is a command used in MAC, Linux,


UNIX operating systems to view and configure network interfaces

Firewall :
1. The firewall is a network security system that is used to monitor the
incoming and outgoing traffic and blocks them based on the firewall
security policies.
2. It acts as a wall between the internet (public network) and the
networking devices (a private network).
a. It is either a hardware device, software program, or a combination
of both.
3. It adds a layer of security to the network.

1. What happens when you enter [Link] in the web browser? (Most Imp)
Steps :
1. Check the browser cache first if the content is fresh and present in the cache
display the same.
2. If not, the browser checks if the IP of the URL is present in the cache (browser
and OS)
3. if not then requests the OS to do a DNS lookup using UDP to get the
corresponding IP address of the URL from the DNS server to establish a new TCP
connection.
4. A new TCP connection is set between the browser and the server using three-way
handshaking.
5. An HTTP request is sent to the server using the TCP connection.
6. The web servers running on the Servers handle the incoming HTTP request and
send the HTTP response.
7. If the response data is cacheable then browsers cache the same.
8. If not The browser processes the HTTP response sent by the server and may close
the TCP connection or reuse the same for future requests.

Hub: Hub is a networking device which is used to transmit the signal to each port
(except one port) to respond from which the signal was received.
Hub is operated on a Physical layer. In this packet filtering is not available. • A switch intelligently sends data packets to
It is of two types: specific devices based on MAC addresses,
a. Active Hub: amplifies the incoming signals and improves the signal strength optimizing network performance and reducing
to reach long distance before transmission of data. collisions.
b. Passive Hub: transmits the data with same signal strength, used for short • A hub broadcasts data to all devices on the
distance data transmission. network, leading to potential network
Switch: Switch is a network device which is used to enable the connection
congestion.
establishment and connection termination on the basis of need. Switch is operated
on the Data link layer. In this packet filtering is available.

Subnetting : subnetting is a process of divide a network into subnets.


It is used for getting a higher routing efficiency and enhances the
security of the network.

Notes Page 52
security of the network.

4. The reliability of a network can be measured by the following factors:


● Downtime: The downtime is defined as the required time to recover.
● Failure Frequency: It is the frequency when it fails to work the way it is
expected.
● Catastrophe: It indicates that the network has been attacked by some
unexpected event such as fire, earthquake.

6. Node and Link : A network is a connection setup of two or more computers directly
connected by some physical mediums like optical fiber or coaxial cable. This physical
medium of connection is known as a link, and the computers that it is connected to are
known as nodes.

7. Gateway and router : A node that is connected to two or more networks is commonly
known as a gateway. It is also known as a router. It is used to forward messages from
one network to another.
Differences between gateway and router: A router sends the data between
two similar networks while gateway sends the data between two dissimilar networks.

NIC (Imp) : NIC stands for Network Interface Card. It is attached to the PC to
connect to a network.
Every NIC has its own MAC address that identifies the PC on the network.
It provides a wireless connection to a local area network (LAN).

9. POP3 stands for Post Office Protocol version3:


POP is responsible for accessing the mail service on a client
machine.
POP3 works on two models such as Delete mode and
Keep mode

11. RAID ( Redundant Array of Inexpensive/Independent Disks):


It is used to store the same data redundantly(duplicate) to improve
the overall performance.

P2p: The processes on each machine that communicate at a


given layer are called peer-peer processes. (P2P)

15. Unicasting: If the message is sent to a single node from the source
then it is known as unicasting. This is commonly used in networks to
establish a new connection.
Anycasting: If the message is sent to any of the nodes from the source
then it is known as any casting. It is mainly used to get the content from
any of the servers in the Content Delivery System.
Multicasting: If the message is sent to a subset of nodes from the
source then it is known as multicasting. Used to send the same data to
multiple receivers.

Notes Page 53
multiple receivers.
Broadcasting: If the message is sent to all the nodes in a network from
a source then it is known as broadcasting. DHCP and ARP in the local
network use broadcasting.

12. What is Bandwidth?


• Answer: Bandwidth is the maximum rate of data transfer across a network
or internet connection, usually measured in bits per second (bps). It
indicates the capacity of a network connection.

Explain the concept of a Three-Way Handshake in TCP.


• Answer: A three-way handshake is a process in TCP used to establish a
reliable connection between a client and server. It involves three steps:
1. SYN: The client sends a SYN (synchronize) packet to start a
connection.
2. SYN-ACK: The server responds with a SYN-ACK packet.
3. ACK: The client sends an ACK packet, confirming the connection.

• Explain NAT and its purpose.


• Answer: NAT (Network Address Translation) translates private IP addresses
within a local network to a single public IP address, allowing multiple devices to
share one IP address for internet access and conserving the limited IPv4
addresses.

9. What is a Proxy Server, and what are its functions?


• Answer: A proxy server acts as an intermediary between a client and the
internet, providing functions like content filtering, increased security,
caching for faster access, and hiding the client's IP address.

25. What is the purpose of the ping command?


• Answer: The ping command is used to tests the reachability of a host on
a [Link] helps in diagnosing connectivity issues.

Notes Page 54
Operating System
15 November 2024 18:41

1. What is an Operating System?


• Answer: An Operating System (OS) is system software that manages hardware resources
and provides services for application programs. It acts as an intermediary between users
and the computer hardware, enabling efficient and secure system operation.

Types of Operating Systems (Interview Perspective)


1. Batch OS:
○ Executes similar jobs in batches.
○ The CPU is assigned a job only after the previous one completes.
○ Suitable for non-interactive processes (e.g., payroll processing).
2. Multiprogramming OS:
○ Multiple jobs are loaded into memory.
○ Efficient utilization of CPU by switching to another job during I/O operations.
○ Provides the illusion of simultaneous job execution.
3. Multitasking OS:
○ Extends multiprogramming with rapid switching between tasks.
○ Users can interact with multiple programs simultaneously.
○ Example: Modern desktop operating systems like Windows and macOS.
4. Time-Sharing OS:
○ Allows multiple users to interact with the system by sharing CPU time in small intervals.
○ Used in systems requiring user interactions like ticket booking systems.
5. Real-Time OS:
○ Designed for time-critical applications where tasks must be completed within specific
deadlines.
Key Interview Tip: Be ready to provide examples of where each type of OS is used and highlight
their real-world applications.

2. What are the main functions of an Operating System?


• Answer: Key functions include:
○ Process Management: Handling processes in the system, including creation,
scheduling, and termination.
○ Memory Management: Allocating and managing system memory among
processes.
○ File System Management: Managing data storage, retrieval, and updates on
storage devices.
○ Device Management: Controlling input/output devices.
○ Security and Access Control: Protecting system resources and ensuring
authorized access.

Process and Process Scheduling (Interview Perspective)


1. Process:
○ A process is a program in execution, managed by the operating system.
○ The Program Counter (PC) holds the address of the next instruction to execute.
▪ Each process is uniquely represented by a Process Control Block (PCB)
containing details like process ID, state, PC, etc.

Process Scheduling Metrics


1. Arrival Time:
○ The time when a process enters the ready queue.
2. Completion Time:
○ The time when the process completes its execution.
3. Burst Time:
○ The total time required by a process for CPU execution.
4. Turnaround Time (TAT):
○ Total time taken for a process to finish, calculated as:
TAT = Completion Time - Arrival Time
5. Waiting Time (WT):
○ The time a process spends waiting in the ready queue, calculated as:
WT = Turnaround Time - Burst Time

Thread
• Definition: A thread is a lightweight sub-unit of a process and is the
smallest unit of CPU utilization.
• Purpose: Threads allow a process to perform multiple tasks
simultaneously.

Notes Page 55
simultaneously.
Key Characteristics of Threads
1. Independent Resources: Each thread has its own program counter,
register set, and stack.
2. Shared Resources: Threads within the same process share resources like
the code section, data section and files.
Key Points for Interview
• ADV: Threads enable multithreading, which allows for parallel execution
within a single process.

1. First Come First Serve (FCFS):


a. Description: Processes are scheduled based on their arrival times; the first to
arrive is executed first.
2. Shortest Job First (SJF):
starvation(waiting for CPU utilization for long time)
a. Description: Processes with the shortest burst time are scheduled first.
b. Key Point: Optimal in minimizing average waiting time but can cause
starvation for longer processes.
3. Shortest Remaining Time First (SRTF):
a. Description: Preemptive version of SJF; if a new process with a shorter burst
time arrives, the current process is preempted to execute that process.
b. Key Point: Improves responsiveness but increases context switching
overhead.
4. Round Robin (RR) Scheduling:
a. Description: Each process is assigned a fixed time (quantum) and scheduled
cyclically.
b. Key Point: Fair and suitable for time-sharing systems, but performance
depends on the quantum size.
5. Priority-Based Scheduling (Non-Preemptive):
a. Description: Processes are scheduled according to their priority (higher
priority executes first). If priorities match, arrival time decides.
b. Key Point: Risk of starvation for lower-priority processes.

Critical Section Problem: Interview Perspective


The Critical Section Problem occurs in concurrent processes when multiple processes Ex: Banking System;
access and update shared resources. This leads to unexpected outputs if not properly
managed.
Key Concepts:
1. Critical Section: The code segment where shared variables are accessed/updated.
2. Remainder Section: The part of the program excluding the critical section.
3. Race Condition: The final output depends on the sequence in which processes
access shared resources.
Conditions for a Solution:
1. Mutual Exclusion: Only one process can execute in its critical section at any given
time.
2. Progress: If no process is in the critical section, the decision to allow a process to
enter cannot be indefinitely delayed.
3. Bounded Waiting: There exists a bound waiting time for other processes to access
the critical section and before the request is granted.
Why It’s Important:
Efficient handling of the critical section ensures data consistency and avoids deadlock or
starvation in multi-threaded or multi-process environments.

Notes Page 56
Synchronization Tools:
Synchronization tools ensure proper coordination among concurrent processes
to access shared resources safely.
1. Semaphore:
Semaphore is a protected variable that is
used to lock the resource being used(0 or 1).
○ Types:
▪ Binary Semaphore:
□ Takes values 0 or 1.
□ Ensures mutual exclusion and synchronizes concurrent
processes.
▪ Counting Semaphore:
□ An integer variable with a range used for managing multiple
instances of a resource.
2. Mutex (Mutual Exclusion):
○ A lock mechanism allowing only one thread to access a shared resource
at a time.
○ Works like a key:
▪ Producer must release the lock for the consumer to proceed, and
vice versa.
▪ Ensures no simultaneous access to shared resources like buffers.
Importance in Interviews:
Understanding semaphores and mutexes is crucial for solving problems like
producer-consumer, dining philosophers, and thread synchronization in
operating systems.

Deadlocks:
Definition:
A deadlock occurs when a set of processes is blocked because each is holding a resource and
waiting for another resource which was held by another process.
Necessary Conditions for Deadlock:
1. Mutual Exclusion:
○ At least one resource is non-shareable (used by only one process at a time).
2. Hold and Wait:
○ A process is holding at least one resource and waiting for others.
3. No Preemption:
○ Resources cannot be forcibly taken from a process; they must be released voluntarily.
4. Circular Wait:
○ A circular chain exists where each process waits for a resource held by the next process in
the chain.
Methods to Handle Deadlocks:
1. Prevention or Avoidance:
○ Ensure the system never enters a deadlock state by designing protocols to prevent one or
more necessary conditions.
○ Example: Banker's algorithm for resource allocation.
2. Detection and Recovery:
○ Allow deadlocks to occur and then detect them. Recover by pre-emiting resources or
terminating processes.
3. Ignoring the Problem:
○ If deadlocks are rare, let them happen and resolve by rebooting.
○ Widely used in practice (e.g., Windows and UNIX systems).
Key Takeaway:
Explain deadlocks clearly, highlight their conditions, and emphasize the practicality of different
handling strategies during interviews.

Banker's Algorithm:
Definition:
The Banker's Algorithm is a deadlock-avoidance technique. It Prevents deadlocks by
ensuring that resources are not allocated in a way that could lead to an unsafe state.

Notes Page 57
External Fragmentation & Solutions:
What Causes External Fragmentation?
• Occurs in Fixed Partitioning and Variable Partitioning when processes require
contiguous memory allocation, leaving unusable gaps in memory.
Solutions to External Fragmentation: Memory Managements
1. Paging:
○ Divides physical memory into fixed-sized frames and logical memory into
pages of the same size.
○ Pages map to frames, allowing non-contiguous allocation and eliminating
external fragmentation.
2. Segmentation:
○ Divides memory into segments based on logical units (e.g., functions,
arrays).
○ Provides a user-friendly view of memory and allows non-contiguous
allocation.
Key Takeaway:
Paging and segmentation are efficient memory management techniques that
address the limitations of contiguous allocation and minimize fragmentation.

Page Fault and Page Replacement Algorithms

Page Fault:
A page fault is a type of interrupt triggered by the hardware when a running
program accesses a memory page that is not available in the physical
memory which was mapped in the virtual memory.

Page Replacement Algorithms:


1. First In First Out (FIFO):
○ The simplest page replacement algorithm.
○ The OS maintains a queue of all pages in memory. The oldest page
(front of the queue) is removed first when a new page needs to be
loaded.
Example:
○ Page Reference String: 1, 3, 0, 3, 5, 6
○ Page Slots: 3
○ Process:
▪ Pages 1, 3, 0 are loaded: 3 page faults.
▪ Page 3 is already in memory: 0 page faults.
▪ Page 5 replaces the oldest page (1): 1 page fault.
▪ Page 6 replaces the oldest page (3): 1 page fault.
○ Total Page Faults: 5
Belady’s Anomaly:
○ This anomaly shows that increasing the number of page frames can
lead to more page faults in FIFO.
○ Example Reference String: 3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4
○ With 3 Slots: 9 page faults.
○ With 4 Slots: 10 page faults.

2. Optimal Page Replacement:


○ Replaces the page that will not be used for the longest time in the
future.
○ It is the best algorithm but impractical, as the future page reference
sequence is unknown.
○ Used as a benchmark for comparing other algorithms.
Example:
○ Page Reference String: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2
○ Page Slots: 4
○ Process:
▪ Pages 7, 0, 1, 2 are loaded: 4 page faults.
▪ Page 0 is already in memory: 0 page faults.
▪ Page 3 replaces 7 (not used for the longest time): 1 page fault.
▪ Page 4 replaces 1: 1 page fault.
▪ Remaining pages are already in memory: 0 page faults.
○ Total Page Faults: 6

Notes Page 58
▪ Page 3 replaces 7 (not used for the longest time): 1 page fault.
▪ Page 4 replaces 1: 1 page fault.
▪ Remaining pages are already in memory: 0 page faults.
○ Total Page Faults: 6

3. Least Recently Used (LRU):


○ Replaces the page that was least recently used.
○ Tracks the recent usage of pages.
Example:
○ Page Reference String: 7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2
○ Page Slots: 4
○ Process:
▪ Pages 7, 0, 1, 2 are loaded: 4 page faults.
▪ Page 0 is already in memory: 0 page faults.
▪ Page 3 replaces 7 (least recently used): 1 page fault.
▪ Page 4 replaces 1: 1 page fault.
▪ Remaining pages are already in memory: 0 page faults.
○ Total Page Faults: 6

These algorithms play a critical role in optimizing memory utilization and


minimizing page faults in operating systems.

Disk Scheduling:
Disk Scheduling organizes I/O requests for efficient access to the disk and is crucial for
improving system performance.
Key Metrics:
1. Seek Time: Time to position the disk arm to the required track.
2. Rotational Latency: Time taken for the desired sector to align with the read/write
head.
3. Transfer Time: Time to transfer data, depending on disk rotation speed and data
size.
4. Disk Access Time:
○ Formula: Seek Time + Rotational Latency + Transfer Time.
5. Disk Response Time: Average time spent by requests waiting to perform I/O
operations.

Disk Scheduling Algorithms:


1. FCFS (First Come First Serve):
○ Processes the request in the order they arrive.
○ Pros: Simple and fair.
○ Cons: High seek time if requests are scattered.
2. SSTF (Shortest Seek Time First):
○ Processes the request closest to the current head position.
○ Pros: Reduces seek time compared to FCFS.
○ Cons: Can cause starvation for distant requests.
3. SCAN (Elevator Algorithm):
○ Disk arm moves in one direction, servicing requests and then moves in
reverse direction to service the remaining requests.
○ Pros: Fairer than SSTF; avoids starvation.
○ Cons: May lead to higher latency for edge requests.
4. CSCAN (Circular SCAN):
○ Similar to SCAN, the disk arm moves to one direction end and process the
requests and then returns to beginning of the disk to process the remaining
requests.
○ Pros: Uniform wait times.
○ Cons: Higher seek time for edge requests.
5. CLOOK (Circular LOOK):
○ The disc arm only goes as far as the last request in each direction, then jumps
to the first request.
○ Pros: Further reduces unnecessary traversal while maintaining fairness.

Key Takeaway: Understanding these algorithms is crucial for system optimization in


scenarios involving heavy disk I/O. SCAN, LOOK, and their variants are preferred for
balancing performance and fairness.

Notes Page 59
Technical Skills
16 November 2024 22:42

Notes Page 60
HTML
16 November 2024 22:42

Top 123 TCS Ninja Interview Questions and Answers 2024 - Page 2 | AmbitionBox

HTML Interview Questions


1. What is HTML?
○ HTML stands for Hyper Text Markup Language.
○ It is used to define the structure of the web pages using
elements and tags.

2. What are Semantic elements in HTML?

The Semantic elements in HTML are the elements that contain


content that is related to their names or reflects their names.
These are the some of semantic HTML elements are listed below:
• Header (contains Navbar)
• Main (contains main content)
• Section (one section in the web page)
• Footer (contains footer content like copy rights, Social media
links).

3. What are the Empty elements in HTML?

1. The empty elements in HTML are the elements that don’t


require a closing tag followed by the opening tag.
2. These elements are also known as self-closing elements.
Example: <img>, <input>, <br>, <hr> etc.
What are void elements in HTML?
• Void elements are self-closing tags that do not require a closing tag.

Examples:
○ <img>, <br>, <input>, <hr>.

4. Differentiate between the Inline and the Block elements in


HTML.

The Inline elements in HTML are the elements that do not start
from a new line every time and take up the same space and width
as acquired by the content. Examples:<span>, <a>, <strong>,
<img>, <input> etc.
The Block elements automatically starts from a new line and takes
up the whole view-port width irrespective of the contained content.
Examples: <div>, <h1> to <h6>, <p>, <table> etc.

5. What is list in HTML? Explain different types of list available


in HTML.

In HTML, the lists are used to represent a collection of different


items. There are two types of lists available in HTML as listed
below:
1. Unordered List: It is defined using the <ul> and the <li> tags. By
default, it represents the items with a bulleted dot.
<ul>
<li>List Item 1</li>
<li>List Item 3</li>
<li>List Item 3</li>
</ul>
2. Ordered List: It is defined using the <ol> and <li> tag. By
default, it represents the list items with numeric digits.
<ol>
<li>List Item 1</li>
<li>List Item 3</li>

Notes Page 61
<li>List Item 3</li>
<li>List Item 3</li>
</ol>

6. What is the basic structure of an HTML document?

The basic structure of an HTML document in HTML5 is shown below:


<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body></body>
</html>

7. Explain the elements used in the basic structure of an HTML


document.

The elements used in the basic structure of an HTML document are


explained below:
• <!DOCTYPE html>: It represents the HTML5 version of the HTML.
• <html>: It is the root element of the HTML document.
• <head>: It contains the meta data i.e. the data about the data. The
content contained by this tag is not visible on the web page.
• <title>: It contains the title of the document which will be visible in the
browser tab.
• <body>: It contains the content of the web page in the form of the HTML HTML Elements
The HTML element is everything from the start tag
tags like <div>, anchor<a>, paragraph<p>, headings<h1>, etc. to the end tag:
<tagname>Content goes
8. Explain tags in HTML. here...</tagname>
Examples of some HTML elements:
The HTML tags are used to define the elements on the web page. <h1>My First Heading</h1>
Basically, they are the keywords that are enclosed inside the angle <p>My first paragraph.</p>
brackets(<>). The examples of HTML tags are <div>, <p>, <a>, <span>,
<img> etc.

9. Why ‘alt’ attribute is used with the <img> tag in HTML?

The alt attrbute provides a alternative content that is related to the


image which will be shown on the web page if the image does not gets
loaded.

[Link] the difference between <div> and <span>.


○ <div>: A block-level element used to group larger sections of content.

○ <span>: An inline element used to style or manipulate small chunks of

content.

11. Why the <meta charset = “UTF-8”> tag is used?

It is used to set the character encoding of the charaters for the document
to UTF-8 to properly display the text and the special characters on the
web page.

[Link] is the purpose of the <meta> tag?


• The <meta> tag provides metadata about the HTML document.

Common uses:
○ Setting character encoding: <meta charset="UTF-8">.

○ Setting viewport for responsiveness:

<meta name="viewport" content="width=device-width,


initial-scale=1.0">.

12. What is the purpose of using the ‘role’ attribute in HTML?

The role attribute defines the functionality and the purpose of an


element mainly the accessibility. It provides the additional information
for the screen readers, to convey the exact meaning of the element to
the users with disabilities.
What are data attributes in HTML?
Notes Page 62
What are data attributes in HTML?
• Data attributes are custom attributes that store additional data

directly in HTML elements.


• Syntax:

<div data-id="123" data-role="user">John Doe</div>


• Access them via JavaScript:

const id = [Link]('div').[Link]; // "123"

13. Differentiate between the GET and the POST methods in HTML
forms.

The below table will explain the differences between the GET and
POST methods in HTML forms:

GET Method POST Method


It is a insecure way to send data It is a secure way of sending the form
on the server. data.
All the form data parameters None of the parameters are visible
are visible in the URL. anywhere.
[Link]
It has a URL length limit that It has a bigger URL length limit as
varies for different browsers. compare to the limit of the GET
method.
Results are cached by the Does not caches the responses in the
browser by default. browser by default.

14. What is the use of the <iframe> tag?

The <iframe> tag is used to embed the external documents or the web
pages inside the current document by specifying its link inside it. It is
mainly used to embed the external videos, maps and other external
content.

15. Explain the features of HTML5?

HTML5 introduced some new features that are listed below:


1. Introduced new semantic elements
like: <header>, <footer>, <nav>, <aside>, <article>, <section> etc.
2. New form input types such as email, url, number, date, etc.
3. It introduced the <audio> and <video> tags to embed audios and
videos and reduces the dependence on the third party libraries.
4. <canvas> element to draw graphics and animations using JavaScript.
5. Introduces the browser storage
as localStorage and sessionStorage to store data in the browser.

16. What is localStorage?

localStorage is a client-side web storage mechanism that Stores data with


no expiration time; data will be available even after the browser is
closed.

17. What is sessionStorage?

It is also a web storage API provided by the web browsers to Stores data
for the session; data is cleared when the browser is closed.

19. What is the purpose of using <figure> and <figcaption> elements


in HTML5?

The <figure> element is used to display the media content on the web
page like audios, videos etc. While, the <figcaption> element is used to
give a caption to the content shown by the <figure> element.

20. Write the HTML code to create a table with 3 columns and 3 rows.

The below code creates a table with 3 rows and 3 columns:

Notes Page 63
The below code creates a table with 3 rows and 3 columns:
<table border="1px">
<thead>
<tr>
<th>col 11</th>
<th>col 12</th>
<th>col 13</th>
</tr>
</thead>
<tbody>
<tr>
<td>col 21</td>
<td>col 22</td>
<td>col 23</td>
</tr>
<tr>
<td>col 31</td>
<td>col 32</td>
<td>col 33</td>
</tr>
</tbody>
</table>

21. How you can merge the rows and columns of a HTML table?

You can use the colspan and the rowspan attributes with
the <td> element and specify the number of rows and columns to be
merged by passing a numerical value to the defined attributes.
The colspan attribute can be used to merge columns while
the rowspan attribute to merge the rows.

1. How do you implement responsive design using HTML?


○ Use the <meta> viewport tag: <meta name="viewport"

content="width=device-width, initial-scale=1.0">.
○ Combine with CSS media queries to adjust layout for different screen

sizes.

Notes Page 64
sizes.
2. What is the difference between id and class attributes?
○ id: Used to uniquely identify a single element. It must be unique on

the page.
○ class: Used to apply styles or behaviors to multiple elements.

3. What is the difference between <link> and <script> tags?


• <link>: Links external resources like stylesheets and CDN links.

○ Example: <link rel="stylesheet" href="[Link]">.

• <script>: Embeds or links JavaScript code.

○ Example: <script src="[Link]"></script>.

4. What is the purpose of the <canvas> element?


• <canvas> is used to draw graphics on the web page via JavaScript,

such as charts, games, or animations.

5. How would you optimize an HTML page for SEO?


• Use semantic tags like <article>, <header>, <footer>.

• Include a descriptive <title> and <meta> description.

• Use proper heading hierarchy (<h1> to <h6>).

• Use alt attributes for images.

• Optimize URLs and include relevant keywords.

6. What are the different types of input fields in HTML forms?


• Common input types:

a. Text: <input type="text">


b. Password: <input type="password">
c. Email: <input type="email">
d. Number: <input type="number">
e. File upload: <input type="file">
f. Date: <input type="date">
g. Checkbox: <input type="checkbox">
h. Radio button: <input type="radio">

7. What are the differences between <b> and <strong>, and <i> and
<em>?
• <b> and <i>: Apply visual styling (bold and italic) without semantic

meaning.
• <strong> and <em>: Indicate importance or emphasis and also

provide semantic meaning.(doing same thing with semantic meaning)

8. What are HTML5 Web Storage APIs?


• APIs that allow storing key-value pairs in the browser:

○ localStorage: Persistent storage. Avails after we close and reopen

the browser.
○ sessionStorage: Temporary storage. Data is removed after we

close the browser.


○ Example:

9.

Notes Page 65
CSS
16 November 2024 23:10

23. What is CSS?


CSS, which stands for the Cascading Style Sheets. It helps to
design and style the web page to make it attractive for users.

24. Explain selectors in CSS.

In CSS, selectors are used to select elements and style the element by
providing CSS properties to it. Below is the list of some common CSS
selectors:
1. Element Selector: Select directly by using the name of the element.

2. ID Selector: Define ID attribute and select using the # prefix followed


by the value of ID attribute. Syntax:
3. Class Selector: Define Class attribute and select using the . prefix selector {
Property: value;
followed by the value of class attribute.
}
4. Universal Selector (*): Select using the * sign- used to apply CSS for
all elements.
5. Attribute Selector: Select the elements based on the attribute values.
Eg: input[type=”text”]{}
6. Direct Child Selector: Select element using any of the above selectors
and use > followed by direct child selector. Eg: parent > child{}
7. Pseudo Selectors: These are selectors like
:hover, :nth-child(), ::after, ::before etc.

25. Explain the precedence of the Class, Id and Element selectors in


CSS.

The precedence of the ID, Class and Element CSS selectors is shown
below:
• ID Selector > Class Selector > Element Selector
• ID Selector + Class Selector > ID Selector + Element Selector > Class
Selector + Element Selector

26. What are the best practices for using JavaScript and CSS?

The best practices for JavaScript and CSS can be defined according to the
project requirements. Below are some general best practices listed for
JavaScript and CSS:
• Always use an external file for defining the JavaScript and CSS
with .js and .css extensions respectively.
• Always link the CSS file inside the <head> tag of the HTML document.
• Always add the script file at the end of the <body> tag just before
where body closes.

27. What is difference between visibility: hidden and display: none


properties in CSS?

The visibility: hidden property only hides the content of the element on
which it is used. It does not removes the element from the document
and keep the space as it is so that no other element can replace it on the
UI. On the other hand, the
display: none property not only hides the element but removes it from
the document and the space acquired by the element is now free to be
acquired by the other elements.

28. Mention the issues faced by developers while running the CSS in
Internet Explorer (IE)?

Below list shows the issues faced by the developers in Internet Explorer:
• Transparency of the images with .png extension.
• Issues related to Z-index property.

Notes Page 66
Below list shows the issues faced by the developers in Internet Explorer:
• Transparency of the images with .png extension.
• Issues related to Z-index property.
• Sometimes, it doubles the margin added to an element.
• Box model has a different interpretation.
• Lack the support for the CSS3 Features.

29. Explain box-model in CSS.

The box model in CSS is basically a blue print of an element with some
properties. The box model contains four elements which are content,
padding, border and margin.
• Content: It can be the text content or the nested HTML elements
with some content inside a element.
• Padding: It is the space around the content of the element or the
space between the content and the borders.
• Border: This is the stroke or outline provided to the element to see
its boundaries or style it.
• Margin: It is the space around the whole element, it is the space
between the border of this element and other elements.

30. What is the purpose of z-index property in CSS?

The z-index property is used to control the stacking order of the


elements that are positioned using the position property in CSS. The
higher or the positive values will make the element appear on the top of
the other elements while the negative or the lower values make them
appear behind the elements with higher values.

31. What is the use of float property?

The float property specifies whether an element should float to the left,
right, or not at all. The possible values for this property are left, right,
initial, inherit, and none.

32. Explain different ways to display an element at the center of the


web page.

There are many ways to center a element on the web page as described
below:
• Using margin: The margin property can be used to center a element
horizontally by giving margin auto from left and right of the element
as margin: 0 auto;.
• Using display: The display property with value flex can be used to center
a element vertically as well as horizontally by using some extra
properties as align-items: center; and justify-content: center;.

33. Describe the use of the position property in CSS.

The position property is used to position an element in the document.


The possible values of this property are relative, absolute, fixed,
sticky, and static.

34. What are pseudo classes and pseudo elements in CSS?

The pseudo classes and pseudo elements are different entities in CSS.
They are combinely known as pseudo selectors in CSS. Below is the
explanation for them:
• pseudo classes: These are the classes that selects the elements based
on their state and the position. Some pseudo classes are
:hover, :nth-child etc.
• pseudo elements: These are the virtual elements that are mainly
defined to style a particular part of an element in the HTML
document. Some pseudo elements are :before and :after.

35. Why is the ‘!important’ used in CSS?

Notes Page 67
document. Some pseudo elements are :before and :after.

35. Why is the ‘!important’ used in CSS?

The !important declaration is used to give higher precedence to a CSS


property to override the other conflicting styles defined on the element
using the same property.
Ex: width: 30px !important; will override the property width:
25px; defined on the same element.

36. What is the purpose of ‘box-sizing’ property in CSS?

The box-sizing property is used to determine the way of calculating the


height and width of a element. It determines whether the border and
padding will be included or not to calculate the height and width of the
element. The common values are content-box(default) and border-box.
Key Values:
1. content-box (Default):
○ The width and height of the element apply only to the content.

Padding and borders are added outside these dimensions,


increasing the element's total size.
○ Example: Total size = width + padding + border.

2. border-box:
○ The width and height include the content, padding, and border.

This makes it easier to manage the total size of an element and


ensures consistent layouts.
○ Example: Total size = width (fixed, no additional size from padding

or border).

Why is it important?
1. Simplifies layout design: Using box-sizing: border-box allows you to
define a fixed size for elements, including padding and borders,
reducing the need for extra calculations.
2. Consistency across browsers: It ensures that the element size
remains predictable, regardless of added padding or borders.
3. Prevents layout issues: Helps avoid overflow and misalignment when
combining elements with different padding or borders.

38. What is the meaning of ‘Cascading’ in Cascading Style Sheet?

Cascading represents the specificity order in applying styles. These styles


can be defined by the user, author or they can be the default browser
styles. The specificity order for the styles is user styles > author styles >
default browser styles.

27. What are the various positioning properties in CSS?

The position property in CSS tells about the method of positioning for an
element or an HTML entity. There are five different types of position
properties available in CSS:
1. Fixed
2. Static
3. Relative
4. Absolute
5. Sticky
The positioning of an element can be done using
the top, right, bottom, and left properties. These specify the distance of
an HTML element from the edge of the viewport. To set the position by
these four properties, we have to declare the positioning method.
Let’s talk about each of these position methods in detail:
1. Fixed: Any HTML element with position: fixed property will be
positioned relative to the viewport. An element with fixed positioning
allows it to remain at the same position even as we scroll the page. We
can set the position of the element using the top, right, bottom, and left.
2. Static: This method of positioning is set by default. If we don’t
Notes Page 68
positioned relative to the viewport. An element with fixed positioning
allows it to remain at the same position even as we scroll the page. We
can set the position of the element using the top, right, bottom, and left.
2. Static: This method of positioning is set by default. If we don’t
mention the method of positioning for any element, the element has
the position: static method by default. By defining Static, the top, right,
bottom and left will not have any control over the element. The element
will be positioned with the normal flow of the page.
3. Relative: An element with position: relative is to be positioned
relatively to it normal position. If we set its top, right, bottom, or left,
other elements will not fill up the gap left by this element.
4. Absolute: An element with position: absolute will be positioned with
respect to its nearest parent. The positioning of this element does not
depend upon its siblings or the elements which are at the same level.
5. Sticky: Toggles between relative and fixed. When it touches the top,
it will be fixed at that place in spite of further scrolling. We can stick the
element at the bottom, with the bottom property.

31. How can we vertically center a text or img in CSS?

39. Explain Media Queries in CSS.

Media queries are the block of CSS code defined for a particular width or
range of the width. These can be defined using the @media keyword
with screen to specify styles for a particular width or range of width.
They are used very commonly to create responsive designs.

41. How you can optimize the loading of CSS files in browser?

There are multiple techniques available to optimize loading of CSS files


as listed below:
• By minimizing number of CSS files.
• CSS minification
• By leveraging the browser cache
• Load the un-necessary styles using asynchronous or deffered loading.

42. How to create responsive designs?

There are some key concepts available in CSS that can help you in
creating responsive designs as listed below:
• Using Media queries
• Using the flexbox layout
• Using the grid layout
• Using responsive CSS properties like percentage and vh, vw and rem to
create responsive designs.

What is the difference between relative, absolute, fixed, and sticky


positioning in CSS?
• relative: Positioned relative to its normal position.

• absolute: Positioned relative to the nearest parent.

• fixed: Positioned relative to the viewport and does not move when

scrolling.
• sticky: Toggles between relative and fixed based on the scroll

position.
What is the difference between inline, block, and inline-block

Notes Page 69
What is the difference between inline, block, and inline-block
elements?
○ inline: Does not start on a new line, only takes up as much width as

necessary.
○ block: Starts on a new line and takes up the full width available.

○ inline-block: Behaves like inline but allows setting width and height.

What is the difference between em, rem, and px units in CSS?


• px: Absolute unit; fixed size.

• em: Relative to the font size of its nearest parent.

• rem: Relative to the root element's font size.

What is the difference between id and class in CSS?


○ id: Unique identifier, applied to a single element (#id).

○ class: Reusable selector, applied to multiple elements (.class).

What are pseudo-classes in CSS?


• Define the special state of an element.

• Examples:

○ :hover - Applies styles when hovering over an element.

○ :nth-child(n) - Targets elements based on their position.

What are pseudo-elements in CSS?


• Used to style parts of an element.

• Examples:

○ ::before - Adds content before an element.

○ ::after - Adds content after an element.

What is the difference between relative and z-index?


• z-index: Controls the stack order of elements (higher values appear in

front).
• position: relative: Allows the element to be positioned relative to its

normal flow.
What is the difference between visibility: hidden and display: none?
○ visibility: hidden: Hides the element but retains its space.

○ display: none: Hides the element and removes it from the layout.

Notes Page 70
6. What are CSS combinators?
○ Used to define the relationship between selectors.
▪ Descendant (A B): Selects all B inside A.
▪ Child (A > B): Selects all direct children B of A.
▪ Adjacent sibling (A + B): Selects the first B immediately following A.
▪ General sibling (A ~ B): Selects all B siblings of A.

What is the difference between opacity and visibility?


○ opacity: Changes the transparency of an element (0 is fully transparent, 1
is fully visible).
○ visibility: Controls whether the element is visible or hidden, but it still
occupies space.

How does the z-index property work?


Determines the stack order of elements. Higher values appear on top of
lower values.

What is the difference between overflow: hidden, scroll, and auto?


○ hidden: Hides content that overflows the container.
○ scroll: Adds a scrollbar, regardless of whether content overflows.
○ auto: Adds a scrollbar only when content overflows.

Notes Page 71
Js
28 August 2024 16:47

Notes Page 72
Notes Page 73
Notes Page 74
Notes Page 75
Notes Page 76
43. What is JavaScript?
JavaScript is a high-level, dynamically typed scripting language
primarily used to add interactivity and dynamic content to Javascript is used to add the functionality of the
websites. content on a webpage.
Actions like onclick, on submit, dynamic
manipulation etc.

It runs on the client-side in the browser, but with [Link], it can


also be used on the server-side. JavaScript is used in both front-
end development (with libraries and frameworks like ReactJS,
[Link], and AngularJS) and back-end development (using
[Link]).
44. What is difference between == and === in JavaScript?
The == operator is the loose equality operator, which compares only
the values of the operands. The === operator is the strict equality
operator, which compares both the value and the type of the operands.
For example:
• 3 == "3" returns true because == only compares values and converts

the string "3" to a number.


• 3 === "3" returns false because === compares both the value and

type, and a number is not the same type as a string.


What is the difference between var, let, and const?
• var: Function-scoped, can be re-declared and updated.

• let: Block-scoped, can be updated but not re-declared.

• const: Block-scoped, cannot be re-declared or updated.

45. How to defer an element’s event handler if it depends on an


external script that takes some time to load?

To defer an event handler that depends on an external script, you can


use the defer attribute in the <script> tag. This ensures the script is
executed after the HTML is fully parsed.

Notes Page 77
executed after the HTML is fully parsed.

46. Optimal strategy for winning a game where let’s say, I start with 1,
opponent can cite a number X within the range [2, 11]. Then I have to
say a number in the range [X + 1, X + 10], then opponent, then me, and
so on. Whoever says 100 in the end wins and the game ends.

The optimal strategy for winning this game is to put your opponent in a
situation where they have no choice to say some number that is closer
to 100 and then you have 100 in the range from that number + 1 to that
number + 10, so that you can say 100 first and wins the game.
In this game, the goal is to force your opponent into a position where
they have no option but to push the count towards 100 in a way that
allows you to say 100 first.
Optimal Strategy:
You want to control the flow by making moves that leave your
opponent in a situation where their only valid choices will allow you
to reach 100.
○ Key Insight: The critical numbers you should aim for are 90, 80,

70, and so on, down to 10. These are the numbers where, no
matter what number your opponent chooses within the allowed
range, you will always be able to choose a number that brings you
closer to 100.

47. Why would you use the prototype in JS?

Prototypes in JavaScript are fundamental to object-oriented


programming and the prototype chain. They allow objects to inherit
properties and methods from other objects.
All JavaScript objects inherit properties and methods from a prototype.
Here's why you would use prototypes:
1. Dynamic modification: You can dynamically add or modify properties
and methods of objects via their prototypes.
2. Inheritance: Prototypes are used to implement inheritance, allowing
objects to inherit methods and properties from other objects.
3. Sharing methods: By using prototypes, methods can be shared
across instances, saving memory because the methods are not
duplicated for each instance.
4. Prototype-based language: JavaScript is a prototype-based language,
meaning every object has a prototype, from which it can inherit
properties and methods.
5. Memory efficiency: Prototypes allow the sharing of methods
between all instances of an object, reducing memory usage
compared to duplicating methods across instances.

48. What is the meaning of ‘this’ in JS?

The this keyword in JavaScript refers to the context in which it is called.


The scoping behaviour of this keyword changes based on the scope
where it is used.
• In the global context: this refers to the global object (in browsers, it's

the window object).


• In an object method: this refers to the scope of the object whose

function is called.

Notes Page 78
What are arrow functions? How are they different from regular
functions?
• Shorter syntax for functions and do not bind their own this. Example:

50. Difference between null and undefined in JS.

Null and undefined in JavaScript are both used to represent "absence


of value," but they differ in meaning and usage:
1. Undefined:
○ A variable is undefined if it is declared but not initialized.

○ Functions return undefined if no return value is specified.

○ Accessing a non-existent property of an object also results in

undefined.

[Link]:
○ null is an explicitly assigned value indicating "no value."

○ It is used to represent an intentionally empty or non-existent

object.

Explain closures in JS with an example of statements in loop


69. Explain the concept of currying in
Closures in JavaScript are formed when an inner function "remembers"JavaScript?
the variables from its parent function, even after the parent function Currying is a technique which is used to transform a
has finished execution. This is because of the lexical scoping and the function that takes n parameters into a chain
of n functions in which each function contains only
way JavaScript manages its scope chain. one parameter.
function normalFunction(a, b){
return a*b;
}
normalFunction(3, 2) // Output: 6
function curryingFunction(a){
return function(b){
return a*b;
}
}
curryingFunction(3)(2); // Output: 6

From <[Link]
ref=lbp>

Notes Page 79
• A closure is a function that retains access to its outer scope, even after
the outer function has returned. Example:

What is event loop in JavaScript?

The event loop in JavaScript is a mechanism that handles asynchronous


operations using callStack and callback queue;
Key Points:
1. JavaScript executes code line by line (synchronously) using the call
stack.
2. Asynchronous tasks (like setTimeout or Promises) are sent to the
callback queue or microtask queue after completing their
operations.
3. The event loop continuously checks if the call stack is empty.
○ If the stack is empty, it pushes tasks from the callback or

microtask queue into the call stack for execution.

[Link] hoisting in JS?

Here's a concise explanation for the interview:


Hoisting in JavaScript is a behavior where variable and function
declarations are moved to the top of their scope during the compilation
phase, before code execution. This allows you to access variables or
functions before they are defined in the code.

54. What are different Data types in JS?

JavaScript is a dynamically typed language, that means unlike the other


programming languages like C, C++ the type of the variables is decided
at the run time instead of the compile time. In JavaScript, there are two
types of data types available: Premitive - holds single value
Non Premitive - holds multiple values
• Primitive Data type: These are the predefined data types and
immutable (cannot be changed) like string, number, boolean,
undefined, null, BigInt etc.
Non-Primitive Data type: These are the data types that are derived

Notes Page 80
• Non-Primitive Data type: These are the data types that are derived
from the primitive data types like arrays and objects.

[Link] the typeof([]) is object, then what is the content and the length of
b in the code below?
let b = [];
b.v = 10;
[Link](11);
Ans: Arrays in JavaScript are a special kind of object that can hold both
indexed (numeric) and key-value data.
1. let b = [];: Creates an empty array.
2. b.v = 10;: Adds a custom property v with the value 10. This does not
affect the numeric indexing or length of the array.
3. [Link](11);: Adds the value 11 to the array at index 0, increasing the
length to 1.
Result:
• Content of b: [11, v: 10].

○ The numeric index 0 holds the value 11.

○ v is a property of the array object, not part of the numeric indices.

• Length of b: 1.

○ The length only accounts for numeric indices, so the v property

does not contribute to the length.


Explain call(), apply(), and bind() methods in JavaScript.
Answer:
In JavaScript, the call(), apply(), and bind() methods are built-in
functions used to invoke a function with a specific context (i.e., setting
the value of this) and arguments. These methods help you control the
context (this) in which a function is executed.
1. call() Method:
• Usage: The call() method calls a function with a specific this value

and individual arguments passed one by one.


• Syntax: [Link](thisArg, arg1, arg2, ...)

○ thisArg: The value of this inside the function.

○ arg1, arg2, ...: The arguments to pass to the function.

2. apply() Method:
• Usage: The apply() method is almost identical to call(), but instead of

passing the arguments individually, you pass them as an array or an


array-like object.
• Syntax: [Link](thisArg, [arg1, arg2, ...])

○ thisArg: The value of this inside the function.

○ [arg1, arg2, ...]: An array of arguments to pass to the function.

• Example:

Notes Page 81
3. bind() Method:
• Usage: The bind() method returns a new function that, when

invoked, has its this value set to a specific value, and the arguments
are pre-filled. Unlike call() and apply(), bind() does not invoke the
function immediately but rather binds the function to a specific
context and arguments, which can be executed later.
• Syntax: [Link](thisArg, arg1, arg2, ...)

○ thisArg: The value to use as this when calling the function.

○ arg1, arg2, ...: Arguments to pass to the function when it is

invoked.

Summary:
• call(): Invokes the function immediately with specified this and

individual arguments.
• apply(): Similar to call(), but passes arguments as an array.

• bind(): Creates a new function with specified this and arguments,

which can be invoked later.


What is event delegation in JavaScript?
Answer:
1. Event delegation is a technique in JavaScript used to improve
performance and reduce memory usage when handling events on
elements.
2. Instead of attaching individual event listeners to each child element,
you attach a single event listener to the parent element.
3. This approach leverages the event bubbling mechanism, where
events propagate (bubble up) from the target element to its parent
element.
How it works:
1. Event Bubbling: When an event is triggered on an element, it
bubbles up to its parent elements in the DOM tree. The parent can
catch and handle the event at a higher level.
2. Parent Element: Instead of attaching an event listener to every child
element, attach it to a common parent.

Notes Page 82
element, attach it to a common parent.
3. Targeting the Event: Inside the event listener, you can use
[Link] to determine which child element triggered the event.

60. Tell me about key features of JavaScript.

There are many features provided by JavaScript, some of them are listed
below:
• It is a Single threaded language.
• Dynamic variable typing.
• Prototypal and classical inheritance
• First class functions
• Higher order functions.
• Hoisting and closures etc.

61. What is the use of “use strict” directive in JavaScript?

The use strict directive is used to write the clean JavaScript code which
is less prone to errors. It catches common coding errors like assigning a
variable without declaring it and disallows functions from having
parameters with duplicate names.

Event Propagation:
Event propagation refers to the way an event moves through the DOM
tree when triggered. There are two phases of event propagation: Event
Bubbling and Event Capturing.
1. Event Bubbling: The event starts from the target element and
bubbles up to the root of the DOM tree.
i. It is the default behaviour of the event propagation.
2. Event Capturing: The event starts from the root of the DOM tree and
triggered down to the target element.
i. It can be enabled by passing an extra parameter as true to
the addEventListener() method at the time of attaching an
event.
Event propagation determines how events are handled by various
elements in the DOM when there are multiple event listeners on
different levels.
Key Points:
Notes Page 83
Key Points:
• It defines how the event is passed between the parent and child

elements.
• It involves two phases: capturing (from outermost to innermost) and

bubbling (from innermost to outermost).


• It allows handlers to control when they execute during these phases.

65. What are callback functions in JavaScript?


A callback function in JavaScript is a function passed as an argument to
another function, which is then executed at a later time. It's commonly
used in asynchronous operations like handling events or executing code
after a delay. Callback functions allow JavaScript to handle tasks without
blocking the main execution thread.

67. Explain Promises in JavaScript.

A Promise is an object that represents the completion or failure of an


asynchronous operation and it resulting value. There are three states of
an promise:
• pending: It is the initial state in which promise is neither rejected nor
fulfilled.
• resolve: It represents the successful state of the promise where it
completes the task.
• rejected: It represents that the asynchronous task gets failed.

Notes Page 84
66. What is callback hell and how to avoid it?
A: Callback hell occurs when multiple nested callback functions make
the code difficult to read and maintain, especially in asynchronous
operations.
To avoid callback hell:
1. Use Promises: Promises allow chaining of operations and make the
code more readable by avoiding multiple nested callbacks.
2. Use async/await: Async/await provides a cleaner and more readable
syntax for handling asynchronous code, resembling synchronous
code flow while still being non-blocking.
The reason "Data displayed" is not logged to the
console is due to the fact that
the displayData function is not designed to call a
callback. It simply contains a setTimeout that logs
"Data displayed" after 1 second, but it doesn't
invoke any callback after that.
Here's a breakdown of what happens in your
code:
1. fetchData is called, which waits for 1 second and
then logs "Data fetched". It then calls the provided
callback, which is the processData function.
2. processData is called, which also waits for 1
second and then logs "Data processed". It then
calls the provided callback, which is
the displayData function.
3. displayData is called, which waits for 1 second and
then logs "Data displayed". However, it does not
call any callback after that.

68. What is the use of async await in JavaScript?

The async statement is used to represent the asynchronous task that


takes sometime to get resolved. While, the await statement is used to
wait for a promise or asynchronous task to resolve or fulfill to continue
the asynchronous function execution.

70. What is the purpose of passing defer or async attributes to the


script tag?

The defer and the async attributes are used to load the script in a
particular manner as explained below:

Notes Page 85
• defer: Ensures the script executes only after the HTML parsing is
complete. Use it when the script depends on the DOM structure.
<script src="script_file_path" defer></script>
• async: Executes the script immediately after it is downloaded, without
waiting for the HTML parsing to finish. Use it for independent scripts.
<script src="script_file_path" async></script>

72. How to stop event propagation in JavaScript?

There is a in-built method [Link]() provided by the


JavaScript events which can be used to stop event propagation. The
method can be implements as follows:
It is a technique used to trigger the
[Link]('event', function(e){ server or run a function only after
[Link](); certain period of time.
})

73. How to prevent the default behaviour of a event in JavaScript?

The [Link]() is a in-built method provided by JavaScript that


can be used to prevent the default behaviour of an JavaScript event.

74. Describe the concept of CORS?

CORS stands for Cross-Origin Resource Sharing. It is a technique used by


the browsers to make our web page more secure. The web browsers
use this feature to prevent requests from one domain to another
domain.

75. Explain debouncing in JavaScript?

It is a technique used to improve the performance of the web page by


ensuring that the time consuming tasks do not fire so often in the code.
One use case of debouncing is to handle the situation in which frequent
server requests are made evertime a key is pressed. For
Example: search functionality on different web pages.

75. Explain debouncing in JavaScript?


Debouncing is a technique used to limit the number of times a function
is executed, ensuring it only runs after a certain period of inactivity. This
improves performance, especially for time-consuming operations
triggered frequently, like resizing a window or typing in a search box.
Use case:
In search functionality, debouncing prevents sending a server request
for every keystroke. Instead, the request is made only after the user
stops typing for a defined duration.

Notes Page 86
What is the difference between map(), forEach(), and filter()?
• map(): Returns a new array by transforming every element.
• forEach(): Executes a provided function on each array
element (no return).
• filter(): Returns a new array with elements that pass a test.

Notes Page 87
Notes Page 88
Notes Page 89
Notes Page 90
What is the advantage of using async and await over then() in handling
promises?
• Answer: The primary advantage of using async/await over .then() is that
it simplifies asynchronous code by making it look and behave more like

Notes Page 91
it simplifies asynchronous code by making it look and behave more like
synchronous code.
• async/await eliminates the need for chaining .then() and .catch()
methods, which can lead to "callback hell" or "promise chaining." It also
allows for easier error handling with try...catch.

When should you use async and await with API calls?
• Answer: You should use async and await when making asynchronous
API calls to make the code cleaner and more readable.
• It helps in handling asynchronous operations like fetch(), [Link](),
etc., in a way that feels synchronous, allowing you to wait for a
promise to resolve before continuing.

What happens if you use await in a non-async function?


• Answer: If you try to use await in a non-async function, it
will result in a syntax error because await can only be used
inside an async function.

How can you handle multiple errors when using async/await with
multiple API calls?
• Answer: You can handle multiple errors using try...catch blocks
inside async functions, or you can catch errors for each promise
individually if you're calling multiple asynchronous operations.

Notes Page 92
What is difference between [Link]() and
[Link]() Methods in JavaScript ?
[Link]() converts JSON strings to JavaScript
objects, while [Link]() converts JavaScript
objects to JSON strings.

Notes Page 93
ReactJs
18 November 2024 19:24

1. What is React? Why is it used?


Answer:
1. React is a JavaScript library for building single-page applications.
2. It allows developers to create reusable UI components and render only the
necessary components when data changes.
3. React is used for its speed, scalability, and flexibility.

2. What is JSX?
Answer:
1. JSX stands for JavaScript XML.
2. It is a syntax extension for JavaScript used in React to write HTML-like
code within JavaScript.
Example:

3. What are React components?


Answer:
1. React components are the building blocks of a React application.
2. A component in React is a reusable and independent piece of code used
to build the user interface. .

Key Features of React:


1. Virtual DOM:
○ React uses a virtual DOM to optimize rendering.

○ It minimizes direct updates to the real DOM by calculating changes

beforehand, improving performance.


2. Component-Based Architecture:
○ UI is divided into reusable components, each handling its logic and

rendering.
○ Promotes modularity and reusability.

[Link]:
○ Allow functional components to manage state and side effects.

○ Examples: useState, useEffect.

Q: Explain the MVC Architecture.


A:
The Model-View-Controller (MVC) is a design pattern used to separate an
application into three interconnected components:
1. Model:
○ Model is responsible for storing and managing data.

2. View:
○ Handles the user interface and presentation.

○ Displays data from the model to the user.

3. Controller:

Notes Page 94
3. Controller:
○ Acts as an intermediary between the Model and View.

○ Handles user inputs and updates the Model or View accordingly.

This separation improves code modularity and maintainability.

3. Explain the building blocks of React.

The five main building blocks of React are:


1. Components: These are reusable blocks of code that return HTML.
2. JSX: It stands for JavaScript and XML and allows you to write HTML in
React.
3. Props and State:
○ Props: Props are arguments passed into React components.

○ State: A component's local data storage and mutable.

4. Context: Provides a way to share data (like themes or authentication)


across components without explicitly passing props.
5. Virtual DOM: It is a lightweight copy of the actual DOM which makes
DOM manipulation easier.

4: Explain props and state in React with differences.


A:
• Props: Short for "properties," used to pass data from parent to child

components. Props are immutable and read-only.


• State: Local data storage within a component. State is mutable and can be

both read and written.


Differences Between Props and State:
Props State
• Data is passed from one • Data is stored and managed within a
component to another. component.
• Immutable (cannot be modified). • Mutable (can be updated).
• Used with both class and • Initially used only with class
functional components. components (before React 16).
• Read-only. • Can be read and written.

5. What is virtual DOM in React?

1. The Virtual DOM acts as a lightweight copy of the real DOM.


2. It helps React to render necessary components when there was a change
occur.
How Virtual DOM Works
1. Efficient Rendering: The Virtual DOM acts as a lightweight copy of the real
DOM that React uses to optimize the process of updating and rendering
UI changes.
2. Diffing Algorithm: React compares the current and previous Virtual DOM
states to determine the minimal changes needed.
3. Batch Updates: Instead of updating the real DOM immediately, React
batches multiple changes to reduce unnecessary re-renders, improving
performance.
4. Faster Updates: Since updating the real DOM is slow, Only necessary
updates are applied to the real DOM to minimize direct DOM
manipulation.
5. Declarative UI: With the Virtual DOM, React allows developers to write
code in a declarative style, then React handle when and how to efficiently
update the UI.

Q: What are components and their types in React?


A:
A component in React is a reusable and independent piece of code used to
build the user interface. It allows developers to divide the UI into smaller,
manageable parts.

Notes Page 95
manageable parts.
React has two main types of components:
1. Functional Components:
○ These are JavaScript functions that take props as an argument and

return React elements.


○ Simple and efficient, especially for rendering UI.

[Link] Components:
• These are ES6 classes that extend [Link].

• They support state and lifecycle methods, making them suitable for more

complex functionality.

8. How do browsers read JSX?

In general, browsers are not capable of reading JSX and only can read pure
JavaScript. The web browsers read JSX with the help of a transpiler.
Transpilers are used to convert JSX into JavaScript. The transpiler used is
called Babel.

9. Explain the steps to create a react application and print Hello World?

To install React, first, make sure Node is installed on your computer. After
installing Node. Open the terminal and type the following command.
npx create-react-app <<Application_Name>>
Navigate to the folder.
cd <<Application_Name>>
This is the first code of ReactJS Hello World!
import React from "react";
import "./[Link]";
function App() {
return (
<div className="App">
Hello World !
</div>
);
}
export default App;
Type the following command to run the application
npm start

Q: How to create an event in React?


A:
To create an event in React, attach an event handler (like onClick, onChange,
etc.) to a JSX element and define a function to handle the event logic. React
events follow camelCase naming convention and prevent the default browser
behavior using [Link]().

Notes Page 96
behavior using [Link]().

Q: Explain the creation of a List in React?


A:
In React, lists are commonly used for displaying repetitive data, such as
menus or items. Lists can be created using the map() function of arrays to
dynamically generate React elements.

Unique Keys: Each list item should have a unique key prop for efficient
rendering and updates in the Virtual DOM.

13. How to write a comment in React?

There are two ways to write comments in React.


• Multi-line comment: We can write multi-line comments in React using
the asterisk format /* */.
• Single line comment: We can write single comments in React using the
double forward slash //.
Q: Explain the difference between React and Angular?
Field [Link] Angular
Used as [Link] is a JavaScript library. Angular is a framework. It
It updates the Virtual DOM. updates the Real DOM.
Architecture Follows a simplified MVC Follows a complex MVVM
(Model-View-Controller) (Model-View-ViewModel)
architecture. architecture.
Scalability Highly scalable. Less scalable compared to
[Link].
Data Binding Supports uni-directional (one- Supports bi-directional
way) data binding. (two-way) data binding.
DOM Uses a Virtual DOM for Uses a Regular DOM which
efficient updates. can be slower for large
applications.
Key Interview Point:
React is suitable for projects needing high scalability and flexibility, while
Angular is better for fully structured enterprise-level applications with built-in
features.

Q: Explain the difference between functional and class components in


React?
Functional Components Class Components
Functional components are plain Class components are ES6 classes that
JavaScript functions that accept extend [Link] and must
props as an argument. include a render() method.

Notes Page 97
props as an argument. include a render() method.
They do not require a render() The render() method is mandatory to
method to return JSX. return JSX.
React lifecycle methods (e.g., React lifecycle methods (e.g.,
componentDidMount) cannot be componentDidMount) can be used.
used directly.
No constructor is needed, and state A constructor is required to initialize and
can be managed using the useState manage state.
hook.

20. Explain one way data binding in React?

1. ReactJS uses One-way data binding in React means that data flows in a
single direction, typically from the parent component to the child
component.
2. Child components are not able to update the data that is coming from the
parent component. It is easy to debug and less prone to errors.

21. What is conditional rendering in React?

Conditional rendering in React involves selectively rendering components


based on specified conditions. By evaluating these conditions, developers can
control which components are displayed, allowing for dynamic and
responsive user interfaces in React applications.
Let us look at this sample code to understand conditional rendering.
{isLoggedIn == false ? <DisplayLoggedOut /> : <DisplayLoggedIn />}
Here if the boolean isLoggedIn is false then the DisplayLoggedOut component
will be rendered otherwise DisplayLoggedIn component will be rendered.

22. What is react router?

React Router is a standard library for routing in React.


It allows navigation between different components or views in a React
Application, allows changing the browser URL, and keeps the UI in sync with
the URL.
To install react router type the following command.
npm i react-router-dom

Basic Usage of React Router:


1. Setting up Router:

Notes Page 98
1. Setting up Router:
○ <BrowserRouter>: Wraps your entire application to enable routing

capabilities.
○ <Route>: Specifies which component to render for a given URL path.

○ <Link>: Provides navigation between different views in the application

without reloading the page.

23. Explain the components of a react-router

The main components of a react-router are:


1. Router(usually imported as BrowserRouter): It is the parent component
that is used to store all of the other components. Everything within this
will be part of the routing functionality
2. Switch: The switch component is used to render only the first route that
matches the url rather than rendering all matching routes.
3. Route: This component checks the current URL and displays the
component associated with that exact path. All routes are placed within
the switch components.
4. Link: The Link component is used to create links to different routes.

24. Explain the lifecycle methods of components

A React Component can go through four stages of its life as follows.


1. Initialization: This is the first phase in the lifecycle of a component where
the component is initialized with props and the initial state. This is done in
the constructor of a Component Class.
2. Mounting: Mounting is the process of rendering the component and
adding it to the DOM.
3. Updating: Updating is the stage when the state of a component is

Notes Page 99
the constructor of a Component Class.
2. Mounting: Mounting is the process of rendering the component and
adding it to the DOM.
3. Updating: Updating is the stage when the state of a component is
updated and the application needs to re-render.
4. Unmounting: As the name suggests Unmounting is the final step of the
component lifecycle where the component is removed from the page.

29. useState Hook in React:


1. The useState hook is used to declare and manage state variables in
functional components.
2. It provides a state variable and a function to update it.
3. Each time the state updates, React re-renders the component.
Syntax:

Example:

Key Points:
• Allows functional components to maintain local state.

• Each useState handles one piece of state.

• React ensures state updates trigger re-renders.

30. useEffect Hook in React:


1. The useEffect hook is used for handling side effects in functional
components based on dependency.
2. It replaces lifecycle methods like componentDidMount and
componentDidUpdate in class components.
Syntax:

Key Points:
• The effect runs after the component renders.

• The second argument (dependency array) controls when the effect is

triggered.
○ Empty array []: Runs once after the initial render.

○ No array: Runs after every render.

○ Array with dependencies: Runs when dependencies change.

Example:

Notes Page 100


Both hooks are essential for managing state and side effects in functional
components.

32. What is a react developer tool?

React Developer Tools is a Chrome DevTools extension for the React


JavaScript library. This extension adds React debugging tools to the Chrome
Developer Tools.
It helps you to inspect and edit the React component tree that builds the
page, and for each component, one can check the props, the state, hooks,
etc.

33. How to use styles in ReactJS?

CSS modules are a way to locally scope the content of your CSS file. We can
create a CSS module file by naming our CSS file as [Link] and then
it can be imported inside [Link] file using the special syntax mentioned
below.
Syntax:
import styles from './[Link]';

34. Styled Components in React:


Styled Components allow developers to write CSS directly in JavaScript files,
creating modular and reusable styles. It removes the mapping between styles
and components, enabling components to serve as styling constructs.
Key Features:
• Scoped styles to components.

• CSS is written as template literals.

• Enhanced developer experience with dynamic styling.

11. What is React Fragments?

when we are trying to render more than one root element we have to put the
entire content inside the ‘div’ tag which is not loved by many developers.
So since React 16.2 version, Fragments were introduced, and we use them
instead of the extraneous ‘div’ tag.
The following syntax is used to create fragment in react.

Notes Page 101


17. What is useRef hook in react?

The useRef is a hook that allows to directly create a reference to the DOM
element in the functional component. The useRef returns a mutable ref
object. This object has a property called .current. The value is persisted in the
[Link] property. These values are accessed from the current
property of the returned object.
Syntax:
const refContainer = useRef(initialValue);

Custom Hooks in React


1. Custom hooks are reusable JavaScript functions that start with "use" and
can call other hooks internally.
2. We use custom hooks to promote code reusability in our application so
that we reuse logic across components, promoting the DRY (Don't Repeat
Yourself) principle.

Notes Page 102


37. How to optimize a React code?

We can improve our react code by following these practices:


• Using binding functions in constructors
• Eliminating the use of inline attributes as they slow the process of loading
• Avoiding extra tags by using React fragmentsx To optimize a React app, you can use techniques such
• Lazy loading as memoization with [Link] and useMemo, lazy
• Memoization - avoid re-renders loading components with [Link], and using keys
• Code Splitting: Divide your code into smaller segments and load them correctly in lists. Additionally, you can minimize re-
selectively based on necessity. renders by avoiding unnecessary state changes.

39. What is react-redux?

React-redux is a state management tool which makes it easier to pass these


states from one component to another irrespective of their position in the React - redux is a state management tool it provides the access of state variables
in overall components which prevents the prop drilling(passing props to many
component tree and hence prevents the complexity of the application. layers).

As the number of components in our application increases it becomes


difficult to pass state as props to multiple components.
To overcome this situation we use react-redux to avoiding the complexity of
prop-drilling (passing props through many layers of components).

Notes Page 103


40. What are benefits of using react-redux?

They are several benfits of using react-redux such as:


1. It provides centralized state management i.e. a single store for whole
application
2. It optimizes performance as it prevents re-rendering of component
3. Makes the process of debugging easier.
4. Since it offers persistent state management therefore storing data for
long times become easier.

41. Explain the core components of react-redux?

There are four fundamental concepts of redux in react which decide how the
data will flow through components
1. Redux Store: It is an object that holds the application state
2. Action Creators: These are functions that return actions (objects).
3. Actions: Actions are simple objects which conventionally have two
properties- type and payload
4. Reducers: Reducers are pure functions that update the state of the
application in response to actions

Notes Page 104


43. What is context API?

1. Context API is used to pass global variables anywhere in the code. It helps
when there is a need for sharing state between a lot of nested
components.
2. It is light in weight and easier to use, to create a context just need to call
[Link]().
3. It eliminates the need to install other dependencies or third-party libraries
like redux for state management.
4. It has two properties Provider and Consumer (or) useContext.

44. Explain provider and consumer in ContextAPI?


A provider is used to provide context to the whole application
whereas a consumer consume the context provided by nearest
provider.
Provider and Consumer:
• The Provider wraps components and provides the global value.

• Components access this value via the Consumer or the

useContext hook.

45. Explain CORS in React?


CORS (Cross-Origin Resource Sharing) is a security mechanism

Notes Page 105


CORS (Cross-Origin Resource Sharing) is a security mechanism
implemented by browsers to restrict how resources on a web page can
be requested from another domain. This prevents unauthorized access
to a server's resources.

Why is CORS Needed in React?


When your React frontend is hosted on one domain (e.g.,
[Link] and your backend API is hosted on another (e.g.,
[Link] the browser restricts cross-origin requests by
default for security reasons. To enable such communication, you must
configure CORS.

46. What is axios and how to use it in React?

Axios, which is a popular library is mainly used to send asynchronous


HTTP requests to REST endpoints. This library is very useful to perform
CRUD operations.
• This popular library is used to communicate with the backend. Axios
supports the Promise API, native to JS ES6.
• Using Axios we make API requests in our application. Once the request is
made we get the data in Return, and then we use this data in our
project.
To install aixos package in react use the following command.
npm i axios

9. What is the difference between state and props?


Answer:
• State:
○ Managed within the component.
○ Can be modified using setState (in class components) or useState (in functional
components).
○ Example: Keeps track of user input, toggle status, etc.
• Props:
○ Passed from parent to child components.
○ Immutable from the child component's perspective.
○ Example: Parent can pass data to the child component to display it.

Notes Page 106


17. What is the virtual DOM in React?
Answer:
1. The Virtual DOM acts as a lightweight copy of the real DOM.
2. It helps React to render necessary components when there
was a change occur.

Notes Page 107


22. What are React hooks? Name a few commonly used hooks.
Answer:
React hooks allow you to use state and other React features in
functional components. Commonly used hooks include:
1. useState - For managing state.
2. useEffect - For side effects like fetching data.
3. useContext - For consuming context values.
4. useRef - For accessing DOM elements without re-renders.
5. useReducer - For managing more complex state logic.

Notes Page 108


Notes Page 109
50. How does React manage updates in the virtual DOM?
Answer:
React uses a virtual DOM to optimize rendering:
1. When state or props change, React creates a new virtual DOM tree.
2. It compares the new virtual DOM with the previous one using a
process called reconciliation.
3. React updates only the necessary parts of the actual DOM based on
the differences (diffing algorithm).

1. [Link]
[Link] is a runtime environment that allows JavaScript to run on the
server side.

2. [Link]
[Link] is a lightweight web application framework built on
top of [Link]. It simplifies the process of building APIs and
web applications.

Notes Page 110


MERN
21 November 2024 22:43

1. Who is a Mern Stack Developer?


A MERN Stack Developer is a skilled programmer who
specializes in building web applications using four key
technologies: MongoDB, Express, React, and [Link].
These technologies work together to create both the front-
end (what the user sees and interacts with) and back-end
(the server-side logic that powers the application) of a
website.

3. What is ReactJS?

1. React is a JavaScript library for building single-page applications.


2. It allows developers to create reusable UI components and
render only the necessary components when data changes.

Q: Explain the MVC Architecture.


A:
The Model-View-Controller (MVC) is a design pattern used to
separate an application into three interconnected components:
1. Models:
a. Model is responsible for storing and managing data
2. Views: are react components that
○ Handles the user interface and presentation.

○ Displays data from the model to the user.

3. Controllers:
○ Acts as an intermediary between the Model and View.

○ Handles user inputs and updates the Model or View

accordingly.
This separation improves code modularity and maintainability.

Q. Explain the building blocks of React.

The five main building blocks of React are:


1. Components: These are reusable blocks of code that return
HTML.
2. JSX: It stands for JavaScript and XML and allows you to write
HTML in React.
3. Props and State:
○ Props: Props are arguments passed into React components.

○ State: A component's local data storage and mutable.

4. Context: Provides a way to share data (like themes or


authentication) across components without explicitly passing
props.
5. Virtual DOM: It is a lightweight copy of the actual DOM which
minimizes direct updates to the real DOM by calculating changes
beforehand and then perform only necessary changes in real
DOM.

Notes Page 111


11. What is the purpose of MongoDB?
1. MongoDB is a NoSQL database designed to store large
volumes of unstructured or semi-structured data in the form
of Collections and documents.
Json- Javascript Object Notation
2. It stores data in the form of documents and collections
instead of rows and tables, as in relational databases.
a JSON-like format called BSON
12. What is the purpose of ExpressJS? (Binary JSON) and organizes it into
ExpressJS is a web application framework for [Link].
It is mainly used to :
• Building RESTful APIs to perform CRUD operations on

Application data by using get and POST methods.


• And Managing the interactions between frontend and backend

by routing HTTP requests.

Notes Page 112


22: How to handle routing in Express JS?
[Link] manages routing through the use of the
`[Link]()` method.
This method yields an instance of a router, enabling the
definition of routes for the application.
Below is an illustration of how to define a basic route using
this router.

What is Middleware?
• In the context of [Link] or [Link] applications,
middleware refers to functions that have access to the request
(req), response (res), and the next middleware function in the
application's request-response cycle.
• Middlewares are functions that are commonly used to perform
operations like logging, authentication, authorization and error
handling.

How to use Middlewares in a real-world scenario:


• Authentication middleware would be used in any route that

requires users to log in to enter into web page.


• Authorization middleware would be used to ensure only certain

users (like admins or managers) can access sensitive resources


(e.g., admin panels or user management).

RESTful API's :
1. A RESTful API is used for constructing web APIs.
2. It utilizes HTTP methods like GET, POST, PUT, and DELETE to
execute CRUD (create, read, update, delete) operations on
application data.
3. These are stateless means each request was independent.

Notes Page 113


3. These are stateless means each request was independent.

Notes Page 114


1. useGLTF
• What it does:
The useGLTF hook is used to load GLTF/GLB 3D models. GLTF
(GL Transmission Format) is a popular format for 3D models
optimized for web-based rendering.
2. <primitive object={scene} />
• What it does:
The <primitive> element allows you to directly add a 3D object (such
as the loaded model's scene) to your React Three Fiber scene.

1. [Link]
[Link] is a runtime environment that allows JavaScript to run on the
server side.

Notes Page 115

You might also like