Notes
Notes
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
• 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.
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.
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:
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.
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.
Notes Page 8
String s="abc";
int i=[Link](s);//NumberFormatException
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
Examples:
○ <img>, <br>, <input>, <hr>.
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.
Notes Page 14
<li>List Item 3</li>
<li>List Item 3</li>
</ol>
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.
content.
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.
Common uses:
○ Setting character encoding: <meta charset="UTF-8">.
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:
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.
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.
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.
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.
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.
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
the browser.
○ sessionStorage: Temporary storage. Data is removed after we
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.
• 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.
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.
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.
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.
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).
• 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).
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) .
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
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'
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]
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];
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;
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 :
Notes Page 43
Aggregate Functions : (Sum,Avg,min,max)
Notes Page 44
Notes Page 45
Networking
14 November 2024 19:08
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
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.
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.
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
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.
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.
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.
Notes Page 51
internet.
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.
Notes Page 52
security of the network.
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).
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.
Notes Page 54
Operating System
15 November 2024 18:41
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.
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:
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.
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
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.
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
Examples:
○ <img>, <br>, <input>, <hr>.
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.
Notes Page 61
<li>List Item 3</li>
<li>List Item 3</li>
</ol>
content.
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.
Common uses:
○ Setting character encoding: <meta charset="UTF-8">.
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:
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.
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.
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.
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.
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.
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
the browser.
○ sessionStorage: Temporary storage. Data is removed after we
9.
Notes Page 65
CSS
16 November 2024 23:10
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.
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.
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.
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.
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.
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;.
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.
Notes Page 67
document. Some pseudo elements are :before and :after.
2. border-box:
○ The width and height include the content, padding, and border.
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.
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.
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 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.
• 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.
• Examples:
• Examples:
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.
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.
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.
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:
undefined.
[Link]:
○ null is an explicitly assigned value indicating "no value."
object.
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:
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].
• Length of b: 1.
2. apply() Method:
• Usage: The apply() method is almost identical to call(), but instead of
• 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, ...)
invoked.
Summary:
• call(): Invokes the function immediately with specified this and
individual arguments.
• apply(): Similar to call(), but passes arguments as an array.
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.
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.
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
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.
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>
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.
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
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:
rendering.
○ Promotes modularity and reusability.
[Link]:
○ Allow functional components to manage state and side effects.
2. View:
○ Handles the user interface and presentation.
3. Controller:
Notes Page 94
3. Controller:
○ Acts as an intermediary between the Model and View.
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
[Link] Components:
• These are ES6 classes that extend [Link].
• They support state and lifecycle methods, making them suitable for more
complex functionality.
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
Notes Page 96
behavior using [Link]().
Unique Keys: Each list item should have a unique key prop for efficient
rendering and updates in the Virtual DOM.
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.
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.
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.
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.
Example:
Key Points:
• Allows functional components to maintain local state.
Key Points:
• The effect runs after the component renders.
triggered.
○ Empty array []: Runs once after the initial render.
Example:
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]';
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.
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);
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
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.
useContext hook.
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.
3. What is ReactJS?
3. Controllers:
○ Acts as an intermediary between the Model and View.
accordingly.
This separation improves code modularity and maintainability.
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.
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.
1. [Link]
[Link] is a runtime environment that allows JavaScript to run on the
server side.